xparse-client 0.2.19__py3-none-any.whl → 0.3.0b8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. example/1_basic_api_usage.py +198 -0
  2. example/2_async_job.py +210 -0
  3. example/3_local_workflow.py +300 -0
  4. example/4_advanced_workflow.py +327 -0
  5. example/README.md +128 -0
  6. example/config_example.json +95 -0
  7. tests/conftest.py +310 -0
  8. tests/unit/__init__.py +1 -0
  9. tests/unit/api/__init__.py +1 -0
  10. tests/unit/api/test_extract.py +232 -0
  11. tests/unit/api/test_local.py +231 -0
  12. tests/unit/api/test_parse.py +374 -0
  13. tests/unit/api/test_pipeline.py +369 -0
  14. tests/unit/api/test_workflows.py +108 -0
  15. tests/unit/connectors/test_ftp.py +525 -0
  16. tests/unit/connectors/test_local_connectors.py +324 -0
  17. tests/unit/connectors/test_milvus.py +368 -0
  18. tests/unit/connectors/test_qdrant.py +399 -0
  19. tests/unit/connectors/test_s3.py +598 -0
  20. tests/unit/connectors/test_smb.py +442 -0
  21. tests/unit/connectors/test_utils.py +335 -0
  22. tests/unit/models/test_local.py +54 -0
  23. tests/unit/models/test_pipeline_stages.py +144 -0
  24. tests/unit/models/test_workflows.py +55 -0
  25. tests/unit/test_base.py +437 -0
  26. tests/unit/test_client.py +110 -0
  27. tests/unit/test_config.py +160 -0
  28. tests/unit/test_exceptions.py +182 -0
  29. tests/unit/test_http.py +562 -0
  30. xparse_client/__init__.py +111 -20
  31. xparse_client/_base.py +188 -0
  32. xparse_client/_client.py +218 -0
  33. xparse_client/_config.py +221 -0
  34. xparse_client/_http.py +351 -0
  35. xparse_client/api/__init__.py +14 -0
  36. xparse_client/api/extract.py +109 -0
  37. xparse_client/api/local.py +225 -0
  38. xparse_client/api/parse.py +209 -0
  39. xparse_client/api/pipeline.py +134 -0
  40. xparse_client/api/workflows.py +204 -0
  41. xparse_client/connectors/__init__.py +45 -0
  42. xparse_client/connectors/_utils.py +138 -0
  43. xparse_client/connectors/destinations/__init__.py +45 -0
  44. xparse_client/connectors/destinations/base.py +116 -0
  45. xparse_client/connectors/destinations/local.py +91 -0
  46. xparse_client/connectors/destinations/milvus.py +229 -0
  47. xparse_client/connectors/destinations/qdrant.py +238 -0
  48. xparse_client/connectors/destinations/s3.py +163 -0
  49. xparse_client/connectors/sources/__init__.py +45 -0
  50. xparse_client/connectors/sources/base.py +74 -0
  51. xparse_client/connectors/sources/ftp.py +278 -0
  52. xparse_client/connectors/sources/local.py +176 -0
  53. xparse_client/connectors/sources/s3.py +232 -0
  54. xparse_client/connectors/sources/smb.py +259 -0
  55. xparse_client/exceptions.py +398 -0
  56. xparse_client/models/__init__.py +60 -0
  57. xparse_client/models/chunk.py +39 -0
  58. xparse_client/models/embed.py +62 -0
  59. xparse_client/models/extract.py +41 -0
  60. xparse_client/models/local.py +38 -0
  61. xparse_client/models/parse.py +132 -0
  62. xparse_client/models/pipeline.py +134 -0
  63. xparse_client/models/workflows.py +74 -0
  64. xparse_client-0.3.0b8.dist-info/METADATA +1075 -0
  65. xparse_client-0.3.0b8.dist-info/RECORD +68 -0
  66. {xparse_client-0.2.19.dist-info → xparse_client-0.3.0b8.dist-info}/WHEEL +1 -1
  67. {xparse_client-0.2.19.dist-info → xparse_client-0.3.0b8.dist-info}/licenses/LICENSE +1 -1
  68. {xparse_client-0.2.19.dist-info → xparse_client-0.3.0b8.dist-info}/top_level.txt +2 -0
  69. xparse_client/pipeline/__init__.py +0 -3
  70. xparse_client/pipeline/config.py +0 -129
  71. xparse_client/pipeline/destinations.py +0 -489
  72. xparse_client/pipeline/pipeline.py +0 -690
  73. xparse_client/pipeline/sources.py +0 -583
  74. xparse_client-0.2.19.dist-info/METADATA +0 -1050
  75. xparse_client-0.2.19.dist-info/RECORD +0 -11
