Import conversational text annotations

How to import annotations on conversational text in a project

Open In Colab

Open this Colab for an interactive tutorial about how to import annotations on conversational text.

Supported annotations

To import annotations in Labelbox, you need to create an annotations payload. In this section, we provide this payload for every supported annotation type.

Labelbox support two formats for the annotations payload:

  • Python annotation types (recommended)
  • NDJSON

Both are described below.

Entity: Message-based

ner_annotation = { 
    "name": "ner",
    "location": { 
      "start": 0, 
      "end": 8 
    },
    "messageId": "4" // this should match the message 
}

Classification: Radio (Single-choice)

radio_annotation = ClassificationAnnotation(
  name="radio_question", 
  value=Radio(answer = ClassificationAnswer(name = "second_radio_answer")),
)
radio_annotation_ndjson = {
  'name': 'radio_question',
  'answer': {'name': 'second_radio_answer'}
}
radio_annotation = {
    'name': 'radio',
    'answer': {
        'name': 'first_radio_answer'
    },
    'messageId': '0' // only applicable when the radio classification is configured as message based.
}

Classification: Checklist (Multi-choice)

checklist_annotation = ClassificationAnnotation(
  name="checklist_question", # must match your ontology feature's name
  value=Checklist(answer = [ClassificationAnswer(name = "first_checklist_answer"), ClassificationAnswer(name = "second_checklist_answer")])
 )
checklist_annotation_ndjson = {
  'name': 'checklist_question',
  'answer': [
    {'name': 'first_checklist_answer'},
    {'name': 'second_checklist_answer'}
  ]
}
checklist_annotation = {
    'name': 'checklist',
    'answers': [
        {'name': 'first_checklist_answer'},
        {'name': 'second_checklist_answer'},
    ],
    'messageId': '2' // only applicable when the checklist classification is configured as message based.
}

Classification - Free-form text

text_annotation = ClassificationAnnotation(
  name="free_text",  # must match your ontology feature's name
  value=Text(answer="sample text")
)
text_annotation_ndjson = {
  'name': 'free_text',
  'answer': 'sample text',
}
radio_annotation = {
    'name': 'free_text',
    'answer': 'here is the free text',
    'messageId': '0' // only applicable when free text classification is configured as message based
}

End-to-end example: Import pre-labels or ground truth

Whether you are importing annotations as pre-labels or as ground truth, the steps are very similar. Steps 5 and 6 (creating and importing the annotation payload) are where the process becomes slightly different and is explained below in detail.

Before you start

You must import these libraries to use the code examples in this section.

import labelbox as lb
import labelbox.types as lb_types
from labelbox.schema.queue_mode import QueueMode
import uuid
import json
import uuid
import numpy as np

Replace with your API key

API_KEY = ""
client = lb.Client(api_key=API_KEY)

Step 1: Import data rows

To attach annotations to a data row, it must first be uploaded to Catalog. Here we create an example data row in Catalog.

# Create one Labelbox dataset

global_key = "conversation-1.json"

asset = {
    "row_data": "https://storage.googleapis.com/labelbox-developer-testing-assets/conversational_text/1000-conversations/conversation-1.json",
    "global_key": global_key
}

dataset = client.create_dataset(name="conversational_annotation_import_demo_dataset")
task = dataset.create_data_rows([asset])
task.wait_till_done()
print("Errors:", task.errors)
print("Failed data rows: ", task.failed_data_rows)

Step 2: Create an ontology

Your project should have the correct ontology set up with all the tools and classifications supported for your annotations. The value for the name parameter should match the name field in your annotations to ensure the correct feature schemas are matched.

Here is an example of creating an ontology programmatically for all the sample annotations above.

ontology_builder = lb.OntologyBuilder(
  tools=[ 
    lb.Tool( # NER tool given the name "ner"
      tool=lb.Tool.Type.NER, 
      name="ner")], 
  classifications=[ 
    lb.Classification( 
      class_type=lb.Classification.Type.TEXT,
      scope=lb.Classification.Scope.INDEX,          
      instructions="text_convo"), 
    lb.Classification( 
      class_type=lb.Classification.Type.CHECKLIST, 
      scope=lb.Classification.Scope.INDEX,                     
      instructions="checklist_convo", 
      options=[
        lb.Option(value="first_checklist_answer"),
        lb.Option(value="second_checklist_answer")            
      ]
    ), 
    lb.Classification( 
      class_type=lb.Classification.Type.RADIO, 
      instructions="radio_convo", 
      scope=lb.Classification.Scope.INDEX,          
      options=[
        lb.Option(value="first_radio_answer"),
        lb.Option(value="second_radio_answer")
      ]
    )
  ]
)

ontology = client.create_ontology("Ontology Conversation Annotations", ontology_builder.asdict(), media_type=lb.MediaType.Conversational)

Step 3: Create a labeling project

Create a project and connect the ontology created above

# Create Labelbox project
project = client.create_project(name="conversational_project", 
                                    media_type=lb.MediaType.Conversational)

# Setup your ontology 
project.setup_editor(ontology) # Connect your ontology and editor to your project

Step 4: Send a batch of data rows to the project

# Setup Batches and Ontology

# Create a batch to send to your MAL project
batch = project.create_batch(
  "first-batch-convo-demo", # Each batch in a project must have a unique name
  global_keys=[global_key], # a list of global keys, data row ids or global keys
  priority=5 # priority between 1(Highest) - 5(lowest)
)

print("Batch: ", batch)

Step 5: Create the annotation payload

Create the annotations payload using the snippets of code shown above.

Labelbox supports two formats for the annotations payload: NDJSON and Python annotation types. Both approaches are described below with instructions to compose annotations into Labels attached to the data rows.

The resulting ndjson_annotation and label from each approach will include every annotation (created above) supported by the respective method.

label_ndjson = []
for annotations in [ner_annotation_ndjson,
                    text_annotation_ndjson,
                    checklist_annotation_ndjson,
                    radio_annotation_ndjson]:
  annotations.update({
      'dataRow': {
          'globalKey': global_key
      }
  })
  label_ndjson.append(annotations)

Step 6: Import the annotation payload

For both options, you can pass either the ndjson_annotation and label payload as the value for the predictions or labels parameter.

Here, we opt to use the payload from the NDJSON approach, since more example annotations are supported.

Option A: Upload to a labeling project as pre-labels (Model-assisted labeling)

# Upload our label using Model-Assisted Labeling
upload_job = lb.MALPredictionImport.create_from_objects(
    client = client, 
    project_id = project.uid, 
    name=f"mal_job-{str(uuid.uuid4())}", 
    predictions=label_ndjson)

upload_job.wait_until_done();
print("Errors:", upload_job.errors)
print("Status of uploads: ", upload_job.statuses)

Option B: Upload to a labeling project as ground truth

# Upload label for this data row in project 
upload_job = lb.LabelImport.create_from_objects(
    client = client, 
    project_id = project.uid, 
    name="label_import_job"+str(uuid.uuid4()),  
    # user label_ndjson if labels were created using python annotation tools
    labels=label_ndjson)

upload_job.wait_until_done();
print("Errors:", upload_job.errors)
print("Status of uploads: ", upload_job.statuses)
Open In Colab

Open this Colab for an interactive tutorial about how to import annotations on document data.