Skip to content

Export Formats

Export Potato annotations to JSON, JSONL, CSV, CoNLL, HuggingFace Datasets, COCO, YOLO, Pascal VOC, and Apache Parquet for downstream ML pipelines.

Potato provides two levels of export:

  1. Native Export - Each annotator's work is saved as JSON under output_annotation_dir, and export_annotation_format adds a periodic export in csv, tsv, jsonl, parquet or any other registered format
  2. Export CLI (New in v2.2.0) - python -m potato.export converts annotations to any of 77 registered formats, among them COCO, YOLO, CoNLL-U, Parquet, TEI, Camtrap DP, Psych-DS and W3C Web Annotation. Run python -m potato.export --list-formats for the set your install actually has. From v2.15.0, potato export runs the same CLI

This page covers both the built-in formats and the export CLI, plus example conversion scripts for common targets.

Basic Export Formats

JSON

Every annotator's work is saved to <output_annotation_dir>/<user>/user_state.json, whatever export_annotation_format says. Trimmed to the annotation payload, the file looks like this:

json
{
  "user_id": "user_1",
  "instance_id_ordering": ["doc_001", "doc_002"],
  "instance_id_to_label_to_value": {
    "doc_001": [[{"schema": "sentiment", "name": "positive"}, "true"]]
  },
  "instance_id_to_span_to_value": {}
}

The export registry has no json format. The retired output_annotation_format: "json" is read as jsonl with a warning, so configure the periodic export as jsonl:

yaml
export_annotation_format: "jsonl"
output_annotation_dir: "output/"

JSON Lines (JSONL)

One record per annotator-instance pair, written to <output_annotation_dir>/exports/jsonl/annotations.jsonl:

jsonl
{"instance_id": "doc_001", "user_id": "user_1", "labels": {"sentiment": {"positive": "true"}}, "spans": {}, "links": {}, "events": {}}
{"instance_id": "doc_002", "user_id": "user_1", "labels": {"sentiment": {"negative": "true"}}, "spans": {}, "links": {}, "events": {}}

links holds the answers of span_link and coreference schemes, and events holds the answers of event_annotation schemes, keyed by scheme name.

yaml
export_annotation_format: "jsonl"

CSV

One row per annotator-instance pair, with instance_id and user_id first and one column per schema.label:

csv
instance_id,user_id,sentiment.negative,sentiment.positive
doc_001,user_1,,true
doc_002,user_1,true,

A span scheme adds a <scheme>._spans column, and a link or event scheme adds a <scheme>._links or <scheme>._events column, each holding JSON.

yaml
export_annotation_format: "csv"

TSV

Tab-separated values:

yaml
export_annotation_format: "tsv"

Export CLI

New in v2.2.0

The export CLI converts Potato annotations to specialized formats with a single command:

bash
# List available export formats
python -m potato.export --list-formats
 
# Export to COCO format
python -m potato.export --config config.yaml --format coco --output ./export/
 
# Export to YOLO format
python -m potato.export --config config.yaml --format yolo --output ./export/
 
# Export with options
python -m potato.export --config config.yaml --format coco --output ./export/ \
    --option split_ratio=0.8 --option include_unlabeled=false

The potato export Command

New in v2.15.0

potato export runs the same export CLI and takes the same flags. The COCO export above can also be written as:

bash
potato export --config config.yaml --format coco --output ./export/

Releases before 2.15.0 reject potato export as an invalid choice. The python -m potato.export form works on every release from 2.2.0, and the examples on the rest of the page use the module form.

CLI Options

OptionDescription
--config, -cPath to Potato YAML config file
--format, -fExport format ID from the tables below, such as coco, conll_u or tei
--output, -oOutput directory (default: ./export_output)
--optionFormat-specific option as key=value (repeatable)
--list-formatsList available formats and exit
--verbose, -vEnable verbose logging

Supported Export Formats

Potato 2.15.0 registers 77 export formats. The tables below group the formats by the kind of project that produces the data, and the ID column holds the value that --format and export_annotation_format take. --list-formats prints the same list with each format's file extensions.

General tables

Any project can use the general tables, whatever its annotation types.

