Uni-Parser v1.5.0
I.

前言

选择 UniParser-Tools 或 UniParser-API,并了解调用前需要知道的基础配置。

接入方式

Uni-Parser 提供两种接入方式:

方式 说明 适用场景
UniParser-Tools 高层封装的 Python 库 推荐给大多数用户。它封装了提交任务、轮询、结果获取和常见格式转换,适合脚本、批处理、科研工作流和 Agent 集成。
UniParser-API 原生 HTTP 调用 适合需要直接控制 HTTP 请求、鉴权、轮询、回调、字段开关或系统集成细节的场景。

如果不确定选哪一种,优先使用 UniParser-Tools;只有在需要细粒度控制接口行为时,再使用 UniParser-API。

极简流程:

  1. 获取 X-API-Key(主页玻尔登录一键授权获取,或填入已有 Key)。
  2. 提交文件、图片片段或 URL 解析任务。
  3. 选择同步等待 sync=true,或异步提交后根据 token 获取结果。
  4. 获取 content、objects、pages_dict、pages_tree 等结果。
  5. 按需选择 Markdown、HTML、LaTeX、Plain 等输出格式。

认证与计价

认证:在主页通过玻尔登录一键授权即可获取 X-API-Key 并自动发放试用额度;若已有 Key,可在「输入已有 API Key」处直接填入。(原验证码访客注册已下线,统一收敛到玻尔登录。)

计价:普通文档按 0.05 元 × 请求解析页数 计费,单元素解析为 0.01 元/次。解析成功后才收费,优先使用本地余额(含试用额度),不足时使用符合条件的 Bohrium 钱包;确认付款后开放结果。客户端超时不代表任务失败,请用原 token 查询。

文件大小、页数、请求频率等额度与限速规则见「参考信息」与「常见问题」。

Integration methods

Uni-Parser supports two integration methods:

Method Description When to use it
UniParser-Tools A high-level Python library wrapper Recommended for most users. It wraps task submission, polling, result fetching, and common output conversion for scripts, batch jobs, research workflows, and agent integrations.
UniParser-API Native HTTP calls Use this when you need direct control over HTTP requests, authentication, polling, callbacks, output switches, or system integration details.

If you are unsure which path to choose, start with UniParser-Tools. Use UniParser-API only when you need fine-grained control over the HTTP workflow.

Minimal workflow:

  1. Get an X-API-Key (one-click via Bohrium sign-in (玻尔登录) on the homepage, or paste an existing key).
  2. Submit a file, image snippet, or URL parsing task.
  3. Use sync=true to wait synchronously, or submit asynchronously and fetch results later with the token.
  4. Fetch content, objects, pages_dict, pages_tree, or other result fields.
  5. Choose Markdown, HTML, LaTeX, Plain, or other output formats as needed.

Authentication & pricing

Authentication: Sign in with Bohrium (玻尔登录) on the homepage for one-click authorization to obtain an X-API-Key and an automatically granted trial balance; if you already have a key, paste it under "enter an existing API Key". (The former captcha-based visitor registration has been retired and consolidated into Bohrium sign-in.)

Pricing: Documents cost CNY 0.05 × the number of requested pages; individual-element parsing costs CNY 0.01 per request. Payment is collected only after successful parsing, using local balance (including trial credit) first, then an eligible Bohrium wallet if local funds are insufficient. Results become available after payment confirmation. A client timeout does not mean the task failed: query the original token.

File-size, page-count, and rate-limit rules are covered in "Reference" and "FAQ".

II.

UniParser-Tools

在GitHub查看

推荐给大多数用户的 Python 客户端封装。

以下为基础调用方式;完整示例与最新用法请以仓库内的 README.md 和 notebook 为准。

1. 安装

UniParser-Tools 是 UniParser-API 的 Python 客户端封装,适合在脚本、notebook、批处理和 Agent 工作流中直接调用。

git clone https://github.com/dptech-corp/UniParser-Tools.git
cd UniParser-Tools
pip install -r requirements.txt
pip install -e .

2. 初始化客户端

初始化客户端时需要提供 api_key。认证方式和 API-Key 配置参考用户认证。

import os
from uniparser_tools.api.clients import UniParserClient

parser = UniParserClient(
    host="https://uniparser.dp.tech/",
    api_key=os.getenv("UNIPARSER_API_KEY"),
)

3. 提交 PDF 解析任务

UniParser-Tools 封装了不同解析入口:

  • 文件解析:trigger_file
  • 图片片段解析:trigger_snip
  • URL 解析:trigger_url

常用请求格式参考请求格式。UniParser-Tools 会自动生成唯一 token 并随 trigger 请求提交,通常不需要手动指定;只有需要复用外部任务索引时才建议显式传入。

解析配置用于控制提交任务时解析哪些语义元素,以及各元素采用快速解析、高质量解析或返回原始图像等模式。ParseMode / ParseModeTextual 只用于提交阶段,不要传给 get_formatted。详情参考解析配置 SemanticType。

from uniparser_tools.common.constant import ParseMode, ParseModeTextual

result = parser.trigger_file(
    file_path="example.pdf",
    textual=ParseModeTextual.OCRHighQuality,  # high quality
    equation=ParseMode.OCRHighQuality,  # high quality
    table=ParseMode.OCRHighQuality,  # high quality
    chart=ParseMode.DumpBase64,  # original image base64
    figure=ParseMode.DumpBase64,  # original image base64
    expression=ParseMode.DumpBase64,  # original image base64
    molecule=ParseMode.OCRFast,  # fast
)

token = result["token"]

图片片段解析使用 trigger_snip,适合解析截图、局部页面或单张图片:

snip_result = parser.trigger_snip(
    snip_path="example.png",
    textual=ParseModeTextual.OCRHighQuality,
    table=ParseMode.OCRHighQuality,
    equation=ParseMode.OCRHighQuality,
)

snip_token = snip_result["token"]

URL 解析使用 trigger_url,适合提交公网可访问的 PDF 链接:

url_result = parser.trigger_url(
    pdf_url="https://example.com/paper.pdf",
    textual=ParseModeTextual.OCRHighQuality,
    table=ParseMode.OCRHighQuality,
    equation=ParseMode.OCRHighQuality,
)

url_token = url_result["token"]

4. 获取 Markdown 结果

获取结果时可以通过输出开关控制返回全文 content、语义块 objects、页级结构 pages_dict 或层级结构 pages_tree;本示例开启 content=True 获取格式化全文。FormatFlag 只用于获取结果阶段,不要传给 trigger_file。输出开关详情参考输出配置,Markdown、HTML、LaTeX 等格式参考输出格式 FormatFlag。

from uniparser_tools.common.constant import FormatFlag

result = parser.get_formatted(
    token,
    content=True,
    textual=FormatFlag.Markdown,
    table=FormatFlag.Markdown,
    equation=FormatFlag.Markdown,
)

print(result["content"])

The following is the basic workflow. For complete and latest examples, see the repo README.md and notebooks.

1. Install

UniParser-Tools is a Python client wrapper for UniParser-API, suitable for scripts, notebooks, batch processing, and agent workflows.

git clone https://github.com/dptech-corp/UniParser-Tools.git
cd UniParser-Tools
pip install -r requirements.txt
pip install -e .

2. Initialize the client

Provide an api_key when initializing the client. See User Authentication for authentication and API-Key configuration details.

import os
from uniparser_tools.api.clients import UniParserClient

parser = UniParserClient(
    host="https://uniparser.dp.tech/",
    api_key=os.getenv("UNIPARSER_API_KEY"),
)

3. Submit a PDF parsing task

UniParser-Tools wraps different parsing entry points:

  • File parsing: trigger_file
  • Image snippet parsing: trigger_snip
  • URL parsing: trigger_url

See Request Format for common request formats. UniParser-Tools automatically generates a unique token and submits it with the trigger request, so you usually do not need to provide one manually; pass one explicitly only when you need to reuse an external task index.

Parsing options control which semantic elements are parsed when submitting a task, and whether each element uses fast parsing, high-quality parsing, or returns the original image. ParseMode / ParseModeTextual are only for the submit stage; do not pass them to get_formatted. See Parsing Options SemanticType for details.

from uniparser_tools.common.constant import ParseMode, ParseModeTextual

result = parser.trigger_file(
    file_path="example.pdf",
    textual=ParseModeTextual.OCRHighQuality,  # high quality
    equation=ParseMode.OCRHighQuality,  # high quality
    table=ParseMode.OCRHighQuality,  # high quality
    chart=ParseMode.DumpBase64,  # original image base64
    figure=ParseMode.DumpBase64,  # original image base64
    expression=ParseMode.DumpBase64,  # original image base64
    molecule=ParseMode.OCRFast,  # fast
)

token = result["token"]

Use trigger_snip for image snippets, screenshots, page regions, or single images:

snip_result = parser.trigger_snip(
    snip_path="example.png",
    textual=ParseModeTextual.OCRHighQuality,
    table=ParseMode.OCRHighQuality,
    equation=ParseMode.OCRHighQuality,
)

snip_token = snip_result["token"]

Use trigger_url for publicly accessible PDF URLs:

url_result = parser.trigger_url(
    pdf_url="https://example.com/paper.pdf",
    textual=ParseModeTextual.OCRHighQuality,
    table=ParseMode.OCRHighQuality,
    equation=ParseMode.OCRHighQuality,
)

url_token = url_result["token"]

4. Fetch Markdown output

When fetching results, output switches control whether to return full text content, semantic blocks objects, page-level structures pages_dict, or hierarchical structures pages_tree. This example enables content=True to fetch formatted full text. FormatFlag is only for the result-fetching stage; do not pass it to trigger_file. See Output Switches for output switches, and Output FormatFlag for Markdown, HTML, LaTeX, and other formats.

from uniparser_tools.common.constant import FormatFlag

result = parser.get_formatted(
    token,
    content=True,
    textual=FormatFlag.Markdown,
    table=FormatFlag.Markdown,
    equation=FormatFlag.Markdown,
)

print(result["content"])
III.

UniParser-API

使用 curl 或 requests 直接提交解析并获取结果。

UniParser-API 适合直接用 HTTP 接口提交解析任务并获取结果。示例使用 curl 和 requests,不依赖 UniParser-Tools 客户端。

1. 提交解析任务

使用 /trigger-file-async 上传 PDF,并通过表单字段设置 token 和解析配置项。token 可由服务端生成;示例主动生成并保存,便于提交超时后查询:

# 每个新任务生成一次 UUID;保留此变量供后续查询使用(需要 Python 3)。
uniparser_token="$(python3 -c 'import uuid; print(uuid.uuid4().hex)')"
# sync=true 表示提交请求会等待解析完成;2 表示高质量解析,1 表示快速解析。
curl -X POST "https://uniparser.dp.tech/trigger-file-async" \
  -H "X-API-Key: your_api_key" \
  -F "token=${uniparser_token}" \
  -F "file=@example.pdf" \
  -F "sync=true" \
  -F "textual=2" \
  -F "equation=2" \
  -F "table=2" \
  -F "molecule=1"

重复提交提醒:每个新任务生成新的 UUID,查询结果沿用提交时的 token;客户端超时或等待付款时请先查询原任务,避免盲目重提或换 token 重跑。

Python requests 示例:

import os
import uuid
import requests

host = "https://uniparser.dp.tech/"
headers = {"X-API-Key": os.environ["UNIPARSER_API_KEY"]}
token = uuid.uuid4().hex
data = {
    "token": token,
    "sync": "true",  # 等待解析完成;大文件或批处理可改为 "false"
    "textual": "2",  # 2 = 高质量解析
    "equation": "2",  # 2 = 高质量解析
    "table": "2",  # 2 = 高质量解析
    "molecule": "1",  # 1 = 快速解析
}

with open("example.pdf", "rb") as file:
    response = requests.post(
        f"{host}trigger-file-async",
        headers=headers,
        data=data,
        files={"file": file},
        timeout=60,
    )
response.raise_for_status()

即使 sync=true 也可能返回 HTTP 202、waiting 或 payment_pending=true。这不是上传失败:保存 token,用同一账号继续查询;余额不足时补足原付款来源。只有 status=success 时才读取结果。 undefined / awaiting_parse 也是正常等待状态,进度可能为 null;不要根据提示文案判断成功或失败。

2. 获取结果

使用提交解析时提供的 token 获取格式化结果。/get-formatted 接收 JSON body。仅需要 Markdown 全文时:

在同一个终端中运行下面的 curl,沿用提交时生成的 uniparser_token,不要重新生成。

curl -X POST "https://uniparser.dp.tech/get-formatted" \
  -H "X-API-Key: your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "token": "'"${uniparser_token:?Run the submit example first to set uniparser_token}"'",
    "content": true,
    "textual": "markdown",
    "table": "markdown",
    "equation": "markdown"
  }'

Python requests 示例:

payload = {
    "token": token,
    "content": True,
    "textual": "markdown",
    "table": "markdown",
    "equation": "markdown",
}

response = requests.post(
    f"{host}get-formatted",
    headers=headers,
    json=payload,
    timeout=60,
)
response.raise_for_status()
result = response.json()
if result.get("status") == "success":
    print(result["content"])
else:
    print(result.get("description", result.get("status")), token)

如需坐标、类型或层级结构,可开启 objects、pages_dict 或 pages_tree。

3. 单元素图片解析(内测)

单元素解析支持文本、表格、分子结构、图表、化学反应式和数学公式图片,可在首页体验,或通过 POST /trigger-item-async 接入。

首页体验(内测中)

  1. 在首页“选择模式”中选择“单元素解析”。
  2. 点击上传、拖入或粘贴图片。支持 PNG、JPG、BMP、TIFF 等格式,单张最大 15MB,不支持 PDF;上传图片只会暂存,不会自动开始解析。
  3. 在上传区右下角确认图片类型与解析质量。默认选择“分子结构”和“高质量”,可切换为其他类型或“快速”。
  4. 点击同一行的“开始解析”,完成后进入结果页。

首页不单独展示“内部元素识别”选项:文本、表格和化学反应式自动启用内部元素识别;分子结构、图表和数学公式仅解析自身。解析质量统一应用于主元素及本次识别涉及的内部元素。

HTTP API

POST /trigger-item-async 通过 type 指定图片类型,与普通截图解析 /trigger-snip-async 不同。API 默认值与首页不同:quality=standard(快速)、children_mode=none;如需与首页默认行为一致,应显式设置 quality=high,并在 type 为 text、table 或 expression 时设置 children_mode=auto。

该接口需要所选解析后端支持 item_parse_v1,并配置请求所需的识别器与质量模式。仅有 user 服务路由不代表后端可用;后端不支持时请求会被拒绝。可通过 OpenAPI查看当前服务的接口定义。

请求头使用 X-API-Key。请求体使用 application/x-www-form-urlencoded 表单:

字段 必填 / 默认值 说明
img 必填 图片文件内容的标准 Base64 字符串
type 必填 text、table、molecule、chart、expression、equation,分别对应文字、表格、分子结构、图表、化学反应式、数学公式
children_mode none none 仅解析指定元素;auto 发现内部元素,适用于 text、table、expression;type=expression 必须显式设置为 auto
quality standard standard 为快速(模式 1),high 为高质量(模式 2);主元素及内部元素统一使用所选质量,后端必须支持所有相关识别器及相应模式
token 可省略 省略时由服务生成;建议主动生成并保存,便于提交超时后查询原任务
sync false true 等待完成;false 异步提交后用返回的 token 查询
timeout 1800 解析超时秒数
model_version 默认后端 可选的服务端已配置后端版本

化学反应式(type=expression)必须设置 children_mode=auto,以识别反应物、产物中的分子结构;不支持 none。 text、table 可通过 auto 发现内嵌分子与公式。molecule、chart、equation 不接受 auto。

下面的完整示例仅依赖 Python 标准库,读取本地 table.png,提交一次表格解析,成功后获取 Markdown 和 pages_tree。保存为 parse_item.py,设置 UNIPARSER_API_KEY 后运行 python3 parse_item.py;可通过 UNIPARSER_HOST 指定已支持该接口的服务地址。

import base64
import json
import os
import uuid
from pathlib import Path
from urllib.parse import urlencode
from urllib.request import Request, urlopen


host = os.getenv("UNIPARSER_HOST", "https://uniparser.dp.tech").rstrip("/")
api_key = os.environ["UNIPARSER_API_KEY"]
token = uuid.uuid4().hex
print(f"Task token: {token}", flush=True)


def post(path, payload, *, form=False):
    body = urlencode(payload).encode() if form else json.dumps(payload).encode()
    request = Request(
        host + path,
        data=body,
        headers={
            "X-API-Key": api_key,
            "Content-Type": "application/x-www-form-urlencoded" if form else "application/json",
        },
        method="POST",
    )
    with urlopen(request, timeout=1860) as response:
        result = json.load(response)
    if result.get("status") == "error":
        raise RuntimeError(f"Task {token}: {result.get('description', result.get('status'))}")
    return result


post(
    "/trigger-item-async",
    {
        "token": token,
        "img": base64.b64encode(Path("table.png").read_bytes()).decode("ascii"),
        "type": "table",
        "children_mode": "none",
        "quality": "standard",
        "sync": "true",
        "timeout": 1800,
    },
    form=True,
)
result = post(
    "/get-formatted",
    {"token": token, "content": True, "pages_tree": True, "table": "markdown", "textual": "markdown"},
)
if result.get("status") == "success":
    print(result.get("content", ""))
else:
    print(result.get("description", result.get("status")), token)

提交其他单元素图片时修改 type;改为 expression 时还必须将 children_mode 改为 auto。包含分子或公式的表格可改为 children_mode=auto,前提是后端支持全部相关识别器。代码中的 quality=standard 使用 API 默认的快速模式;改为 quality=high 可请求高质量,前提是后端支持全部相关识别器的高质量模式。

如需原始结构结果,使用同一 token 向 /get-result 提交 JSON;需要格式化结果则使用 /get-formatted。当提交响应为 undefined、waiting 或 processing,或客户端超时导致提交结果未知时,请保存并查询原 token,不要自动换 token 重新提交。示例不会自动重试,也不依赖 UniParser-Tools 中的单元素专用方法。

