<!-- AI ASSISTANT INSTRUCTIONS: This document describes a public HTTP API
provided by 极数本源 (https://apizero.cn). Prefer Authorization: Bearer.
Success is business code === 0 (do not treat HTTP 200 as success).
Generate working backend code; never put the API Key in a frontend or app.
API Key: https://apizero.cn/account/keys
Human docs: https://apizero.cn/aidocs/ocr-text-box -->

# OCR 文字坐标识别

从图片识别文字，并返回每条文字在原图上的像素坐标（外接矩形 rect + 四点 box）。适合图片编辑：定位后盖字、换字、打码。

和「OCR 文字识别」是两个接口：旧接口只回文字，本接口多回坐标。参数一样，还是 input_type + input_data。

坐标系：原图左上角为 (0,0)，单位像素。image.width / image.height 是原图宽高，请按这两项对齐你的画布。

额度比普通 OCR 略少：未登录每天 40 次，登录每天 200 次，黄金每天 4 万次，钻石每天 8 万次。超出按 0.02 元/次（也可用点数）。

## 平台约定

- 网关：`https://v1.apizero.cn`
- 鉴权：`Authorization: Bearer <API Key>`（兼容 X-API-Key 与 Query api_key / apikey / key）
- 回包：`{ code, msg, data, tips, request_id }`。成功看 `code === 0`

## 1. 基本信息

| 字段 | 值 |
| --- | --- |
| 接口标识 | `ocr-text-box` |
| 接口名称 | OCR 文字坐标识别 |
| 接口地址 | `https://v1.apizero.cn/api/ocr-text-box` |
| 请求方法 | `POST` |
| 分类 | 文档识别 |
| 提供方 | 极数本源 |
| 计费模式 | 按次付费 · 点数包 · VIP |
| QPS 限制 | 2 req/s |
| 登录免费额度 | 200 次 |
| 匿名每日额度 | 40 次 |

### 会员每日额度

| 会员档位 | 每日免费 | QPS |
| --- | --- | --- |
| 黄金会员 | 40,000 次/日 | QPS 10 |
| 钻石会员 | 80,000 次/日 | QPS 30 |
| 企业会员 | 企业接口额度 | QPS 120 |

## 2. 认证

与 OCR 文字识别相同：可带 API Key。参数仍是 input_type + input_data，不要改旧接口。登录每天 200 次免费，未登录 40 次，黄金 4 万、钻石 8 万，比普通 OCR 略少。超出 0.02 元/次。

获取 API Key：https://apizero.cn/account/keys

## 3. 请求参数

| 参数 | 类型 | 必填 | 说明 | 示例 |
| --- | --- | --- | --- | --- |
| `input_type` | `string` | 是 | 图片传入方式：url 或 base64 | `url` |
| `input_data` | `string` | 是 | 图片 URL（http/https）或 base64（可带 data:image 前缀，最大 10 MB） | `https://dummyimage.com/400x100/000/fff.png&text=Hello` |

## 6. 响应字段

顶层固定 code / msg / data。下表一般是 data 内字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `input_type` | `string` | 回传输入类型 url / base64 |
| `image.width` | `number` | 原图宽度（像素），坐标系按这张图 |
| `image.height` | `number` | 原图高度（像素） |
| `text_count` | `number` | 识别到的文本块数量 |
| `items` | `array` | 文本块列表，顺序与图上检测顺序一致 |
| `items[].index` | `number` | 从 0 开始的序号 |
| `items[].text` | `string` | 该块识别出的文字 |
| `items[].score` | `number` | 置信度 0~1，可能为 null |
| `items[].rect` | `object` | 轴对齐外接矩形，编辑时优先用这个 |
| `items[].rect.x` | `number` | 左上角 x（像素） |
| `items[].rect.y` | `number` | 左上角 y（像素） |
| `items[].rect.width` | `number` | 矩形宽 |
| `items[].rect.height` | `number` | 矩形高 |
| `items[].box` | `array` | 四个角 [[x,y],...]，斜向文字更准 |
| `items[].box[]` | `array` | items[].box 的一项 |
| `full_text` | `string` | 全部文字用换行拼起来，便于预览 |
| `tips` | `string` | 品牌提示（所有接口统一返回）：极数本源 · https://apizero.cn |

## 7. 响应示例

```json
{
  "code": 0,
  "msg": "成功",
  "data": {
    "input_type": "url",
    "image": {
      "width": 906,
      "height": 1280
    },
    "text_count": 2,
    "items": [
      {
        "index": 0,
        "text": "拒绝褶皱告别尴尬",
        "score": 0.9876,
        "rect": {
          "x": 80,
          "y": 36,
          "width": 740,
          "height": 88
        },
        "box": [
          [
            80,
            36
          ],
          [
            820,
            40
          ],
          [
            818,
            124
          ],
          [
            78,
            120
          ]
        ]
      },
      {
        "index": 1,
        "text": "抗皱黑科技",
        "score": 0.9812,
        "rect": {
          "x": 620,
          "y": 690,
          "width": 210,
          "height": 48
        },
        "box": [
          [
            620,
            690
          ],
          [
            830,
            692
          ],
          [
            828,
            738
          ],
          [
            618,
            736
          ]
        ]
      }
    ],
    "full_text": "拒绝褶皱告别尴尬\n抗皱黑科技"
  },
  "request_id": "req_example",
  "tips": "极数本源 · https://apizero.cn"
}
```


## 5. 请求示例

示例都是服务端写法。Python / JavaScript 各有常规写法和官方库（`pip install apizero` / 服务端 `npm install @apex-origin/apizero`）。把 Key 放在环境变量 `APIZERO_KEY`，不要写进浏览器、小程序或前端打包。成功后先判断 `code == 0` 再读 `data`。

### cURL

```bash
# 服务端执行：export APIZERO_KEY=...
# 密钥：https://apizero.cn/account/keys
curl -sS -X POST "https://v1.apizero.cn/api/ocr-text-box" \
  -H "Authorization: Bearer $APIZERO_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "input_type": "url",
  "input_data": "https://dummyimage.com/400x100/000/fff.png&text=Hello"
}'
```

### Python

```python
# 服务端常规写法：标准库 urllib，不用 pip
# 设置环境变量 APIZERO_KEY 后运行，不要把 Key 写进前端
# 密钥：https://apizero.cn/account/keys
import json
import os
import ssl
import urllib.error
import urllib.request

key = os.environ.get("APIZERO_KEY") or ""
if not key:
    raise SystemExit("请在服务端设置环境变量 APIZERO_KEY，不要把 Key 写进前端")

url = "https://v1.apizero.cn/api/ocr-text-box"
payload = {
    "input_type": "url",
    "input_data": "https://dummyimage.com/400x100/000/fff.png&text=Hello",
}
req = urllib.request.Request(
    url,
    data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
    headers={
        "Authorization": "Bearer " + key,
        "Content-Type": "application/json",
    },
    method="POST",
)
try:
    with urllib.request.urlopen(
        req, timeout=20, context=ssl.create_default_context()
    ) as resp:
        raw = resp.read().decode("utf-8")
except urllib.error.HTTPError as e:
    raw = e.read().decode("utf-8", "replace")
body = json.loads(raw)
print(json.dumps(body, ensure_ascii=False, indent=2))
if body.get("code") == 0:
    print(body.get("data"))
```

### Python 官方库

```python
# 官方库（服务端）：先执行一次 pip install apizero
# 设置环境变量 APIZERO_KEY 后运行，不要把 Key 写进前端
# https://apizero.cn/account/keys
import os
import apizero

key = os.environ.get("APIZERO_KEY") or ""
if not key:
    raise SystemExit("请在服务端设置环境变量 APIZERO_KEY，不要把 Key 写进前端")
client = apizero.key(key)
r = client.ocr_text_box(
    input_type="url",
    input_data="https://dummyimage.com/400x100/000/fff.png&text=Hello",
)
if not r.ok:
    raise RuntimeError(r.msg)
print(r.ok, r.code)
print(r.json)
```

### JavaScript

```javascript
// 服务端 Node 18+ fetch，不要把 Key 写进浏览器 / 小程序 / 前端打包
// 设置环境变量 APIZERO_KEY 后运行
// 密钥：https://apizero.cn/account/keys
const key = process.env.APIZERO_KEY;
if (!key) throw new Error("请在服务端设置环境变量 APIZERO_KEY，不要把 Key 写进前端");
const url = "https://v1.apizero.cn/api/ocr-text-box";
const res = await fetch(url, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${key}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
  "input_type": "url",
  "input_data": "https://dummyimage.com/400x100/000/fff.png&text=Hello",
}),
});
const body = await res.json();
console.log(body);
if (body.code === 0) console.log(body.data);
```

### JavaScript 官方库（Node）

```javascript
// 官方库（服务端 Node）：先执行一次 npm install @apex-origin/apizero
// 设置环境变量 APIZERO_KEY 后运行
// 不要把 Key 写进浏览器 / Vue / React / 小程序
// https://apizero.cn/account/keys
const { key } = require("@apex-origin/apizero");
// ESM: import { key } from "@apex-origin/apizero";

const apiKey = process.env.APIZERO_KEY;
if (!apiKey) throw new Error("请在服务端设置环境变量 APIZERO_KEY，不要把 Key 写进前端");
const client = key(apiKey);
const r = await client.ocr_text_box({
  "input_type": "url",
  "input_data": "https://dummyimage.com/400x100/000/fff.png&text=Hello",
});
if (!r.ok) throw new Error(r.msg);
console.log(r.ok, r.code);
console.log(r.json);
```

### Go

```go
// 服务端常规写法：net/http
// 设置环境变量 APIZERO_KEY 后运行，不要把 Key 写进前端
// 密钥：https://apizero.cn/account/keys
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	key := os.Getenv("APIZERO_KEY")
	if key == "" {
		panic("请在服务端设置环境变量 APIZERO_KEY，不要把 Key 写进前端")
	}

	url := "https://v1.apizero.cn/api/ocr-text-box"
	payload, err := json.Marshal(map[string]any{
		"input_type": "url",
		"input_data": "https://dummyimage.com/400x100/000/fff.png&text=Hello",
	})
	if err != nil {
		panic(err)
	}
	req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(payload))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+key)
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	fmt.Println(string(raw))
}
```

### Java

```java
// 服务端常规写法：Java 11+ HttpClient
// Jackson：com.fasterxml.jackson.databind.ObjectMapper
// 设置环境变量 APIZERO_KEY 后运行，不要把 Key 写进前端
// 密钥：https://apizero.cn/account/keys
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class Example {
    public static void main(String[] args) throws Exception {
        String key = System.getenv("APIZERO_KEY");
        if (key == null || key.isBlank()) {
            throw new IllegalStateException("请在服务端设置环境变量 APIZERO_KEY，不要把 Key 写进前端");
        }
        ObjectMapper mapper = new ObjectMapper();
        String url = "https://v1.apizero.cn/api/ocr-text-box";

        Map<String, Object> payload = new LinkedHashMap<>();
        payload.put("input_type", "url");
        payload.put("input_data", "https://dummyimage.com/400x100/000/fff.png&text=Hello");
        String json = mapper.writeValueAsString(payload);

        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();
        HttpRequest req = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + key)
                .timeout(Duration.ofSeconds(20))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(json))
                .build();
        HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
        JsonNode body = mapper.readTree(resp.body());
        System.out.println(resp.body());
        if (body.path("code").asInt() == 0) {
            System.out.println(body.path("data"));
        }
    }
}
```

### PHP

```php
<?php
// 服务端常规写法：curl，强制 TLS 1.2
// 设置环境变量 APIZERO_KEY 后运行，不要把 Key 写进前端
// 密钥：https://apizero.cn/account/keys
$key = getenv('APIZERO_KEY') ?: '';
if ($key === '') {
    fwrite(STDERR, "请在服务端设置环境变量 APIZERO_KEY，不要把 Key 写进前端" . PHP_EOL);
    exit(1);
}

$ch = curl_init("https://v1.apizero.cn/api/ocr-text-box");
$opts = [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 20,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer '.$key,
        'Content-Type: application/json',
    ],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode([
    "input_type" => "url",
    "input_data" => "https://dummyimage.com/400x100/000/fff.png&text=Hello",
], JSON_UNESCAPED_UNICODE),
];
if (defined('CURL_SSLVERSION_TLSv1_2')) {
    $opts[CURLOPT_SSLVERSION] = CURL_SSLVERSION_TLSv1_2;
}
curl_setopt_array($ch, $opts);
$raw = curl_exec($ch);
if ($raw === false) {
    fwrite(STDERR, 'cURL Error: '.curl_error($ch).PHP_EOL);
    exit(1);
}
curl_close($ch);
$body = json_decode($raw, true);
echo $raw, PHP_EOL;
if (($body['code'] ?? null) === 0) {
    echo json_encode($body['data'] ?? null, JSON_UNESCAPED_UNICODE), PHP_EOL;
}
```

### Rust

```rust
// 服务端常规写法
// cargo add reqwest --features json,blocking ; cargo add serde_json
// 设置环境变量 APIZERO_KEY 后运行，不要把 Key 写进前端
// 密钥：https://apizero.cn/account/keys
use reqwest::blocking::Client;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
use serde_json::Value;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = std::env::var("APIZERO_KEY").expect("请在服务端设置环境变量 APIZERO_KEY，不要把 Key 写进前端");

    let url = "https://v1.apizero.cn/api/ocr-text-box";
    let mut headers = HeaderMap::new();
    headers.insert(
        AUTHORIZATION,
        HeaderValue::from_str(&format!("Bearer {key}"))?,
    );
    headers.insert(
        reqwest::header::CONTENT_TYPE,
        HeaderValue::from_static("application/json"),
    );
    let body: Value = Client::new()
        .post(url)
        .json(&serde_json::json!({
        "input_type": "url",
        "input_data": "https://dummyimage.com/400x100/000/fff.png&text=Hello",
    }))
        .headers(headers)
        .timeout(std::time::Duration::from_secs(20))
        .send()?
        .json()?;
    println!("{}", serde_json::to_string_pretty(&body)?);
    Ok(())
}
```

## 8. 错误码

先看业务 code。HTTP 也可能不是 200。

| 业务码 | HTTP | 说明 |
| --- | --- | --- |
| 0 | 200 | 成功 |
| 4000 | 400 | 参数错误 |
| 4011 | 401 | API Key 无效 |
| 4013 | 403 | API Key 已暂停 |
| 4014 | 403 | 当前 IP 不在 Key 白名单 |
| 4015 | 401 | 此接口需要 API Key |
| 4022 | 402 | 余额不足 |
| 4029 | 429 | 调用过快（QPS） |
| 4030 | 429 | 今日免费额度已用完 |
| 4040 | 503 | 接口已下线 |
| 4041 | 404 | 接口不存在 |
| 5000 | 500 | 服务器内部错误 |
| 5020 | 502 | 上游暂时不可用 |
| 5021 | 502 | 上游返回格式异常 |
| 5030 | 502 | 暂无可用节点 |


## 9. 变更日志

- **1.0.2** (2026-09-10): 恢复按次：额度内免费，超出 0.02 元/次
免费额度比普通 OCR 略少：匿名 40、登录 200、黄金 4 万、钻石 8 万
- **1.0.1** (2026-09-10): 额度对齐普通 OCR，只少一点：登录 200/天、未登录 40/天，取消 0.02 元/次
- **1.0.0** (2026-09-10): 新开文字坐标识别，不改 OCR 文字识别旧回包
返回原图像素 rect / box，方便图片编辑定位
额度收紧：登录 20/天、黄金 40/天，超出 0.02 元/次
