Skip to content

Conversation

@alicup29
Copy link
Collaborator

Summary

Implements Step 1 (Client Registry Infrastructure) of the add-client-model-registry change proposal. This PR introduces a comprehensive client-side model registry system for tracking downloaded and imported models, complete with a web-based viewer and full test coverage.

What's New

🗄️ Core Registry System

sleap_rtc/client/client_model_registry.py (359 lines)

  • JSON-based persistence at ~/.sleap-rtc/models/manifest.json
  • Atomic write operations for crash safety (temp file + rename)
  • Automatic corruption recovery with timestamped backups
  • CRUD operations: register(), get(), list(), update(), delete(), exists()
  • Advanced filtering by model type, source, location, and alias presence
  • Support for optional metadata (metrics, hyperparameters, tags, notes)

🌐 Web Viewer

sleap_rtc/client/registry_server.py (448 lines)

  • Beautiful web interface at http://localhost:8765
  • Dashboard statistics (total models, aliases, worker sync status)
  • Responsive card-based UI showing all model details
  • Real-time filtering by type and location
  • REST API endpoints (/api/models, /api/stats, /api/model/{id})
  • Zero external dependencies (uses Python's built-in http.server)

Usage:

# Start the viewer
uv run python -m sleap_rtc.client.registry_server

# Open in browser
open http://localhost:8765

✅ Testing

tests/test_client_model_registry.py (32 tests, 100% passing)

  • Registry initialization and schema validation
  • CRUD operations and error handling
  • Filtering and sorting functionality
  • Atomic write operations and persistence
  • Corruption recovery
  • Metadata handling
  • Concurrent access patterns

Run tests:

uv run python -m pytest tests/test_client_model_registry.py -v

📚 Documentation & Examples

Demo Scripts:

  • examples/demo_client_registry.py - Interactive demonstration of all features
  • examples/populate_demo_registry.py - Populate registry with sample data
  • examples/test_concurrent_registries.py - Concurrent access patterns
  • examples/WEBVIEW_README.md - Complete web viewer guide

Project Organization:

  • Moved documentation to docs/ directory
  • Moved configuration to config/ directory
  • Added README files for each directory
  • Updated references in main README

Key Features

📋 Model Tracking

  • Track models by 8-character hash ID
  • Optional human-readable aliases
  • Source tracking (worker-training, local-import, worker-pull, client-upload)
  • Worker synchronization status (local-only vs synced)
  • Timestamps for all operations

🎯 Metadata Support

  • Training metrics (validation loss, accuracy, epochs)
  • Hyperparameters (learning rate, batch size, optimizer)
  • User-defined tags (production, experimental, validated)
  • Free-form notes
  • Model type (centroid, topdown, bottomup)

🔒 Safety & Reliability

  • Atomic writes prevent corruption
  • Automatic backup on corruption detection
  • Schema version tracking for future migrations
  • Graceful degradation when registry is missing
  • No data loss on crashes or interruptions

Testing

All 32 tests passing:

$ uv run python -m pytest tests/test_client_model_registry.py -v
================================ 32 passed in 0.17s ================================

Test coverage includes:

  • ✅ Fresh and existing registry initialization
  • ✅ Corrupted registry recovery
  • ✅ All CRUD operations
  • ✅ Filtering and sorting
  • ✅ Atomic operations and persistence
  • ✅ Metadata preservation
  • ✅ Concurrent access patterns

Demo

Quick demo:

# 1. Populate with demo data
uv run python examples/populate_demo_registry.py

# 2. View in terminal
uv run python examples/demo_client_registry.py

# 3. View in browser
uv run python -m sleap_rtc.client.registry_server
# Open http://localhost:8765

Project Structure

sleap-RTC/
├── sleap_rtc/client/
│   ├── client_model_registry.py    # Core registry (NEW)
│   └── registry_server.py          # Web viewer (NEW)
├── tests/
│   └── test_client_model_registry.py  # 32 tests (NEW)
├── examples/
│   ├── demo_client_registry.py     # Demo script (NEW)
│   ├── populate_demo_registry.py   # Sample data (NEW)
│   ├── test_concurrent_registries.py  # Concurrency tests (NEW)
│   └── WEBVIEW_README.md           # Viewer docs (NEW)
├── docs/                            # Documentation (ORGANIZED)
│   ├── README.md
│   ├── DEVELOPMENT.md
│   └── INFERENCE_CLI_PROPOSAL.md
└── config/                          # Configuration (ORGANIZED)
    ├── README.md
    ├── config.example.toml
    └── sleap-rtc.toml

API Examples

Python API:

from sleap_rtc.client.client_model_registry import ClientModelRegistry

# Initialize registry
registry = ClientModelRegistry()

# Register a model
registry.register({
    "id": "a3f5e8c9",
    "model_type": "centroid",
    "alias": "production-v1",
    "source": "worker-training",
    "local_path": "~/.sleap-rtc/models/centroid_a3f5e8c9/",
    "metrics": {"final_val_loss": 0.0234}
})

# List models
models = registry.list(filters={"model_type": "centroid"})

# Get specific model
model = registry.get("a3f5e8c9")

# Update metadata
registry.update("a3f5e8c9", {"notes": "Best model for mice"})

REST API:

# Get all models
curl http://localhost:8765/api/models

# Get statistics
curl http://localhost:8765/api/stats

# Get single model
curl http://localhost:8765/api/model/a3f5e8c9

Next Steps

This PR implements Step 1 of the add-client-model-registry proposal. Future steps include:

  • Step 2: Alias management system
  • Step 3: Model import command
  • Step 4: Enhanced list and info commands
  • Step 5+: WebRTC transfer protocol and push/pull commands

Breaking Changes

None. This is fully additive and backward compatible.

Checklist

  • ✅ Core registry implementation complete
  • ✅ Web viewer functional
  • ✅ All tests passing (32/32)
  • ✅ Documentation complete
  • ✅ Example scripts provided
  • ✅ Project organization improved
  • ✅ No breaking changes

🤖 Generated with Claude Code

alicup29 and others added 6 commits November 10, 2025 18:05
Add comprehensive model registry system for client-side model tracking,
including web viewer and complete test suite.

Core Features:
- ClientModelRegistry class with JSON persistence at ~/.sleap-rtc/models/manifest.json
- Atomic write operations (temp file + rename) for crash safety
- Corruption recovery with automatic backups
- CRUD operations: register, get, list, update, delete, exists
- Advanced filtering by type, source, location, and alias presence
- Optional metadata support (metrics, hyperparameters, tags, notes)

Web Viewer:
- Lightweight web interface at http://localhost:8765
- Dashboard with statistics (total models, aliases, worker sync status)
- Responsive card-based UI with model details
- Filtering by model type and location
- REST API endpoints for programmatic access
- Zero external dependencies (uses Python http.server)

Testing:
- 32 comprehensive unit tests (100% passing)
- Tests for initialization, CRUD, filtering, atomicity, metadata
- Concurrent access testing and best practices documentation
- Demo scripts for interactive exploration

Documentation:
- Complete API documentation with Google-style docstrings
- Usage examples and demo scripts
- Web viewer guide with API documentation
- Organized docs/ and config/ directories

Project Organization:
- Moved documentation files to docs/
- Moved configuration files to config/
- Added README files for each directory
- Cleaned up root directory structure

This implements Step 1 (Client Registry Infrastructure) of the
add-client-model-registry change proposal.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
This commit implements comprehensive alias management for the client-side
model registry, enabling human-readable model names alongside model IDs.

Key features:
- Alias validation and sanitization with clear error messages
- Collision detection with optional force overwrite
- Flexible identifier resolution (supports both IDs and aliases)
- Auto-suggestion system for generating valid, unique aliases
- Complete test coverage for all alias operations
- Documentation and demo scripts showing practical usage patterns

Changes:
- sleap_rtc/client/client_model_registry.py: Added 8 new alias management methods
- tests/test_client_model_registry.py: Added 100+ tests for alias functionality
- examples/alias_usage_examples.md: Comprehensive usage documentation
- examples/demo_alias_management.py: Interactive demo of alias features
- Updated demo scripts to use consistent temporary paths

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
This commit implements the model import functionality, completing step 3
of the add-client-model-registry feature. Users can now import pre-trained
models into the client registry from local directories.

Key features:
- Model file detection utilities (find checkpoints, detect type, validate)
- Automatic model type detection from training_config.yaml
- Generate stable model IDs from config hash (or random if no config)
- Support for both symlink (default) and copy import modes
- Interactive and non-interactive alias assignment
- Comprehensive validation and error handling
- Rich CLI output with step-by-step progress

New components:
- sleap_rtc/client/model_utils.py: Utility functions for model detection
  - find_checkpoint_files(): Discover .ckpt, .h5, .pth, .pt files
  - detect_model_type(): Auto-detect from training config
  - calculate_model_size(): Sum checkpoint file sizes
  - validate_checkpoint_files(): Verify files are readable
  - generate_model_id_from_config(): Create stable IDs
  - format_size(): Human-readable size formatting

- sleap_rtc/cli.py: Added import-model command
  - Accepts model path as required argument
  - Options: --alias, --model-type, --copy, --registry-path
  - Interactive prompts for missing information
  - Collision detection and confirmation prompts
  - Auto-suggestion for aliases

- tests/test_model_utils.py: 26 unit tests covering all utilities
  - Tests for checkpoint discovery with various formats
  - Model type detection from different config structures
  - Size calculation and formatting
  - Validation and error handling

- examples/demo_model_import.py: Comprehensive demo script
  - Creates mock models for testing
  - Demonstrates programmatic import workflow
  - Uses /tmp/sleap-rtc-alias-demo/ as requested
  - Shows model detection, import, and query operations

Usage examples:
  # Auto-detect model type and create symlink
  sleap-rtc import-model /path/to/model --alias production-v1

  # Specify model type and copy files
  sleap-rtc import-model /path/to/model --model-type centroid --copy

  # Import without alias (prompt interactively)
  sleap-rtc import-model /path/to/model

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
This commit completes step 3 of the client model registry feature,
implementing the model import command with comprehensive config format
support and enhanced web view capabilities.

Major features:
- Model import CLI command with auto-detection and validation
- JSON config support for backward compatibility with older SLEAP
- Interactive path display in web view with copy-to-clipboard
- SLEAP-NN config structure alignment and verification

Components:

1. Model Utilities (sleap_rtc/client/model_utils.py):
   - find_checkpoint_files(): Discovers .ckpt, .h5, .pth, .pt files
   - detect_model_type(): Auto-detects from SLEAP-NN head_configs
   - calculate_model_size(): Sums checkpoint file sizes
   - validate_checkpoint_files(): Verifies readability
   - generate_model_id_from_config(): Creates stable 8-char hex IDs
   - format_size(): Human-readable size formatting
   - Supports both YAML and JSON config formats

2. Import Command (sleap_rtc/cli.py):
   - sleap-rtc import-model <MODEL_PATH> [OPTIONS]
   - Options: --alias, --model-type, --copy, --registry-path
   - Auto-detects model type from config (YAML or JSON)
   - Creates symlinks (default) or copies files
   - Interactive prompts for missing information
   - Validates checkpoints before import
   - Integrates with alias system
   - Collision detection and confirmation prompts

3. Config Format Support:
   - SLEAP-NN format: model_config.head_configs structure
   - Older SLEAP format: simple model_type field
   - Both YAML (.yaml, .yml) and JSON (.json) formats
   - Searches 15+ config file name variants
   - Verified with real SLEAP-NN training configs

4. Web View Enhancements (sleap_rtc/client/registry_server.py):
   - Hover tooltip shows full file paths
   - Click-to-copy clipboard functionality for all paths
   - Visual feedback with copy icon and success notification
   - Displays local path, checkpoint path, and original path
   - CSS animations and hover states for better UX

5. Tests (tests/test_model_utils.py):
   - 36 comprehensive unit tests (all passing)
   - YAML and JSON config detection tests
   - Checkpoint discovery and validation tests
   - Model ID generation and determinism tests
   - Size calculation and formatting tests

6. Demo Script (examples/demo_model_import.py):
   - Creates SLEAP-NN style mock models
   - Demonstrates programmatic import workflow
   - Uses /tmp/sleap-rtc-alias-demo/ directory
   - Shows detection, import, listing, and query operations

Model Import Workflow:
1. Validates source directory and finds checkpoints
2. Auto-detects model type from config (or prompts)
3. Generates stable model ID from config hash
4. Creates symlink or copy to ~/.sleap-rtc/models/{type}_{id}/
5. Registers in client registry with metadata
6. Optionally sets alias with validation

Supported Model Types:
- centroid: Single animal centroid detection
- centered_instance: Top-down (centered instance)
- bottomup: Multi-animal bottom-up
- single_instance: Single instance

Registry Storage:
- Default: ~/.sleap-rtc/models/manifest.json (client-side)
- Models stored: ~/.sleap-rtc/models/{type}_{id}/
- on_worker flag: false (client-side import)

Usage Examples:
  # Auto-detect and create symlink
  sleap-rtc import-model models/centroid_251024_152308 --alias prod-v1

  # Specify type and copy files
  sleap-rtc import-model /path/to/model --model-type centered_instance --copy

  # Custom registry location (testing/demo)
  sleap-rtc import-model models/my_model --registry-path /tmp/test/manifest.json

Web View Usage:
  python -m sleap_rtc.client.registry_server
  # Open http://localhost:8765
  # Hover over paths to see full path
  # Click paths to copy to clipboard

Testing:
- All 36 unit tests passing
- Verified with real SLEAP-NN configs (centroid.yaml, centered_instance.yaml)
- JSON and YAML parsing tested
- Demo script runs successfully

Architecture Alignment:
- Correctly parses SLEAP-NN model_config.head_configs
- Uses exact SLEAP model type names
- Supports PyTorch Lightning .ckpt format
- Compatible with older SLEAP JSON configs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Add model resolution to client-track CLI command, enabling users to
reference models by filesystem path, model ID, or alias.

Features:
- Model resolution utilities (resolve_model_path, resolve_model_paths)
- Support for three identifier types:
  * Filesystem paths (absolute/relative)
  * Model IDs (8-character hex strings)
  * Aliases (user-defined friendly names)
- Integration with client-track CLI command
- Helpful error messages with actionable suggestions
- Custom registry path support via --registry-path option
- Backward compatible (direct paths still work)

Implementation:
- Add resolve_model_path() and resolve_model_paths() to model_utils.py
- Update client-track command to resolve models before packaging
- Add --registry-path option to CLI
- Display clear resolution logs for debugging
- Exit with helpful errors if models cannot be resolved

Testing:
- 14 new unit tests for model resolution (50 total in test_model_utils.py)
- All tests passing (100% success rate)
- Tested with existing demo registry
- Verified resolution by path, ID, and alias
- Verified mixed identifier support
- Verified error handling for nonexistent models

Documentation:
- Added "Model Registry" section to README.md
- Created TESTING_MODEL_REGISTRY.md with testing guide
- Added examples/test_model_registry_integration.py demo script
- Updated CLI help text for --model-paths option

Example usage:
  sleap-rtc client-track -d data.slp -m production-v1 --session-string <session>
  sleap-rtc client-track -d data.slp -m a3b4c5d6 --session-string <session>
  sleap-rtc client-track -d data.slp -m /path/to/model --session-string <session>

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Add CLI commands for managing model aliases and metadata (notes/tags).

Features:
- tag-model command: Set or update aliases for models
  * Resolve models by ID or existing alias
  * Sanitize and validate alias names
  * Collision detection with user prompts
  * Force flag to override without prompting

- update-model command: Manage model metadata
  * Add/update notes field
  * Add/remove tags (multiple tag support)
  * Clear all tags with --clear-tags
  * Resolve models by ID or alias

- Extended registry schema:
  * Added "notes" field (default: empty string)
  * Added "tags" field (default: empty list)
  * Automatically set defaults on model registration

Implementation:
- tag-model CLI command in cli.py (lines 630-731)
- update-model CLI command in cli.py (lines 734-886)
- Extended ClientModelRegistry to support notes and tags
- Updated register() to set metadata defaults

Testing:
- 14 new tests for metadata and alias management
- Tests for notes: default, update, clear
- Tests for tags: default, update, clear
- Tests for alias operations: set, update, collision, force
- All tests passing (100% success rate)

Example usage:
  sleap-rtc tag-model a3b4c5d6 production-v1
  sleap-rtc tag-model old-alias new-alias --force
  sleap-rtc update-model production-v1 --notes "Best model"
  sleap-rtc update-model a3b4c5d6 --add-tag validated --add-tag production

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants