跳转到内容

用于自定义标注类型和显示类型的 Potato 插件

用已安装的 Python 包为 Potato 添加标注类型和显示类型。配置文件负责启用插件,potato validate 负责检查插件的类型。

Potato 插件是一个 Python 包,无需修改 Potato 自身的代码即可添加标注类型或显示类型。每个项目在顶层 plugins 键下写出插件名称即可启用该插件,插件的类型随后可以像内置类型一样用于 annotation_schemes 和 instance_display。插件自 Potato 2.12.0 起成为 Potato 的一部分。Potato 仓库中的 counter 示例是一个完整的插件和项目,本页的演示使用的是该示例在 v2.14.0 版本中的代码。

启用已安装的插件

Potato 通过已安装 Python 包的 potato.plugins 入口点组来查找插件。potato plugins 根据包的元数据列出所有已安装的插件,不会导入任何插件代码:

bash
potato plugins
text
counter              potato-plugin-example 0.1.0  (potato_plugin_example:register)
 
Turn one on with `plugins: [<name>]` in a config. `potato plugins <name>` loads it and lists its types.

每一行依次给出插件的入口点名称、提供该插件的包及其版本,以及 Potato 用来注册插件类型而调用的函数。potato plugins counter 会导入一个插件并打印该插件注册的内容。可以用这条命令检查安装情况:

text
counter: potato-plugin-example 0.1.0
  annotation types: counter
  display types:    word_count
  scripts:          counter.js
  styles:           counter.css

配置文件在 plugins 下以入口点名称列表的形式写出要加载的插件。下面的部分配置展示了与插件有关的各个块:

yaml
plugins:
  - counter
 
instance_display:
  fields:
    - key: text
      type: word_count          # a display type from the plugin
      label: Scene
 
annotation_schemes:
  - annotation_type: counter    # an annotation type from the plugin
    name: people
    description: How many people does the scene mention?
    min: 0
    max: 50

plugins 键接受由非空字符串组成且不含重复名称的列表,Potato 在验证时会拒绝其他任何形式。phases 中 type: jspsych 的页面另有一个单独的 plugins 列表。该 jsPsych 列表指定的是单个页面使用的 jsPsych 插件,与顶层键无关。

插件类型的验证

插件在配置验证开始时加载,早于 Potato 检查任何类型名称。因此服务器、potato validate 和 potato preview 看到的类型集合相同。验证对插件适用以下规则:

  • 已安装。 plugins 下的每个名称都必须对应一个已安装的插件。未知的名称会导致验证失败,并给出列出已安装插件的消息。
  • 已列出。 使用某个插件类型的配置必须列出该插件。Potato 执行这条规则,是因为同一个进程可能为一个配置加载插件,然后去验证另一个配置。设计阶段的 MCP 服务器会在同一个进程中验证多个配置,没有这条规则时,某个配置可能借助另一个配置加载的插件在那里通过验证,却在 potato start 于全新进程中运行该配置时失败。在全新进程中,annotation_schemes 里未列出的插件类型所产生的错误末尾带有提示。当插件名称与类型名称相同时,提示会指出需要添加的插件,否则内容为 If 'x' comes from a plugin, list it under plugins:; installed plugins: a, b, c。未列出的插件显示类型得到的是 Valid types are: ... 错误,不带提示。阶段文件中未列出的插件类型得到的是 'x' is not an annotation type,同样不带提示。
  • 名称唯一。 插件不得重用内置类型的名称,也不得重用其他已加载插件的类型名称。重用已占用名称的插件不会注册它的任何类型。
  • 调查阶段文件。 阶段文件(phases: ... file:)中的问题要接受已列出插件检查和方案键检查,每个问题的类型必须是内置类型或来自已列出的插件。验证不会检查阶段文件中插件的必填字段。因此,已列出插件类型的阶段文件问题即使缺少必填字段也能通过验证。
  • 方案键。 插件类型的方案可以带有该插件声明的键,以及通用的方案键。Potato 会把其他任何键记录为无法识别的配置键,potato validate --strict 会因该键而失败。
  • 必填字段。 在 annotation_schemes 中,插件声明为必填的字段(name 和 description 之外)会在验证时检查,与内置类型的必填字段相同。

Potato 的检查在两处不涵盖插件类型。第一,Potato 对插件显示类型跳过 display_options 名称检查。因此插件字段上拼写错误的显示选项能通过 --strict。第二,依据 Potato 公开的 JSON Schema 检查配置的编辑器(示例配置顶部的 yaml-language-server 行)会把插件类型标记为未知。该 schema 只列出内置类型,而加载插件的检查是 potato validate。