IDWritesSee
csvOne row per annotator and item, plus participants.csv, trials.csv and regions.csv when the study uses experiment flow, timed trials or self-paced readingExperiment flow
tsvThe same tables, tab-separated
jsonlOne JSON object per annotator and item, with the full answer structure
parquetApache Parquet tables for pandas, DuckDB or SparkParquet export
data_packageThe CSV tables plus a Frictionless Data Package v2 datapackage.json with a Table Schema for each fileOnline behavioral experiments
psych_dsThe same tables in the Psych-DS layout, with dataset_description.json and keyword file names under data/Online behavioral experiments
huggingfaceThe annotations, pushed to the Hugging Face Hub as a datasetHuggingFace Datasets
consensusVote counts and fractions per answer with a retired or needs-review flag, clusters of image points, and median consensus boxes, as CSV and JSON. The consensus_aggregation block sets the thresholds
pre_annotationOne study's answers as the next study's pre_annotation.predictions_file, by majority, consensus, or one annotator (New in v2.15.0)Pre-annotations for the next study

Text, qualitative coding and reliability

Span labels and qualitative codes export in the formats below, along with the agreement and adjudication records built on them.

IDWritesSee
conll_2003CoNLL-2003 columns (word, POS, chunk, NER)CoNLL format
conll_uCoNLL-U, with NER tags in the MISC column, and HEAD and DEPREL from a directed span_link schemeCoNLL format
qdpxA REFI-QDA project for NVivo, ATLAS.ti, MAXQDA, Quirkos and QDA MinerQDA mode
codebookThe codebook as CSV, with code names, hierarchy and use countsQDA mode
quotation_reportOne CSV row per coded span, with code, text, offsets, source and coderQDA mode
reliabilityKrippendorff's alpha per question with a bootstrap interval, as CSV and a Markdown tableContent analysis
adjudicationAdjudicated final labels as CSV, and the decision log as JSONL with notes, sources and error categoriesAdjudication
convokitConvoKit info.<field>.jsonl overlays for an existing corpus, or a full corpusThreaded conversations
ontology_termsOne row per ontology term picked through label_source, with its OBO ID, label, IRI, and ontology version

Images, video, 3D and medical volumes

Computer Vision Formats says which geometry survives each of the computer-vision exports below.

IDWrites
cocoCOCO JSON for detection and segmentation
yoloYOLO label files for Ultralytics
pascal_vocPascal VOC XML
cvatCVAT XML 1.1 for images
darwinV7 Darwin JSON v2, one file per item
labelmeLabelMe JSON, one file per image
kittiKITTI 2D detection labels
kitti_3dKITTI 3D boxes, and KITTI tracking labels for point-cloud sequences
motMOTChallenge tracking ground truth
video_pointsPoints on video frames and point-track keyframes, one row per point, as JSON and CSV (New in v2.15.0, see Video annotation)
scene_graphRelations between video tracks as scene-graph JSON and a CSV table, and optionally one JSONL line per frame (New in v2.15.0, see Video annotation)
davisDAVIS and YouTube-VOS indexed PNG masks, one per frame
cityscapesCityscapes polygon JSON
mask_pngSegmentation masks as PNG images (needs Pillow)
volume_niftiNIfTI label volumes for volume_annotation, in the source's voxel order, with a label table
dicom_segDICOM Segmentation objects that reference the source series
dicom_srA DICOM SEG plus a Comprehensive 3D SR (TID 1500) with each segment's volume and the annotator as observer
swcSkeletons traced with the volume_annotation skeleton tool, one SWC file per annotator and item, in the volume's units (New in v2.15.0)
qupath_geojsonWhole-slide regions as QuPath GeoJSON in level-0 slide pixels, one file per annotator and slide
asap_xmlWhole-slide regions as ASAP XML in level-0 slide pixels, one file per annotator and slide
microscopyMicroscopy regions as GeoJSON in pixel coordinates, cell classes as CSV, and class label images as OME-Zarr

Experiments, surveys and social science

Each of these formats reads one kind of question or study design and writes the scores or estimates computed from it.