@@ -1,1050 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: xparse-client
3
- Version: 0.2.19
4
- Summary: 面向Agent和RAG的新一代文档处理 AI Infra
5
- License-Expression: MIT
6
- Project-URL: Homepage, https://gitlab.intsig.net/xparse1/xparse-pipeline
7
- Project-URL: Repository, https://gitlab.intsig.net/xparse1/xparse-pipeline
8
- Keywords: xparse,pipeline,rag
9
- Requires-Python: >=3.8
10
- Description-Content-Type: text/markdown
11
- License-File: LICENSE
12
- Requires-Dist: boto3
13
- Requires-Dist: pymilvus
14
- Requires-Dist: milvus-lite; sys_platform != "win32"
15
- Requires-Dist: requests
16
- Requires-Dist: pysmb
17
- Requires-Dist: qdrant-client
18
- Dynamic: license-file
19
-
20
- # xParse
21
-
22
- 面向Agent和RAG的新一代文档处理 AI Infra。
23
-
24
- xParse的同步pipeline实现,支持多种数据源与输出。
25
-
26
- ## 🌟 特点
27
-
28
- - **灵活的数据源**:支持兼容 S3 协议的对象存储、本地文件系统以及 FTP/SMB 协议文件系统
29
- - **灵活的输出**:支持 Milvus/Zilliz/Qdrant 向量数据库、兼容 S3 协议的对象存储以及本地文件系统
30
- - **统一 Pipeline API**:使用 `/api/xparse/pipeline` 一次性完成 parse → chunk → embed 全流程
31
- - **配置化处理**:支持灵活配置 parse、chunk、embed 参数
32
- - **详细统计信息**:返回每个阶段的处理统计数据
33
- - **易于扩展**:基于抽象类,可轻松添加新的 Source 和 Destination
34
- - **完整日志**:详细的处理日志和错误追踪
35
-
36
- ## 📋 架构
37
-
38
- ```
39
- ┌──────────────┐
40
- │ Source │ 数据源(S3/本地/FTP)
41
- └──────┬───────┘
42
- │ read_file()
43
-
44
- ┌──────────────────────────────────────┐
45
- │ Pipeline API │
46
- │ /api/xparse/pipeline │
47
- │ │
48
- │ ┌────────┐ ┌────────┐ ┌────────┐ │ ┌────────┐
49
- │ │ Parse │→ │ Chunk │→ │ Embed │ |────→│ Deduct │ 计费
50
- │ └────────┘ └────────┘ └────────┘ │ └────────┘
51
- │ │
52
- └──────────────┬───────────────────────┘
53
- │ [embeddings + stats]
54
-
55
- ┌──────────────┐
56
- │ Destination │ 目的地(Milvus/Zilliz/Qdrant/本地)
57
- └──────────────┘
58
- ```
59
-
60
- ## 🚀 快速开始
61
-
62
- ### 1. 安装依赖
63
-
64
- ```bash
65
- pip install --upgrade xparse-client
66
- ```
67
-
68
- ### 2. 运行
69
-
70
- `xparse-client`支持两种配置方式,即通过代码配置,以及直接通过config字典配置
71
-
72
- #### 代码配置
73
- ```python
74
- from xparse_client import ParseConfig, ChunkConfig, EmbedConfig, Stage, Pipeline, S3Source, MilvusDestination, QdrantDestination
75
-
76
- # 使用新的 stages 格式创建配置
77
- stages = [
78
- Stage(
79
- type='parse',
80
- config=ParseConfig(provider='textin')
81
- ),
82
- Stage(
83
- type='chunk',
84
- config=ChunkConfig(
85
- strategy='by_title',
86
- include_orig_elements=False,
87
- new_after_n_chars=512,
88
- max_characters=1024,
89
- overlap=50
90
- )
91
- ),
92
- Stage(
93
- type='embed',
94
- config=EmbedConfig(
95
- provider='qwen',
96
- model_name='text-embedding-v4'
97
- )
98
- )
99
- ]
100
-
101
- # 创建 Pipeline
102
- source = S3Source(...)
103
- destination = MilvusDestination(...)
104
-
105
- pipeline = Pipeline(
106
- source=source,
107
- destination=destination,
108
- api_base_url='https://api.textin.com/api/xparse',
109
- api_headers={...},
110
- stages=stages
111
- )
112
-
113
- pipeline.run()
114
- ```
115
-
116
- #### 字典配置
117
-
118
- ```python
119
- config = {
120
- 'source': {...},
121
- 'destination': {...},
122
- 'api_base_url': 'https://api.textin.com/api/xparse',
123
- 'api_headers': {...},
124
-
125
- # Stages 配置
126
- 'stages': [
127
- {
128
- 'type': 'parse',
129
- 'config': {
130
- 'provider': 'textin' # 当前支持textin文档解析,未来可扩展
131
- }
132
- },
133
- {
134
- 'type': 'chunk',
135
- 'config': {
136
- 'strategy': 'basic', # 分块策略: 'basic' | 'by_title' | 'by_page'
137
- 'include_orig_elements': False, # 是否包含原始元素
138
- 'new_after_n_chars': 512, # 多少字符后创建新块
139
- 'max_characters': 1024, # 最大字符数
140
- 'overlap': 0 # 重叠字符数
141
- }
142
- },
143
- {
144
- 'type': 'embed',
145
- 'config': {
146
- 'provider': 'qwen', # 向量化供应商: 'qwen'/'doubao'
147
- 'model_name': 'text-embedding-v3' # 模型名称
148
- }
149
- }
150
- ]
151
- }
152
-
153
- # 使用配置创建 pipeline
154
- from xparse_client import create_pipeline_from_config
155
- pipeline = create_pipeline_from_config(config)
156
- pipeline.run()
157
- ```
158
-
159
- 详见下文的 [使用示例](#-使用示例) 一章,或参考`example/run_pipeline.py`文件。
160
-
161
- ## 📝 配置说明
162
-
163
- ### Source 配置
164
-
165
- #### MinIO / S3兼容数据源(OSS/COS/TOS/OBS/S3)
166
-
167
- 1. MinIO
168
-
169
- 接入代码如下:
170
- ```python
171
- source = S3Source(
172
- endpoint='https://your-minio-endpoint',
173
- access_key='IEQspf******mp3AZWl',
174
- secret_key='kLj96I8FGb**********zBijOJWKWOt1',
175
- bucket='textin',
176
- prefix='',
177
- region='us-east-1',
178
- pattern=['*.pdf'] # 可选,通配符模式列表,支持多个扩展名
179
- )
180
- ```
181
- 请确保配置的访问凭证至少包括以下几项权限:
182
- ```
183
- s3:ListBucket
184
- s3:GetObject
185
- ```
186
-
187
- 2. 阿里云OSS
188
-
189
- 接入代码示例如下:
190
- ```python
191
- source = S3Source(
192
- endpoint='https://s3.oss-cn-shanghai.aliyuncs.com',
193
- access_key='LTAI5tBg**********bPyuB17',
194
- secret_key='JFIIaTGiX**********SStofF0S98',
195
- bucket='textin',
196
- prefix='',
197
- region='cn-shanghai',
198
- pattern=['*.pdf'] # 可选,通配符模式列表,支持多个扩展名
199
- )
200
- ```
201
- 请确保配置的访问凭证至少包括以下几项权限:
202
- ```
203
- oss:HeadBucket
204
- oss:ListObjects
205
- oss:GetObject
206
- ```
207
-
208
- 3. 腾讯云COS
209
-
210
- 接入代码示例如下:
211
- ```python
212
- source = S3Source(
213
- endpoint='https://cos.ap-shanghai.myqcloud.com',
214
- access_key='AKIDRnws********nlUzHLAmAJ',
215
- secret_key='we7KJ4bux**********UKxWu3yeDZi',
216
- bucket='textin',
217
- prefix='',
218
- region='ap-shanghai',
219
- pattern=['*.pdf'] # 可选,通配符模式列表,支持多个扩展名
220
- )
221
- ```
222
-
223
- 请确保配置的访问凭证至少包括以下几项权限:
224
- ```
225
- cos:HeadBucket
226
- cos:GetBucket
227
- cos:GetObject
228
- ```
229
- 4. 火山引擎TOS
230
-
231
- 接入代码示例如下:
232
- ```python
233
- source = S3Source(
234
- endpoint='https://tos-s3-cn-shanghai.volces.com',
235
- access_key='AKLTMzNkZ**************BjYjZjYzA',
236
- secret_key='TnpWaE0yRTVa**************RrMFlqVQ==',
237
- bucket='textin',
238
- prefix='',
239
- region='cn-shanghai',
240
- pattern=['*.pdf'] # 可选,通配符模式列表,支持多个扩展名
241
- )
242
- ```
243
-
244
- 请确保配置的访问凭证至少包括以下几项权限:
245
- ```
246
- tos:HeadBucket
247
- tos:ListBucket
248
- tos:GetObject
249
- ```
250
-
251
- 5. 华为云OBS
252
-
253
- 接入代码示例如下:
254
- ```python
255
- source = S3Source(
256
- endpoint='https://obs.cn-east-3.myhuaweicloud.com',
257
- access_key='HPUAL6********YAT7JMWY',
258
- secret_key='z9cm95UXCw**********bwDYz8PVoBGDI',
259
- bucket='textin',
260
- prefix='',
261
- region='cn-east-3',
262
- pattern=['*.pdf'] # 可选,通配符模式列表,支持多个扩展名
263
- )
264
- ```
265
-
266
- 请确保配置的访问凭证至少包括以下几项权限:
267
- ```
268
- HeadBucket
269
- ListBucket
270
- GetObject
271
- ```
272
-
273
- 6. AWS S3
274
-
275
- 接入代码示例如下:
276
- ```python
277
- source = S3Source(
278
- endpoint='https://s3.us-east-1.amazonaws.com',
279
- access_key='AKIA6Q******UWA4PO',
280
- secret_key='OfV4r9/u+CmlLx**************WLADKdPek7',
281
- bucket='textin-xparse',
282
- prefix='',
283
- region='us-east-1',
284
- pattern=['*.pdf'] # 可选,通配符模式列表,支持多个扩展名
285
- )
286
- ```
287
- 请确保配置的访问凭证至少包括以下几项权限:
288
- ```
289
- s3:ListBucket
290
- s3:GetObject
291
- ```
292
-
293
-
294
- #### 本地文件系统数据源
295
-
296
- ```python
297
- source = LocalSource(
298
- directory='./input',
299
- pattern=['*.pdf', '*.docx'] # 支持多个通配符模式列表
300
- )
301
- ```
302
-
303
- #### FTP数据源
304
-
305
- ```python
306
- source = FtpSource(
307
- host='127.0.0.1',
308
- port=21,
309
- username='', # 用户名,按照实际填写
310
- password='', # 密码,按照实际填写
311
- pattern=['*.pdf'] # 可选,通配符模式列表,过滤指定类型文件
312
- )
313
- ```
314
-
315
- #### SMB数据源
316
-
317
- ```python
318
- source = SmbSource(
319
- host='your-smb-host',
320
- share_name='your-smb-share-name',
321
- username='', # 用户名,按照实际填写
322
- password='', # 密码,按照实际填写
323
- domain='your-smb-domain',
324
- pattern=['**/*.pdf'] # 可选,通配符模式列表,支持多级匹配
325
- )
326
- ```
327
-
328
- > 注 1:所有 Source 均支持 `pattern` 参数,使用通配符模式列表(如 `['*.pdf', '*.docx']`)来过滤需要处理的文件。支持多个通配符模式,如果列表中包含 `'*'` 则匹配所有文件。默认为 `None`,即处理全部文件。
329
-
330
- > 注 2:所有 Source 均支持 `recursive` 参数,表示是否递归遍历,默认为 `False`。
331
-
332
- ### Destination 配置
333
-
334
- #### 本地 Milvus 向量存储
335
-
336
- collection 中至少需要包含 `element_id`,`text`,`embeddings`,`record_id` 四个字段。
337
-
338
- ```python
339
- destination = MilvusDestination(
340
- db_path='./milvus_pipeline.db', # 本地数据库文件
341
- collection_name='my_collection', # 数据库collection名称
342
- dimension=1024 # 向量维度,需与 embed API 返回一致
343
- )
344
- ```
345
-
346
- #### Zilliz 向量存储
347
-
348
- collection 中至少需要包含 `element_id`,`text`,`embeddings`,`record_id` 四个字段。
349
-
350
- ```python
351
- destination = MilvusDestination(
352
- db_path='https://xxxxxxx.serverless.xxxxxxx.cloud.zilliz.com.cn', # zilliz连接地址
353
- collection_name='my_collection', # 数据库collection名称
354
- dimension=1024, # 向量维度,需与 embed API 返回一致
355
- api_key='your-api-key' # Zilliz Cloud API Key
356
- )
357
- ```
358
-
359
- #### Qdrant 向量存储
360
-
361
- ```python
362
- destination = QdrantDestination(
363
- url='http://localhost:6333', # Qdrant 服务地址(本地或云端)
364
- collection_name='my_collection', # Collection 名称
365
- dimension=1024, # 向量维度,需与 embed API 返回一致
366
- api_key='your-api-key', # 可选,Qdrant Cloud API Key
367
- prefer_grpc=False # 可选,是否优先使用 gRPC(默认 False)
368
- )
369
- ```
370
-
371
- **Qdrant Cloud 示例:**
372
- ```python
373
- destination = QdrantDestination(
374
- url='https://xxxxxxx.us-east-1-0.aws.cloud.qdrant.io',
375
- collection_name='my_collection',
376
- dimension=1024,
377
- api_key='your-api-key'
378
- )
379
- ```
380
-
381
- #### 本地文件系统目的地
382
-
383
- 将在配置的本地文件地址中写入`json`文件。
384
-
385
- ```python
386
- destination = LocalDestination(
387
- output_dir='./output'
388
- )
389
- ```
390
-
391
- #### MinIO / S3兼容数据源(OSS/COS/TOS/OBS/S3)
392
-
393
- 将在配置的本地文件地址中写入`json`文件。
394
-
395
- 配置可参考上文中 Source 的配置,需要注意的是,需要确保配置的访问凭证在上述权限的基础上包括 `PutObject` 权限,例如在使用阿里云OSS时,需要包括以下权限:
396
- ```
397
- oss:HeadBucket
398
- oss:ListObjects
399
- oss:GetObject
400
- oss:PutObject
401
- ```
402
-
403
- ### API 配置
404
-
405
- 该配置即为pipeline主逻辑接口的请求配置,api_base_url固定为 `https://api.textin.com/api/xparse` ,api_headers中需要填入 [TextIn 开发者信息](https://www.textin.com/console/dashboard/setting) 中获取的 `x-ti-app-id` 与 `x-ti-secret-code`。
406
-
407
- ```python
408
- 'api_base_url': 'https://api.textin.com/api/xparse',
409
- 'api_headers': {
410
- 'x-ti-app-id': 'your-app-id',
411
- 'x-ti-secret-code': 'your-secret-code'
412
- }
413
- ```
414
-
415
- ## 🔌 API 接口规范
416
-
417
- ### Pipeline 接口(统一接口)
418
-
419
- **Endpoint:** `POST /api/xparse/pipeline`
420
-
421
- **请求格式:**
422
- ```
423
- Content-Type: multipart/form-data
424
-
425
- file: <binary file>
426
- stages: [
427
- {
428
- "type": "parse",
429
- "config": {
430
- "provider": "textin",
431
- ...
432
- }
433
- },
434
- {
435
- "type": "chunk",
436
- "config": {
437
- "strategy": "basic",
438
- "include_orig_elements": false,
439
- "new_after_n_chars": 512,
440
- "max_characters": 1024,
441
- "overlap": 0
442
- }
443
- },
444
- {
445
- "type": "embed",
446
- "config": {
447
- "provider": "qwen",
448
- "model_name": "text-embedding-v3"
449
- }
450
- }
451
- ]
452
- ```
453
-
454
- **Stages 说明:**
455
-
456
- Pipeline 接口使用 stages 数组来定义处理流程,每个 stage 包含:
457
- - `type`: 阶段类型,可选值:`parse`、`chunk`、`embed`
458
- - `parse`节点必选,且顺序必须在第一位
459
- - `chunk`/`embed`节点可选,若二者同时存在`embed`节点需在`chunk`后面
460
- - 若不存在`embed`节点且Destination为向量数据库类型(例如`Milvus`),运行时会报错
461
- - `config`: 该阶段的配置,具体字段取决于阶段类型
462
-
463
- **各阶段配置:**
464
-
465
- 1. **Parse Stage** (`type: "parse"`)
466
-
467
- Parse 参数中有必填项`Provider`,表示文档解析服务的供应商,目前可选项如下:
468
- - textin: 合合信息提供的文档解析服务,在速度、准确性上均为行业领先
469
- - 支持的文档解析参数参考 [TextIn 文档解析官方API文档](https://docs.textin.com/api-reference/endpoint/parse)
470
- - 接口调用将按照 `TextIn 通用文档解析` 服务的计费标准进行计费
471
- - textin-lite:
472
- - 接口调用将按照 `TextIn 通用表格识别` 服务的计费标准进行计费
473
- - mineru:
474
- - 接口调用将按照 `TextIn 通用文档解析` 服务的计费标准进行计费
475
- - paddle:
476
- - 接口调用将按照 `TextIn 通用文档解析` 服务的计费标准进行计费
477
-
478
- 2. **Chunk Stage** (`type: "chunk"`)
479
-
480
- | 参数名 | 类型 / 可选性 | 说明 | 默认值 | 使用场景 / 注意事项 |
481
- | ------ | ------------- | ---- | ------ | -------------------- |
482
- | **strategy** | string/必填 | 分块策略 | basic | <br>- `basic`: 基础分块,按字符数分割<br>- `by_title`: 按标题分块,保持章节完整性<br>- `by_page`: 按页面分块,保持页面完整性 |
483
- | **combine_text_under_n_chars** | `int` / 可选 | 将同一部分中的元素合并成一个数据块,直到该部分的总长度达到指定字符数。 | `None` | 可用于将过短的小块合并成较长文本,提高语义连贯性。 |
484
- | **include_orig_elements** | `bool` / 可选 | 如果为 `true`,用于构成数据块的原始元素会出现在该数据块的 `.metadata.orig_elements` 中。 | `False` | 用于调试或需要保留原始元素追溯的场景。 |
485
- | **new_after_n_chars** | `int` / 可选 | 当文本长度达到指定字符数时,强制结束当前章节并开始新的章节(近似限制)。 | `None` | 适用于需要控制章节最大长度的情况下。 |
486
- | **max_characters** | `int` / 可选 | 数据块中允许的最大字符数上限。 | `None` | 用于硬性限制块大小,避免过大块带来的处理延迟或内存占用。 |
487
- | **overlap** | `int` / 可选 | 将前一个文本分块末尾指定数量的字符,作为前缀应用到由过大元素分割而成的第二个及后续文本块。 | `None` | 常用于确保分块之间的上下文连续性。 |
488
- | **overlap_all** | `bool` / 可选 | 如果为 `true`,重叠也会应用到由完整元素组合而成的“普通”块。 | `False` | 谨慎使用,可能在语义上引入噪声。 |
489
-
490
-
491
- 3. **Embed Stage** (`type: "embed"`)
492
-
493
- `xparse-pipeline`当前支持的文本向量化模型如下:
494
- - `qwen` 供应商,即通义千问:
495
- - `text-embedding-v3`
496
- - `text-embedding-v4`
497
- - `doubao` 供应商,即火山引擎:
498
- - `doubao-embedding-large-text-250515`
499
- - `doubao-embedding-text-240715`
500
-
501
- **返回格式:**
502
- ```json
503
- {
504
- "code": 200,
505
- "msg": "success",
506
- "data": {
507
- "elements": [
508
- {
509
- "element_id": "f6d5beee53d4f3d90589472974abd7f75c54988c72375cd206f74089391c92b2",
510
- "type": "plaintext",
511
- "text": "文本内容",
512
- "metainfo": {
513
- "record_id": "08f8e327d05f97e545d04c81d2ef8de1",
514
- ...
515
- },
516
- "embeddings": [0.1, 0.2, 0.3, ...]
517
- }
518
- ],
519
- "stats": {
520
- "original_elements": 10, // 原始解析的元素数量
521
- "chunked_elements": 15, // 分块后的元素数量
522
- "embedded_elements": 15, // 向量化后的元素数量
523
- "stages": [
524
- {
525
- "type": "parse",
526
- "config": {
527
- "provider": "textin-lite"
528
- }
529
- },
530
- {
531
- "type": "chunk",
532
- "config": {
533
- "strategy": "by_title"
534
- }
535
- }
536
- ]
537
- }
538
- }
539
- }
540
- ```
541
-
542
- ## 💡 使用示例
543
-
544
- ### 示例 1: 手动创建 Pipeline(推荐)
545
-
546
- ```python
547
- from xparse_client import (
548
- Pipeline, S3Source, MilvusDestination,
549
- ParseConfig, ChunkConfig, EmbedConfig, Stage
550
- )
551
-
552
- # 创建数据源
553
- source = S3Source(
554
- endpoint='https://your-minio.com',
555
- access_key='your-access-key',
556
- secret_key='your-secret-key',
557
- bucket='documents',
558
- prefix='pdfs/',
559
- region='us-east-1',
560
- pattern=['*.pdf'], # 仅处理匹配的文件
561
- recursive=False # 不递归子目录
562
- )
563
-
564
- # 创建目的地
565
- destination = MilvusDestination(
566
- db_path='./vectors.db',
567
- collection_name='documents',
568
- dimension=1024
569
- )
570
-
571
- # 配置处理阶段
572
- stages = [
573
- Stage(
574
- type='parse',
575
- config=ParseConfig(provider='textin')
576
- ),
577
- Stage(
578
- type='chunk',
579
- config=ChunkConfig(
580
- strategy='by_title', # 按标题分块
581
- include_orig_elements=False,
582
- new_after_n_chars=512,
583
- max_characters=1024,
584
- overlap=50 # 块之间重叠 50 字符
585
- )
586
- ),
587
- Stage(
588
- type='embed',
589
- config=EmbedConfig(
590
- provider='qwen',
591
- model_name='text-embedding-v3'
592
- )
593
- )
594
- ]
595
-
596
- # 创建并运行 Pipeline
597
- pipeline = Pipeline(
598
- source=source,
599
- destination=destination,
600
- api_base_url='https://api.textin.com/api/xparse',
601
- api_headers={
602
- 'x-ti-app-id': 'your-app-id',
603
- 'x-ti-secret-code': 'your-secret-code'
604
- },
605
- stages=stages
606
- )
607
-
608
- pipeline.run()
609
- ```
610
-
611
- ### 示例 1.1: 输出配置字典
612
-
613
- 手动创建 Pipeline 后,可以使用 `get_config()` 方法获取配置字典:
614
-
615
- ```python
616
- from xparse_client import (
617
- Pipeline, LocalSource, LocalDestination,
618
- ParseConfig, ChunkConfig, EmbedConfig, Stage
619
- )
620
-
621
- # 手动创建 Pipeline
622
- source = LocalSource(
623
- directory='./test_files',
624
- pattern=['*.pdf'],
625
- recursive=False
626
- )
627
-
628
- destination = LocalDestination(output_dir='./test_output')
629
-
630
- stages = [
631
- Stage(type='parse', config=ParseConfig(provider='textin')),
632
- Stage(type='chunk', config=ChunkConfig(strategy='basic', max_characters=1024)),
633
- Stage(type='embed', config=EmbedConfig(provider='qwen', model_name='text-embedding-v3'))
634
- ]
635
-
636
- pipeline = Pipeline(
637
- source=source,
638
- destination=destination,
639
- api_base_url='https://api.textin.com/api/xparse',
640
- api_headers={
641
- 'x-ti-app-id': 'your-app-id',
642
- 'x-ti-secret-code': 'your-secret-code'
643
- },
644
- stages=stages
645
- )
646
-
647
- # 获取配置字典(格式与 create_pipeline_from_config 的入参一致)
648
- config_dict = pipeline.get_config()
649
-
650
- # 可以保存为 JSON 文件
651
- import json
652
- with open('pipeline_config.json', 'w', encoding='utf-8') as f:
653
- json.dump(config_dict, f, indent=2, ensure_ascii=False)
654
-
655
- # 或者用于创建新的 Pipeline(需要补充敏感信息如 access_key, secret_key 等)
656
- # from xparse_client import create_pipeline_from_config
657
- # new_pipeline = create_pipeline_from_config(config_dict)
658
- ```
659
-
660
- ### 示例 2: 本地到本地(测试)
661
-
662
- ```python
663
- from xparse_client import (
664
- Pipeline, LocalSource, LocalDestination,
665
- ParseConfig, ChunkConfig, EmbedConfig, Stage
666
- )
667
-
668
- # 创建本地数据源
669
- source = LocalSource(
670
- directory='./test_files',
671
- pattern=['*.pdf'],
672
- recursive=False
673
- )
674
-
675
- # 创建本地输出目的地
676
- destination = LocalDestination(output_dir='./test_output')
677
-
678
- # 配置处理阶段
679
- stages = [
680
- Stage(
681
- type='parse',
682
- config=ParseConfig(provider='textin')
683
- ),
684
- Stage(
685
- type='chunk',
686
- config=ChunkConfig(
687
- strategy='basic',
688
- max_characters=1024
689
- )
690
- ),
691
- Stage(
692
- type='embed',
693
- config=EmbedConfig(
694
- provider='qwen',
695
- model_name='text-embedding-v3'
696
- )
697
- )
698
- ]
699
-
700
- # 创建并运行 Pipeline
701
- pipeline = Pipeline(
702
- source=source,
703
- destination=destination,
704
- api_base_url='https://api.textin.com/api/xparse',
705
- api_headers={
706
- 'x-ti-app-id': 'your-app-id',
707
- 'x-ti-secret-code': 'your-secret-code'
708
- },
709
- stages=stages
710
- )
711
-
712
- pipeline.run()
713
- ```
714
-
715
- ### 示例 3: 不同分块策略的配置
716
-
717
- ```python
718
- from xparse_client import (
719
- Pipeline, S3Source, MilvusDestination,
720
- ParseConfig, ChunkConfig, EmbedConfig, Stage
721
- )
722
-
723
- # 创建数据源和目的地
724
- source = S3Source(...)
725
- destination = MilvusDestination(...)
726
-
727
- # 配置 1:按页面分块(适合 PDF 文档)
728
- stages_by_page = [
729
- Stage(
730
- type='parse',
731
- config=ParseConfig(provider='textin')
732
- ),
733
- Stage(
734
- type='chunk',
735
- config=ChunkConfig(
736
- strategy='by_page', # 按页面分块
737
- max_characters=2048, # 增大块大小
738
- overlap=100 # 页面间重叠 100 字符
739
- )
740
- ),
741
- Stage(
742
- type='embed',
743
- config=EmbedConfig(
744
- provider='qwen',
745
- model_name='text-embedding-v4' # 使用更高精度的模型
746
- )
747
- )
748
- ]
749
-
750
- # 配置 2:按标题分块(适合结构化文档)
751
- stages_by_title = [
752
- Stage(
753
- type='parse',
754
- config=ParseConfig(provider='textin')
755
- ),
756
- Stage(
757
- type='chunk',
758
- config=ChunkConfig(
759
- strategy='by_title', # 按标题分块
760
- include_orig_elements=True, # 保留原始元素信息
761
- max_characters=1536
762
- )
763
- ),
764
- Stage(
765
- type='embed',
766
- config=EmbedConfig(
767
- provider='qwen',
768
- model_name='text-embedding-v3'
769
- )
770
- )
771
- ]
772
-
773
- # 根据文档类型选择配置
774
- pipeline = Pipeline(
775
- source=source,
776
- destination=destination,
777
- api_base_url='https://api.textin.com/api/xparse',
778
- api_headers={...},
779
- stages=stages_by_page # 或 stages_by_title
780
- )
781
- pipeline.run()
782
- ```
783
-
784
- ### 示例 4: FTP 数据源配置
785
-
786
- ```python
787
- from xparse_client import (
788
- Pipeline, FtpSource, MilvusDestination,
789
- ParseConfig, ChunkConfig, EmbedConfig, Stage
790
- )
791
-
792
- # 创建 FTP 数据源
793
- source = FtpSource(
794
- host='ftp.example.com',
795
- port=21,
796
- username='user',
797
- password='pass',
798
- pattern=['*.pdf'],
799
- recursive=False
800
- )
801
-
802
- # 创建 Milvus 目的地
803
- destination = MilvusDestination(
804
- db_path='./vectors.db',
805
- collection_name='ftp_docs',
806
- dimension=1024
807
- )
808
-
809
- # 配置处理阶段
810
- stages = [
811
- Stage(
812
- type='parse',
813
- config=ParseConfig(provider='textin')
814
- ),
815
- Stage(
816
- type='chunk',
817
- config=ChunkConfig(
818
- strategy='basic',
819
- max_characters=1024
820
- )
821
- ),
822
- Stage(
823
- type='embed',
824
- config=EmbedConfig(
825
- provider='qwen',
826
- model_name='text-embedding-v3'
827
- )
828
- )
829
- ]
830
-
831
- # 创建并运行 Pipeline
832
- pipeline = Pipeline(
833
- source=source,
834
- destination=destination,
835
- api_base_url='https://api.textin.com/api/xparse',
836
- api_headers={
837
- 'x-ti-app-id': 'app-id',
838
- 'x-ti-secret-code': 'secret'
839
- },
840
- stages=stages
841
- )
842
-
843
- pipeline.run()
844
- ```
845
-
846
- ### 示例 5: 获取处理统计信息
847
-
848
- ```python
849
- from datetime import datetime, timezone
850
- from xparse_client import (
851
- Pipeline, LocalSource, LocalDestination,
852
- ParseConfig, ChunkConfig, EmbedConfig, Stage
853
- )
854
-
855
- # 创建 Pipeline
856
- source = LocalSource(
857
- directory='./docs',
858
- pattern=['*.pdf'],
859
- recursive=False
860
- )
861
-
862
- destination = LocalDestination(output_dir='./output')
863
-
864
- stages = [
865
- Stage(
866
- type='parse',
867
- config=ParseConfig(provider='textin')
868
- ),
869
- Stage(
870
- type='chunk',
871
- config=ChunkConfig(
872
- strategy='basic',
873
- max_characters=1024
874
- )
875
- ),
876
- Stage(
877
- type='embed',
878
- config=EmbedConfig(
879
- provider='qwen',
880
- model_name='text-embedding-v3'
881
- )
882
- )
883
- ]
884
-
885
- pipeline = Pipeline(
886
- source=source,
887
- destination=destination,
888
- api_base_url='https://api.textin.com/api/xparse',
889
- api_headers={
890
- 'x-ti-app-id': 'your-app-id',
891
- 'x-ti-secret-code': 'your-secret-code'
892
- },
893
- stages=stages
894
- )
895
-
896
- # 处理单个文件并获取统计信息
897
- file_bytes, data_source = pipeline.source.read_file('document.pdf')
898
- data_source['date_processed'] = datetime.now(timezone.utc).timestamp()
899
- result = pipeline.process_with_pipeline(file_bytes, 'document.pdf', data_source)
900
-
901
- if result:
902
- elements, stats = result
903
- print(f"原始元素: {stats.original_elements}")
904
- print(f"分块后: {stats.chunked_elements}")
905
- print(f"向量化: {stats.embedded_elements}")
906
- print(f"执行的 stages: {[s.type for s in stats.stages]}")
907
-
908
- # 写入目的地
909
- metadata = {
910
- 'file_name': 'document.pdf',
911
- 'data_source': data_source
912
- }
913
- pipeline.destination.write(elements, metadata)
914
- ```
915
-
916
- ## 📊 Pipeline 统计信息
917
-
918
- Pipeline 接口会返回详细的处理统计信息:
919
-
920
- | 字段 | 类型 | 说明 |
921
- |------|------|------|
922
- | `original_elements` | int | 原始解析的元素数量 |
923
- | `chunked_elements` | int | 分块后的元素数量 |
924
- | `embedded_elements` | int | 向量化后的元素数量 |
925
- | `stages` | List[Stage] | 实际执行的 stages 配置 |
926
-
927
- **示例输出:**
928
- ```
929
- ✓ Pipeline 完成:
930
- - 原始元素: 25
931
- - 分块后: 42
932
- - 向量化: 42
933
- ✓ 写入 Milvus: 42 条
934
- ```
935
-
936
- ## 🔧 扩展开发
937
-
938
- ### 添加新的 Source
939
-
940
- ```python
941
- from typing import List, Dict, Any, Tuple
942
- from xparse_client import Source
943
-
944
- class MyCustomSource(Source):
945
- def __init__(self, custom_param):
946
- self.custom_param = custom_param
947
-
948
- def list_files(self) -> List[str]:
949
- # 实现文件列表逻辑
950
- return ['file1.pdf', 'file2.pdf']
951
-
952
- def read_file(self, file_path: str) -> Tuple[bytes, Dict[str, Any]]:
953
- # 实现文件读取逻辑并返回数据来源信息
954
- data_source = {
955
- 'url': f'custom://{file_path}',
956
- 'version': None,
957
- 'date_created': None,
958
- 'date_modified': None,
959
- 'record_locator': {
960
- 'protocol': 'custom',
961
- 'remote_file_path': file_path
962
- }
963
- }
964
- return b'file content', data_source
965
- ```
966
-
967
- ### 添加新的 Destination
968
-
969
- ```python
970
- from xparse_client import Destination
971
-
972
- class MyCustomDestination(Destination):
973
- def __init__(self, custom_param):
974
- self.custom_param = custom_param
975
-
976
- def write(self, data: List[Dict], metadata: Dict) -> bool:
977
- # 实现数据写入逻辑
978
- return True
979
- ```
980
-
981
- ## 📊 数据格式
982
-
983
- ### 元素格式
984
-
985
- 每个处理步骤都使用统一的元素格式:
986
-
987
- ```python
988
- {
989
- "element_id": str, # 唯一标识符
990
- "type": str, # 元素类型: plaintext, table, image, etc.
991
- "text": str, # 文本内容
992
- "metainfo": { # 元数据
993
- "filename": str,
994
- "orig_elements": list, # chunk处理后添加
995
- # 其他字段
996
- },
997
- "embeddings": list # 向量(embed 步骤后添加)
998
- }
999
- ```
1000
-
1001
- ## ⚠️ 注意事项
1002
-
1003
- 1. **API 端点**:确保 API 服务正常运行并可访问,目前需要固定使用`https://api.textin.com/api/xparse`,同时需要配置请求头上的app-id/secret-code
1004
- 2. **向量维度**:Milvus 的 dimension 必须与 pipeline API 返回的向量维度一致,目前pipeline API使用的是1024维度
1005
- 3. **写入Milvus**:确保目标collection中包含`element_id`,`text`,`record_id`,`embeddings`,`metadata`这些字段
1006
- 4. **错误重试**:默认每个 API 调用失败会重试 3 次
1007
-
1008
- ## 💰 计费
1009
-
1010
- Pipeline接口调用将按页进行计费,具体计费标准可以参考:[通用文档解析](https://www.textin.com/market/detail/xparse)。
1011
-
1012
- ## 🐛 故障排除
1013
-
1014
- ### API 连接失败
1015
-
1016
- - 检查 `api_base_url` 是否正确
1017
- - 确认网络连接正常
1018
- - 查看 API 服务日志
1019
-
1020
- ### S3 连接失败
1021
-
1022
- - 验证 endpoint、access_key、secret_key
1023
- - 确认 bucket 存在且有访问权限
1024
-
1025
- ### FTP 连接失败
1026
-
1027
- - 验证路径端口是否正确
1028
- - 确认用户名密码是否正确
1029
-
1030
- ### 本地文件找不到
1031
-
1032
- - 确认路径正确
1033
- - 检查文件匹配模式
1034
- - 验证文件权限
1035
-
1036
- ### Milvus 写入失败
1037
-
1038
- - 检查向量维度是否匹配
1039
- - 确认必须字段是否存在
1040
- - 查看 Milvus 日志
1041
-
1042
- ## 🔗 相关文件
1043
-
1044
- - `core.py` - 核心 Pipeline 实现
1045
- - `run_pipeline.py` - 运行示例
1046
-
1047
- ## 📄 License
1048
-
1049
- MIT License
1050
-