xparse-client 0.2.2__py3-none-any.whl → 0.2.3__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.
@@ -0,0 +1,465 @@
1
+ #!/usr/bin/env python
2
+ # -*- encoding: utf-8 -*-
3
+ '''
4
+ Pipeline 运行脚本
5
+ 快速启动和运行 Pipeline 的示例
6
+ '''
7
+
8
+ from datetime import datetime, timezone
9
+ from xparse_client import create_pipeline_from_config, S3Source, LocalSource, MilvusDestination, LocalDestination, Pipeline, SmbSource, S3Destination, FtpSource
10
+
11
+
12
+ # ============================================================================
13
+ # 常量配置
14
+ # ============================================================================
15
+
16
+ # API 请求头配置
17
+ API_HEADERS = {
18
+ 'x-ti-app-id': '',
19
+ 'x-ti-secret-code': ''
20
+ }
21
+
22
+
23
+ # ============================================================================
24
+ # 方式 1: 使用配置字典
25
+ # ============================================================================
26
+
27
+ def run_with_config():
28
+ """使用配置字典运行 pipeline"""
29
+
30
+ config = {
31
+ 'source': {
32
+ 'type': 's3',
33
+ 'endpoint': 'https://textin-minio-api.ai.intsig.net',
34
+ 'access_key': 'IEQspf8C7fVcgmp3AZWl',
35
+ 'secret_key': 'kLj96I8FGbIrPFW08meXivCy4AVdzBijOJWKWOt1',
36
+ 'bucket': 'textin-test',
37
+ 'prefix': '', # 留空处理所有文件,或指定如 'milvus/'
38
+ 'region': 'us-east-1'
39
+ },
40
+ 'destination': {
41
+ 'type': 'milvus',
42
+ 'db_path': './milvus_pipeline.db',
43
+ 'collection_name': 'pipeline_collection',
44
+ 'dimension': 1024
45
+ },
46
+ 'api_base_url': 'https://api.textin.com/api/xparse',
47
+ 'api_headers': API_HEADERS,
48
+ # Stages 配置
49
+ 'stages': [
50
+ {
51
+ 'type': 'parse',
52
+ 'config': {
53
+ 'provider': 'textin'
54
+ }
55
+ },
56
+ {
57
+ 'type': 'chunk',
58
+ 'config': {
59
+ 'strategy': 'basic', # 分块策略: 'basic' | 'by_title' | 'by_page'
60
+ 'include_orig_elements': False, # 是否包含原始元素
61
+ 'new_after_n_chars': 512, # 多少字符后创建新块
62
+ 'max_characters': 1024, # 最大字符数
63
+ 'overlap': 0 # 重叠字符数
64
+ }
65
+ },
66
+ {
67
+ 'type': 'embed',
68
+ 'config': {
69
+ 'provider': 'qwen', # 向量化供应商: 'qwen'
70
+ 'model_name': 'text-embedding-v3' # 模型名称: 'text-embedding-v3' | 'text-embedding-v4'
71
+ }
72
+ }
73
+ ]
74
+ }
75
+
76
+ pipeline = create_pipeline_from_config(config)
77
+ pipeline.run()
78
+
79
+
80
+ # ============================================================================
81
+ # 方式 2: 手动创建组件
82
+ # ============================================================================
83
+
84
+ def run_with_manual_setup():
85
+ """手动创建 Source、Destination 和 Pipeline"""
86
+ from xparse_client import ChunkConfig, EmbedConfig, ParseConfig, Stage, PipelineConfig, LocalDestination
87
+
88
+ # 创建 S3 数据源
89
+ # source = S3Source(
90
+ # endpoint='https://textin-minio-api.ai.intsig.net',
91
+ # access_key='IEQspf8C7fVcgmp3AZWl',
92
+ # secret_key='kLj96I8FGbIrPFW08meXivCy4AVdzBijOJWKWOt1',
93
+ # bucket='textin-test',
94
+ # prefix='',
95
+ # region='us-east-1'
96
+ # )
97
+ # source = S3Source(
98
+ # endpoint='https://s3.oss-cn-shanghai.aliyuncs.com',
99
+ # access_key='',
100
+ # secret_key='',
101
+ # bucket='textin',
102
+ # prefix='',
103
+ # region='cn-shanghai',
104
+ # pattern='*.png'
105
+ # )
106
+ # source = S3Source(
107
+ # endpoint='https://cos.ap-shanghai.myqcloud.com',
108
+ # access_key='',
109
+ # secret_key='',
110
+ # bucket='textin-1300705866',
111
+ # prefix='',
112
+ # region='ap-shanghai'
113
+ # )
114
+ # source = S3Source(
115
+ # endpoint='https://tos-s3-cn-shanghai.volces.com',
116
+ # access_key='',
117
+ # secret_key='',
118
+ # bucket='textin',
119
+ # prefix='',
120
+ # region='cn-shanghai'
121
+ # )
122
+ # source = S3Source(
123
+ # endpoint='https://obs.cn-east-3.myhuaweicloud.com',
124
+ # access_key='',
125
+ # secret_key='',
126
+ # bucket='textin',
127
+ # prefix='',
128
+ # region='cn-east-3'
129
+ # )
130
+ # source = S3Source(
131
+ # endpoint='https://s3.us-east-1.amazonaws.com',
132
+ # access_key='',
133
+ # secret_key='',
134
+ # bucket='textin-xparse',
135
+ # prefix='',
136
+ # region='us-east-1'
137
+ # )
138
+ # source = S3Source(
139
+ # endpoint='http://127.0.0.1:9000',
140
+ # access_key='',
141
+ # secret_key='',
142
+ # bucket='textin',
143
+ # prefix='',
144
+ # region='us-east-1'
145
+ # )
146
+ # source = SmbSource(
147
+ # host='internal-storage.intsig.net',
148
+ # share_name='ke_wang',
149
+ # username='ke_wang',
150
+ # password='',
151
+ # domain='INTSIG.COM'
152
+ # )
153
+ # source = FtpSource(
154
+ # host='127.0.0.1',
155
+ # port=21,
156
+ # username='', # 用户名,按照实际填写
157
+ # password='' # 密码,按照实际填写
158
+ # )
159
+ source = LocalSource(
160
+ directory='/Users/ke_wang/Documents/doc',
161
+ pattern='*.pdf' # 支持通配符: *.pdf, *.docx, **/*.txt
162
+ )
163
+
164
+ # 创建 Milvus 目的地
165
+ # destination = MilvusDestination(
166
+ # db_path='./milvus_pipeline1.db',
167
+ # collection_name='pipeline_collection',
168
+ # dimension=1024
169
+ # )
170
+
171
+ destination = LocalDestination(
172
+ output_dir='./result'
173
+ )
174
+
175
+ # destination = S3Destination(
176
+ # endpoint='https://cos.ap-shanghai.myqcloud.com',
177
+ # access_key='',
178
+ # secret_key='',
179
+ # bucket='textin-1300705866',
180
+ # prefix='result',
181
+ # region='ap-shanghai'
182
+ # )
183
+
184
+ # 使用新的 stages 格式创建配置
185
+ stages = [
186
+ Stage(
187
+ type='parse',
188
+ config=ParseConfig(provider='textin')
189
+ ),
190
+ Stage(
191
+ type='chunk',
192
+ config=ChunkConfig(
193
+ strategy='by_title', # 按标题分块
194
+ include_orig_elements=False,
195
+ new_after_n_chars=512,
196
+ max_characters=1024,
197
+ overlap=50 # 块之间重叠 50 字符
198
+ )
199
+ )
200
+ ]
201
+
202
+ # 配置中间结果保存
203
+ intermediate_results_destination = LocalDestination(
204
+ output_dir='./intermediate_results'
205
+ )
206
+
207
+ pipeline_config = PipelineConfig(
208
+ include_intermediate_results=True,
209
+ intermediate_results_destination=intermediate_results_destination
210
+ )
211
+
212
+ # 创建 Pipeline
213
+ pipeline = Pipeline(
214
+ source=source,
215
+ destination=destination,
216
+ api_base_url='https://textin-api-go-pre.ai.intsig.net/api/xparse',
217
+ api_headers=API_HEADERS,
218
+ stages=stages,
219
+ pipeline_config=pipeline_config
220
+ )
221
+
222
+ # 运行
223
+ pipeline.run()
224
+
225
+
226
+ # ============================================================================
227
+ # 方式 3: 本地测试(本地文件 -> 本地输出)
228
+ # ============================================================================
229
+
230
+ def run_local_test():
231
+ """使用本地文件进行测试"""
232
+
233
+ config = {
234
+ 'source': {
235
+ 'type': 'local',
236
+ 'directory': '/Users/ke_wang/Documents/doc',
237
+ 'pattern': '*.pdf'
238
+ },
239
+ 'destination': {
240
+ 'type': 's3',
241
+ 'endpoint': 'https://textin-minio-api.ai.intsig.net',
242
+ 'access_key': '',
243
+ 'secret_key': '',
244
+ 'bucket': 'textin-test',
245
+ 'prefix': '',
246
+ 'region': 'us-east-1'
247
+ },
248
+ 'api_base_url': 'https://api.textin.com/api/xparse',
249
+ 'api_headers': API_HEADERS,
250
+ # Stages 配置
251
+ 'stages': [
252
+ {
253
+ 'type': 'parse',
254
+ 'config': {
255
+ 'provider': 'textin'
256
+ }
257
+ },
258
+ {
259
+ 'type': 'embed',
260
+ 'config': {
261
+ 'provider': 'qwen',
262
+ 'model_name': 'text-embedding-v3'
263
+ }
264
+ }
265
+ ]
266
+ }
267
+
268
+ pipeline = create_pipeline_from_config(config)
269
+ pipeline.run()
270
+
271
+
272
+ # ============================================================================
273
+ # 方式 4: 处理单个文件
274
+ # ============================================================================
275
+
276
+ def run_single_file():
277
+ """只处理单个文件"""
278
+ from xparse_client import ChunkConfig, EmbedConfig, ParseConfig, Stage
279
+
280
+ # 创建 pipeline
281
+ source = LocalSource(directory='/Users/ke_wang/Documents/doc', pattern='*.pdf')
282
+ destination = LocalDestination(output_dir='./output')
283
+
284
+ # 使用新的 stages 格式创建配置
285
+ stages = [
286
+ Stage(
287
+ type='parse',
288
+ config=ParseConfig(provider='textin')
289
+ ),
290
+ Stage(
291
+ type='chunk',
292
+ config=ChunkConfig(
293
+ strategy='by_page', # 按页面分块
294
+ max_characters=2048, # 增大块大小
295
+ overlap=100
296
+ )
297
+ ),
298
+ Stage(
299
+ type='embed',
300
+ config=EmbedConfig(
301
+ provider='qwen',
302
+ model_name='text-embedding-v4' # 使用更高精度的模型
303
+ )
304
+ )
305
+ ]
306
+
307
+ pipeline = Pipeline(
308
+ source=source,
309
+ destination=destination,
310
+ api_base_url='https://api.textin.com/api/xparse',
311
+ api_headers=API_HEADERS,
312
+ stages=stages
313
+ )
314
+
315
+ # 只处理指定文件
316
+ file_path = '4e3250f00210431fb29ca0c808.pdf' # 相对于 source directory 的路径
317
+ success = pipeline.process_file(file_path)
318
+
319
+ if success:
320
+ print(f"\n✅ 文件 {file_path} 处理成功!")
321
+ else:
322
+ print(f"\n❌ 文件 {file_path} 处理失败!")
323
+
324
+
325
+ # ============================================================================
326
+ # 方式 5: 自定义处理流程
327
+ # ============================================================================
328
+
329
+ def run_custom_flow():
330
+ """自定义处理流程,手动控制文件处理"""
331
+ from xparse_client import ChunkConfig, EmbedConfig, ParseConfig, Stage
332
+
333
+ # 创建组件
334
+ source = S3Source(
335
+ endpoint='https://textin-minio-api.ai.intsig.net',
336
+ access_key='',
337
+ secret_key='',
338
+ bucket='textin-test',
339
+ prefix='',
340
+ region='us-east-1',
341
+ pattern='*.pdf'
342
+ )
343
+
344
+ destination = MilvusDestination(
345
+ db_path='./milvus_custom.db',
346
+ collection_name='custom_collection',
347
+ dimension=1024
348
+ )
349
+
350
+ # 使用新的 stages 格式创建配置
351
+ stages = [
352
+ Stage(
353
+ type='parse',
354
+ config=ParseConfig(provider='textin')
355
+ ),
356
+ Stage(
357
+ type='chunk',
358
+ config=ChunkConfig(
359
+ strategy='by_title',
360
+ include_orig_elements=True,
361
+ max_characters=1536,
362
+ overlap=80
363
+ )
364
+ ),
365
+ Stage(
366
+ type='embed',
367
+ config=EmbedConfig(
368
+ provider='qwen',
369
+ model_name='text-embedding-v4'
370
+ )
371
+ )
372
+ ]
373
+
374
+ pipeline = Pipeline(
375
+ source=source,
376
+ destination=destination,
377
+ api_base_url='https://api.textin.com/api/xparse',
378
+ api_headers=API_HEADERS,
379
+ stages=stages
380
+ )
381
+
382
+ # 手动控制文件处理
383
+ files = source.list_files()
384
+
385
+ for file_path in files[:2]: # 只处理前2个文件
386
+ print(f"\n处理: {file_path}")
387
+ file_bytes, data_source = source.read_file(file_path)
388
+ data_source['date_processed'] = datetime.now(timezone.utc).timestamp()
389
+
390
+ # 使用 pipeline 接口处理
391
+ result = pipeline.process_with_pipeline(file_bytes, file_path, data_source)
392
+
393
+ if result:
394
+ embedded, stats = result
395
+ print(f" - 原始元素: {stats.original_elements}")
396
+ print(f" - 分块后: {stats.chunked_elements}")
397
+ print(f" - 向量化: {stats.embedded_elements}")
398
+
399
+ # 写入
400
+ metadata = {
401
+ 'file_name': file_path,
402
+ 'data_source': data_source,
403
+ 'stats': {
404
+ 'original_elements': stats.original_elements,
405
+ 'chunked_elements': stats.chunked_elements,
406
+ 'embedded_elements': stats.embedded_elements
407
+ }
408
+ }
409
+ destination.write(embedded, metadata)
410
+ print(f"✓ 完成: {file_path}")
411
+ else:
412
+ print(f"✗ 失败: {file_path}")
413
+
414
+
415
+ # ============================================================================
416
+ # 主函数
417
+ # ============================================================================
418
+
419
+ def main():
420
+ """主函数 - 选择运行方式"""
421
+
422
+ print("=" * 60)
423
+ print("Pipeline 运行脚本")
424
+ print("=" * 60)
425
+ print("\n请选择运行方式:")
426
+ print("1. 使用配置字典 (S3 -> Milvus) [基础配置]")
427
+ print("2. 手动创建组件 (S3 -> Milvus) [按标题分块 + 自定义配置]")
428
+ print("3. 本地测试 (本地文件 -> 本地输出) [基础配置]")
429
+ print("4. 处理单个文件 [按页面分块 + V4模型]")
430
+ print("5. 自定义处理流程 [手动控制 + 统计信息]")
431
+ print()
432
+
433
+ try:
434
+ choice = input("请输入选项 (1-5) [默认: 1]: ").strip() or '1'
435
+
436
+ if choice == '1':
437
+ print("\n使用配置字典运行...")
438
+ run_with_config()
439
+ elif choice == '2':
440
+ print("\n手动创建组件运行...")
441
+ run_with_manual_setup()
442
+ elif choice == '3':
443
+ print("\n本地测试模式...")
444
+ run_local_test()
445
+ elif choice == '4':
446
+ print("\n处理单个文件...")
447
+ run_single_file()
448
+ elif choice == '5':
449
+ print("\n自定义处理流程...")
450
+ run_custom_flow()
451
+ else:
452
+ print("无效的选项,使用默认方式运行...")
453
+ run_with_config()
454
+
455
+ except KeyboardInterrupt:
456
+ print("\n\n用户中断执行")
457
+ except Exception as e:
458
+ print(f"\n程序异常: {str(e)}")
459
+ import traceback
460
+ traceback.print_exc()
461
+
462
+
463
+ if __name__ == '__main__':
464
+ main()
465
+