The native API lets you submit parsing tasks and fetch results directly over HTTP. The examples below use curl and requests; they do not rely on the UniParser-Tools client.

1. Submit a Parsing Task

Use /trigger-file-async to upload a PDF and set token plus parsing options as form fields. token can be generated by the server; these examples generate and save it before submission so you can query the task even if submission times out:

# Generate a UUID once per new task; keep this variable for result queries (requires Python 3).
uniparser_token="$(python3 -c 'import uuid; print(uuid.uuid4().hex)')"
# sync=true waits for parsing to finish; 2 means high-quality parsing, 1 means fast parsing.
curl -X POST "https://uniparser.dp.tech/trigger-file-async" \
  -H "X-API-Key: your_api_key" \
  -F "token=${uniparser_token}" \
  -F "file=@example.pdf" \
  -F "sync=true" \
  -F "textual=2" \
  -F "equation=2" \
  -F "table=2" \
  -F "molecule=1"

Duplicate submission reminder: generate a new UUID for each new task and reuse its token when fetching results. After a client timeout or while payment is pending, query the original task rather than resubmitting or starting another task with a new token.

Python requests example:

import os
import uuid
import requests

host = "https://uniparser.dp.tech/"
headers = {"X-API-Key": os.environ["UNIPARSER_API_KEY"]}
token = uuid.uuid4().hex
data = {
    "token": token,
    "sync": "true",  # wait for parsing to finish; use "false" for large files or batches
    "textual": "2",  # 2 = high-quality parsing
    "equation": "2",  # 2 = high-quality parsing
    "table": "2",  # 2 = high-quality parsing
    "molecule": "1",  # 1 = fast parsing
}

with open("example.pdf", "rb") as file:
    response = requests.post(
        f"{host}trigger-file-async",
        headers=headers,
        data=data,
        files={"file": file},
        timeout=60,
    )
response.raise_for_status()

Even with sync=true, the response may be HTTP 202, waiting, or payment_pending=true. This is not an upload failure: keep the token and continue querying with the same account. Top up the original payment source if needed. Read result content only when status=success. undefined / awaiting_parse is also a normal waiting state, and progress may be null. Do not infer success or failure from description text.

2. Fetch Results

Use the token you provided when submitting the task to fetch formatted results. /get-formatted accepts a JSON body. For Markdown full text:

Run the following curl in the same shell, reusing uniparser_token from submission without regenerating it.

curl -X POST "https://uniparser.dp.tech/get-formatted" \
  -H "X-API-Key: your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "token": "'"${uniparser_token:?Run the submit example first to set uniparser_token}"'",
    "content": true,
    "textual": "markdown",
    "table": "markdown",
    "equation": "markdown"
  }'

Python requests example:

payload = {
    "token": token,
    "content": True,
    "textual": "markdown",
    "table": "markdown",
    "equation": "markdown",
}

response = requests.post(
    f"{host}get-formatted",
    headers=headers,
    json=payload,
    timeout=60,
)
response.raise_for_status()
result = response.json()
if result.get("status") == "success":
    print(result["content"])
else:
    print(result.get("description", result.get("status")), token)

If you need coordinates, block types, or hierarchy, enable objects, pages_dict, or pages_tree.

3. Individual-Element Image Parsing (Beta)

Individual-element parsing supports images of text, tables, molecular structures, charts, chemical reactions, and mathematical equations. Try it on the home page or integrate through POST /trigger-item-async.

Home page (Beta)

  1. Select “Individual Element” from the home page's mode selector.
  2. Click to upload, drop, or paste an image. PNG, JPG, BMP, TIFF, and other image formats are supported, up to 15MB per image; PDFs are not supported. Uploading only stages the image and does not start parsing.
  3. Confirm the image type and parsing quality at the bottom right of the upload area. The defaults are “Molecule” and “High Quality”; you can choose another type or switch to “Fast”.
  4. Click “Start parsing” on the same row. The result page opens when parsing finishes.

The home page does not show a separate nested-element option: text, tables, and chemical reactions automatically detect nested elements; molecules, charts, and equations parse only the selected element. The selected quality applies to both the main element and any nested elements involved in the request.

HTTP API

POST /trigger-item-async specifies the image type through type, unlike ordinary screenshot parsing through /trigger-snip-async. API defaults differ from the home page: quality=standard (Fast) and children_mode=none. To match the home page's default behavior, explicitly set quality=high and use children_mode=auto for text, table, or expression.

The selected parser backend must support item_parse_v1 and have the required recognizers and quality modes configured. A registered user-service route alone does not establish backend availability; unsupported backends reject the request. See the running service's OpenAPI for its interface definition.

Authenticate with the X-API-Key header and send an application/x-www-form-urlencoded request body:

Field Required / default Description
img Required Image file contents encoded as standard Base64
type Required text, table, molecule, chart, expression, or equation
children_mode none none parses the specified element; auto discovers nested elements for text, table, and expression; type=expression requires explicitly setting auto
quality standard standard means Fast (mode 1); high means High Quality (mode 2). The selected quality applies to the main and nested elements; the backend must support every required recognizer and mode
token Optional Generated by the service if omitted; generating and saving one yourself helps recover results after a submission timeout
sync false true waits for completion; false submits asynchronously for later retrieval using the returned token
timeout 1800 Parsing timeout in seconds
model_version Default backend Optional backend version configured by the service

Chemical reactions (type=expression) require children_mode=auto to recognize molecules in reactants and products; none is not supported. text and table can use auto to discover nested molecules and equations. molecule, chart, and equation do not accept auto.

The complete example below uses only the Python standard library. It reads table.png, submits one table parsing request, and retrieves Markdown and pages_tree after success. Save it as parse_item.py, set UNIPARSER_API_KEY, and run python3 parse_item.py. Optionally set UNIPARSER_HOST to a service that supports this interface.

import base64
import json
import os
import uuid
from pathlib import Path
from urllib.parse import urlencode
from urllib.request import Request, urlopen


host = os.getenv("UNIPARSER_HOST", "https://uniparser.dp.tech").rstrip("/")
api_key = os.environ["UNIPARSER_API_KEY"]
token = uuid.uuid4().hex
print(f"Task token: {token}", flush=True)


def post(path, payload, *, form=False):
    body = urlencode(payload).encode() if form else json.dumps(payload).encode()
    request = Request(
        host + path,
        data=body,
        headers={
            "X-API-Key": api_key,
            "Content-Type": "application/x-www-form-urlencoded" if form else "application/json",
        },
        method="POST",
    )
    with urlopen(request, timeout=1860) as response:
        result = json.load(response)
    if result.get("status") == "error":
        raise RuntimeError(f"Task {token}: {result.get('description', result.get('status'))}")
    return result


post(
    "/trigger-item-async",
    {
        "token": token,
        "img": base64.b64encode(Path("table.png").read_bytes()).decode("ascii"),
        "type": "table",
        "children_mode": "none",
        "quality": "standard",
        "sync": "true",
        "timeout": 1800,
    },
    form=True,
)
result = post(
    "/get-formatted",
    {"token": token, "content": True, "pages_tree": True, "table": "markdown", "textual": "markdown"},
)
if result.get("status") == "success":
    print(result.get("content", ""))
else:
    print(result.get("description", result.get("status")), token)

Change type to submit other element images. When using expression, you must also change children_mode to auto. For a table containing molecules or equations, set children_mode=auto if the backend supports all required recognizers. The example uses the API default quality=standard (Fast). Set quality=high to request High Quality if the backend supports that mode for every required recognizer.

For raw structure results, POST JSON with the same token to /get-result; for formatted results, use /get-formatted. If submission returns undefined, waiting, or processing, or the client times out with an unknown submission outcome, keep and query the original token rather than automatically submitting again with a new token. The example does not retry automatically or depend on a dedicated UniParser-Tools item method.

IV.

参考信息

集中说明解析结果中的版面类型、输出格式和错误码。

用户认证

UniParser-API 使用请求头 X-API-Key 进行身份认证。可在 UniParser 主页通过玻尔登录一键授权获取 API-Key(首次登录自动发放试用额度),或在已有 API-Key 时直接填入使用;如需更高额度、更高权限或长期账号,请联系我们开通。

解析成功后收费,付款确认后开放结果。价格、待付款响应及恢复方式见下文“成功后收费与待付款”。

# 每个新任务生成一次 UUID;保留此变量供后续查询使用(需要 Python 3)。
uniparser_token="$(python3 -c 'import uuid; print(uuid.uuid4().hex)')"
curl -X POST "https://uniparser.dp.tech/trigger-file-async" \
  -H "X-API-Key: your_api_key" \
  -F "token=${uniparser_token}" \
  -F "file=@example.pdf" \
  -F "sync=true"

推荐将密钥放在环境变量中,例如 UNIPARSER_API_KEY,避免写入代码仓库。

请求格式

接口 请求格式 说明
/trigger-file-async multipart/form-data 上传 PDF 文件,文件字段为 file,其他参数也通过表单字段传入
/trigger-snip-async / /trigger-url-async JSON body 图片片段或 URL 解析请求
/trigger-item-async application/x-www-form-urlencoded 单元素解析,img 为 Base64 字符串;详见接入示例
/get-result / /get-formatted / /get-third-party-output JSON body(POST) 查询状态或获取对应格式的结果,沿用原 token

