跳轉到內容

用於自定義標註類型和顯示類型的 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配置使用了某個外掛類型,卻沒有列出該外掛。

延伸閱讀

有關實現細節,請參閱源文件。