instalabel 0.0.6
InstaLabel Inc.
Keywords: InstaLabel

# InstaLabel Python SDK Documentation

The InstaLabel Python SDK provides a simple and intuitive interface for interacting with the InstaLabel platform. With this SDK, you can authenticate your account, manage workspaces and projects, and perform various image operations—including uploading individual images, batch uploads, and even COCO dataset uploads with annotations.

This documentation will walk you through each functionality with clear examples.

---

## Table of Contents

- [Installation](#installation)
- [Authentication](#authentication)
- [Workspace Operations](#workspace-operations)
  - [List All Workspaces](#list-all-workspaces)
  - [Get Workspace by ID](#get-workspace-by-id)
  - [Create a New Workspace](#create-a-new-workspace)
  - [Check Workspace Credits](#check-workspace-credits)
  - [List AWS Integrations](#list-aws-integrations)
- [Project Operations](#project-operations)
  - [List Projects in a Workspace](#list-projects-in-a-workspace)
  - [Get Project by ID](#get-project-by-id)
  - [Create an Object Detection Project](#create-an-object-detection-project)
- [Image Operations](#image-operations)
  - [List Project Images](#list-project-images)
  - [Upload a Single Image](#upload-a-single-image)
  - [Upload a Batch of Images](#upload-a-batch-of-images)
  - [Upload a COCO Dataset](#upload-a-coco-dataset)
- [Complete Workflow Example](#complete-workflow-example)
- [Troubleshooting](#troubleshooting)
- [License](#license)

---

## Installation

Before you begin, ensure you have Python 3.7+ installed. You can install the InstaLabel SDK using pip:

```bash
pip install instalabel
```

> **Note:** Additional dependencies (if any) will be automatically installed with the SDK.

---

## Authentication

Before accessing any resources, you must authenticate with the InstaLabel platform.

### Example: Authenticate a User

```python
from instalabel import InstaLabel
from typing import Optional

def authenticate_user(username: str, password: str) -> Optional[InstaLabel]:
    """
    Authenticate the user with the InstaLabel platform.

    Returns:
        An authenticated InstaLabel client instance if login is successful; otherwise, None.
    """
    client = InstaLabel()
    if client.login(username, password):
        print("✅ Authentication successful!")
        return client
    print("❌ Authentication failed.")
    return None

# Replace with your actual credentials
USERNAME = "your_email@example.com"
PASSWORD = "your_password"

client = authenticate_user(USERNAME, PASSWORD)
if not client:
    exit("Exiting due to failed authentication.")
```

---

## Workspace Operations

Workspaces are the organizational units in InstaLabel. The SDK allows you to retrieve, create, and inspect workspaces.

### List All Workspaces

Retrieve all workspaces accessible by the authenticated user.

```python
# Assuming 'client' is already authenticated
workspaces = client.get_workspaces()
print(f"Found {len(workspaces)} workspace(s):")
for ws in workspaces:
    print(ws)
```

### Get Workspace by ID

Fetch a specific workspace using its unique ID.

```python
workspace_id = "your-workspace-id"
workspace = client.get_workspace(workspace_id)
if workspace:
    print("Workspace found:", workspace)
else:
    print("Workspace not found.")
```

### Create a New Workspace

Create a new workspace by providing a name and description.

```python
workspace_name = "My New Workspace"
description = "This workspace is created for demonstration purposes."
new_workspace = client.create_workspace(workspace_name=workspace_name, description=description)
if new_workspace:
    print("✅ New workspace created:", new_workspace)
else:
    print("❌ Failed to create workspace.")
```

### Check Workspace Credits

Inspect the available credits in a workspace.

```python
credits = workspace.get_credits()
print("Available credits in workspace:", credits)
```

### List AWS Integrations

List any AWS integrations configured for the workspace. This is particularly useful when you plan to use cloud storage for dataset uploads.

```python
integrations = workspace.get_integrations()
if integrations:
    print(f"Found {len(integrations)} AWS integration(s):")
    for integration in integrations:
        print(f"- Integration ID: {integration.integration_id}")
        print(f"  Bucket: {integration.bucket_name}")
else:
    print("No AWS integrations found.")
```

---

## Project Operations

Projects are created within a workspace to manage your annotation tasks. Use the following examples to manage projects.

### List Projects in a Workspace

Retrieve all projects within a specified workspace.

```python
projects = workspace.get_projects()
print(f"Found {len(projects)} project(s) in workspace '{workspace.name}':")
for project in projects:
    print(project)
```

### Get Project by ID

Fetch a specific project by its unique ID.

```python
project_id = "your-project-id"
project = workspace.get_project(project_id)
if project:
    print("Project found:", project)
else:
    print("Project not found.")
```

### Create an Object Detection Project

Create a new project for object detection tasks. This uses the task enumeration provided by the SDK.

```python
from instalabel.client.models.task_enum import TaskEnum

project_name = "Object Detection Project"
description = "Project for testing object detection capabilities."
detection_project = workspace.create_project(
    project_name=project_name,
    task=TaskEnum.OBJECT_DETECTION,
    project_description=description
)
if detection_project:
    print("✅ Detection project created:", detection_project)
else:
    print("❌ Failed to create project.")
```

---

## Image Operations

Images are at the core of data annotation. The SDK provides functionalities to list images, upload individual images, upload images in bulk, and even import COCO datasets with annotations.

### List Project Images

Retrieve all images along with their annotations within a project.

```python
images = project.get_images()
print(f"Found {len(images)} image(s) in project '{project.name}':")
for image in images:
    print(image)
    annotations = image.get_annotations()
    if annotations:
        total_annotations = len(annotations.rectangles) + len(annotations.polygons)
        print(f"  Annotations count: {total_annotations}")
```

### Upload a Single Image

Upload one image file to a project.

```python
import os

image_path = "path/to/your/image.jpg"
if os.path.exists(image_path):
    image = project.upload_single_image(image_path)
    if image:
        print("✅ Image uploaded successfully:", image)
    else:
        print("❌ Image upload failed.")
else:
    print("❌ Image file does not exist:", image_path)
```

### Upload a Batch of Images

Upload multiple images from a directory. Supported image formats include `.jpg`, `.jpeg`, and `.png`.

```python
import os

image_directory = "path/to/your/image_directory"
if os.path.exists(image_directory):
    image_files = [
        os.path.join(image_directory, f)
        for f in os.listdir(image_directory)
        if f.lower().endswith((".jpg", ".jpeg", ".png"))
    ]
    if image_files:
        project.upload_images(image_files)
        print(f"✅ Batch upload complete: {len(image_files)} images uploaded.")
    else:
        print("❌ No supported image files found in the directory.")
else:
    print("❌ Image directory does not exist:", image_directory)
```

### Upload a COCO Dataset

The SDK supports uploading a COCO format dataset—which includes images and their corresponding annotations—to an existing project. This feature requires that your workspace has AWS integrations properly configured.

#### Example COCO JSON File

Below is an example of a COCO JSON file for a vehicle detection dataset:

```json
{
  "info": {
    "year": "2025",
    "version": "1.0",
    "description": "Example COCO dataset for vehicle detection",
    "contributor": "Example Contributor",
    "url": "https://example.com/vehicle-detection",
    "date_created": "2025-02-09T10:00:00+00:00"
  },
  "licenses": [
    {
      "id": 1,
      "url": "https://opensource.org/licenses/MIT",
      "name": "MIT License"
    }
  ],
  "categories": [
    { "id": 1, "name": "car", "supercategory": "vehicle" },
    { "id": 2, "name": "truck", "supercategory": "vehicle" },
    { "id": 3, "name": "bus", "supercategory": "vehicle" }
  ],
  "images": [
    {
      "id": 101,
      "license": 1,
      "file_name": "s3://examplebucket/vehicle1.jpg",
      "height": 720,
      "width": 1280,
      "date_captured": "2025-02-09T10:00:00+00:00"
    },
    {
      "id": 102,
      "license": 1,
      "file_name": "s3://examplebucket/vehicle2.jpg",
      "height": 720,
      "width": 1280,
      "date_captured": "2025-02-09T10:05:00+00:00"
    }
  ],
  "annotations": [
    {
      "id": 201,
      "image_id": 101,
      "category_id": 1,
      "bbox": [100, 200, 400, 300],
      "area": 120000,
      "segmentation": [[110, 210, 110, 490, 510, 490, 510, 210]],
      "iscrowd": 0
    },
    {
      "id": 202,
      "image_id": 102,
      "category_id": 2,
      "bbox": [50, 100, 600, 350],
      "area": 210000,
      "segmentation": [[55, 105, 55, 445, 645, 445, 645, 105]],
      "iscrowd": 0
    }
  ]
}
```

#### Example: Upload a COCO Dataset

Use the following Python code snippet to upload your COCO dataset to an existing project:

```python
import os
import json

coco_json_path = "path/to/your/annotations.coco.json"
if os.path.exists(coco_json_path):
    with open(coco_json_path, "r") as f:
        coco_data = json.load(f)

    integrations = workspace.get_integrations()
    if integrations:
        # Use the first available AWS integration
        uploaded_images = project.upload_coco_from_s3(
            integration_id=integrations[0].integration_id,
            coco_data=coco_data
        )
        print(f"✅ COCO dataset uploaded: {len(uploaded_images)} images processed.")
        # Optionally, inspect a few of the uploaded images and their annotations
        for img in uploaded_images[:3]:
            print(img)
            annotations = img.get_annotations()
            if annotations:
                total_annotations = len(annotations.rectangles) + len(annotations.polygons)
                print(f"  Annotation count: {total_annotations}")
    else:
        print("❌ No AWS integrations configured for the workspace.")
else:
    print("❌ COCO JSON file does not exist:", coco_json_path)
```

---

## Complete Workflow Example

The following example demonstrates a complete workflow—from authentication, selecting a workspace, creating a project, and uploading images and a COCO dataset.

```python
import os
import json
from instalabel import InstaLabel
from instalabel.client.models.task_enum import TaskEnum

# Step 1: Authenticate
def authenticate_user(username: str, password: str):
    client = InstaLabel()
    if client.login(username, password):
        print("✅ Authentication successful!")
        return client
    print("❌ Authentication failed.")
    return None

USERNAME = "your_email@example.com"
PASSWORD = "your_password"
client = authenticate_user(USERNAME, PASSWORD)
if not client:
    exit("Exiting due to failed authentication.")

# Step 2: Workspace Operations
workspaces = client.get_workspaces()
if workspaces:
    workspace = workspaces[0]
    print("Using workspace:", workspace)
else:
    exit("No workspaces available.")

credits = workspace.get_credits()
print("Workspace credits:", credits)

integrations = workspace.get_integrations()
if integrations:
    print("AWS Integrations:")
    for integration in integrations:
        print(" -", integration.integration_id, integration.bucket_name)
else:
    print("No AWS integrations found.")

# Step 3: Project Operations
project = workspace.create_project(
    project_name="My Object Detection Project",
    task=TaskEnum.OBJECT_DETECTION,
    project_description="Project for testing object detection"
)
if project:
    print("✅ Project created:", project)
else:
    exit("Failed to create project.")

# Step 4: Image Operations
# Upload a single image
single_image_path = "path/to/your/single_image.jpg"
if os.path.exists(single_image_path):
    image = project.upload_single_image(single_image_path)
    if image:
        print("✅ Single image uploaded:", image)
else:
    print("Single image file not found.")

# Batch upload images
image_directory = "path/to/your/image_directory"
if os.path.exists(image_directory):
    image_files = [
        os.path.join(image_directory, f)
        for f in os.listdir(image_directory)
        if f.lower().endswith((".jpg", ".jpeg", ".png"))
    ]
    if image_files:
        project.upload_images(image_files)
        print(f"✅ Batch upload complete: {len(image_files)} images uploaded.")
else:
    print("Image directory not found.")

# Upload a COCO dataset
coco_json_path = "path/to/your/annotations.coco.json"
if os.path.exists(coco_json_path):
    with open(coco_json_path, "r") as f:
        coco_data = json.load(f)
    if integrations:
        uploaded_images = project.upload_coco_from_s3(
            integration_id=integrations[0].integration_id,
            coco_data=coco_data
        )
        print(f"✅ COCO dataset uploaded: {len(uploaded_images)} images processed.")
    else:
        print("No AWS integrations configured; cannot upload COCO dataset.")
else:
    print("COCO JSON file not found.")
```

---

## Troubleshooting

- **Authentication Issues:**

  - Verify that your username and password are correct.
  - Ensure you have a stable network connection.

- **Workspace/Project Not Found:**

  - Double-check the workspace or project IDs.
  - Confirm that your account has the necessary permissions.

- **File Not Found Errors:**

  - Verify that the paths provided for images, directories, and the COCO JSON file are correct.

- **AWS Integration Issues:**
  - Ensure that your workspace has AWS integrations properly configured before attempting COCO dataset uploads.

---

## License

This project is licensed under the [MIT License](LICENSE).

---