Skip to content

Architecture and Pipeline

github-actions[bot] edited this page Nov 30, 2026 · 2 revisions

Architecture and Pipeline

AutoSegmentor is a modular desktop application: a PyQt5 annotation studio drives an asynchronous background engine wrapping SAM2 (temporal mask propagation) and CoTracker3 (learned keypoint tracking), while a decoupled downstream toolchain (DatasetManager/) converts verified outputs into YOLO-ready training datasets. This page documents v3.0.1.


End-to-End Call Flow

run_main.py
  → autosegmentor/tools/main_app.py :: start_application()
      → (interactive)   ui/SetupDialog.py :: SetupDialog           — user picks video + config
      → (--demo <name>) tools/demo_registry.py :: resolve_demo()   — loads demo/*_session_state.json
    for each video:
      → autosegmentor/pipeline.py :: run_pipeline()
          → core/AutoSegmentorEngine.py :: AutoSegmentorEngine(...)
              builds AppConfig, runs FrameExtractor (video → JPEGs), constructs
              AnnotationManager / MaskProcessor / UserInteractionHandler
          → engine.run()
              → ui/UserInteraction.py :: UserInteractionHandler.start_ui_loop()
                  lazily imports and opens the real PyQt5 UI:
                  → ui/MainWindow.py :: AnnotationWindow  (modal QDialog hosting QMainWindow docks)
                      user places SAM2/pose prompts, presses "Process Batch" (Enter)
                      → BatchProcessorThread (background QThread)
                          → FrameHandler.move_and_copy_frames()    — stage batch frames
                          → MaskProcessor.generate_mask()          — SAM2 mask propagation
                          → AutoSegmentorEngine._track_batch_inline()
                              → models/Tracking/CoTrackerPredictor.py — CoTracker3 tracking
                          → AnnotationManager.save_tracked_batch() — continuous JSON persistence
          → (if pose enabled) file_management/PoseExporter.py :: process_masks()
          → ImageOverlayProcessor / ImageCopier / VideoCreator     — QC overlays, verified copies, .mp4 outputs
      → (user presses Ctrl+E, decoupled from pipeline) ui/ExportDialog.py
          → DatasetManager/YolovDatasetManager/DatasetCreator.py :: YoloProcessor
              — exports YOLO detection + instance segmentation + pose dataset

Key Architectural Boundaries

  1. Lazy UI launch: run_main.py and pipeline.py never import PyQt5 directly. UserInteractionHandler.start_ui_loop() (autosegmentor/ui/UserInteraction.py) lazily imports AnnotationWindow and runs it modally.
  2. Decoupled YOLO export: pipeline.py never imports DatasetManager/. Export only runs when the user triggers Ctrl+E (or clicks Export Dataset), which opens ExportDialog and dynamically loads DatasetManager/YolovDatasetManager/DatasetCreator.py::YoloProcessor.

Master System Architecture

flowchart TD
    subgraph "User / HITL Studio"
        U["User / Annotator"]
        UI["AnnotationWindow (PyQt5 Docks)\nautosegmentor/ui/MainWindow.py"]
        AM["AnnotationManager\nsave/load prompts & keypoints"]
        JP[("User Prompts JSON\npoints_labels_*.json")]
    end

    subgraph "Orchestration"
        DRIVER["run_main.py"]
        MAINAPP["main_app.py :: start_application"]
        SETUP["SetupDialog.py (Launchpad)"]
        REG["demo_registry.py (--demo CLI)"]
        PIPE["pipeline.py :: run_pipeline"]
        ENGINE["AutoSegmentorEngine"]
        UIH["UserInteractionHandler"]
        CFG["default_config.yaml /\ndemo/*_session_state.json"]
        S2CFG["AppConfig"]
    end

    subgraph "FileManagement (ETL)"
        FE["FrameExtractor"]
        MP["MaskProcessor"]
        OVL["ImageOverlayProcessor"]
        CP["ImageCopier"]
        VC["VideoCreator"]
        PTRACK["PoseExporter"]
    end

    subgraph "Model Runtime"
        PVT["PreviewThread\n500ms debounce, single-frame SAM2"]
        BPT["BatchProcessorThread\nper-stage plan + ETA QThread"]
        S2LIB["SAM2 (vendored)\nexternal/segment_anything_2/"]
        CT["CoTrackerPredictor.py"]
        CTLIB["CoTracker3 (git submodule)\nexternal/co-tracker/"]
        GPU{{"PyTorch + CUDA"}}
    end

    subgraph "Downstream Export (User-Triggered)"
        EXPD["ExportDialog.py (Ctrl+E)"]
        YDC["YoloProcessor"]
        YOLO[("YOLO Dataset\ntrain/valid/test + data.yaml")]
    end

    U --> UI
    UI -->|"save/load"| AM --> JP
    DRIVER --> MAINAPP
    MAINAPP -->|interactive| SETUP
    MAINAPP -->|"--demo name"| REG
    SETUP --> CFG
    REG --> CFG
    CFG --> PIPE
    MAINAPP --> PIPE
    PIPE --> ENGINE
    ENGINE --> S2CFG
    ENGINE --> FE
    ENGINE --> UIH
    UIH -->|"opens"| UI
    UI -->|"debounced edit"| PVT
    UI -->|"Process Batch"| BPT
    PVT --> MP
    BPT --> MP
    BPT --> CT
    MP --> S2LIB
    CT --> CTLIB
    MP --> GPU
    CT --> GPU
    JP --> MP
    PIPE -->|"pose enabled"| PTRACK
    PIPE --> OVL --> CP --> VC
    UI -->|"Ctrl+E"| EXPD --> YDC --> YOLO
Loading

1. Repository & Package Layout

Directory Role
autosegmentor/core/ AutoSegmentorEngine.py — central orchestrator subclassing SAM2Model; builds AppConfig, extracts frames, owns MaskProcessor / AnnotationManager / UserInteractionHandler.
autosegmentor/ui/ PyQt5 Midnight Slate studio: MainWindow.py, AnnotationCanvas.py, SidePanel.py (SidePanel, ProcessingStagePanel, LogPanel, ModelRoutingPanel, LiveConfigPanel), NavigationManager.py, SetupDialog.py, ExportDialog.py, AnnotationManager.py, UserInteraction.py, UITheme.py.
autosegmentor/models/ ML wrappers: SAM/SAM2Model.py + AppConfig.py, Tracking/CoTrackerPredictor.py (unified resolve_cotracker_checkpoint()) + LKKeypointTracker.py, model_info.py (platformdirs cache resolver).
autosegmentor/file_management/ FrameExtractor.py, FrameHandler.py, MaskProcessor.py, ImageOverlayProcessor.py, ImageCopier.py, VideoCreator.py, PoseExporter.py, FileManager.py.
autosegmentor/tools/ main_app.py, demo_registry.py, export_yolo_pose.py, visualize_pose_images.py, visualize_pose_video.py.
autosegmentor/pipeline.py Module-level run_pipeline() orchestrating engine → pose export → overlays → verified copy → video assembly per video.
autosegmentor/tests/ Automated unit, integration, and PyQt5 UI test suites (pytest).
DatasetManager/ Downstream YOLO export (YolovDatasetManager/), offline SyntheticEngine/, and DatasetHandler/.
external/ Vendored segment_anything_2 (plain files) and co-tracker (git submodule).
demo/ Bundled demo footage + dynamic *_session_state.json definitions.
docs/ Live Product & Demo Showcase site (https://thippeswammy.github.io/AutoSegmentor/).
wiki/ Source Markdown mirrored automatically to this GitHub Wiki.

2. Async Threading Model

  • PreviewThread: Triggered by a 500 ms debounce timer (_preview_debounce_timer) after scrolling pauses or points change, keeping rapid A/D scrubbing smooth. Queues at most one _preview_pending refresh if edits arrive mid-inference.
  • BatchProcessorThread: Triggered by ▶ Process Batch (Enter). Builds an explicit per-batch plan (copy → sam2 → cotracker → save) reflecting whether the batch is full, SAM-only, pose-only, or a mid-batch forward/backward refinement, and emits per-frame progress and rolling ETA updates to ProcessingStagePanel.

3. Output Specifications & Directory Layout

  • Extracted frames: .jpeg named {prefix}{video_number}_{frame_index:05d}.jpeg (FrameExtractor).
  • Masks: Color-mapped PNGs supporting up to 10 distinguishable classes (MaskProcessor.binary_mask_2_color_mask).
  • Reconstructed videos: .mp4 (mp4v codec via VideoCreator).
workspace/
├── VideoInputs/                         # Drop your custom input videos here
├── inputs/
│   ├── config/
│   │   ├── default_config.yaml          # Persistent defaults
│   │   └── session_state.json           # Last Launchpad session
│   └── UserPrompts/                     # Saved point/keypoint JSONs
├── working_dir/<video>/
│   ├── images/                          # Extracted video frames
│   ├── render/                          # Color-mapped segmentation masks
│   ├── overlap/                         # QC visual mask overlays
│   ├── temp/                            # Active batch staging
│   └── verified/
│       ├── images/                      # Verified frames for export
│       └── mask/                        # Verified masks for export
└── outputs/                             # Reconstructed OrgVideo / MaskVideo / OverlappedVideo .mp4

4. Key Technical Mechanisms

  • Bounding-Box Auto-Refinement: Feeds each batch's SAM2 mask bounding box forward as a prompt to preserve mask stability across long videos.
  • Batch-Aware VRAM Management: Processes configurable batches (default 30, tunable to 8–16) so hour-long videos run on consumer GPUs.
  • Occlusion-Aware Keypoint Visibility: CoTracker3 outputs per-keypoint pred_visibility booleans natively; occluded points stay visible and draggable on canvas with manual override toggles in KeypointProgressPanel.
  • Single-Source Versioning: autosegmentor/_version.py defines __version__, exposed via autosegmentor.__version__ and python run_main.py --version.