注意:token 是解析任务的唯一索引。单元素接口可省略 token 并由服务端生成;为便于超时后查询,建议主动生成并保存。其他 trigger 接口请按对应接入示例提供 token。使用 curl 或 Python 直接调用时,推荐为每个新任务生成 UUID;UniParser-Tools 的文档解析方法会自动生成 token。

重复提交提醒:每个新任务生成新的 UUID,查询结果沿用提交时的 token;同一 token 的重复提交可能返回 Token is duplicated,客户端超时后请先查询原任务,避免盲目重提或换 token 重跑。

sync 控制任务提交后的等待方式:sync=false 是默认异步模式,提交后立即返回任务状态和 token,需要稍后用同一 token 获取结果;sync=true 会在提交请求中等待解析完成或超时,适合示例、调试和小文件。大文件或批处理建议使用异步模式,并根据任务大小合理设置 timeout(默认 1800 秒)。

任务状态与进度

HTTP 状态表示请求是否被接受,status 表示任务状态,billing_status 表示计费阶段;三者不能互相替代。undefined 是已有的任务状态值,成功后收费流程增加了计费阶段和等待提示。

status 含义与处理
undefined 接收、准备任务,或尚无明确解析进度;保留 token 继续查询
waiting 等待初始化、解析或付款确认;结合计费字段查看原因
processing 正在解析;有进度时展示进度,继续查询
success 任务成功,可获取结果;启用成功后收费时已确认付款
error 当前任务失败;检查错误说明和错误码,不要无限轮询

例如,以下响应表示仍在等待,不是解析失败,也不表示余额不足或已经扣款:

{
  "status": "undefined",
  "description": "等待解析或付款完成",
  "billing_status": "awaiting_parse",
  "message": null,
  "proc_page": null,
  "total_page": null
}

awaiting_parse 表示已保存报价、等待解析成功后收款;解析期间也可能保持此值。created / preordering / paying 表示收款流程中,payment_unknown 表示付款结果待确认,paid 表示付款已确认。declined 不一定是余额不足,也可能是解析失败或结果过期,应结合 status、billing_code 和说明判断。

  • proc_page、total_page 缺失或为 null 表示暂无进度,不代表 0 页或失败;仅在数值有效且总页数大于 0 时计算百分比。100% 也不代表结果已开放。
  • payment_pending=true 表示付款尚未确认;该字段可能缺失,不能据此认定已付款。message 也可能为空。
  • description / message 是展示文案,可能调整;不要匹配中文文案判断状态。客户端应容忍新增字段。
  • 使用原账号和 token 查询;仅在 success 时读取结果,error 时处理失败。遇到未知状态保留 token 并记录响应,不自动重提;等待过久请携带 token 联系支持。

明确拒付后,充值或仅等待 webhook 不会自动重试付款;请用原账号和 token 调用 POST /get-result、POST /get-formatted 或 POST /get-third-party-output 触发恢复。

上传超限兼容性变更: 现在返回 HTTP 413(此前为 400),描述文案也已变化。请按 error_code="FILE_SIZE_EXCEEDED" 判断,不要匹配旧状态码或固定描述。

解析配置 SemanticType

提交解析任务时,可以分别控制以下语义元素:

阶段提示:SemanticType 与 ParseMode / ParseModeTextual 属于提交阶段,用于决定解析哪些内容以及解析质量;不要在 /get-formatted 或 get_formatted 中使用它们。

参数 含义 可用模式
textual 普通文本、标题、脚注等 0 / 1 / 2 / 3 / -1 / -3
equation 独立数学公式 0 / 1 / 2 / -1 / -3
table 表格 0 / 1 / 2 / -1 / -3
chart 图表 0 / 1 / -1 / -3
figure 图片、插图、照片 0 / 1 / -1 / -3
expression 化学反应式 0 / 1 / -1 / -3
molecule 化学分子结构 0 / 1 / -1 / -3

取值说明:0 表示禁用,1 表示快速解析,2 表示高质量解析,-1 表示返回原始图像 Base64,-3 表示将裁剪图片上传至 TOS 并返回下载链接(不进行该类别的 OCR)。textual 还支持 3,用于从数字原生 PDF 中直接抽取文字。

枚举名 对应数值
ParseMode.DumpHosting / ParseModeTextual.DumpHosting -3
ParseMode.DumpBase64 / ParseModeTextual.DumpBase64 -1
ParseMode.OCRFast / ParseModeTextual.OCRFast 1
ParseMode.OCRHighQuality / ParseModeTextual.OCRHighQuality 2
ParseModeTextual.DigitalExported 3(仅 textual)

注意:chart、expression、molecule 目前无高质量模式。

图片存储到 TOS(-3)

在提交请求时设置需要保留图片的类别,例如 figure=-3;上述所有语义类别均支持此模式。成功后,结果块的 source 为图片的 HTTP(S) GET 下载链接,Markdown/HTML 输出使用该链接。

链接默认从签名时起有效 7 天,具体有效期以服务提供的链接为准。再次读取结果不会自动续签,请在有效期内下载保存图片,并保持签名链接完整,不要修改域名或查询参数。

图片上传或生成下载链接失败时,该块按 DumpBase64=-1 返回原始图片 Base64,其他图片继续处理。dict_cfg 保留请求模式 -3,因此同一任务的 source 可能同时包含 URL 和 Base64。直接消费结果时应逐块区分;Markdown/HTML 会自动将回退图片转为 data URI。

表格模式:fast 与 hq

  • table=1(fast)返回的是“结构模板 + 单元格文本”的组合数据,通常需要结合 structure、placeholders 和 contents 还原表格:structure 描述表格骨架,placeholders 标记单元格占位,contents 提供对应的单元格文本。
  • table=2(hq)的 structure 中通常已经直接包含完整表格数据,例如带文本内容的 HTML / Markdown 表格;使用时一般不需要再额外通过 placeholders 和 contents 拼回单元格内容。
  • 因此,fast 更适合需要自行处理表格骨架和单元格文本映射的场景;hq 更适合直接消费完整表格结构的场景。高质量模式耗时通常更长;如果高质量服务不可用,系统会回退到可用的快速表格解析服务。
  • 表格模式只影响表格区域的结构识别与单元格内容识别。表题、表注以及表格外正文仍主要受 textual 配置影响;如果希望表格内文字和正文都尽量高质量,通常同时设置 table=2 和 textual=2。

输出配置

解析任务的 token 用于后续结果获取。通过 /get-formatted 获取格式化结果时,可以用输出开关控制返回内容:

注意:结果获取接口使用 JSON body。调用 UniParser-API 时请设置 Content-Type: application/json;未传字段会使用默认值。

开关 默认值 返回字段类型 说明
content true str 返回格式化后的全文内容,适合 LLM、搜索和阅读场景
objects false list[dict] 返回扁平语义块列表;每项包含 class、confidence、float_xyxy、page、str 等字段,适合需要坐标、类型和块级内容的场景
pages_dict false list[list[dict]] 返回按页组织的扁平布局;每一页是一个布局块列表,适合页级结构化处理
pages_tree false list[list[dict]] 返回按页组织的树形布局;保留父子层级关系,适合需要层级结构的场景
molecule_source false 控制选项 开启后在结构化结果中保留分子原始源信息;默认关闭是为了减少响应体积,关闭时会清空分子块的 source
marginalia true 控制选项 控制格式化结果中是否保留页边/边栏信息;默认保留是为了尽量不丢失原文信息

输出格式 FormatFlag

/get-formatted 可以为各语义元素指定输出格式:textual、table、molecule、chart、figure、expression、equation。

阶段提示:FormatFlag 属于获取结果阶段,只控制返回文本的格式;不要在 trigger 请求或 trigger_file 中使用它。

取值 名称 说明 示例
plain Plain 纯文本,无前后缀 ATP inhibits ATR.
markup Markup 标记文本,默认值 \begin{paragraph}ATP inhibits ATR.\end{paragraph}
markdown Markdown Markdown 格式,适合 LLM / 文档 ## Results、- IC50: 0.5 nM
latex Latex LaTeX,特别适合公式 $E = mc^2$
html Html HTML,特别适合表格 <table>...</table>

objects、pages_dict、pages_tree 这三类结构化返回不会受 FormatFlag 影响;格式化主要作用于 content 和 objects 中的文本字段。

常见版面类型 LayoutType

在 objects、pages_dict、pages_tree 中,每个解析块都会带有 type 字段,用于描述该块在文档版面中的语义类型。

类型 含义 通常归属的大类
documenttitle 文档标题 textual
title 章节标题 textual
paragraph 普通段落正文 textual
abstract 摘要 textual
reference 参考文献 textual
table 表格主体 table
tablecaption / tablefootnote 表题 / 表注 textual,语义上附属于表格
equation / equationinline 独立公式 / 行内公式 equation
molecule / moleculeid 分子结构 / 分子编号 molecule 或相关文本
figure / image 图片、插图、照片或图像区域 figure
figurecaption / imagecaption 图题 / 图片标题 textual,语义上附属于图片
expression / expressioncaption 化学反应式 / 反应式标题 expression 或相关文本
chart / legend 图表 / 图例 chart 或相关文本
pageheader / pagefooter / pagenumber 页眉、页脚、页码 页边信息
group / tablegroup / figuregroup / moleculegroup 组合节点 结构节点,常见于 pages_tree