IDWritesSee
runtimeRun, trial and interaction tables from runtime phase pages: jsPsych timelines, headphone checks and external tasksRuntime phases
jspsychThe same tables for type: jspsych pages onlyRuntime phases
listening_testRatings by condition, MOS and MUSHRA means with intervals, ABX results and BS.1534 post-screeningListening tests
incentivesSeeded draws and bonuses per participant, and a Prolific bulk-bonus file. Nothing is paidIncentive payments
survey_experimentsPrevalence estimates with standard errors for list experiments and randomized-response questionsSensitive questions
lextaleLexTALE-style vocabulary scores per participantVocabulary test
ego_networkEgo, alter and edge tables, and one GraphML file per network. Names are left out unless --option export_names=trueEgo networks
scheduleFollow-up waves, experience-sampling prompts, and Delphi rounds, with windows, compliance, and latency, plus the notification log without contact details
affect_traceaffect_grid answers, one CSV row per placed point, plus the time-stamped trace a continuous grid records during playback (New in v2.15.0)
cultural_domainFree-list salience (Smith's S, Sutrop's CSI), pile-sort and triad similarity matrices, and a cultural consensus analysisCultural domain analysis

Signals, chemistry and spectra

The 2.13 science schemes write the tables below.

IDWrites
interval_labelOne CSV or JSONL row per interval or point event marked on a time_series signal
bids_eventsThe same labels as BIDS events.tsv files, with onset, duration, trial type, and channel
chemistryChemical structures as CSV with SMILES and InChIKey and as an SD file, plus the atoms selected on molecule displays
peak_tableOne row per picked peak, integrated region, and rejected suggestion from peak_picking, as CSV and JSONL

Linguistics and speech

Tiers and interlinear glosses go back out to ELAN, Praat, FLEx and Toolbox, the tools linguists edit them in.

IDWritesSee
eafELAN annotation filesTranscript formats
textgridPraat TextGridsTranscript formats
flextextFieldWorks (FLEx) interlinear XML, one .flextext per annotatorInterlinear gloss
toolboxToolbox and Shoebox standard-format text, one file per annotatorInterlinear gloss
igtInterlinear examples as aligned plain text (igt.txt) and gb4e LaTeX (igt.tex)Interlinear gloss
segmentsAudio and video segments as one JSONL row per segment, plus one RTTM file per annotatorTimeline segments

Digital humanities and maps

The targets here are IIIF viewers, transcription platforms, TEI editions and GIS software.

IDWritesSee
web_annotationW3C Web Annotation JSON-LD, which IIIF viewers, Annotorious and Hypothesis readDigital humanities
iiif_annotationsIIIF annotation pages per canvas, and a copy of the manifest that references them, for Mirador or Universal ViewerDigital humanities
page_xmlPAGE XML with the corrected line text or layout written into the project's copies of the source filesDigital humanities
teiTEI P5 XML with spans as inline elements, and overlapping spans in <standOff>Digital humanities
geojsongeo_annotation answers as RFC 7946 GeoJSON, per item or in one fileGeo annotation
geo_overlapHeat maps of the share of participants whose polygons cover each grid cell, as GeoJSON and PNG, with CSVs of the typed namesPerceptual dialectology

Ecology

Reviewed camera-trap detections and spectrogram boxes go back to the tools ecologists already use.

IDWritesSee
megadetectorMegaDetector batch-output JSON (1.4) with the reviewed boxesCamera traps
camtrap_dpA Camtrap DP 1.0 data package (deployments, media, observations, datapackage.json)Camera traps
darwin_coreA Darwin Core occurrence table of the identified animalsCamera traps
ravenRaven selection tables from spectrogram boxes, one per recording and annotatorBioacoustics
audacity_labelsAudacity label tracks, in the spectral form when a box has frequenciesBioacoustics

Model, agent and process data

Human judgments of models and agents become training or evaluation data in the formats below, and the process records Potato keeps about annotators export here as well.

IDWritesSee
agent_evalAgent evaluation scores and error distributionsAgent evaluation
coding_evalCoding-agent evaluation data for process reward models, DPO, SWE-bench and code reviewCoding agent evaluation
trajectory_correctionCorrected agent trajectories as SFT targets and DPO preference pairsTrajectory correction
labeling_engineEvery item's label with its provenance, the quality certificate and the model-call logLabeling engine
episode_jsonlA per-frame JSONL sidecar for robot episodes (phase, progress reward, outcome)Robot episodes
annotation_telemetryDrawing event streams with no coordinates, and per-annotation process featuresDrawing telemetry
keystrokesKeystroke event streams with no typed characters, and typing-dynamics featuresKeystroke logging

Answers from a viewer_selection scheme, the residues or loci picked in the protein structure and genome viewers, have no exporter of their own. jsonl, csv and tsv write each selection's JSON as the scheme's value.

