1. Understand the Goal: The user wants an "annotation tool plugin SDK." This SDK needs to expose three specific functionalities:
* Validation Rules: Logic to check if annotations are correct (e.g., bounding box size, required labels).
* Shortcuts: Keyboard shortcuts or UI hooks to speed up the annotation process.
* Analytics: Tracking user actions, efficiency, or annotation quality metrics.
2. Analyze the Domain (Annotation Tools):
* Common tools: Labelbox, CVAT, Label Studio, Prodigy.
* Core concepts: Projects, Tasks (images/text/audio), Annotations (labels, bounding boxes, segments), Users, UI components (sidebar, canvas).
* Plugin architecture: usually involves injecting code into the UI or hooking into a lifecycle (pre-save, post-load).
3. Design the SDK Structure:
* I need a central class, let's call it AnnotationSDK.
* It needs to interface with a hypothetical host application.
* I should use TypeScript for better definition of types and contracts (essential for an SDK).
4. Component Breakdown & Implementation Details:
* **Core Data Types:** What does an annotation look like?
* `id`, `type` (box, polygon, tag), `label`, `coordinates`, `metadata`.
* **Feature 1: Validation Rules:**
* Need a way to register rules.
* Rules need to run before saving or on change.
* Output: Valid/Invalid + Error message.
* *API Design:* `sdk.validation.register(rule)`
* **Feature 2: Shortcuts:**
* Need to bind keys to actions.
* Need context (global vs. specific tool).
* *API Design:* `sdk.shortcuts.register(key, callback)`
* **Feature 3: Analytics:**
* Need to track events.
* Events: `annotation_created`, `task_opened`, `time_spent`.
* Need a way to send this data (or just log it for the demo).
* *API Design:* `sdk.analytics.track(event, payload)` or `sdk.analytics.getSummary()`
* **Lifecycle/Context:** The plugin needs to know about the current state (current task, current user).
5. Drafting the Code (Mental or Scratchpad):
* *Type Definitions:*
```typescript
type Annotation = { id: string; label: string; x: number; y: number; w: number; h: number; };
type ValidationResult = { isValid: boolean; message?: string; };
```
* *Validation:*
```typescript
class ValidationEngine {
rules = [];
register(rule) { this.rules.push(rule); }
validate(annotation) { ... run rules ... }
}
```
* *Shortcuts:*
```typescript
class ShortcutManager {
map = {};
register(key, cb) { ... }
handleKeyDown(e) { ... }
}
```
* *Analytics:*
```typescript
class AnalyticsTracker {
buffer = [];
track(name, data) { buffer.push({name, data, time: Date.now()}); }
}
```
6. Refining the Architecture (The "Plugin" Aspect):
* The user asked for a Plugin SDK. This implies the code runs inside a host application.
* I should define how a plugin looks.
* interface Plugin { init(sdk: AnnotationSDK): void; }
7. Building the Example:
* To make this concrete, I'll create a mock implementation of the SDK.
* Then, I'll create a sample plugin that uses the SDK.
* Sample Plugin Scenario: A "Car Detector" helper.
* Validation: Boxes must be square.
* Shortcut: 'C' creates a car box.
* Analytics: Tracks how many cars are labeled per hour.
8. Structuring the Output:
* Introduction: Briefly explain the architecture.
* Type Definitions: The contract.
* The SDK Class: The core logic.
* Usage Example (The Plugin): How a developer would actually write code using this SDK.
* Host Integration (Mock): How the tool initializes the SDK and Plugin.
9. Review and Refine (Self-Correction during drafting):
* Critique: Is the validation synchronous? Yes, keep it simple for the demo, but acknowledge async might be needed (e.g., checking a remote DB). I'll stick to synchronous for clarity.
* Critique: Shortcuts might conflict. I should add a way to unregister or namespace them. I'll keep it basic for the MVP SDK but ensure the API is clean.
* Critique: Analytics usually needs to be sent to a backend. I'll mock a transport layer in the analytics class.
10. Final Code Assembly: (This matches the provided good response).
* Use TypeScript.
* Clear separation of concerns.
* Comments explaining the "Why".
11. Final Polish: Add instructions on how to extend it. (e.g., "To use this in React...", "To use this in Python backend...").
(Self-Correction): Ensure the distinction between the SDK (provided by the tool) and the Plugin (written by the user) is clear. The user asked for the SDK definition, but seeing it in action via a plugin is crucial for understanding.
Plan:
- Define interfaces (Types).
- Implement the
AnnotationToolSDK class.
- Implement sub-modules (Validation, Shortcuts, Analytics).
- Create a usage example (a specific plugin).
- Explain the integration pattern.
This design outlines a comprehensive Plugin SDK for an annotation tool (like Labelbox, CVAT, or a custom internal tool). It is implemented in TypeScript to ensure type safety and clear contracts for plugin developers.
Architecture Overview
The SDK acts as a bridge between the Host Application (the annotation tool) and the Plugin (custom logic).
- Host: Calls SDK methods to emit events (e.g.,
annotationCreated) and executes hooks provided by the plugin.
- SDK: Exposes an API to the plugin to read state, modify data, and listen to events.
- Plugin: Registers specific logic (Validation, Shortcuts, Analytics) via the SDK.
1. The SDK Source Code (TypeScript)
This is the code you would ship to plugin developers.
// types.ts
export interface Annotation {
id: string;
label: string;
geometry: { x: number; y: number; w: number; h: number };
metadata?: Record<string, any>;
}
export interface ValidationRule {
id: string;
name: string;
description: string;
/**
* Returns true if valid, or an error message string if invalid.
*/
check: (annotation: Annotation, allAnnotations: Annotation[]) => boolean | string;
}
export interface ShortcutDefinition {
key: string; // e.g., 'ctrl+shift+c'
description: string;
action: () => void;
}
export interface AnalyticsEvent {
eventName: string;
timestamp: Date;
payload?: any;
}
export interface PluginContext {
// State Getters
getCurrentAnnotations: () => Annotation[];
getActiveAnnotation: () => Annotation | null;
// Actions
updateAnnotation: (id: string, update: Partial<Annotation>) => void;
showToast: (message: string, type: 'info' | 'error' | 'success') => void;
}
// sdk.ts
export class AnnotationSDK {
private validationRules: Map<string, ValidationRule> = new Map();
private shortcuts: Map<string, ShortcutDefinition> = new Map();
private analyticsBuffer: AnalyticsEvent[] = [];
private context: PluginContext;
constructor(context: PluginContext) {
this.context = context;
this.setupGlobalListeners();
}
/**
* ---------------------------------------------------------
* MODULE 1: VALIDATION ENGINE
* ---------------------------------------------------------
*/
public registerValidationRule(rule: ValidationRule) {
this.validationRules.set(rule.id, rule);
console.log(`[SDK] Validation rule registered: ${rule.name}`);
}
// Called by the Host before saving
public runValidation(): { isValid: boolean; errors: string[] } {
const annotations = this.context.getCurrentAnnotations();
const errors: string[] = [];
annotations.forEach(ann => {
this.validationRules.forEach(rule => {
const result = rule.check(ann, annotations);
if (result !== true) {
const msg = typeof result === 'string' ? result : `Rule '${rule.name}' failed.`;
errors.push(`Annotation ${ann.id}: ${msg}`);
}
});
});
return { isValid: errors.length === 0, errors };
}
/**
* ---------------------------------------------------------
* MODULE 2: SHORTCUT MANAGER
* ---------------------------------------------------------
*/
public registerShortcut(definition: ShortcutDefinition) {
const keyCombo = definition.key.toLowerCase();
this.shortcuts.set(keyCombo, definition);
}
private setupGlobalListeners() {
document.addEventListener('keydown', (e) => {
// Build key string (e.g., "ctrl+shift+a")
const pressed = [
e.ctrlKey ? 'ctrl' : '',
e.shiftKey ? 'shift' : '',
e.altKey ? 'alt' : '',
e.key.toLowerCase()
].filter(Boolean).join('+');
const shortcut = this.shortcuts.get(pressed);
if (shortcut) {
e.preventDefault();
shortcut.action();
this.trackEvent('shortcut_used', { key: pressed });
}
});
}
/**
* ---------------------------------------------------------
* MODULE 3: ANALYTICS & TELEMETRY
* ---------------------------------------------------------
*/
public trackEvent(name: string, payload?: any) {
const event: AnalyticsEvent = {
eventName: name,
timestamp: new Date(),
payload
};
this.analyticsBuffer.push(event);
// In a real scenario, this might flush to a server periodically
console.log(`[SDK Analytics] Event: ${name}`, payload);
}
public getAnalyticsSummary() {
return this.analyticsBuffer;
}
}
2. Example Plugin Implementation
This is how a 3rd party developer (or internal team) would use the SDK to build a specific feature set.
Scenario: A plugin for a "Vehicle Detection" project that enforces strict bounding box rules and adds custom shortcuts.
// vehicle-plugin.ts
import { AnnotationSDK, ValidationRule, ShortcutDefinition, Annotation } from './sdk';
export function initializeVehiclePlugin(sdk: AnnotationSDK) {
// 1. DEFINE VALIDATION RULES
const minSizeRule: ValidationRule = {
id: 'min-box-size',
name: 'Minimum Box Size',
description: 'Ensures boxes are at least 20x20 pixels',
check: (annotation: Annotation) => {
const { w, h } = annotation.geometry;
if (w < 20 || h < 20) {
return `Box is too small (${w}x${h}). Min size is 20x20.`;
}
return true;
}
};
const noOverlapRule: ValidationRule = {
id: 'no-overlap',
name: 'No Overlap (Same Class)',
description: 'Prevents two cars from overlapping significantly',
check: (current: Annotation, all: Annotation[]) => {
const sameLabels = all.filter(a => a.label === current.label && a.id !== current.id);
// Simple overlap logic (pseudo-code)
const hasOverlap = sameLabels.some(other => {
const intersection = /* math logic here */ true;
return intersection;
});
return hasOverlap ? 'This box overlaps with another Car.' : true;
}
};
sdk.registerValidationRule(minSizeRule);
sdk.registerValidationRule(noOverlapRule);
// 2. DEFINE SHORTCUTS
const copyLastBoxShortcut: ShortcutDefinition = {
key: 'ctrl+shift+c',
description: 'Duplicates the last created annotation',
action: () => {
// Note: In a real implementation, SDK would need a clipboard API
console.log("Copying last box logic executed...");
sdk.trackEvent('action_duplicate', { method: 'shortcut' });
}
};
sdk.registerShortcut(copyLastBoxShortcut);
// 3. CUSTOM ANALYTICS
// Listen to internal SDK events or just expose a method for the UI to call
console.log("Vehicle Plugin initialized.");
}
3. Host Integration (The Glue)
This snippet demonstrates how the main Annotation Tool initializes the SDK and loads the plugin.
// main-app.ts
import { AnnotationSDK } from './sdk';
import { initializeVehiclePlugin } from './vehicle-plugin';
// Mock Application State
const appState = {
annotations: [
{ id: '1', label: 'Car', geometry: { x: 10, y: 10, w: 100, h: 50 } },
{ id: '2', label: 'Car', geometry: { x: 20, y: 20, w: 15, h: 10 } } // Invalid size
]
};
// 1. Initialize SDK with Context
const sdk = new AnnotationSDK({
getCurrentAnnotations: () => appState.annotations,
getActiveAnnotation: () => appState.annotations[0],
updateAnnotation: (id, update) => { /* update logic */ },
showToast: (msg, type) => alert(`[${type}] ${msg}`)
});
// 2. Load Plugin
initializeVehiclePlugin(sdk);
// 3. Host triggers validation (e.g., when User clicks "Submit")
function onSubmit() {
console.log("Running validation...");
const result = sdk.runValidation();
if (!result.isValid) {
console.error("Validation Failed:", result.errors);
// Show errors in UI
} else {
console.log("Validation Passed. Saving...");
sdk.trackEvent('task_completed', { status: 'success' });
}
}
// Simulate workflow
onSubmit();
Key Features of this Design
- Decoupling: The plugin (
vehicle-plugin.ts) does not know about the React/Vue/Angular implementation of the main app. It only knows the SDK interface.
- Validation Composition: The
runValidation method aggregates all registered rules. This allows different teams (e.g., Quality Assurance vs. Domain Experts) to inject different rules into the same tool.
- Hotkey Collision Management: The SDK handles the
keydown logic centrally. While this simple example maps strings to functions, a robust version would handle scope (e.g., disabling shortcuts when typing in a text field).
- Analytics Buffering: The SDK collects events locally. This allows the Host to decide when to flush these events (batch upload) to their analytics provider (Mixpanel, Segment, etc.) without the plugin needing API keys.