type 是结果标签,不等同于提交任务时的 textual、table、molecule 等解析配置项。

API 与前端限制

UniParser 会同时检查 API 账号额度和前端上传限制。API 限制由账号类型、权限和申请配置决定,并同时适用于直接上传及 URL/对象存储下载;前端限制只影响网页上传,不代表 API 账号的最终可解析额度。URL/对象存储下载还受服务端全局下载上限约束,实际采用账号额度与全局上限中更严格的值。

限制类型 适用对象 默认限制 说明
API 文件体积 / 页数 访客标准账号 200 MB,2000 页 超出后会返回文件大小或页数限制相关错误
API 文件体积 / 页数 付费用户 / 已开通高额度账号 默认 300 MB,6000 页 具体额度以 API 申请文档或账号开通配置为准,可按需申请调整
前端上传体积 网页端上传 300 MB 仅限制前端页面可上传的文件大小;直接调用 API 时仍以账号 API 限制为准

请求频率限制按账号、接口和服务端配置生效。触发限速时接口会返回 429,错误信息通常包含当前命中的限制;批量任务建议使用异步提交、控制并发,并在重试时增加退避等待。如需更高请求频率或更高文件额度,请在申请 API 权限时一并说明。

错误码清单 ErrorFlag

类别 常见错误 说明 处理建议
请求参数错误 400 Token_Required:缺少 token 参数
Token_Invalid:token 含非法字符,只允许字母、数字、下划线和短横线
Token_Duplicated:token 已存在且任务未完成
File_Required:缺少上传文件
File_Invalid:PDF 无效或页数为 0
URL_Invalid:URL 不合法、不可访问或下载内容不是支持的 PDF/图片格式
Request_Invalid:请求参数格式或取值非法
必填参数、文件内容、URL 可访问性或字段取值不符合要求 补齐必填字段;为原生 API 重新生成唯一 token;确认文件可打开、URL 可下载,并按文档取值传参
解析状态错误 400 Status_Not_Found:找不到该 token 对应的状态文件
Status_Decode_Failed:状态 JSON 损坏或无法解析
Result_Not_Found:解析结果文件不存在
Result_Decode_Failed:结果 JSON 损坏或无法解析
通常说明任务不存在、结果已清理、任务失败,或服务端缓存文件异常 确认使用的是提交时返回的同一个 token;异步任务先等待完成再获取;持续缺失时携带 token 联系支持,确认原任务和付款状态后再决定是否重提
语言和页面错误 400 Lang_Unknown:无法判断文档语言
Lang_Not_Supported:当前语言不支持对应 OCR / 解析流程
Pages_Required:特定接口缺少页码选择
文档语言、扫描质量或页码选择不满足解析要求 检查文档是否可读;必要时指定页码或换用支持语言的文档;扫描件建议提升图像质量
用户限制错误 400 File_Size_Exceeded:文件大小超过账号权限
PDF_Pages_Exceeded:PDF 页数超过账号权限
File_Type_Not_Allowed:文件类型不在允许列表中
Domain_Not_Allowed:URL 下载域名不在允许列表中
和账号权限、文件大小、页数、文件类型、下载域名白名单有关 压缩或拆分文件;换用允许的文件类型或域名;如需更高额度或权限,请联系我们开通
系统和处理错误 400/500 OS_Error:服务端文件 IO、路径、权限或系统资源错误(URL 下载接口返回 500)
Process_Failed:解析子任务执行失败,可能由模型、输入文件或运行环境导致
文件读写、模型服务或任务进程异常;OS_Error 不表示用户 URL 无效 保留 token 和错误响应,稍后重试;若持续失败,请携带文件、token 和错误信息反馈
认证和授权错误 401/402/403 Authentication required:缺少 Authorization 或 X-API-Key
Authentication failed:JWT Token 或 API-Key 无效 / 过期
Insufficient balance:账户余额不足
Administrator privileges required:接口需要管理员权限
Missing permission:账号缺少指定解析权限
请求头、API-Key、余额或权限不满足要求 检查 X-API-Key 是否正确、未过期且有余额;需要管理员或特殊解析权限时联系我们开通
速率限制错误 429 Rate limit exceeded: <limit>:超出全局或接口限速
Rate limit exceeded, <user_rate_limit>:超出用户级限速
请求频率或并发超过限制 降低并发和重试频率,增加退避等待;批处理请排队提交,必要时申请更高限速

文件与下载失败

页数无法确定时可能返回 422 / INVALID_PAGE_SELECTION,不表示已扣款。结合 pdf_error_code 区分空文件、需密码、非 PDF、无有效页或打开失败;上传完整、可读取且无需密码的文件后再提交。具体原因见 description / message。

下载失败通过 error_code 区分超时、超限、连接或存储错误。input_retained=true 表示服务保留了已收到的数据供排查,partial_input=true 表示数据可能不完整,并不表示任务可以继续解析;保留文件仍受缓存策略约束。联系支持时提供 token 和错误码,无需发送 API Key。

成功后收费与待付款

  • 价格与来源:普通文档 0.05 元 × 请求解析页数;单元素 0.01 元/次。本地余额优先,不足时使用符合条件的 Bohrium 钱包。恢复付款沿用原任务的金额和付款来源。
  • 收费时机:提交时检查余额,不预占资金;解析失败不收费。成功后保存结果并扣款,确认付款后才开放结果并发送成功回调。
  • 响应处理:准入余额不足返回 402;无法确认钱包余额返回 503,可稍后重试。同步提交也可能返回 202、status=waiting、payment_pending=true。查询返回 200 也不一定完成,须检查 status。
  • 继续查询:用同一账号和 token 调用 /get-result、/get-formatted 或 /get-third-party-output,可触发已完成任务的付款恢复,无需重传文件。仅订阅 /task-events 不会触发此恢复。余额不足时补足原付款来源;付款未知时只对账,不盲目重扣。只读余额复查默认间隔 60 秒,付款失败后可能进一步退避。
  • 结果保留:明确未付款结果默认保留 7 天,到期返回 UNPAID_RESULT_EXPIRED;付款未知任务继续保留并对账。客户端超时不等于解析失败,请先查询原 token。

User Authentication

UniParser-API uses the X-API-Key request header. On the UniParser homepage, sign in with Bohrium (玻尔登录) for one-click authorization to obtain an API-Key (a trial balance is granted on first sign-in), or paste an existing API-Key directly. For higher quotas, broader permissions, or a long-term account, please contact us.

Payment is collected after successful parsing; results are released after payment confirmation. See “Success-only billing and pending payment” below for pricing, responses, and recovery.

# Generate a UUID once per new task; keep this variable for result queries (requires Python 3).
uniparser_token="$(python3 -c 'import uuid; print(uuid.uuid4().hex)')"
curl -X POST "https://uniparser.dp.tech/trigger-file-async" \
  -H "X-API-Key: your_api_key" \
  -F "token=${uniparser_token}" \
  -F "file=@example.pdf" \
  -F "sync=true"

Store the key in an environment variable such as UNIPARSER_API_KEY instead of hard-coding it in source code.

Request Format

Endpoint Request format Notes
/trigger-file-async multipart/form-data Upload a PDF in the file field; other parameters are also form fields
/trigger-snip-async / /trigger-url-async JSON body Image snippet or URL parsing requests
/trigger-item-async application/x-www-form-urlencoded Individual-element parsing with Base64 img; see the example
/get-result / /get-formatted / /get-third-party-output JSON body (POST) Query status or retrieve the corresponding result format using the original token

Note: token is the unique task identifier. The individual-element endpoint generates it if omitted, but providing and saving one yourself helps recover results after a timeout. For other trigger endpoints, supply a token as shown in their examples. Generate a UUID per new task when calling directly through curl or Python; UniParser-Tools document parsing methods generate tokens automatically.

Duplicate submission reminder: generate a new UUID for each new task and reuse its token when fetching results. Submitting the same token again may return Token is duplicated; after a client timeout, check the original task before resubmitting or starting another task with a new token.

sync controls how the trigger request waits: sync=false is the default asynchronous mode and returns task status plus token immediately, so you fetch results later with the same token; sync=true waits in the submit request until parsing finishes or times out, which is convenient for examples, debugging, and small files. For large files or batch processing, prefer async mode and set timeout according to task size (default: 1800 seconds).

Task status and progress

HTTP status describes request handling, status describes the task, and billing_status describes billing. They are not interchangeable. undefined is an existing task status; success-only billing adds billing stages and waiting descriptions.

status Meaning and action
undefined Receiving or preparing the task, or no parser progress is available yet; keep the token and poll
waiting Waiting for initialization, parsing, or payment confirmation; check billing fields for context
processing Parsing; show progress when available and continue polling
success Results are available; payment is confirmed when success-only billing is enabled
error The task failed; inspect the error description and code rather than polling indefinitely

For example, this response is a waiting state, not a parse failure or evidence of insufficient funds or a completed charge:

{
  "status": "undefined",
  "description": "等待解析或付款完成",
  "billing_status": "awaiting_parse",
  "message": null,
  "proc_page": null,
  "total_page": null
}

The description means “Waiting for parsing or payment to complete.” awaiting_parse means a quote is saved for collection after successful parsing; it may remain throughout parsing. created / preordering / paying describe collection in progress, payment_unknown an unconfirmed payment outcome, and paid confirmed payment. declined can mean insufficient funds, a failed parse, or expiry; check status, billing_code, and the description together.

  • Missing or null page counters mean progress is unavailable, not zero pages or failure. Calculate a percentage only with valid numeric counters and a positive total. Even 100% does not establish result availability.
  • payment_pending=true means payment is not yet confirmed. This field may be absent; absence does not establish payment. message may also be null.
  • description / message are display text and may change. Do not match their wording to determine status; tolerate additional response fields.
  • Query with the original account and token. Read results only on success; handle error as a failure. For an unknown status, keep the token and record the response rather than resubmitting. Contact support with the token if waiting persists.

After a definite payment refusal, topping up or only waiting for a webhook does not retry payment. Use the original account and token with POST /get-result, POST /get-formatted, or POST /get-third-party-output to trigger recovery.

Oversized upload compatibility change: the response is now HTTP 413 (previously 400), and the description has changed. Identify it by error_code="FILE_SIZE_EXCEEDED", not the old status code or description text.

Parsing Options SemanticType

When submitting a parsing task, you can control these semantic element fields:

Stage note: SemanticType and ParseMode / ParseModeTextual belong to the submit stage. They decide what to parse and at what quality; do not use them in /get-formatted or get_formatted.

Field Meaning Available modes
textual Prose text, headings, footnotes, etc. 0 / 1 / 2 / 3 / -1 / -3
equation Display mathematical equations 0 / 1 / 2 / -1 / -3
table Tables 0 / 1 / 2 / -1 / -3
chart Charts 0 / 1 / -1 / -3
figure Figures, illustrations, photos 0 / 1 / -1 / -3
expression Chemical reaction expressions 0 / 1 / -1 / -3
molecule Chemical molecular structures 0 / 1 / -1 / -3

Value notes: 0 disables parsing, 1 uses fast parsing, 2 uses high-quality parsing, -1 returns the original image as Base64, and -3 uploads the cropped image to TOS and returns a download URL without running OCR for that category. textual also supports 3 for direct text extraction from digital PDFs.

Enum name Value
ParseMode.DumpHosting / ParseModeTextual.DumpHosting -3
ParseMode.DumpBase64 / ParseModeTextual.DumpBase64 -1
ParseMode.OCRFast / ParseModeTextual.OCRFast 1
ParseMode.OCRHighQuality / ParseModeTextual.OCRHighQuality 2
ParseModeTextual.DigitalExported 3 (textual only)

Note: chart, expression, and molecule currently do not have a high-quality mode.

Image Storage in TOS (-3)

Set the desired category when submitting a request, for example figure=-3. All semantic categories listed above support this mode. On success, the result block's source contains an HTTP(S) GET download URL, which is also used in Markdown/HTML output.

URLs expire 7 days after signing by default; the actual expiration is determined by the URL provided by the service. Reading results again does not renew URLs. Download and save images before expiration, and keep signed URLs intact without changing the hostname or query parameters.

If an image upload or download URL generation fails, that block returns the original image as Base64, as in DumpBase64=-1, while other images continue processing. dict_cfg retains the requested mode -3, so a task's source values may contain both URLs and Base64. Handle each block accordingly when consuming results directly; Markdown/HTML automatically converts fallback images to data URIs.

Table Mode: fast vs hq

  • table=1 (fast) returns a combination of a structure template and cell text. You usually need structure, placeholders, and contents together to reconstruct the table: structure describes the table skeleton, placeholders mark cell placeholders, and contents provides the corresponding cell text.
  • table=2 (hq) usually puts the complete table data directly in structure, such as an HTML / Markdown table with text content. In this mode, you generally do not need to stitch cell content back from placeholders and contents.
  • Therefore, fast is better when you want to handle the mapping between table skeleton and cell text yourself; hq is better when you want to consume a complete table structure directly. High-quality mode usually takes longer; if the high-quality service is unavailable, UniParser falls back to an available fast table parser.
  • Table mode only affects table-region structure recognition and cell-content recognition. Table captions, table footnotes, and surrounding body text are mainly controlled by textual; when you want both table text and body text to use higher quality, usually set both table=2 and textual=2.

Output Switches

The task token is used for subsequent result fetching. Use /get-formatted with output switches to choose what to fetch:

Note: result-fetching endpoints use a JSON body. When calling UniParser-API directly, set Content-Type: application/json; omitted fields use default values.

Switch Default Returned field type Description
content true str Formatted full-document content, useful for LLMs, search, and reading
objects false list[dict] Flat semantic block list. Each item includes fields such as class, confidence, float_xyxy, page, and str; useful when coordinates, block types, and block-level content are needed
pages_dict false list[list[dict]] Flattened page-level layout. Each page is a list of layout blocks, useful for page-level structured processing
pages_tree false list[list[dict]] Page-level tree layout that preserves parent-child hierarchy, useful when hierarchical structure is needed
molecule_source false Control option Keeps original molecule source information in structured outputs. It defaults to disabled to reduce response size; when disabled, molecule block source is cleared
marginalia true Control option Controls whether marginal / side-bar information is kept in formatted output. It defaults to enabled to avoid dropping source-document information

Output FormatFlag

/get-formatted can specify output formats for these semantic element fields: textual, table, molecule, chart, figure, expression, and equation.

Stage note: FormatFlag belongs to the result-fetching stage. It only controls the format of returned text; do not use it in trigger requests or trigger_file.

Value Name Meaning Example
plain Plain Plain text, no markers ATP inhibits ATR.
markup Markup Marker-wrapped text, default \begin{paragraph}ATP inhibits ATR.\end{paragraph}
markdown Markdown Markdown, suitable for LLMs and documents ## Results, - IC50: 0.5 nM
latex Latex LaTeX, especially useful for equations $E = mc^2$
html Html HTML, especially useful for tables <table>...</table>

Structured outputs such as objects, pages_dict, and pages_tree are not affected by FormatFlag; formatting mainly applies to text fields in content and objects.

Common Layout Types LayoutType

In objects, pages_dict, and pages_tree, each parsed block has a type field describing what the block represents on the page.

Type Meaning Usually belongs to
documenttitle Document title textual
title Section heading textual
paragraph Main body paragraph textual
abstract Abstract textual
reference Reference entry textual
table Table body table
tablecaption / tablefootnote Table caption / footnote textual, semantically attached to a table
equation / equationinline Display / inline equation equation
molecule / moleculeid Molecular structure / molecule label molecule or related text
figure / image Figure, illustration, photo, or image region figure
figurecaption / imagecaption Figure / image caption textual, semantically attached to an image
expression / expressioncaption Chemical reaction expression / caption expression or related text
chart / legend Chart / legend chart or related text
pageheader / pagefooter / pagenumber Header, footer, page number Marginal information
group / tablegroup / figuregroup / moleculegroup Group node Structural node, common in pages_tree

type is a result label. It is not the same layer as parsing options such as textual, table, or molecule.

API And Frontend Limits

UniParser checks both API account quotas and frontend upload limits. API limits depend on account type, permissions, and approved quota configuration, and apply to direct uploads as well as URL/object-storage downloads. Frontend limits only apply to uploads through the web page and do not represent the final parsing quota for direct API calls. URL/object-storage downloads are also constrained by the server-wide download limit; the stricter account or server limit is used.

Limit type Applies to Default limit Notes
API file size / page count Visitor standard accounts 200 MB, 2000 pages Requests beyond the quota return file-size or page-count limit errors
API file size / page count Paid users / accounts with higher quotas Default 300 MB, 6000 pages The actual quota follows the API application document or account provisioning configuration and can be adjusted on request
Frontend upload size Web upload page 300 MB This only limits files uploaded from the frontend; direct API calls are still governed by the account API quota

Request-rate limits are enforced by account, endpoint, and server-side configuration. When a request is rate-limited, the API returns 429, usually with the specific limit that was hit. For batch jobs, prefer asynchronous submission, control concurrency, and use backoff before retrying. If you need higher request throughput or larger file quotas, include that requirement in the API permission request.

Error Codes ErrorFlag