Format Compatibility Matrix

Annotation TypeCOCOYOLOPascal VOCCoNLL-2003CoNLL-UMask
Bounding boxesYesYesYes---
PolygonsYes----Yes
KeypointsYes-----
Text spans---YesYes-
ClassificationsPartial-----

Programmatic Export

Use the export registry directly in Python:

python
from potato.export.registry import export_registry
from potato.export.cli import build_export_context
 
context = build_export_context("path/to/config.yaml")
result = export_registry.export("coco", context, "./output/")
 
if result.success:
    print(f"Exported {len(result.files_written)} files")

Custom Exporters

Create custom exporters by subclassing BaseExporter:

python
from potato.export.base import BaseExporter, ExportContext, ExportResult
 
class MyExporter(BaseExporter):
    format_name = "my_format"
    description = "My custom export format"
    file_extensions = [".myformat"]
 
    def can_export(self, context: ExportContext) -> tuple:
        has_spans = any(ann.get("spans") for ann in context.annotations)
        if not has_spans:
            return False, "No span annotations found"
        return True, None
 
    def export(self, context: ExportContext, output_path: str,
               options: dict = None) -> ExportResult:
        # Perform the export
        return ExportResult(
            success=True,
            format_name=self.format_name,
            files_written=["output.myformat"],
            stats={"annotations": len(context.annotations)}
        )
 
from potato.export.registry import export_registry
export_registry.register(MyExporter())

NLP Export Formats

CoNLL Format

Standard format for sequence labeling tasks (NER, POS tagging):

text
The     O
quick   B-ADJ
brown   I-ADJ
fox     B-NOUN
jumps   B-VERB

Potato writes this format itself, so no conversion script is needed:

bash
python -m potato.export --config config.yaml --format conll_2003 --output ./export/

The exporter tokenizes each item's text, converts every span's character offsets to BIO tags, and writes annotations.conll with -DOCSTART- markers between documents. Use --option schema_name=entities to pick the span scheme and --option tokenization=whitespace to pick the tokenizer.

The conll_u format writes the 10-column Universal Dependencies layout, with span labels as NER tags in the MISC column and LEMMA, UPOS, XPOS, and FEATS left as _. From Potato 2.14.0, HEAD and DEPREL come from a span_link scheme with a directed link type over the exported spans, with each link drawn from the head span to the dependent span. The first token of each span attaches to the first token of the span's head, a span with no head is 0 and root, and every other token gets _. A link that crosses a sentence boundary is left out with a warning. Pass --option link_schema=<name> to choose the link scheme, or the exporter takes the first directed span_link scheme over the span scheme:

text
# sent_id = item_002-s1
# text = the cat sat
1	the	_	_	_	_	2	det	_	_
2	cat	_	_	_	_	3	nsubj	_	_
3	sat	_	_	_	_	0	root	_	_
bash
python -m potato.export --config config.yaml --format conll_u --output ./export/

IOB2 Format

Inside-Outside-Beginning tagging for entity recognition:

text
John    B-PER
Smith   I-PER
works   O
at      O
Google  B-ORG

spaCy Format

There is no spaCy exporter, so this one needs a script. It reads the jsonl export for the spans and the data file for the text, since the export carries offsets rather than the item text:

python
import json
 
import spacy
from spacy.tokens import DocBin
 
def convert_to_spacy(annotations_file, data_file, output_file, scheme_name="entities"):
    """Convert a Potato jsonl export to a spaCy DocBin for NER training."""
    with open(data_file) as f:
        texts = {item["id"]: item["text"] for item in json.load(f)}
 
    nlp = spacy.blank("en")
    doc_bin = DocBin()
 
    with open(annotations_file) as f:
        for line in f:
            record = json.loads(line)
            text = texts.get(record["instance_id"])
            if text is None:
                continue
 
            doc = nlp.make_doc(text)
            ents = []
            for span in record["spans"].get(scheme_name, []):
                # start and end are character offsets into the item text,
                # and the label name is under "name".
                char_span = doc.char_span(
                    span["start"], span["end"], label=span["name"]
                )
                if char_span is not None:
                    ents.append(char_span)
            doc.ents = ents
            doc_bin.add(doc)
 
    doc_bin.to_disk(output_file)
 