设计阶段的 MCP 服务器(potato mcp serve)为编码智能体提供了 list_plugins 工具。不带参数时,list_plugins 读取包元数据且不导入任何内容,不过同一进程中已被其他配置加载的插件也会显示其类型。给定插件名称时,该工具会加载指定的插件(这会在服务器进程内运行插件的代码)并列出该插件的类型。未安装的名称会返回列出已安装插件的错误。list_annotation_types 和 list_display_types 工具会给出每个类型背后的插件,内置类型则为 null。

插件代码与服务器权限

插件是在 Potato 服务器进程内以服务器权限运行的普通 Python 代码。因此插件代码可以读取服务器能读取的数据、标注和凭据。只从你愿意让其拥有与 Potato 服务器本身相同访问权限的来源安装插件。Potato 用两条规则限制仅靠配置能做的事:

  • 只加载已列出的插件。 在配置没有写出某插件名称的项目中,安装该包不会带来任何变化。
  • 只接受入口点名称。 plugins 接受入口点名称,不接受文件路径或模块名。配置无法让 Potato 指向磁盘上的代码,因此编辑配置无法运行从未安装到环境中的代码。

Potato 只为服务器进程中已加载的插件提供静态文件,并且只来自各插件自己的静态文件夹。在普通服务器中,已加载的插件就是配置所列出的插件。Flask 的 send_from_directory 会拒绝任何离开该文件夹的路径。运行中的服务器从不卸载插件。

编写插件包

插件是一个在 potato.plugins 组中带有入口点的 Python 包。入口点名称就是配置在 plugins 下列出的名称。examples/plugins/counter/plugin 中的示例结构如下:

text
plugin/
├── pyproject.toml
└── potato_plugin_example/
    ├── __init__.py          # register(api)
    └── static/
        ├── counter.js
        └── counter.css

示例的 pyproject.toml 声明入口点,并把 static 文件夹作为包数据安装:

toml
[build-system]
requires = ["setuptools>=64"]
build-backend = "setuptools.build_meta"
 
[project]
name = "potato-plugin-example"
version = "0.1.0"
description = "Example Potato plugin: a counter annotation type and a word-count display"
requires-python = ">=3.9"
 
[project.entry-points."potato.plugins"]
counter = "potato_plugin_example:register"
 
[tool.setuptools]
packages = ["potato_plugin_example"]
 
[tool.setuptools.package-data]
potato_plugin_example = ["static/*"]

入口点可以指向一个函数,也可以指向带有 register 函数的模块。其他任何目标都会加载失败,并给出指明该入口点的错误。没有 package-data 表时,常规安装可能漏掉 static 文件夹,插件会因 static folder not found 错误而注册失败。

register 函数

当配置列出某个插件时,Potato 会导入该入口点,然后用一个 PluginAPI 对象调用 register(api)。该 API 对象有三个方法:

方法该方法注册的内容
add_schema(name, generator, *, required_fields=("name", "description"), optional_fields=(), description="", supports_keybindings=False)一个标注类型,以及构建该方案 HTML 的生成器
add_display(name, display)一个显示类型,是 potato.server_utils.displays.base 中 BaseDisplay 子类的实例
add_assets(static_dir, *, scripts=(), styles=())一个文件夹(相对于定义 register 的模块所在的文件夹),在 /plugin-static/<plugin>/ 提供服务,以及该文件夹中要在每个页面上加载的脚本和样式

在 register 返回之前,Potato 不会注册任何内容。如果 register 抛出异常,或者插件使用的任何名称已被占用,该插件不会注册任何类型,验证会报告错误。中途失败的插件不会留下部分类型。在同一个插件中两次注册同一个名称、传入不可调用的生成器,以及传入不是 BaseDisplay 实例的显示,都会在 register 内部引发错误。

标注类型生成器

生成器以字典形式接收方案的配置,并返回由 HTML 和键盘快捷键列表组成的元组,与 potato/server_utils/schemas/ 中的内置生成器一样。请在 optional_fields 中列出生成器读取的每一个配置键,因为验证会标记该类型方案上的其他任何键。通用的方案键(例如 label_requirement 和 display_logic)无需声明,在插件类型上也被接受。Potato 会自行把生成器的 HTML 包进 display_logic 容器,因此条件显示不需要插件中的任何代码。

标注页面只会保存和恢复来自页面已能处理的输入的答案。每个输入都需要 annotation-input 类、值为方案名称的 schema 属性,以及 label_name 属性。potato.server_utils.schemas.identifier_utils 中的 generate_element_identifier(scheme_name, label_name, element_type) 会构建 id、name、schema 和 label_name 的值。页面会保存带有该类的 checkbox、radio、text、textarea、range、select、number 和 hidden 输入。range 或 hidden 输入只有在某次更改把它标记为已修改后才会被保存。因此,更改 hidden 输入值的插件脚本也要设置该输入的 data-modified 属性。email、date 及其他输入类型不会被保存。

