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:
- Native Export - Each annotator's work is saved as JSON under
output_annotation_dir, andexport_annotation_formatadds a periodic export in csv, tsv, jsonl, parquet or any other registered format - Export CLI (New in v2.2.0) -
python -m potato.exportconverts annotations to any of 77 registered formats, among them COCO, YOLO, CoNLL-U, Parquet, TEI, Camtrap DP, Psych-DS and W3C Web Annotation. Runpython -m potato.export --list-formatsfor the set your install actually has. From v2.15.0,potato exportruns 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:
{
"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:
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:
{"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.
export_annotation_format: "jsonl"CSV
One row per annotator-instance pair, with instance_id and user_id first and one column per schema.label:
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.
export_annotation_format: "csv"TSV
Tab-separated values:
export_annotation_format: "tsv"Export CLI
New in v2.2.0
The export CLI converts Potato annotations to specialized formats with a single command:
# 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=falseThe 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:
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
| Option | Description |
|---|---|
--config, -c | Path to Potato YAML config file |
--format, -f | Export format ID from the tables below, such as coco, conll_u or tei |
--output, -o | Output directory (default: ./export_output) |
--option | Format-specific option as key=value (repeatable) |
--list-formats | List available formats and exit |
--verbose, -v | Enable 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.
| ID | Writes | See |
|---|---|---|
csv | One row per annotator and item, plus participants.csv, trials.csv and regions.csv when the study uses experiment flow, timed trials or self-paced reading | Experiment flow |
tsv | The same tables, tab-separated | |
jsonl | One JSON object per annotator and item, with the full answer structure | |
parquet | Apache Parquet tables for pandas, DuckDB or Spark | Parquet export |
data_package | The CSV tables plus a Frictionless Data Package v2 datapackage.json with a Table Schema for each file | Online behavioral experiments |
psych_ds | The same tables in the Psych-DS layout, with dataset_description.json and keyword file names under data/ | Online behavioral experiments |
huggingface | The annotations, pushed to the Hugging Face Hub as a dataset | HuggingFace Datasets |
consensus | Vote 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_annotation | One 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.
| ID | Writes | See |
|---|---|---|
conll_2003 | CoNLL-2003 columns (word, POS, chunk, NER) | CoNLL format |
conll_u | CoNLL-U, with NER tags in the MISC column, and HEAD and DEPREL from a directed span_link scheme | CoNLL format |
qdpx | A REFI-QDA project for NVivo, ATLAS.ti, MAXQDA, Quirkos and QDA Miner | QDA mode |
codebook | The codebook as CSV, with code names, hierarchy and use counts | QDA mode |
quotation_report | One CSV row per coded span, with code, text, offsets, source and coder | QDA mode |
reliability | Krippendorff's alpha per question with a bootstrap interval, as CSV and a Markdown table | Content analysis |
adjudication | Adjudicated final labels as CSV, and the decision log as JSONL with notes, sources and error categories | Adjudication |
convokit | ConvoKit info.<field>.jsonl overlays for an existing corpus, or a full corpus | Threaded conversations |
ontology_terms | One 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.
| ID | Writes |
|---|---|
coco | COCO JSON for detection and segmentation |
yolo | YOLO label files for Ultralytics |
pascal_voc | Pascal VOC XML |
cvat | CVAT XML 1.1 for images |
darwin | V7 Darwin JSON v2, one file per item |
labelme | LabelMe JSON, one file per image |
kitti | KITTI 2D detection labels |
kitti_3d | KITTI 3D boxes, and KITTI tracking labels for point-cloud sequences |
mot | MOTChallenge tracking ground truth |
video_points | Points on video frames and point-track keyframes, one row per point, as JSON and CSV (New in v2.15.0, see Video annotation) |
scene_graph | Relations 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) |
davis | DAVIS and YouTube-VOS indexed PNG masks, one per frame |
cityscapes | Cityscapes polygon JSON |
mask_png | Segmentation masks as PNG images (needs Pillow) |
volume_nifti | NIfTI label volumes for volume_annotation, in the source's voxel order, with a label table |
dicom_seg | DICOM Segmentation objects that reference the source series |
dicom_sr | A DICOM SEG plus a Comprehensive 3D SR (TID 1500) with each segment's volume and the annotator as observer |
swc | Skeletons 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_geojson | Whole-slide regions as QuPath GeoJSON in level-0 slide pixels, one file per annotator and slide |
asap_xml | Whole-slide regions as ASAP XML in level-0 slide pixels, one file per annotator and slide |
microscopy | Microscopy 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.
| ID | Writes | See |
|---|---|---|
runtime | Run, trial and interaction tables from runtime phase pages: jsPsych timelines, headphone checks and external tasks | Runtime phases |
jspsych | The same tables for type: jspsych pages only | Runtime phases |
listening_test | Ratings by condition, MOS and MUSHRA means with intervals, ABX results and BS.1534 post-screening | Listening tests |
incentives | Seeded draws and bonuses per participant, and a Prolific bulk-bonus file. Nothing is paid | Incentive payments |
survey_experiments | Prevalence estimates with standard errors for list experiments and randomized-response questions | Sensitive questions |
lextale | LexTALE-style vocabulary scores per participant | Vocabulary test |
ego_network | Ego, alter and edge tables, and one GraphML file per network. Names are left out unless --option export_names=true | Ego networks |
schedule | Follow-up waves, experience-sampling prompts, and Delphi rounds, with windows, compliance, and latency, plus the notification log without contact details | |
affect_trace | affect_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_domain | Free-list salience (Smith's S, Sutrop's CSI), pile-sort and triad similarity matrices, and a cultural consensus analysis | Cultural domain analysis |
Signals, chemistry and spectra
The 2.13 science schemes write the tables below.
| ID | Writes |
|---|---|
interval_label | One CSV or JSONL row per interval or point event marked on a time_series signal |
bids_events | The same labels as BIDS events.tsv files, with onset, duration, trial type, and channel |
chemistry | Chemical structures as CSV with SMILES and InChIKey and as an SD file, plus the atoms selected on molecule displays |
peak_table | One 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.
| ID | Writes | See |
|---|---|---|
eaf | ELAN annotation files | Transcript formats |
textgrid | Praat TextGrids | Transcript formats |
flextext | FieldWorks (FLEx) interlinear XML, one .flextext per annotator | Interlinear gloss |
toolbox | Toolbox and Shoebox standard-format text, one file per annotator | Interlinear gloss |
igt | Interlinear examples as aligned plain text (igt.txt) and gb4e LaTeX (igt.tex) | Interlinear gloss |
segments | Audio and video segments as one JSONL row per segment, plus one RTTM file per annotator | Timeline segments |
Digital humanities and maps
The targets here are IIIF viewers, transcription platforms, TEI editions and GIS software.
| ID | Writes | See |
|---|---|---|
web_annotation | W3C Web Annotation JSON-LD, which IIIF viewers, Annotorious and Hypothesis read | Digital humanities |
iiif_annotations | IIIF annotation pages per canvas, and a copy of the manifest that references them, for Mirador or Universal Viewer | Digital humanities |
page_xml | PAGE XML with the corrected line text or layout written into the project's copies of the source files | Digital humanities |
tei | TEI P5 XML with spans as inline elements, and overlapping spans in <standOff> | Digital humanities |
geojson | geo_annotation answers as RFC 7946 GeoJSON, per item or in one file | Geo annotation |
geo_overlap | Heat maps of the share of participants whose polygons cover each grid cell, as GeoJSON and PNG, with CSVs of the typed names | Perceptual dialectology |
Ecology
Reviewed camera-trap detections and spectrogram boxes go back to the tools ecologists already use.
| ID | Writes | See |
|---|---|---|
megadetector | MegaDetector batch-output JSON (1.4) with the reviewed boxes | Camera traps |
camtrap_dp | A Camtrap DP 1.0 data package (deployments, media, observations, datapackage.json) | Camera traps |
darwin_core | A Darwin Core occurrence table of the identified animals | Camera traps |
raven | Raven selection tables from spectrogram boxes, one per recording and annotator | Bioacoustics |
audacity_labels | Audacity label tracks, in the spectral form when a box has frequencies | Bioacoustics |
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.
| ID | Writes | See |
|---|---|---|
agent_eval | Agent evaluation scores and error distributions | Agent evaluation |
coding_eval | Coding-agent evaluation data for process reward models, DPO, SWE-bench and code review | Coding agent evaluation |
trajectory_correction | Corrected agent trajectories as SFT targets and DPO preference pairs | Trajectory correction |
labeling_engine | Every item's label with its provenance, the quality certificate and the model-call log | Labeling engine |
episode_jsonl | A per-frame JSONL sidecar for robot episodes (phase, progress reward, outcome) | Robot episodes |
annotation_telemetry | Drawing event streams with no coordinates, and per-annotation process features | Drawing telemetry |
keystrokes | Keystroke event streams with no typed characters, and typing-dynamics features | Keystroke 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 Type | COCO | YOLO | Pascal VOC | CoNLL-2003 | CoNLL-U | Mask |
|---|---|---|---|---|---|---|
| Bounding boxes | Yes | Yes | Yes | - | - | - |
| Polygons | Yes | - | - | - | - | Yes |
| Keypoints | Yes | - | - | - | - | - |
| Text spans | - | - | - | Yes | Yes | - |
| Classifications | Partial | - | - | - | - | - |
Programmatic Export
Use the export registry directly in 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:
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):
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:
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:
# sent_id = item_002-s1
# text = the cat sat
1 the _ _ _ _ 2 det _ _
2 cat _ _ _ _ 3 nsubj _ _
3 sat _ _ _ _ 0 root _ _python -m potato.export --config config.yaml --format conll_u --output ./export/IOB2 Format
Inside-Outside-Beginning tagging for entity recognition:
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:
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:
python -m spacy train config.cfg --paths.train ./annotations.spacyHuggingFace Datasets
Potato's own HuggingFace exporter pushes straight to the Hub:
python -m potato.export --config config.yaml --format huggingface \
--output your-org/my-annotations --option token=hf_xxxTo build a local dataset instead, read the jsonl export and join it to the data file for the text:
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:
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:
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:
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:
pre_annotation:
enabled: true
predictions_file: data/predictions.json
allow_modification: trueThe 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.consensuswrites only the answers that at leastagreement_thresholdof the annotators gave, on items with at leastmin_classifiersannotators. Both values come from theconsensus_aggregationblock, or from--optionwith the same names, and default to 0.8 and 2.annotator:<user id>, such asannotator: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:
{
"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:
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:
# 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:
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:
<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:
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:
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.
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".
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.
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:
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:
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:
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:
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:
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:
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
# After exporting to YOLO format
yolo train data=dataset.yaml model=yolov8n.pt epochs=100dataset.yaml:
train: ./images/train
val: ./images/val
nc: 3
names: ['person', 'car', 'dog']