# Usage
convert_to_spacy(
    "annotation_output/exports/jsonl/annotations.jsonl",
    "data/items.json", "train.spacy", "entities"
)

The export holds one record per annotator and instance, so filter on user_id when several annotators labeled the same item.

The output can be directly used with spacy train:

bash
python -m spacy train config.cfg --paths.train ./annotations.spacy

HuggingFace Datasets

Potato's own HuggingFace exporter pushes straight to the Hub:

bash
python -m potato.export --config config.yaml --format huggingface \
    --output your-org/my-annotations --option token=hf_xxx

To build a local dataset instead, read the jsonl export and join it to the data file for the text:

python
import json
from datasets import Dataset
 
def convert_to_huggingface(annotations_file, data_file, output_dir, scheme_names):
    """Convert a Potato jsonl export to a HuggingFace Dataset."""
    with open(data_file) as f:
        texts = {item["id"]: item["text"] for item in json.load(f)}
 
    records = []
    with open(annotations_file) as f:
        for line in f:
            r = json.loads(line)
            record = {
                "id": r["instance_id"],
                "user_id": r["user_id"],
                "text": texts.get(r["instance_id"], ""),
            }
            for scheme in scheme_names:
                # A single-choice scheme stores {label_name: "true"}.
                chosen = [name for name, value in r["labels"].get(scheme, {}).items()
                          if value == "true"]
                record[scheme] = chosen[0] if chosen else None
            records.append(record)
 
    dataset = Dataset.from_list(records)
    dataset.save_to_disk(output_dir)
    print(f"Saved {len(records)} examples to {output_dir}")
 
# Usage
convert_to_huggingface(
    "annotation_output/exports/jsonl/annotations.jsonl",
    "data/items.json", "hf_dataset/", ["sentiment"]
)

Load in your training script:

python
from datasets import load_from_disk
 
dataset = load_from_disk("hf_dataset/")

Timeline Segments

New in v2.14.0

The segments format exports the segments of audio_annotation and video_annotation schemes, which the CSV, TSV, and JSONL exports carry only as one JSON string per scheme:

bash
python -m potato.export --config config.yaml --format segments --output ./export/

segments.jsonl has one row per segment, with instance_id, user_id, schema, start, end, duration in seconds, label, and media when the item names the recording. rttm/<user_id>.rttm holds the same segments as NIST RTTM, the input that pyannote.metrics, dscore, and md-eval score diarization against. Each annotator gets a separate RTTM file, because one RTTM file is one reference. With more than one audio or video scheme, each scheme's files go under rttm/<schema>/. The RTTM file id is the recording's name without the extension, the item id when the item names no recording, or <name>__<item id> when two items' recordings share a name. Spaces in a label become _, because RTTM separates fields with spaces. A zero-length segment stays in segments.jsonl and is left out of the RTTM files. A diarization imported with potato import -f rttm therefore goes back to the scoring tools after correction (Importing a Project).

Pre-annotations for the Next Study

New in v2.15.0

In a two-stage study, a second group of annotators reviews and corrects the first group's answers. The pre_annotation format writes the first study's answers as the second study's pre_annotation.predictions_file, and each item in the second study then opens with the first study's answer filled in:

bash
python -m potato.export --config stage1/config.yaml --format pre_annotation \
    --output stage2/data/

The export writes predictions.json, keyed by item id and then by scheme name, and a README.txt with the second study's config block and a count of the answers left out. Add the block to the second study's config, with the path relative to the second study's task_dir:

yaml
pre_annotation:
  enabled: true
  predictions_file: data/predictions.json
  allow_modification: true

The schemes in the second study need the same names and labels as the schemes in the first study. --option source= chooses whose answer goes into the file:

  • majority (the default) writes the answer most annotators gave. A slider or number scheme gets the median, a multiselect gets the options more than half of the annotators ticked, and a span scheme gets the spans more than half of the annotators marked.
  • consensus writes only the answers that at least agreement_threshold of the annotators gave, on items with at least min_classifiers annotators. Both values come from the consensus_aggregation block, or from --option with the same names, and default to 0.8 and 2.
  • annotator:<user id>, such as annotator:alice, copies one annotator's answers.