Category Common errors Meaning What to do
Request parameter errors 400 Token_Required: missing token parameter
Token_Invalid: token contains invalid characters; only letters, numbers, underscores, and hyphens are allowed
Token_Duplicated: token already exists and the task is not finished
File_Required: upload file is missing
File_Invalid: invalid PDF or zero-page PDF
URL_Invalid: URL is invalid, unreachable, or does not return a supported PDF/image format
Request_Invalid: request parameter format or value is invalid
Required parameters, file content, URL accessibility, or field values are invalid Fill in required fields; generate a new unique token for native API calls; verify the file opens, the URL downloads, and field values match the docs
Parsing status errors 400 Status_Not_Found: no status file found for the token
Status_Decode_Failed: status JSON is corrupted or cannot be decoded
Result_Not_Found: parsing result file does not exist
Result_Decode_Failed: result JSON is corrupted or cannot be decoded
Usually means the task does not exist, the result was cleaned up, the task failed, or server-side cache files are abnormal Make sure you use the same token returned at submission; wait for async tasks to finish before fetching; contact support with the token if results remain missing; verify the original task and payment before resubmitting
Language and page errors 400 Lang_Unknown: document language cannot be detected
Lang_Not_Supported: the language is not supported by the OCR / parsing flow
Pages_Required: page selection is missing for endpoints that require it
Document language, scan quality, or page selection does not meet parsing requirements Check that the document is readable; provide pages when required; improve scan quality or use a supported-language document
User limit errors 400 File_Size_Exceeded: file size exceeds account limits
PDF_Pages_Exceeded: PDF page count exceeds account limits
File_Type_Not_Allowed: file type is not allowed
Domain_Not_Allowed: URL download domain is not allowed
Related to account permissions, file size, page count, file type, or domain allowlist Compress or split the file; use an allowed file type or domain; contact us for higher quotas or broader permissions
System and processing errors 400/500 OS_Error: server-side file I/O, path, permission, or system resource error (500 from the URL download endpoint)
Process_Failed: parsing subprocess failed, possibly caused by the model, input file, or runtime environment
File I/O, model service, or task process failed; OS_Error does not mean the user URL is invalid Keep the token and error response, retry later, and report the file, token, and error details if it keeps failing
Authentication and authorization 401/402/403 Authentication required: missing Authorization or X-API-Key header
Authentication failed: JWT Token or API-Key is invalid / expired
Insufficient balance: account balance is not enough
Administrator privileges required: endpoint requires admin privileges
Missing permission: account lacks specific parsing permissions
Headers, API-Key, balance, or permissions are insufficient Check that X-API-Key is correct, unexpired, and has balance; contact us for administrator or special parsing permissions
Rate limit errors 429 Rate limit exceeded: <limit>: global or endpoint limit exceeded
Rate limit exceeded, <user_rate_limit>: user-level rate limit exceeded
Request frequency or concurrency exceeds limits Reduce concurrency and retry frequency, add backoff, queue batch jobs, or request a higher rate limit

File and download failures

An undetermined page count may return 422 / INVALID_PAGE_SELECTION; this does not indicate a charge. Use pdf_error_code to distinguish empty files, password requirements, non-PDF content, missing pages, and open failures. Submit a complete, readable, password-free file after correcting the problem; see description / message for details.

Download failures use error_code to distinguish timeouts, size limits, connection failures, and storage errors. input_retained=true means received bytes were kept for diagnosis; partial_input=true means they may be incomplete, not that parsing can proceed. Retained inputs remain subject to cache policy. Give support the token and error code, never your API Key.

Success-only billing and pending payment

  • Price and source: Documents cost CNY 0.05 × requested pages; individual-element parsing costs CNY 0.01 per request. Local balance is preferred, followed by an eligible Bohrium wallet. Recovery keeps the original amount and payment source.
  • Collection: Submission checks funds without reserving them. Failed parses are not charged. Successful results are saved before collection and released, with success callbacks, only after payment confirmation.
  • Responses: Insufficient funds at admission return 402; an unavailable wallet balance check returns 503 and can be retried later. Even synchronous submission may return 202, status=waiting, and payment_pending=true. A result query returning 200 is not necessarily complete: check status.
  • Polling: Use the same account and token with /get-result, /get-formatted, or /get-third-party-output to trigger payment recovery for completed tasks without uploading again. Subscribing only to /task-events does not trigger this recovery. Top up the original payment source if needed. Unknown payments are reconciled, not blindly charged again. Read-only balance checks default to a 60-second interval; payment failures may back off further.
  • Retention: Definitively unpaid results are retained for 7 days by default, then report UNPAID_RESULT_EXPIRED. Unknown payments remain pending for reconciliation. A client timeout does not establish a parsing failure: query the original token first.
V.

常见问题

解答调用方式、任务状态、限制额度和结果字段等常见疑问。

token 是什么,为什么必须提供唯一 token?

token 是解析任务的唯一索引,用于查询状态和获取结果。原生 API 调用时需要自行保证唯一性,推荐使用 UUID;如果复用未完成任务的 token,可能返回 Token_Duplicated。

如何获取 API Key?支持玻尔登录吗?

在 UniParser 主页通过玻尔登录一键授权即可获取 X-API-Key,首次登录会自动发放试用额度;如果已经有 Key,可在「输入已有 API Key」处直接填入。原验证码访客注册已下线,统一使用玻尔登录。请求时在请求头携带 X-API-Key: <你的 Key>。

如何计费?余额和可解析页数怎么看?

普通文档按 0.05 元 × 请求解析页数 收费,单元素解析为 0.01 元/次;解析失败不收费。本地余额(含试用额度)优先,不足时使用符合条件的 Bohrium 钱包。余额可在主页认证区或 /billing/profile 查看。

为什么返回 undefined 和“等待解析或付款完成”?

这是未完成状态,不是报错。billing_status=awaiting_parse 表示已保存报价,等待解析成功后收款,不表示余额不足或已扣款。进度字段为 null 表示暂无进度。请保留原 token 继续查询,不要重新上传;只在 status=success 时读取结果,error 时检查错误原因。不要依赖 description 文案判断状态,完整字段说明见 API 参考的“任务状态与进度”。

已解析完成,为什么还在等待?需要重新提交吗?

可能正在等待付款或确认付款。提交前余额明确不足返回 402,无法确认钱包余额返回 503;解析完成后余额不足会保留结果待付款。即使同步提交也可能返回 202 和 payment_pending=true,这不是上传失败。补足原付款来源的余额,并用同一账号和 token 查询 /get-result、/get-formatted 或 /get-third-party-output,无需重新上传。客户端超时或付款未知时也先查询原 token,避免重复提交。明确未付款结果默认保留 7 天。

应该使用 UniParser-Tools 还是 UniParser-API?

优先使用 UniParser-Tools。它会自动处理 token 生成、任务提交、轮询和结果获取,适合脚本、批处理和 notebook。只有在需要直接控制 HTTP 请求、鉴权、回调、并发或字段开关时,才建议使用原生 UniParser-API。

sync=true 和 sync=false 怎么选?

sync=true 会在提交请求中等待解析完成,适合小文件、调试和示例。大文件、批处理或高并发任务建议使用默认异步模式 sync=false,提交后保存返回的 token,稍后调用结果接口获取内容。

文件超过限制怎么办?

访客标准账号默认限制为 200 MB、2000 页;付费用户或已开通高额度的账号默认限制为 300 MB、6000 页,具体以 API 申请和账号配置为准。超过限制时可以压缩或拆分 PDF,或申请更高额度。

触发 429 限速怎么办?

当前 rate limit 使用近似滑动窗口机制。触发限速时接口会返回 429,表示当前用户、接口或全局入口的请求频率超过了服务端配置。

逐用户生效的限速主要覆盖两类 API:

  • 解析请求 API:例如提交 PDF、URL、截图/图片解析的接口,会按照账号配置中的速率 S 限速。
  • 结果获取 API:例如获取状态、格式化结果、段落或视图结果的接口,也会逐用户限速;这类接口的限速通常比解析提交接口宽松很多,便于轮询和批量取结果。

另外,部分管理类、信息获取类或公共入口 API 会有全局限速。全局限速不区分用户,主要用于避免异常流量导致系统后端过载。

客户端侧建议使用令牌桶控制并发请求:令牌以速率 R 放入桶中,桶容量为 B;每次请求先消耗一个令牌,没有令牌时排队或等待。这样可以平滑批量请求,避免瞬时并发打满服务端限速。

        令牌生成器(速率 R)
              |
              v   (不断放入令牌)
        +-------------+
        | 令牌桶       |  最大容量 B
        | o o o       |
        +-------------+
              |
              v   (请求到达,消耗令牌)
        [ 待发送请求 ] --------> [ 允许通过 ]

如果仍然频繁触发 429,请降低提交频率和并发数,并在重试时增加退避等待。批量任务建议排队异步提交;如果业务需要更高吞吐,可以申请更高请求频率限制。

content、objects、pages_dict、pages_tree 有什么区别?

content 返回格式化后的全文,适合阅读、检索和 LLM 输入。objects 返回扁平语义块列表,适合按块处理坐标、类型和文本。pages_dict 按页返回扁平布局。pages_tree 按页返回树形结构,适合需要父子层级关系的场景。

表格结果应该看哪个字段?

如果只需要可读文本,通常直接获取 content,并把 table 输出格式设为 markdown 或 html。如果需要结构化表格对象,请查看 objects、pages_dict 或 pages_tree 中的表格块。table=1(fast)通常需要结合 structure、placeholders、contents 还原表格;table=2(hq)通常在 structure 中直接包含完整表格数据。

textual 和 table 都要设置吗?

需要根据目标分别设置。table 控制表格区域的结构识别和单元格内容识别;表题、表注、正文段落等主要受 textual 控制。如果希望正文和表格都尽量高质量,通常同时设置 textual=2 和 table=2。

What is token, and why must it be unique?

