跳转到内容

导出格式

将 Potato 标注导出为 JSON、JSONL、CSV、CoNLL、HuggingFace Datasets、COCO、YOLO、Pascal VOC 和 Apache Parquet,供下游机器学习流程使用。

Potato 提供两个层次的导出:

  1. 原生导出 - 每个标注者的工作以 JSON 形式保存在 output_annotation_dir 下,export_annotation_format 会另外生成 csv、tsv、jsonl、parquet 或任何其他已注册格式的定期导出
  2. 导出 CLI(v2.2.0 新增)- python -m potato.export 将标注转换为 72 种已注册格式中的任意一种,其中包括 COCO、YOLO、CoNLL-U、Parquet、TEI、Camtrap DP、Psych-DS 和 W3C Web Annotation。运行 python -m potato.export --list-formats 可查看你的安装实际具备哪些格式

本页涵盖内置格式和导出 CLI,以及常见目标格式的示例转换脚本。

基本导出格式

JSON

无论 export_annotation_format 设成什么,每个标注者的工作都会保存到 <output_annotation_dir>/<user>/user_state.json。只保留标注数据部分的话,文件是这样的:

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": {}
}

导出注册表中没有 json 格式。已废弃的 output_annotation_format: "json" 会被当作 jsonl 读取并给出警告,所以请把定期导出配置为 jsonl:

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

JSON Lines (JSONL)

每个标注者-实例对一条记录,写入 <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 保存 span_link 和 coreference 方案的答案,events 保存 event_annotation 方案的答案,均以方案名为键。

yaml
export_annotation_format: "jsonl"

CSV

每个标注者-实例对一行,instance_id 和 user_id 排在最前,每个 schema.label 占一列:

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

片段方案会增加一列 <scheme>._spans,链接或事件方案会增加一列 <scheme>._links 或 <scheme>._events,每列都保存 JSON。

yaml
export_annotation_format: "csv"

TSV

制表符分隔值:

yaml
export_annotation_format: "tsv"

导出 CLI

v2.2.0 新增

导出 CLI 用一条命令将 Potato 标注转换为专用格式:

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

CLI 选项

选项描述
--config, -cPotato YAML 配置文件路径
--format, -f下表中的导出格式 ID,例如 coco、conll_u 或 tei
--output, -o输出目录(默认:./export_output)
--option格式特定选项,写成 key=value(可重复)
--list-formats列出可用格式并退出
--verbose, -v启用详细日志

支持的导出格式

Potato 2.14.0 注册了 72 种导出格式。下面的表格按产生数据的项目类型对它们分组,ID 列中是 --format 和 export_annotation_format 接受的取值。--list-formats 会打印同一份列表,并附上每种格式的文件扩展名。

通用表格

任何项目都可以使用通用表格,不论它用的是哪些标注类型。

ID写出内容参见
csv每个标注者和条目一行;如果研究使用了实验流程、计时试次或自定步速阅读,还会写出 participants.csv、trials.csv 和 regions.csv实验流程
tsv同样的表格,以制表符分隔
jsonl每个标注者和条目一个 JSON 对象,带有完整的答案结构
parquet供 pandas、DuckDB 或 Spark 使用的 Apache Parquet 表Parquet 导出
data_packageCSV 表格,加上一个 Frictionless Data Package v2 的 datapackage.json,其中为每个文件附有 Table Schema在线行为实验
psych_ds采用 Psych-DS 布局的同样表格,带有 dataset_description.json,data/ 下的文件按关键词命名在线行为实验
huggingface把标注作为数据集推送到 Hugging Face HubHuggingFace Datasets
consensus每个答案的票数和比例,带有退役或待复核标记,以及图像点的聚类和中位数共识框,格式为 CSV 和 JSON。阈值由 consensus_aggregation 块设置

文本、质性编码与信度

跨度标签和质性编码以下列格式导出,基于它们生成的一致性记录和裁定记录也一样。

ID写出内容参见
conll_2003CoNLL-2003 列(词、词性、组块、NER)CoNLL 格式
conll_uCoNLL-U,NER 标签放在 MISC 列,HEAD 和 DEPREL 来自有向的 span_link 方案CoNLL 格式
qdpx供 NVivo、ATLAS.ti、MAXQDA、Quirkos 和 QDA Miner 使用的 REFI-QDA 项目QDA 模式
codebookCSV 格式的编码本,包含编码名称、层级和使用次数QDA 模式
quotation_report每个已编码跨度一行 CSV,包含编码、文本、偏移量、来源和编码者QDA 模式
reliability每个问题的 Krippendorff alpha 及其 bootstrap 区间,格式为 CSV 和 Markdown 表格内容分析
adjudication裁定后的最终标签(CSV),以及决策日志(JSONL),带有备注、来源和错误类别裁定
convokit针对现有语料库的 ConvoKit info.<field>.jsonl 叠加文件,或一个完整的语料库串联对话
ontology_terms每个通过 label_source 选取的本体术语一行,包含其 OBO ID、标签、IRI 和本体版本