更改输入值的脚本会在该输入上派发 input 和 change 事件,事件触发时页面保存该值。要检查答案是否持久化,请回答一个条目,按下 Next(下一个),再按下 Previous(上一个),确认答案仍然显示。刷新页面不能用来测试保存,因为即使什么都没有保存,浏览器也会在刷新后恢复表单值。

显示类型

显示类型是 BaseDisplay 的子类,以实例的形式注册。该子类实现 render(field_config, data),并返回一个字段的内部 HTML。Potato 会把返回的 HTML 包进标准字段容器,并加上该字段的 label。类属性包括 name、description、required_fields、optional_fields 和 supports_span_target,其中 optional_fields 把每个选项名称映射到该选项的默认值。

脚本和样式

Potato 会相对于定义 register 的模块所在的文件夹解析 add_assets 文件夹,并以工作目录作为后备。像 counter 示例那样把 register 函数放在包的 __init__.py 中,就会以包文件夹为基准。add_assets 中指定的文件在每个标注页面和阶段页面上、annotation.js 之后加载。因此插件脚本可以使用 annotation.js 定义的函数。每个文件在 /plugin-static/<plugin>/<file>?v=<package version> 提供服务。文件更改时请提升包版本。版本是每个文件 URL 的一部分,新版本会让浏览器获取新的副本。只有项目配置所列出的插件,其脚本和样式才会出现在该项目的页面上。插件 CSS 可以使用 potato/static/styles.css 中定义的设计令牌(例如 --border 和 --space-sm)。

counter 示例演示

counter 示例添加了一个标注类型和一个显示类型。在该示例中,counter 类型显示位于减号按钮和加号按钮之间的数字输入,用于统计条目中的事物,例如场景中的人数。word_count 显示先给出一个文本字段,再给出该字段的字数。

克隆 v2.14.0 标签的 Potato 仓库,以可编辑模式安装示例插件,并在仓库根目录启动示例项目:

bash
git clone --branch v2.14.0 https://github.com/davidjurgens/potato.git
cd potato
pip install -e examples/plugins/counter/plugin
potato start examples/plugins/counter/config.yaml -p 8000

打开 http://localhost:8000,登录,然后数一数每个场景中的人数。项目的配置启用了该插件,用 word_count 渲染每个条目的 text 字段,并把一个 counter 方案放在普通的 radio 方案旁边:

yaml
# yaml-language-server: $schema=https://potatoannotator.readthedocs.io/en/latest/schemas/potato-config.schema.json
# Needs the example plugin installed first:
#   pip install -e examples/plugins/counter/plugin
annotation_task_name: Plugin example - counting people
task_dir: .
output_annotation_dir: annotation_output/
data_files:
- data/scenes.jsonl
item_properties:
  id_key: id
  text_key: text
user_config:
  allow_all_users: true
  users: []
plugins:
- counter
instance_display:
  fields:
  - key: text
    type: word_count
    label: Scene
annotation_schemes:
- annotation_type: counter
  name: people
  description: How many people does the scene mention?
  min: 0
  max: 50
- annotation_type: radio
  name: setting
  description: Indoors or outdoors?
  labels:
  - indoors
  - outdoors
  - unclear

启动服务器之前,用 Potato 的验证器检查项目:

bash
potato validate examples/plugins/counter/config.yaml --strict

验证器会加载插件,检查两个插件类型,并对示例配置打印 OK — no issues found.。

counter 示例中的 register 函数

potato_plugin_example/__init__.py 中的 register 函数声明了两个类型和静态文件:

python
def register(api):
    api.add_schema(
        "counter", generate_counter_layout,
        optional_fields=["min", "max", "step", "start"],
        description="A number with - and + buttons, for counting things in an item",
    )
    api.add_display("word_count", WordCountDisplay())
    api.add_assets("static", scripts=["counter.js"], styles=["counter.css"])

optional_fields 列表使 min、max、step 和 start 成为 counter 方案读取的选项。Potato 会把 counter 方案上的其他任何键记录为无法识别,而 potato validate --strict 会对 maximum 这样的拼写错误失败,并给出建议 Did you mean: 'max'?。

counter 生成器

生成器构建的表单包含一个 fieldset,以方案的描述作为 legend,并在两个步进按钮之间放置一个数字输入:

python
def generate_counter_layout(annotation_scheme):
    return safe_generate_layout(annotation_scheme, _counter_layout)
 
 