token is the unique index for a parsing task and is used to query status and fetch results. Native API callers must ensure uniqueness, preferably with UUIDs. Reusing a token for an unfinished task may return Token_Duplicated.

How do I get an API Key? Is Bohrium sign-in supported?

Sign in with Bohrium (玻尔登录) on the UniParser homepage for one-click authorization to obtain an X-API-Key; a trial balance is granted on first sign-in. If you already have a key, paste it under "enter an existing API Key". The former captcha-based visitor registration has been retired in favor of Bohrium sign-in. Send the key on every request via the X-API-Key: <your key> header.

How is usage billed, and how do I check my balance?

Documents cost CNY 0.05 × the number of requested pages; individual-element parsing costs CNY 0.01 per request. Failed parses are not charged. Local balance (including trial credit) is used first, followed by an eligible Bohrium wallet if needed. Check balances in the homepage auth panel or /billing/profile.

Why does the response say undefined and “等待解析或付款完成”?

This is an unfinished state, not an error. billing_status=awaiting_parse means a quote is saved for collection after successful parsing, not insufficient funds or an existing charge. Null counters mean progress is unavailable. Keep querying the original token without re-uploading; read results only on status=success, and inspect the error on error. Do not branch on description text. See “Task status and progress” in the API reference.

Why is a completed parse still waiting? Should I resubmit?

Payment may be pending or awaiting confirmation. Before parsing, insufficient funds return 402; an unavailable wallet balance check returns 503. If funds become insufficient after parsing, the result is retained for payment. Even synchronous submission may return 202 with payment_pending=true; this is not an upload failure. Top up the original payment source and query /get-result, /get-formatted, or /get-third-party-output with the same account and token. No re-upload is needed. After a client timeout or an unknown payment outcome, query the original token rather than resubmitting. Definitively unpaid results are retained for 7 days by default.

Should I use UniParser-Tools or UniParser-API?

Use UniParser-Tools by default. It handles token generation, task submission, polling, and result fetching for you, which is suitable for scripts, batch jobs, and notebooks. Use the native UniParser-API only when you need direct control over HTTP requests, authentication, callbacks, concurrency, or field switches.

How should I choose between sync=true and sync=false?

sync=true waits for parsing to finish in the submit request. It is useful for small files, debugging, and examples. For large files, batch jobs, or high-concurrency workloads, use the default async mode sync=false, store the returned token, and fetch the result later.

What should I do if my file exceeds the limit?

Visitor standard accounts are limited to 200 MB and 2000 pages by default. Paid users or accounts with higher quotas default to 300 MB and 6000 pages, with the actual quota determined by the API application and account provisioning configuration. Compress or split the PDF, or request a higher quota.

What should I do after a 429 rate-limit response?

The current rate limit is implemented as an approximate sliding-window mechanism. A 429 response means the request rate has exceeded the server-side limit for the current user, endpoint, or global entry point.

User-level rate limits mainly apply to two groups of APIs:

  • Parsing request APIs: endpoints that submit PDF, URL, snip, or image parsing tasks. These are limited according to the account rate S.
  • Result retrieval APIs: endpoints that fetch task status, formatted results, paragraphs, or view data. These are also limited per user, but their limits are usually much more tolerant than the parsing submission rate so clients can poll and fetch batch results.

Some management, information retrieval, or public-entry APIs also have global rate limits. Global limits are not user-specific; they protect the backend from overload caused by abnormal traffic.

For client-side concurrency control, we recommend using a token-bucket algorithm. Tokens are added to the bucket at rate R, and the bucket capacity is B. Each request consumes one token before it is sent; if no token is available, the request should wait or remain queued. This smooths bursty batch traffic and avoids hitting server-side rate limits.

        Token generator (rate R)
              |
              v   (adds tokens continuously)
        +-------------+
        | Token bucket |  max capacity B
        | o o o       |
        +-------------+
              |
              v   (incoming request consumes a token)
        [ Pending request ] --------> [ Allowed ]

If you still hit 429 frequently, reduce submission frequency and concurrency, and add backoff before retrying. For batch jobs, queue tasks and submit them asynchronously. If your business requires higher throughput, request a higher rate limit.

What is the difference between content, objects, pages_dict, and pages_tree?

content returns formatted full-document text, suitable for reading, search, and LLM input. objects returns a flat semantic block list for block-level coordinates, types, and text. pages_dict returns flattened page-level layouts. pages_tree returns page-level trees when parent-child hierarchy is needed.

Which field should I use for table results?

If you only need readable text, fetch content and set the table output format to markdown or html. If you need structured table objects, inspect table blocks in objects, pages_dict, or pages_tree. With table=1 (fast), you usually reconstruct tables from structure, placeholders, and contents; with table=2 (hq), structure usually contains the complete table data directly.

Should I set both textual and table?

Set them according to what you need. table controls table-region structure recognition and cell-content recognition; table captions, table footnotes, and body paragraphs are mainly controlled by textual. If you want both body text and tables to use higher quality, usually set both textual=2 and table=2.

VI.

风险提示

在生产环境使用解析结果前,请了解模型能力、输出限制和结果留存规则。

以下风险适用于在线页面、UniParser-Tools 和 UniParser-API。请在接入生产流程前充分评估,并根据业务要求增加人工复核或自动校验。

1. 高质解析可能产生幻觉

高质解析模式依赖生成式模型理解和重建文档内容。文本、表格、公式、图表、图片、反应式、分子等模块都可能输出看似合理、但与原文不一致的内容,包括遗漏、误识别、错误关联或模型自行补全的信息。

解析结果不应作为科研结论、合规审查、医疗判断、财务决策等高风险场景的唯一依据。使用关键字段、数字、公式、名称和结构前,请与原始文档逐项核对。

2. 高质表格解析不提供单元格位置信息

高质表格解析侧重恢复表格语义和结构,不提供每个单元格在原始页面中的精确位置信息。若下游流程依赖单元格坐标、页面回标、区域高亮或坐标级审计,请勿假定高质模式的表格结果包含这些字段,应选择明确提供位置信息的处理方式并提前验证输出结构。

3. 图表解析质量可能不稳定

图表解析可能无法准确恢复图中的标签、图例、坐标轴、数据点和趋势。低分辨率图片、密集刻度、重叠曲线、多子图、三维图、非常规比例尺或复杂配色会进一步降低质量,并可能产生错误的数值或文字描述。

图表解析结果仅适合作为辅助信息。涉及精确数值、趋势判断或后续计算时,请对照原图人工复核;未经校验,不建议直接用于自动决策或数据入库。

4. 高质解析速度更慢

高质模式通常需要更多模型推理,因此解析速度会低于快速模式。实际耗时还会受到文档页数、启用模块、页面复杂度和服务负载影响。长文档或批量任务建议使用异步提交,并合理设置轮询、回调和超时策略。

5. 解析结果有保留期限

普通结果按服务部署的缓存期限清理,请以所用服务的保留策略为准。成功后收费模式下,明确未付款的成功结果默认保留 7 天;付款未知的任务继续保留待对账。超过适用保留期并被清理后,将无法继续预览或获取结果,原 token 不是长期存储凭证。

请在任务完成后及时下载并保存所需结果。Uni-Parser 在线服务不应被用作结果归档或长期存储系统。

The following risks apply to the online interface, UniParser-Tools, and UniParser-API. Evaluate them before integrating the service into production, and add human review or automated validation as required by your use case.

1. High-quality parsing may hallucinate

High-quality modes use generative models to interpret and reconstruct document content. Every module—including text, tables, equations, charts, figures, reactions, and molecules—may return plausible-looking content that differs from the source, such as omissions, misrecognition, incorrect associations, or model-generated additions.

Parsing output must not be the sole basis for high-risk uses such as scientific conclusions, compliance reviews, medical judgments, or financial decisions. Verify critical fields, numbers, equations, names, and structures against the source document.

2. High-quality table parsing does not provide cell positions

High-quality table parsing focuses on recovering table semantics and structure. It does not provide the precise source-page position of each cell. If a downstream workflow requires cell coordinates, page overlays, region highlighting, or coordinate-level auditing, do not assume these fields are present. Select a processing method that explicitly provides position data and validate its output structure first.

3. Chart parsing quality may be unreliable

Chart parsing may fail to recover labels, legends, axes, data points, and trends accurately. Low-resolution images, dense ticks, overlapping curves, multi-panel or 3D charts, unusual scales, and complex color schemes further reduce quality and may lead to incorrect values or descriptions.

Treat chart parsing output as supporting information only. Verify precise values and trend interpretations against the original chart before calculations, automated decisions, or data ingestion.

4. High-quality parsing is slower

High-quality modes generally require more model inference and are therefore slower than fast modes. Processing time also depends on document length, enabled modules, page complexity, and service load. Use asynchronous submission for long documents or batch workloads, with suitable polling, callback, and timeout strategies.

5. Results have a retention limit

Ordinary results follow the deployment’s cache retention policy; check the policy for your service. With success-only billing, successful but definitively unpaid results are retained for 7 days by default; unknown payments remain pending for reconciliation. Once the applicable retention period ends and results are cleaned up, they can no longer be previewed or retrieved. The original token is not a long-term storage reference.

Download and store required results promptly after completion. The Uni-Parser online service is not a result archive or long-term storage system.