A tied answer is left out by default (ties=skip), and --option ties=first takes the first tied answer in the scheme's label order. --option schemas=sentiment,entities limits the export to the named schemes. The format writes radio, likert, multiselect, slider, number, one-box text, and span answers, and leaves other scheme types out with a warning. Where the annotators who marked a span agree on the span's attributes, such as a claim's stance, the span keeps the attribute values. The labeling engine's static source reads the same predictions.json file.

Computer Vision Export Formats

COCO Format

Standard format for object detection and segmentation:

json
{
  "images": [
    {"id": 1, "file_name": "image_001.jpg", "width": 640, "height": 480}
  ],
  "annotations": [
    {
      "id": 1,
      "image_id": 1,
      "category_id": 1,
      "bbox": [100, 150, 200, 300],
      "area": 60000,
      "segmentation": [[100, 150, 300, 150, 300, 450, 100, 450]]
    }
  ],
  "categories": [
    {"id": 1, "name": "person"}
  ]
}

Use the exporter rather than a script of your own:

bash
python -m potato.export --config config.yaml --format coco --output ./export/

The browser stores each shape's coordinates normalized to the image, under a coordinates key, so a script that reads the stored numbers as pixels puts every box at the wrong scale. The exporter multiplies them by the image size, converts polygons, ellipses and brush masks into COCO segmentation, and sets iscrowd. It takes the pixel size from image_width and image_height on the item, from a mask's own RLE size, or from the image file, and warns when it cannot determine one.

YOLO Format

One text file per image for YOLO training:

text
# class_id center_x center_y width height (normalized 0-1)
0 0.5 0.5 0.3 0.4
1 0.2 0.3 0.1 0.2

Potato writes these files for you:

bash
python -m potato.export --config config.yaml --format yolo --output ./export/

It writes one labels/<image>.txt per image with class_id cx cy w h, a classes.txt listing the class names in id order, and a data.yaml for Ultralytics. YOLO needs the pixel size of every image, so the export is refused outright when a dimension is missing rather than writing coordinates against a zero-sized frame.

Pascal VOC Format

XML format used by many detection frameworks:

xml
<annotation>
  <filename>image_001.jpg</filename>
  <size>
    <width>640</width>
    <height>480</height>
  </size>
  <object>
    <name>person</name>
    <bndbox>
      <xmin>100</xmin>
      <ymin>150</ymin>
      <xmax>300</xmax>
      <ymax>450</ymax>
    </bndbox>
  </object>
</annotation>

The pascal_voc format writes one XML file per image:

bash
python -m potato.export --config config.yaml --format pascal_voc --output ./export/

Coordinates come out as absolute xmin, ymin, xmax, ymax pixels, converted from the normalized values the browser stores.

Labeling Engine Export

New in v2.11.0

The labeling_engine format writes the labeling engine's final labels for every item, machine and human, with the provenance of each label, plus the quality certificate, a dataset card and the model-call log. It refuses to run unless labeling_engine.enabled is true in the config:

bash
python -m potato.export --config config.yaml --format labeling_engine --output ./export/

potato label export writes the same files. Files written by export lists the columns. When the engine is on, the csv, parquet and huggingface exports of people's annotations also gain engine_purpose and engine_request columns, which say which engine request each annotation answered. Filter on engine_purpose to separate the blind random sample from answers people gave after seeing a machine label.

Custom Export Scripts

Basic Export Script

The jsonl export already combines every annotator into one file, so a script starts by loading it. Each line is one record for one annotator and one instance.

python
import json
 
def load_annotations(annotations_file):
    """Load a Potato jsonl export into a list of records."""
    with open(annotations_file) as f:
        return [json.loads(line) for line in f]
 
# Usage
records = load_annotations("annotation_output/exports/jsonl/annotations.jsonl")

Aggregating Multiple Annotators

Majority vote over the records loaded above. A single-choice scheme stores its answer as {label_name: "true"}, so the chosen label is the key whose value is "true".

python
from collections import Counter
 
def chosen_label(record, scheme_name):
    """The label an annotator selected for a single-choice scheme, or None."""
    for name, value in record["labels"].get(scheme_name, {}).items():
        if value == "true":
            return name
    return None
 
def aggregate_labels(records, scheme_name):
    """Majority vote aggregation for classification tasks."""
    item_labels = {}
    for record in records:
        label = chosen_label(record, scheme_name)
        if label is not None:
            item_labels.setdefault(record["instance_id"], []).append(label)
 
    return {item_id: Counter(labels).most_common(1)[0][0]
            for item_id, labels in item_labels.items()}