图像、视频、3D 与医学体数据

计算机视觉格式说明了下列每种计算机视觉导出会保留哪些几何信息。

ID写出内容
coco用于检测和分割的 COCO JSON
yolo供 Ultralytics 使用的 YOLO 标签文件
pascal_vocPascal VOC XML
cvat用于图像的 CVAT XML 1.1
darwinV7 Darwin JSON v2,每个条目一个文件
labelmeLabelMe JSON,每张图像一个文件
kittiKITTI 2D 检测标签
kitti_3dKITTI 3D 框,以及用于点云序列的 KITTI 跟踪标签
motMOTChallenge 跟踪真值
davisDAVIS 和 YouTube-VOS 索引 PNG 掩码,每帧一个
cityscapesCityscapes 多边形 JSON
mask_pngPNG 图像形式的分割掩码(需要 Pillow)
volume_nifti用于 volume_annotation 的 NIfTI 标签体,按源数据的体素顺序排列,并附标签表
dicom_seg引用源序列的 DICOM Segmentation 对象
dicom_sr一个 DICOM SEG,加上一个 Comprehensive 3D SR(TID 1500),其中记录每个分割段的体积,并把标注者作为观察者
qupath_geojson以 0 级切片像素表示的全切片区域,格式为 QuPath GeoJSON,每个标注者和切片一个文件
asap_xml以 0 级切片像素表示的全切片区域,格式为 ASAP XML,每个标注者和切片一个文件
microscopy以像素坐标表示的显微区域(GeoJSON)、细胞类别(CSV),以及类别标签图像(OME-Zarr)

实验、调查与社会科学

这些格式各自读取一类问题或研究设计,并写出据此计算的分数或估计值。

ID写出内容参见
runtime来自运行时阶段页面的运行、试次和交互表格:jsPsych 时间线、耳机检测和外部任务运行时阶段
jspsych同样的表格,但只针对 type: jspsych 页面运行时阶段
listening_test按条件的评分、带区间的 MOS 和 MUSHRA 均值、ABX 结果以及 BS.1534 事后筛选听音测试
incentives每位参与者的带种子抽签结果和奖金,以及一个 Prolific 批量奖金文件。不会实际付款激励支付
survey_experiments列表实验和随机化回答问题的流行率估计及其标准误敏感问题
lextale每位参与者的 LexTALE 式词汇得分词汇测试
ego_network自我、他者和边的表格,以及每个网络一个 GraphML 文件。除非设置 --option export_names=true,否则不包含姓名自我中心网络
schedule追踪波次、经验取样提示和德尔菲轮次,包含时间窗、依从性和延迟,另附不含联系方式的通知日志
cultural_domain自由列举显著性(Smith's S、Sutrop's CSI)、堆分类和三元组相似度矩阵,以及文化共识分析文化领域分析

信号、化学与光谱

2.13 的科学类方案写出下列表格。

ID写出内容
interval_label在 time_series 信号上标记的每个区间或点事件一行 CSV 或 JSONL
bids_events同样的标签,写成 BIDS events.tsv 文件,包含起始时间、持续时间、试次类型和通道
chemistry化学结构,以带 SMILES 和 InChIKey 的 CSV 和 SD 文件写出,另附在 molecule 显示上选中的原子
peak_tablepeak_picking 中每个选取的峰、积分区域和被拒绝的建议各一行,格式为 CSV 和 JSONL

语言学与语音

层级和行间注释会导回 ELAN、Praat、FLEx 和 Toolbox,也就是语言学家编辑它们所用的工具。

ID写出内容参见
eafELAN 标注文件转写格式
textgridPraat TextGrid转写格式
flextextFieldWorks(FLEx)行间注释 XML,每个标注者一个 .flextext行间注释
toolboxToolbox 和 Shoebox 标准格式文本,每个标注者一个文件行间注释
igt行间注释例句,写成对齐的纯文本(igt.txt)和 gb4e LaTeX(igt.tex)行间注释
segments音频和视频片段,每个片段一行 JSONL,另为每位标注者写一个 RTTM 文件时间线片段

数字人文与地图