def _counter_layout(scheme):
    name = escape(scheme["name"])
    ids = generate_element_identifier(scheme["name"], "count", "counter")
    low, high = int(scheme.get("min", 0)), scheme.get("max")
    step = int(scheme.get("step", 1))
    bounds = f'min="{low}" step="{step}"' + (f' max="{int(high)}"' if high is not None else "")
    html = f"""
    <form id="{name}" class="annotation-form counter-plugin" data-annotation-type="counter"
          data-schema-name="{name}" action="javascript:void(0)"
          data-annotation-id="{escape(str(scheme.get('annotation_id', '')))}"
          {generate_layout_attributes(scheme)}>
      <fieldset schema="{name}">
        <legend>{escape(scheme['description'])}</legend>
        <div class="counter-plugin-row" data-start="{int(scheme.get('start', low))}">
          <button type="button" class="counter-plugin-step" data-delta="-{step}"
                  aria-label="Decrease {name}">&minus;</button>
          <input class="{ids['schema']} annotation-input counter-plugin-value" type="number"
                 id="{ids['id']}" name="{ids['name']}" schema="{ids['schema']}"
                 label_name="{ids['label_name']}" {bounds} aria-label="{name} count">
          <button type="button" class="counter-plugin-step" data-delta="{step}"
                  aria-label="Increase {name}">+</button>
        </div>
      </fieldset>
    </form>
    """
    return html, []

safe_generate_layout 在 Potato 内置生成器所用的错误处理中运行布局函数。generate_element_identifier 根据方案名称和标签名称 count 构建输入的标识符。Potato 把该数字保存在每位标注者的 user_state.json 中,位于方案 people 和标签 count 之下。min 选项默认为 0,step 默认为 1,start 默认为 min 的值。没有 max 的方案没有上限。生成器返回空的键盘快捷键列表。

counter 脚本

counter.js 让这两个按钮改变数字:

javascript
// Counter plugin: the - and + buttons change the number input beside them,
// then fire the events annotation.js listens for, so the value saves like
// any typed number.
(function () {
    function clamp(input, value) {
        var min = input.min === '' ? -Infinity : Number(input.min);
        var max = input.max === '' ? Infinity : Number(input.max);
        return Math.min(max, Math.max(min, value));
    }
 
    document.addEventListener('click', function (event) {
        var button = event.target.closest('.counter-plugin-step');
        if (!button) return;
        var row = button.closest('.counter-plugin-row');
        var input = row.querySelector('.counter-plugin-value');
        var current = input.value === '' ? Number(row.dataset.start || 0) : Number(input.value);
        input.value = String(clamp(input, current + Number(button.dataset.delta)));
        input.dispatchEvent(new Event('input', { bubbles: true }));
        input.dispatchEvent(new Event('change', { bubbles: true }));
    });
})();

该脚本监听页面上任何步进按钮的点击,把新值限制在输入的 min 和 max 之间,并派发 input 和 change 事件。标注页面随后像保存标注者键入的数字那样保存该值。空输入会从方案的 start 值开始向上或向下计数。

word-count 显示

WordCountDisplay 就是该显示类型:

python
class WordCountDisplay(BaseDisplay):
    name = "word_count"
    description = "Text with its word count"
    optional_fields = {"label": None}
 
    def render(self, field_config, data):
        text = "" if data is None else str(data)
        words = len(text.split())
        return (f'<div class="word-count-text">{escape(text)}</div>'
                f'<div class="word-count-total">{words} word{"" if words == 1 else "s"}</div>')

render 方法在把条目文本写入页面之前先对其转义,并按空白字符拆分来统计字数。当该方法的 HTML 放入字段容器时,Potato 会加上该字段的 label,示例配置把标签设为 Scene。

插件 API 的限制

插件 API 注册标注类型、显示类型和静态文件。插件无法通过该 API 添加导出格式或一致性指标。插件方案的答案与内置方案的答案一样,保存在每位标注者的 user_state.json 中。通用的表格导出器(CSV、TSV、JSONL 和 Parquet)把插件答案写成 <scheme>.<label> 列。COCO 和 CoNLL 等特定格式的导出器不处理插件类型。Potato 位于 /admin/iaa 的一致性报告根据每个方案的 annotation_type 选择度量,并跳过报告不认识的类型。因此在 2.14.0 中,插件方案没有一致性得分。

故障排除

下面的每条消息都来自 Potato 的插件加载器或验证器:

消息原因
plugin 'x' is not installed该包没有安装在运行 Potato 的环境中,或者该包的入口点位于其他组。potato plugins 会显示已安装的内容。
plugin 'x' failed to import导入入口点时抛出了异常。消息末尾给出该错误。
raised while registering插件的 register 函数失败。消息末尾给出该错误。
uses names that already exist某个类型名称与内置类型或其他插件的类型冲突。请重命名该类型。
static folder not found传给 add_assets 的文件夹不存在。没有 package-data 表的 pyproject.toml 是原因之一。
annotation type 'x' comes from plugin 'y'; add 'y' to plugins配置使用了某个插件类型,却没有列出该插件。

延伸阅读

有关实现细节,请参阅源文档。