Computing Inter-Annotator Agreement

Group the same records by user_id, then score the items both annotators labeled.

python
from sklearn.metrics import cohen_kappa_score
 
def compute_agreement(records, scheme_name, user_a, user_b):
    """Compute Cohen's Kappa between two annotators on their shared items."""
    by_user = {}
    for record in records:
        label = chosen_label(record, scheme_name)
        if label is not None:
            by_user.setdefault(record["user_id"], {})[record["instance_id"]] = label
 
    a, b = by_user.get(user_a, {}), by_user.get(user_b, {})
    common_ids = sorted(set(a) & set(b))
 
    return cohen_kappa_score([a[i] for i in common_ids],
                             [b[i] for i in common_ids])

Best Practices

1. Export Regularly

Set up automated exports for backup and analysis:

Potato already writes the periodic export itself, so a backup job copies what is there rather than producing it:

python
import json
import shutil
import schedule
from datetime import date
 
EXPORT = "annotation_output/exports/jsonl/annotations.jsonl"
 
def daily_backup():
    shutil.copy(EXPORT, f"backups/annotations_{date.today()}.jsonl")
 
schedule.every().day.at("18:00").do(daily_backup)

2. Include Metadata

Preserve context in exports:

python
from datetime import datetime
 
records = load_annotations("annotation_output/exports/jsonl/annotations.jsonl")
 
export_data = {
    "metadata": {
        "task": "Sentiment Analysis",
        "exported_at": datetime.now().isoformat(),
        "total_records": len(records),
        "annotators": sorted({r["user_id"] for r in records}),
    },
    "records": records,
}

3. Validate Exports

Check export integrity:

python
def validate_export(export_file, expected_records):
    """The jsonl export is one record per annotator per instance."""
    records = load_annotations(export_file)
 
    assert len(records) == expected_records, "Missing records"
    assert all("instance_id" in r and "user_id" in r for r in records), "Missing keys"
    print(f"Export validated: {len(records)} records")

4. Version Your Exports

Use timestamps or version numbers:

text
exports/
  annotations_v1_2024-01-15.json
  annotations_v2_2024-01-20.json
  annotations_final_2024-01-25.json

Integration Examples

Training a HuggingFace Model

A record carries instance_id, user_id, labels, spans and links. It does not carry the item text, so the text comes from the data file you gave Potato, joined back on the instance id:

python
import json
from datasets import Dataset
from transformers import AutoTokenizer, AutoModelForSequenceClassification
 
records = load_annotations("annotation_output/exports/jsonl/annotations.jsonl")
labels = aggregate_labels(records, "sentiment")
 
with open("data/items.json") as f:
    text_by_id = {item["id"]: item["text"] for item in json.load(f)}
 
dataset = Dataset.from_list([
    {"text": text_by_id[item_id], "label": label}
    for item_id, label in labels.items()
    if item_id in text_by_id
])
 
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
model = AutoModelForSequenceClassification.from_pretrained(
    "bert-base-uncased", num_labels=3)

Training spaCy NER

record["spans"] is keyed by scheme name. Each span carries start, end and name — the label is under name, not label — and the jsonl exporter adds the text it covers, sliced from the item the span was drawn on:

python
import json
import spacy
from spacy.tokens import DocBin
 
records = load_annotations("annotation_output/exports/jsonl/annotations.jsonl")
 
with open("data/items.json") as f:
    text_by_id = {item["id"]: item["text"] for item in json.load(f)}
 
nlp = spacy.blank("en")
doc_bin = DocBin()
 
for record in records:
    text = text_by_id.get(record["instance_id"])
    if text is None:
        continue
    doc = nlp.make_doc(text)
    ents = []
    for span in record["spans"].get("entities", []):
        ent = doc.char_span(span["start"], span["end"], label=span["name"])
        if ent:
            ents.append(ent)
    doc.ents = ents
    doc_bin.add(doc)
 
doc_bin.to_disk("./train.spacy")

YOLO Training

bash
# After exporting to YOLO format
yolo train data=dataset.yaml model=yolov8n.pt epochs=100

dataset.yaml:

yaml
train: ./images/train
val: ./images/val
nc: 3
names: ['person', 'car', 'dog']