这里的目标是 IIIF 查看器、转写平台、TEI 校勘本和 GIS 软件。

ID写出内容参见
web_annotationW3C Web Annotation JSON-LD,IIIF 查看器、Annotorious 和 Hypothesis 都能读取数字人文
iiif_annotations每个画布的 IIIF 标注页,以及引用它们的清单副本,供 Mirador 或 Universal Viewer 使用数字人文
page_xmlPAGE XML,校正后的行文本或版面写入项目所持有的源文件副本中数字人文
teiTEI P5 XML,跨度作为行内元素,重叠的跨度放在 <standOff> 中数字人文
geojsongeo_annotation 的答案,写成 RFC 7946 GeoJSON,按条目分文件或合为一个文件地理标注
geo_overlap热力图,显示多边形覆盖每个网格单元的参与者比例,格式为 GeoJSON 和 PNG,另附输入名称的 CSV感知方言学

生态学

经过复核的相机陷阱检测结果和声谱图框会回到生态学家已经在用的工具中。

ID写出内容参见
megadetector带有复核后框的 MegaDetector 批量输出 JSON(1.4)相机陷阱
camtrap_dp一个 Camtrap DP 1.0 数据包(部署、媒体、观测、datapackage.json)相机陷阱
darwin_core已识别动物的 Darwin Core 出现记录表相机陷阱
raven由声谱图框生成的 Raven 选区表,每个录音和标注者一个生物声学
audacity_labelsAudacity 标签轨,框带有频率时采用频谱形式生物声学

模型、智能体与过程数据

人对模型和智能体的判断会以下列格式变成训练或评估数据,Potato 记录的关于标注者的过程记录也在这里导出。

ID写出内容参见
agent_eval智能体评估得分和错误分布智能体评估
coding_eval用于过程奖励模型、DPO、SWE-bench 和代码评审的编码智能体评估数据编码智能体评估
trajectory_correction校正后的智能体轨迹,作为 SFT 目标和 DPO 偏好对轨迹校正
labeling_engine每个条目的标签及其来源记录、质量证书和模型调用日志标注引擎
episode_jsonl机器人回合的逐帧 JSONL 附属文件(阶段、进度奖励、结果)机器人回合
annotation_telemetry不含坐标的绘制事件流,以及每个标注的过程特征绘制遥测
keystrokes不含所输入字符的按键事件流,以及打字动态特征按键记录

viewer_selection 方案的答案,也就是在蛋白质结构和基因组查看器中选取的残基或位点,没有自己的导出器。jsonl、csv 和 tsv 会把每个选择的 JSON 写成该方案的值。

格式兼容性矩阵

标注类型COCOYOLOPascal VOCCoNLL-2003CoNLL-UMask
边界框是是是---
多边形是----是
关键点是-----
文本片段---是是-
分类部分-----

编程导出

在 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")

自定义导出器

通过继承 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 导出格式

CoNLL 格式

序列标注任务(NER、词性标注)的标准格式:

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

Potato 自己就能写出这种格式,不需要转换脚本:

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

导出器会对每条数据的文本分词,把每个片段的字符偏移转换成 BIO 标签,写出 annotations.conll,文档之间用 -DOCSTART- 标记分隔。用 --option schema_name=entities 指定片段方案,用 --option tokenization=whitespace 指定分词器。

conll_u 格式写出 10 列的 Universal Dependencies 版式,片段标签作为 NER 标签放在 MISC 列,LEMMA、UPOS、XPOS 和 FEATS 保持为 _。从 Potato 2.14.0 起,HEAD 和 DEPREL 来自在已导出片段上使用有向链接类型的 span_link 方案,每条链接从中心语片段画向依存片段。每个片段的第一个词元连到该片段中心语的第一个词元,没有中心语的片段为 0 和 root,其余每个词元为 _。跨越句子边界的链接会被略去并给出警告。用 --option link_schema=<name> 选择链接方案,否则导出器会取片段方案上第一个有向的 span_link 方案:

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 格式

用于实体识别的 Inside-Outside-Beginning 标注:

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

spaCy 格式

没有 spaCy 导出器,所以这种格式需要写脚本。脚本从 jsonl 导出里读取片段,从数据文件里读取文本,因为导出中带的是偏移量而不是条目文本:

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"
)

导出中每个标注者和每条实例各占一条记录,所以当多个标注者标注了同一条数据时,要按 user_id 过滤。

输出可以直接用于 spacy train:

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

HuggingFace Datasets

Potato 自带的 HuggingFace 导出器可以直接推送到 Hub:

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

