Label Studio ML Backend
repository·master·Indexed 22 days ago
https://github.com/humansignal/label-studio-ml-backendAn SDK for wrapping machine learning models into a web server that integrates with Label Studio for automated labeling, pre-annotation, and interactive model training. It supports deployment via Docker or local Python environments and includes examples for BERT-based text classification, Deepgram Text-to-Speech annotation, and Docling Serve integration.
What's inside label-studio-ml-backend
- The YOLO ML backend integrates YOLOv8 models into Label Studio to automate and assist in various computer vision tasks. It supports object detection, segmentation, classification, and video object tracking, allowing users to leverage pre-trained models to generate predictions for large datasets.
What is the Label Studio ML backend?
masterThe Label Studio ML backend is an SDK that allows you to wrap machine learning code into a web server. This server can be connected to a running Label Studio instance to automate labeling tasks through pre-annotations, interactive labeling, or model training.
Note: If you only need to load static pre-annotated data, you should use Label Studio's import pre-annotated data feature instead of running an ML backend.
Use Deepgram for Text to Speech annotation
masterThis ML backend integrates the Deepgram API with Label Studio to perform Text-to-Speech (TTS) tasks. It takes input text from a user in Label Studio, processes it via Deepgram, and returns the generated audio for annotation.
Important: After submitting the text in Label Studio, you must refresh the page to see the generated audio appear.
Map Label Studio labels to YOLO model names
masterBecause ML model labels often differ from the human-readable labels used in Label Studio, you must define a mapping.
Default Mapping: By default, the YOLO ML backend uses the same name (or a lowercased version) as specified in the
valueattribute of your Label Studio tag.- Example:
<Choice value="Jeep"/>maps tojeepin the model.
- Example:
Precise Mapping: For more control, use the
predicted_valuesattribute to map a single Label Studio label to one or more specific labels from the ML model. This is a comma-separated list.
<Choice value="Car" predicted_values="jeep,cab,limousine"/>Tip: To find the exact names used by your YOLO model, check the ML model logs at the
INFOlogging level when the backend starts, or refer toYOLO_CLASSES.mdin the repository.Understand Annotation Types: Range vs. Instant
masterThe backend supports two distinct ways of annotating time series data:
Range Annotations
- Use case: Events with a duration (e.g., "Running from 10s to 30s").
- Creation: Dragging across the time series.
- Technical behavior:
start≠end, andinstantis set tofalse.
Instant Annotations
- Use case: Point events or specific moments (e.g., "Fall detected at 15s").
- Creation: Double-clicking a specific point.
- Technical behavior:
start=end, andinstantis set totrue.
Note: Instant labels often create highly imbalanced datasets. The backend uses a balanced learning approach (class-weighted loss and balanced accuracy monitoring) to handle this.
Understand the TimelineLabelsModel architecture
masterThe
TimelineLabelsModelis the primary interface for the<TimelineLabels>control tag in Label Studio. It extendsControlModeland manages two distinct operational modes for temporal video multi-label classification: Simple mode and Trainable mode.Operational Modes
Simple Mode (
self.trainable == False): Uses pre-trained YOLO classes for prediction without additional training. It relies oncached_yolo_predictto extract probabilities from frames and converts them into timeline labels.Trainable Mode (
self.trainable == True): Uses a custom-trained LSTM neural network to capture temporal dependencies. It extracts features viacached_feature_extraction, loads a trained classifier, and uses the LSTM to predict probabilities across the video sequence.
Key Methods in
timeline_labels.pypredict_regions(video_path): The entry point for prediction requests. It routes the request to eithercreate_timelines_simpleorcreate_timelines_trainablebased on thetrainableattribute.fit(event, data, **kwargs): The entry point for incremental training. It is triggered by Label Studio events likeANNOTATION_CREATEDorANNOTATION_UPDATEDto update the LSTM model with new human-labeled data.
Compare SAM Model Architectures (AdvancedSAM vs ONNXSAM)
masterChoose the model based on your hardware and accuracy requirements:
Advanced Segment Anything Model
Supports mixing different prompt types (rectangles, positive/negative keypoints) and using MobileSAM.
- MobileSAM: Lightweight, runs on laptops/CPU, fast inference (<1s), but lower accuracy.
- Original SAM: High accuracy, supports mixed prompts, but requires good GPUs and takes longer (~2s for embeddings).
ONNX Segment Anything Model
- Pros: Much faster than Advanced SAM.
- Cons: Only supports one smart label per prediction; image size must be defined before generating the model and cannot be easily generalized to different image sizes.
How Project Isolation works in the Time Series Segmenter
masterThe backend provides multi-tenant support by maintaining separate trained models for each Label Studio project. This prevents cross-project interference and ensures data isolation.
Key Mechanisms:
- Model Storage: Each project receives a unique model file named
model_project_{project_id}.pt(e.g.,model_project_47.pt). - Training: The backend identifies the source project ID from annotation webhook events to save the correct model.
- Prediction: The backend detects the project ID from the task context or request metadata to load the corresponding model. If no project information is available, it falls back to a default model (
model_project_0.pt). - Benefits: Sensitive data from Project A cannot influence the model for Project B, and each model optimizes specifically for its own project's labeling configuration.
- Model Storage: Each project receives a unique model file named
Understand the SAM2 Wire Protocol: Prewarm and Predict modes
masterThe SAM2 backend multiplexes two modes through the
/predictendpoint, determined by thecontext.eventvalue in the request parameters.Prewarm Mode
Used to cache frames in a window around a specific frame to reduce latency during navigation.
- Request
context.event:prewarm - Response: Returns status and information about cached and pending frames.
Predict Mode
Used for actual inference based on user prompts (clicks or boxes).
- Request
context.event: (Implicitly triggered by presence ofresultin context) - Response: Returns a standard
PredictionValuecontaining the segmentation results (bitmasks, rectangles, or polygons).
### Prewarm Request Example ```json { "tasks": [{"id": 1, "data": {"video": "..."}}], "params": { "context": { "event": "prewarm", "frame": 42, "window": 20, "direction": "forward" } } }Predict Request Example
{ "tasks": [{"id": 1, "data": {"video": "..."}}], "params": { "context": { "frame": 42, "result": [ {"type": "keypointlabels", "value": {"x": 45.2, "y": 30.1, "positive": true}}, {"type": "keypointlabels", "value": {"x": 60.0, "y": 55.0, "positive": false}} ] } } }- Request
Customize the ML backend with custom models
masterYou can extend the ML backend functionality by adding your own models and custom logic. Place your implementation files inside the directory you pass to the start command (e.g.,./dir_with_your_model).Map keypoints to specific labels using `model_index`
masterTo ensure detected keypoints are correctly identified in the Label Studio interface, use the
model_indexandpredicted_valuesattributes within yourLabeltags.For standard YOLO pose models, the mapping follows this index pattern:
0: Nose1: Left Eye2: Right Eye3: Left Ear4: Right Ear5: Left Shoulder6: Right Shoulder7: Left Elbow8: Right Elbow9: Left Wrist10: Right Wrist11: Left Hip12: Right Hip13: Left Knee14: Right Knee15: Left Ankle16: Right Ankle
<Label value="left_eye" predicted_values="person" model_index="1" /> <Label value="right_eye" predicted_values="person" model_index="2" />How Control Models map YOLO to Label Studio annotations
masterControl models are specialized subclasses of
ControlModelthat translate YOLO model outputs into Label Studio-compatible annotation formats. Each model is responsible for a specificControlTagfound in the Label Studio configuration.Annotation Type Control Model Purpose Bounding Boxes RectangleLabelsModelHandles axis-aligned or oriented (OBB) rectangles for images. Polygons PolygonLabelsModelConverts segmentation masks into polygon coordinates. Classification ChoicesModelMaps classification outputs to Label Studio Choicesformat.Keypoints KeyPointLabelsModelConverts pose estimation outputs into keypoint annotations. Video Tracking VideoRectangleModelUses YOLO tracking to generate bounding boxes across video frames. Timelines TimelineLabelsModelSupports temporal event annotations.