Label Studio Python SDK

repository·master·Indexed 41 days ago

https://github.com/humansignal/label-studio-sdk

A programmatic interface for the Label Studio API (v2.1.3) that allows developers to manage projects, tasks, and annotations. The SDK supports workflows for active learning, weak supervision, data migration between instances, and Enterprise-specific user and task management. It includes a CLI that mirrors the SDK's resources and methods for interacting with Label Studio from the terminal.

Tokens
142.8K
Snippets
574
Records
619
Agent score
46%

What's inside Label Studio SDK

  1. Manage annotation history with client.annotation_history

    master

    The annotation_history client allows you to manage logs of all actions performed with annotations (e.g., imports, submits, updates, reviews).

    Note: These methods are only available in Label Studio Enterprise.

    Available Methods

    • list(): List history items for a specific annotation.
    • delete(): Delete all history items for a specific annotation, task, or project. Requires administrator roles.
    • retrieve(id=...): Get a single annotation history item by ID with full details.
    • list_for_project(id=...): List all annotation history items for a specific project with pagination.
  2. Deploy or retrieve provider-agnostic custom metric functions

    master

    Label Studio Enterprise supports routing custom metric functions to either AWS Lambda or GCP Cloud Functions based on the CUSTOM_METRIC_PROVIDER server setting. You can use provider-agnostic methods to deploy or retrieve code without specifying the cloud provider explicitly.

    Note: These endpoints are only available in Label Studio Enterprise.

    # Deploy code to the active provider (AWS or GCP)
    client.projects.metrics.custom.deploy_function(id=1, code="code")
    
    # Get code from the active provider (AWS or GCP)
    client.projects.metrics.custom.get_function(id=1)
    
    # Get execution logs from the active provider (AWS or GCP)
    client.projects.metrics.custom.get_function_logs(id=1)
  3. How interface JSX modules should be structured

    master

    An interface is a JSX module where the final expression returns an object containing a default React component and several optional metadata/logic exports.

    Important Constraints:

    • No import statements: Use globals provided by the Label Studio runtime (e.g., React, getField, EditorUI, hooks).
    • The default export must be a React function component.

    Required and Optional Exports

    • default: The React component (receives task, regions, setRegions, and params as props).
    • getResults(regions, relations): Serializes interface state into Label Studio annotation results.
    • parseResults(results): Deserializes Label Studio results back into { regions: [...] }.
    • inputSchema: Declares task data fields used by the interface.
    • outputSchema: Declares fields produced by the interface (used by Prompter-style auto-labeling).
    • paramsSchema: Declares per-project configuration passed into the component as params.
    • regionSchema: (Optional) Metadata for custom region shapes.
    • specVersion: (Optional) Numeric compatibility marker.
    function Screen({ task, regions, setRegions, params }) {
      return <div>{task.data.text}</div>;
    }
    
    function getResults(regions) {
      return regions;
    }
    
    function parseResults(results) {
      return { regions: results };
    }
    
    ({
      default: Screen,
      getResults,
      parseResults,
      inputSchema: {
        type: "object",
        properties: {
          text: { type: "dataField", default: "text" },
        },
      },
      outputSchema: {
        type: "object",
        properties: {
          sentiment: { type: "string", enum: ["Positive", "Negative"] },
        },
      },
      paramsSchema: {
        type: "object",
        properties: {
          mode: { type: "string", default: "review" },
        },
      },
    });
  4. Manage Project Templates with client.project_templates

    master

    The project_templates attribute on the LabelStudio client allows you to manage project templates for an organization.

    Note: These endpoints are only available in Label Studio Enterprise and are not available in the Community Edition.

    Available operations:

    • list(): Retrieve all project templates.
    • create(request, request_options): Create a new template.
    • get(id, request_options): Retrieve a specific template by ID.
    • update(id, ...): Update an existing template's details.
    • delete(id, request_options): Remove a template.
    • create_project_from_template(id, title, ...): Instantiate a new project using an existing template.
    from label_studio_sdk import LabelStudio
    from label_studio_sdk.environment import LabelStudioEnvironment
    
    client = LabelStudio(
        api_key="<value>",
        environment=LabelStudioEnvironment.DEFAULT,
    )
    
    # Example: List templates
    client.project_templates.list()
    
    # Example: Create a template
    client.project_templates.create(
        name="name",
        project_id=1,
    )
    
    # Example: Create a project from a template
    client.project_templates.create_project_from_template(
        id=1,
        title="title",
    )
  5. Manage Azure SPI export storage connections

    master

    The client.export_storage.azure_spi interface allows managing Azure export storage connections using Service Principal (SPI) or workload-identity authentication.

    Note: These features are exclusive to Label Studio Enterprise and are not available in the Community Edition.

    Authentication Modes

    • service_principal (default): Requires tenant_id, client_id, and client_secret.
    • workload_identity: A secretless mode. client_secret must be omitted and tenant_id is not required. An optional client_id can be used to select a user-assigned managed identity.

    Security Note: client_secret is never included in GET responses.

  6. How media URL resolution and downloading works

    master

    Label Studio tools use a specific flow to resolve media URLs to local files via get_local_path. The process follows these logic paths based on the URL shape:

    • Upload Keys (upload/project/file): The downloader first attempts to use the /storage-data/uploaded/?filepath=... proxy. If that fails (common with Nginx + FileSystemStorage), it falls back to /data/upload/project/file.
    • Local Storage (/data/local-files?d=...): The tool attempts to read from the LOCAL_FILES_DOCUMENT_ROOT or downloads from the host.
    • Cloud Storage (s3://, gs://, azure-blob://): These are resolved via the /tasks/{taskId}/presign?fileuri=... endpoint to obtain a downloadable URL.
    • Direct HTTP: Standard http(s):// URLs are downloaded directly.
    • Proxy Endpoints: Handles various LS proxy endpoints like /api/storages/... or /api/projects/.../file-proxy.

    When download_resources=True is used, the files are downloaded and stored in the provided cache_dir.

  7. Manage Azure Service Principal import storage (Enterprise only)

    master

    The client.import_storage.azure_spi namespace provides methods to manage Azure import storage connections using Service Principal or workload-identity authentication.

    Note: These features are only available in Label Studio Enterprise and are not available in the Community Edition.

    Authentication Modes

    • service_principal (default): Requires tenant_id, client_id, and client_secret.
    • workload_identity: A secretless mode. client_secret must be omitted and tenant_id is not required. An optional client_id can be used to select a user-assigned managed identity.

    Security Note: client_secret is never included in GET responses.

  8. Understand Sidecar Files for Interface Management

    master

    When you run sync or pull, the CLI creates a sidecar file next to your source file with the naming convention [filename].ls-interface.json (e.g., Screen.jsx.ls-interface.json).

    These sidecar files are keyed by your Label Studio base URL and store metadata including:

    • interface id
    • interface title
    • workspace id
    • source version
    • last pushed source hash
    • last pushed timestamp

    Why this matters: The presence of a sidecar allows commands like preview, sync, start, and open to automatically locate the saved interface without you having to manually provide the --id flag.

  9. Manage GCS import storage with Service Account Impersonation

    master

    The client.import_storage.gcs_sa namespace provides methods to manage Google Cloud Storage (GCS) import storage connections that use Service Account (SA) Impersonation.

    Note: These features are exclusive to Label Studio Enterprise and are not available in the Community Edition.

    Available operations:

    • list(project=...): Retrieve all GCS import storage connections for a specific project.
    • create(request=...): Create a new GCS import storage connection using SA Impersonation.
    • get(id=...): Retrieve details for a specific storage connection.
    • update(id=..., **kwargs): Update an existing connection's configuration (e.g., bucket, prefix, target_service_account_email).
    • delete(id=...): Remove a storage connection.
    • validate(request=...): Validate a specific connection configuration.
    • sync(id=...): Manually trigger a task synchronization from the storage connection.
  10. Modify project labels in real-time

    master

    The SDK allows you to add new labels to an ongoing project without restarting it. This is demonstrated in adding_new_labels_to_project.ipynb.

    This technique can be applied to:

    • The <Taxonomy> tag for document-level labels.
    • Computer vision applications (bounding boxes, polygons, etc.).
    • Text or audio segments using nested <Taxonomy> tags.
  11. Use the Label Studio Converter to export tasks

    master

    The Label Studio Converter allows you to encode Label Studio annotations into various machine learning formats (JSON, CSV, COCO, etc.). You can use it via the Command Line Interface (CLI) or the Python API.

    Python API Usage

    To use the Python API, instantiate a Converter with your Label Studio configuration XML file, then call the specific conversion method for your desired format.

    CLI Usage

    Use the label-studio-converter command with the appropriate subcommands (e.g., export) and flags to specify input, configuration, output, and format.

    from label_studio_converter import Converter
    
    # Initialize with the project configuration XML
    c = Converter('examples/sentiment_analysis/config.xml')
    
    # Convert completions to JSON
    c.convert_to_json('examples/sentiment_analysis/completions/', 'tmp/output.json')
    
    # Convert completions to CSV
    c.convert_to_csv('examples/sentiment_analysis/completions/', 'output_dir', sep='\t', header=True)
  12. Run the CLI with uv

    master

    You can run the CLI directly using uv without manual installation.

    # from PyPI
    uv run --with label_studio_sdk label-studio-sdk --help
    
    # from github
    uv run --with git+https://github.com/HumanSignal/label-studio-sdk.git label-studio-sdk --help
    
    # from local
    uv run --with-editable . label-studio-sdk --help