> ## Documentation Index
> Fetch the complete documentation index at: https://docs.textin.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 文档解析 - Parse

> 了解 xParse 中的文档解析模块，将非结构化文档转换为结构化元素

## 概念

文档解析是将非结构化文件内容提取并转换为结构化[文档元素](/pipeline/elements-metadata)的过程。

与简单将文件视为纯文本不同，xParse 通过解析保留了文件的语义结构，让您能够在后续处理流程中进行更灵活的控制，并能充分考虑文件的结构特点。同时，通过将不同文件格式统一转换为 xParse 的元素类型，无论源文件是什么格式，您都可以在下游采用相同的方式处理。

## 用途

文档解析的主要用途：

* **内容提取**：从 PDF、WORD、EXCEL、PPT、图片等[多种格式](/pipeline/sources/overview#支持的文件格式)中提取文本和其他内容
* **结构化转换**：将提取的内容转换为标准化的文档元素，便于后续处理
* **语义保留**：保留文档的语义结构，如标题、段落、表格等
* **格式统一**：将不同格式的文档统一转换为相同的元素结构

## 参数说明

### provider

**类型**: `string` <br />
**必填**: 是 <br />
**默认值**: `textin` <br />
**可选值**: `textin` | `textin-lite` | `mineru` | `paddle`

Parser 解析引擎选择：

* **textin**: TextIn 自研高性能解析引擎，在速度、准确性上均为行业领先，适合大多数场景（推荐）
* **textin-lite**: TextIn 全文识别解析引擎，适合纯文本、表格图片、电子档 pdf 等场景，速度更快，价格更低
* **mineru**: MinerU 解析引擎，在学术论文等场景表现优异
* **paddle**: PaddleOCR 解析引擎，在多语言和复杂文档场景（如PPT）表现优异

更多先进引擎正在陆续支持中，敬请期待。

### pdf\_pwd

**类型**: `string` <br />
**必填**: 否

PDF 密码。当 PDF 为加密文档时，需要提供密码。

<Warning>
  **安全提示**：对前端封装该接口参数时，需要自行对密码进行安全防护。
</Warning>

### page\_ranges

**类型**： `string` <br />
**必填**: 否

指定解析页码范围，格式为逗号分隔的字符串。

* **15**: 只解析第 15 页
* **20-25**: 解析第 20 页到第 25 页
* **1,3,5-7**: 解析第 1、3、5、6、7 页

### crop\_dewarp

**类型**: `integer` <br />
**必填**: 否 <br />
**默认值**: `0` <br />
**可选值**: `0` | `1` <br />

是否进行切边矫正预处理，默认为0，不进行切边矫正。

* **0**: 不进行切边矫正
* **1**: 进行切边矫正

### remove\_watermark

**类型**: `integer` <br />
**必填**: 否 <br />
**默认值**: `0` <br />
**可选值**: `0` | `1`

是否进行去水印预处理，默认为0，不去水印。

* **0**: 不去水印
* **1**: 去水印

### get\_page\_image

**类型**: `boolean` <br />
**必填**: 否 <br />
**默认值**: `false` <br />

是否返回每一页的图片，适用于PDF等需要转成图片解析的文件。当设置为 `true` 时，返回结果中会包含 `page_image_url` 字段。

### get\_sub\_image

**类型**: `boolean` <br />
**必填**: 否 <br />
**默认值**: `false` <br />

是否返回页面内的子图。当设置为 `true` 时，返回结果中会包含 `image_base64` 字段。

### image\_storage\_config

**类型**: `object` <br />
**必填**: 否 <br />

S3存储配置，用于存储每页的图片。如果缺省，默认托管在xParse后台，通过xParse提供的链接下载图片。

**字段说明**：

* `endpoint` (string): S3端点地址，例如 `"https://s3.oss-cn-beijing.aliyuncs.com"`
* `access_key` (string): S3访问密钥
* `secret_key` (string): S3密钥
* `bucket` (string): S3存储桶名称
* `region` (string): S3区域，例如 `"cn-beijing"`
* `prefix` (string): 存储前缀，默认为空字符串
* `url_prefix` (string): 自定义配置图片下载服务URL前缀。xParse会将图片存储到目标S3，每张图片拥有唯一的hash\_id，通过 `url_prefix + hash_id` 即可下载图片

### Textin 引擎特定参数（provider = textin 时）

#### parse\_mode

**类型**: `string` <br />
**必填**: 否 <br />
**默认值**: `scan` <br />
**可选值**: `auto` | `scan`

pdf文档的解析模式，默认为scan模式。图片不用设置，均默认按scan模式处理。

* auto: 综合文字识别和解析模式：对pdf电子档解析，会直接提取pdf中的文字
* scan: 仅按文字识别模式：将pdf当成图片处理

#### underline\_level

**类型**: `integer` <br />
**必填**: 否 <br />
**默认值**: `0` <br />
**可选值**: `0` | `1` |

控制下划线识别范围。

* **0**: 不识别
* **1**: 仅识别无文字的下划线（仅 scan 模式可用）

#### apply\_chart

**类型**: `integer` <br />
**必填**: 否 <br />
**默认值**: `0` <br />
**可选值**: `0` | `1`

图表识别。是否开启图表识别，开启图表识别会将识别到的图表以表格形式输出。

* **0**: 不开启图表识别
* **1**: 开启图表识别

### MinerU 引擎特定参数（provider = mineru 时）

xParse 支持 MinerU vlm 模型，除了上述通用参数，xParse 内部会将其余参数设置为默认值，暂时不支持用户自定义，具体参数请参考[MinerU API 文档](https://mineru.net/apiManage/docs)。

### Paddle 引擎特定参数（provider = paddle 时）

xParse 支持 PaddleOCR-VL 模型，除了上述通用参数，xParse 内部会将其余参数设置为默认值，暂时不支持用户自定义，具体参数请参考[PaddleOCR API 文档](https://ai.baidu.com/ai-doc/AISTUDIO/2mh4okm66)。

## 输出结果说明

parse 阶段返回一个[文档元素](/pipeline/elements-metadata)列表。每个元素包含以下字段：

* **element\_id**: 元素的唯一标识符（文本+坐标+页码+文件名的 SHA-256）
* **type**: 元素类型（如 `NarrativeText`、`Title`、`Table` 等）
* **text**: 提取的文本内容
* **metadata**: 元数据信息，常见字段包括：
  * `filename` / `filetype`
  * `last_modified`
  * `page_number` / `page_width` / `page_height`
  * `coordinates`：8位数组，表示四边形四个点，归一化坐标，范围 \[0, 1]
  * `parent_id` / `category_depth`
  * `image_base64` / `image_mine_type`：`image_base64` 当开启 `get_sub_image` 时返回
  * `page_image_url`：当开启 `get_page_image` 时返回，表示页面图片的下载链接。如果开启预处理参数，返回的是预处理后的页面图片
  * `original_image_url`：仅在开启预处理参数（`crop_dewarp=1`或`remove_watermark=1`）时返回，表示未经预处理的原始页面图片链接
  * `figure_caption_id`：当元素为图片时（`type=Image`），表示图片对应的标题元素id（`type=FigureCaption`）
  * `text_as_html`：表格或富文本元素的HTML表示
  * `data_source` ：数据源详细信息

## 返回结果示例

```json theme={null}
{
    "code": 200,
    "message": "success",
    "x_request_id": "81017abf0fdd3f63ca5c42872cd09a0b",
    "data": {
        "elements": [
            {
                "element_id": "13a9939f23e485ca20a16c741658bcf64efd82309a6f0a8cf35679a65b2fd0dc",
                "type": "NarrativeText",
                "text": "xParse 是一个端到端文档处理 AI 基础设施，致力于将非结构化文档高效转化为可查询、可分析的向量数据资产。",
                "metadata": {
                    "filename": "example.pdf",
                    "filetype": "application/pdf",
                    "last_modified": "1758624866230",
                    "page_number": 1,
                    "page_width": 1191,
                    "page_height": 1684,
                    "parent_id": "23a9939f23e485ca20a16c741658bcf64efd82309a6f0a8cf35679a65b2fd0dc",
                    "category_depth": 1,
                    "coordinates": [0.1822, 0.2316, 0.6717, 0.2316, 0.6717, 0.2732, 0.1822, 0.2732],
                    "text_as_html": "<p>...</p>",
                    "data_source": {
                        "record_locator": {
                            "protocol": "file",
                            "remote_file_path": "/projects/demo/example.pdf"
                        },
                        "url": "file:///projects/demo/example.pdf",
                        "version": "1758624866230967485",
                        "date_created": "1764555574237",
                        "date_modified": "1758624866230",
                        "date_processed": "1764742970688"
                    }
                }
            },
            // ... more elements
        ]
    },
}
```

更多返回结果示例请参考[文档元素和元数据](/pipeline/elements-metadata)。

## 使用示例

### 示例 1：基础解析配置

```python theme={null}
from xparse_client import (
    Pipeline,
    LocalSource,
    LocalDestination,
    Stage,
    ParseConfig
)

# 创建数据源
source = LocalSource(
    directory='./documents',
    pattern=['*.pdf']
)

# 创建目标存储
destination = LocalDestination(
    output_dir='./output'
)

# 创建解析配置
parse_config = ParseConfig(
    provider='textin',
    parse_mode='auto'
)

# 创建 Pipeline
pipeline = Pipeline(
    source=source,
    destination=destination,
    api_base_url='https://api.textin.com/api/xparse',
    api_headers={
        'x-ti-app-id': 'your-app-id',
        'x-ti-secret-code': 'your-secret-code'
    },
    stages=[
        Stage(
            type='parse',
            config=parse_config
        )
    ]
)

pipeline.run()
```

### 示例 2：解析加密 PDF

```python theme={null}
from xparse_client import ParseConfig

# 创建解析配置，包含 PDF 密码
parse_config = ParseConfig(
    provider='textin',
    pdf_pwd='your-password'  # 提供 PDF 密码
)

# 在 Pipeline 中使用
# pipeline = Pipeline(
#     source=source,
#     destination=destination,
#     stages=[
#         Stage(type='parse', config=parse_config)
#     ],
#     # ... 其他配置
# )
```

### 示例 3：仅解析特定页面

```python theme={null}
from xparse_client import ParseConfig

# 创建解析配置，指定解析页面范围
parse_config = ParseConfig(
    provider='textin',
    page_ranges='5-7'  # 解析第 5 页到第 7 页
)

# 在 Pipeline 中使用
# pipeline = Pipeline(
#     source=source,
#     destination=destination,
#     stages=[
#         Stage(type='parse', config=parse_config)
#     ],
#     # ... 其他配置
# )
```

### 示例 4：使用图片存储功能

```python theme={null}
from xparse_client import ParseConfig

# 创建解析配置，启用图片存储功能
parse_config = ParseConfig(
    provider='textin',
    get_page_image=True,  # 返回页面图片
    get_sub_image=True,    # 返回子图
    image_storage_config={
        'endpoint': 'https://s3.oss-cn-beijing.aliyuncs.com',
        'access_key': 'your-access-key',
        'secret_key': 'your-secret-key',
        'bucket': 'your-bucket-name',
        'region': 'cn-beijing',
        'prefix': '',
        'url_prefix': 'https://your-file-server.com/download?filename='
    }
)

# 在 Pipeline 中使用
# pipeline = Pipeline(
#     source=source,
#     destination=destination,
#     stages=[
#         Stage(type='parse', config=parse_config)
#     ],
#     # ... 其他配置
# )
```

## Parse API说明

xParse提供了三种方式使用Parse功能：

### 1. Pipeline中的Parse节点

在Pipeline API中使用Parse作为第一个stage，可以与其他stage（chunk、embed、extract）组合使用。

**适用场景**：

* 需要组合多个处理阶段（parse + chunk + embed）
* 需要批量处理文档
* 需要将结果存储到向量数据库

**API文档**：[Pipeline API](/api-reference/endpoint/pipeline)

### 2. Parse同步API

直接调用Parse API，立即返回解析结果。

**适用场景**：

* 只需要文档解析功能
* 需要同步获取结果
* 处理单个文档

**API文档**：[Parse同步API](/api-reference/endpoint/parse-sync)

### 3. Parse异步API

提交Parse任务，通过job\_id查询处理状态和结果。

**适用场景**：

* 处理大文件或批量文件
* 需要异步处理，避免长时间等待
* 需要webhook回调通知

**API文档**：[Parse异步API](/api-reference/endpoint/parse-async)

**使用教程**：详细的使用示例和最佳实践请参考[API使用指南](/pipeline/tutorial/standalone-api-tutorial)。

## 同步 vs 异步API比较

| 特性        | 同步API     | 异步API           |
| --------- | --------- | --------------- |
| 响应方式      | 立即返回结果    | 返回job\_id，需查询状态 |
| 等待时间      | 需要等待处理完成  | 立即返回，后台处理       |
| 适用场景      | 小文件、单个文档  | 大文件、批量处理        |
| 超时限制      | 受HTTP超时限制 | 无超时限制           |
| Webhook支持 | 不支持       | 支持              |
| 使用复杂度     | 简单        | 需要轮询或webhook    |

### 选择建议

* **小文件（\<10MB）**：使用同步API，简单直接
* **大文件（>10MB）或批量处理**：使用异步API，避免超时
* **需要组合处理**：使用Pipeline API
* **需要实时响应**：使用同步API
* **需要后台处理**：使用异步API + Webhook

## 相关文档

* [文档元素和元数据](/pipeline/elements-metadata) - 了解解析后的元素结构
* [分块模块](/pipeline/chunk) - 了解如何对解析后的元素进行分块
* [向量化模块](/pipeline/embed) - 了解如何对元素进行向量化
* [信息抽取模块](/pipeline/extract) - 了解如何对解析后的元素进行信息抽取