如果要改为构建本地数据集,读取 jsonl 导出并与数据文件连接以取得文本:

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"]
)

在训练脚本中加载:

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

时间线片段

v2.14.0 新增

segments 格式导出 audio_annotation 和 video_annotation 方案的片段,而 CSV、TSV 和 JSONL 导出只把这些片段作为每个方案一个 JSON 字符串携带:

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

segments.jsonl 每个片段一行,包含 instance_id、user_id、schema、start、end、以秒为单位的 duration、label,以及条目指明录音时的 media。rttm/<user_id>.rttm 以 NIST RTTM 格式保存同样的片段,这是 pyannote.metrics、dscore 和 md-eval 给说话人分离结果打分时使用的输入。每位标注者各有一个 RTTM 文件,因为一个 RTTM 文件就是一份参考标注。存在多个音频或视频方案时,每个方案的文件放在 rttm/<schema>/ 下。RTTM 的文件 id 是去掉扩展名的录音名;条目没有指明录音时用条目 id;两个条目的录音同名时用 <name>__<item id>。标签中的空格会变成 _,因为 RTTM 用空格分隔字段。零长度的片段保留在 segments.jsonl 中,但不写入 RTTM 文件。因此用 potato import -f rttm 导入的说话人分离结果,修正后可以回到打分工具中(导入项目)。

计算机视觉导出格式

COCO 格式

目标检测和分割的标准格式:

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"}
  ]
}

请使用导出器,而不是自己写脚本:

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

浏览器存储的每个形状坐标都是相对图像归一化的,放在 coordinates 键下,所以把存储的数字当成像素来读的脚本会让每个框都落在错误的比例上。导出器会把它们乘以图像尺寸,把多边形、椭圆和画笔掩码转换成 COCO 分割数据,并设置 iscrowd。像素尺寸取自条目上的 image_width 和 image_height、掩码自身的 RLE 尺寸,或图像文件本身,取不到时会给出警告。

YOLO 格式

每张图片一个文本文件,用于 YOLO 训练:

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 替你写出:

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

它为每张图片写出一个 labels/<image>.txt,内容是 class_id cx cy w h,另外写出按 id 顺序列出类名的 classes.txt,以及给 Ultralytics 用的 data.yaml。YOLO 需要每张图片的像素尺寸,所以缺少某个尺寸时导出会直接拒绝执行,而不是对着零尺寸的画面写坐标。

Pascal VOC 格式

许多检测框架使用的 XML 格式:

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>

pascal_voc 格式为每张图片写出一个 XML 文件:

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

坐标输出为绝对像素值 xmin、ymin、xmax、ymax,由浏览器存储的归一化值换算而来。

标注引擎导出

v2.11.0 新增

labeling_engine 格式会写出标注引擎为每个条目给出的最终标签(机器标签和人工标签都包括),附上每个标签的来源记录,另外还有质量证书、数据集卡片和模型调用日志。除非配置中的 labeling_engine.enabled 为 true,否则它会拒绝运行:

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

potato label export 写出的是同样的文件。导出写出的文件列出了各列。开启引擎时,人工标注的 csv、parquet 和 huggingface 导出还会多出 engine_purpose 和 engine_request 两列,说明每条标注回答的是引擎的哪个请求。按 engine_purpose 筛选,就能把盲态随机样本与人们看过机器标签之后给出的答案分开。

自定义导出脚本

基本导出脚本

jsonl 导出已经把所有标注者合并到一个文件里,所以脚本从加载它开始。每一行是一个标注者对一条实例的一条记录。

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")

聚合多个标注者

对上面加载的记录做多数投票。单选方案把答案存成 {label_name: "true"},所以被选中的标签就是值为 "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()}

计算标注者间一致性

把同一批记录按 user_id 分组,然后对两位标注者都标过的条目算分。

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])

最佳实践

1. 定期导出

设置自动导出,用于备份和分析:

Potato 自己就会周期性地写出导出文件,所以备份任务是把已有的文件复制走,而不是自己生成:

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. 包含元数据

在导出中保留上下文:

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. 验证导出

检查导出完整性:

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. 版本化导出

使用时间戳或版本号:

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

集成示例

训练 HuggingFace 模型

一条记录带的是 instance_id、user_id、labels、spans 和 links。它不带条目正文,所以文本要从你交给 Potato 的数据文件里按 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)

训练 spaCy NER

record["spans"] 按 scheme 名称分组。每个 span 带 start、end 和 name(标签在 name 里,不是 label),jsonl 导出器还会补上它覆盖的 text,是从这个 span 所标注的条目上切出来的:

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 训练

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']