xparse-client 0.2.5__py3-none-any.whl → 0.2.7__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.
- example/run_pipeline.py +18 -17
- xparse_client/pipeline/config.py +1 -0
- xparse_client/pipeline/destinations.py +32 -7
- xparse_client/pipeline/pipeline.py +61 -23
- xparse_client/pipeline/sources.py +175 -17
- {xparse_client-0.2.5.dist-info → xparse_client-0.2.7.dist-info}/METADATA +8 -2
- xparse_client-0.2.7.dist-info/RECORD +13 -0
- xparse_client-0.2.5.dist-info/RECORD +0 -13
- {xparse_client-0.2.5.dist-info → xparse_client-0.2.7.dist-info}/WHEEL +0 -0
- {xparse_client-0.2.5.dist-info → xparse_client-0.2.7.dist-info}/licenses/LICENSE +0 -0
- {xparse_client-0.2.5.dist-info → xparse_client-0.2.7.dist-info}/top_level.txt +0 -0
example/run_pipeline.py
CHANGED
|
@@ -96,8 +96,8 @@ def run_with_manual_setup():
|
|
|
96
96
|
# )
|
|
97
97
|
# source = S3Source(
|
|
98
98
|
# endpoint='https://s3.oss-cn-shanghai.aliyuncs.com',
|
|
99
|
-
# access_key='',
|
|
100
|
-
# secret_key='',
|
|
99
|
+
# access_key='LTAI5tBgsaVfkbh9rbPyuB17',
|
|
100
|
+
# secret_key='JFIIaTGiXelv7DgBYNIBSStofF0S98',
|
|
101
101
|
# bucket='textin',
|
|
102
102
|
# prefix='',
|
|
103
103
|
# region='cn-shanghai',
|
|
@@ -113,8 +113,8 @@ def run_with_manual_setup():
|
|
|
113
113
|
# )
|
|
114
114
|
# source = S3Source(
|
|
115
115
|
# endpoint='https://tos-s3-cn-shanghai.volces.com',
|
|
116
|
-
# access_key='',
|
|
117
|
-
# secret_key='',
|
|
116
|
+
# access_key='AKLTMzNkZjk1OGM3MzBjNGQ1ZjhkMGQ4MThlNjBjYjZjYzA',
|
|
117
|
+
# secret_key='TnpWaE0yRTVaamRqTmpSbU5EY3pObUZrTTJVNE5qUm1NR0ppWkRrMFlqVQ==',
|
|
118
118
|
# bucket='textin',
|
|
119
119
|
# prefix='',
|
|
120
120
|
# region='cn-shanghai'
|
|
@@ -127,14 +127,14 @@ def run_with_manual_setup():
|
|
|
127
127
|
# prefix='',
|
|
128
128
|
# region='cn-east-3'
|
|
129
129
|
# )
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
130
|
+
source = S3Source(
|
|
131
|
+
endpoint='https://s3.us-east-1.amazonaws.com',
|
|
132
|
+
access_key='AKIA6QUE3TVZADUWA4PO',
|
|
133
|
+
secret_key='OfV4r9/u+CmlLxmiZDYwtiFSl0OsNdWLADKdPek7',
|
|
134
|
+
bucket='textin-xparse',
|
|
135
|
+
prefix='',
|
|
136
|
+
region='us-east-1'
|
|
137
|
+
)
|
|
138
138
|
# source = S3Source(
|
|
139
139
|
# endpoint='http://127.0.0.1:9000',
|
|
140
140
|
# access_key='',
|
|
@@ -153,13 +153,14 @@ def run_with_manual_setup():
|
|
|
153
153
|
# source = FtpSource(
|
|
154
154
|
# host='127.0.0.1',
|
|
155
155
|
# port=21,
|
|
156
|
+
# # recursive=True,
|
|
156
157
|
# username='', # 用户名,按照实际填写
|
|
157
158
|
# password='' # 密码,按照实际填写
|
|
158
159
|
# )
|
|
159
|
-
source = LocalSource(
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
)
|
|
160
|
+
# source = LocalSource(
|
|
161
|
+
# directory='/Users/ke_wang/Documents/doc',
|
|
162
|
+
# pattern='*.pdf' # 支持通配符: *.pdf, *.docx, **/*.txt
|
|
163
|
+
# )
|
|
163
164
|
|
|
164
165
|
# 创建 Milvus 目的地
|
|
165
166
|
# destination = MilvusDestination(
|
|
@@ -174,7 +175,7 @@ def run_with_manual_setup():
|
|
|
174
175
|
|
|
175
176
|
destination = MilvusDestination(
|
|
176
177
|
db_path='https://in03-5388093d0db1707.serverless.ali-cn-hangzhou.cloud.zilliz.com.cn', # zilliz连接地址
|
|
177
|
-
collection_name='
|
|
178
|
+
collection_name='textin_test_3', # 数据库collection名称
|
|
178
179
|
dimension=1024, # 向量维度,需与 embed API 返回一致
|
|
179
180
|
api_key='872c3f5b3f3995c80dcda5c3d34f1f608815aef7671b6ee391ab37e40e79c892ce56d9c8c6565a03a3fd66da7e11b67f384c5c46' # Zilliz Cloud API Key
|
|
180
181
|
)
|
xparse_client/pipeline/config.py
CHANGED
|
@@ -89,8 +89,7 @@ class MilvusDestination(Destination):
|
|
|
89
89
|
schema.add_field(field_name="element_id", datatype=DataType.VARCHAR, max_length=128, is_primary=True)
|
|
90
90
|
schema.add_field(field_name="embeddings", datatype=DataType.FLOAT_VECTOR, dim=dimension)
|
|
91
91
|
schema.add_field(field_name="text", datatype=DataType.VARCHAR, max_length=65535)
|
|
92
|
-
schema.add_field(field_name="record_id", datatype=DataType.VARCHAR, max_length=
|
|
93
|
-
schema.add_field(field_name="metadata", datatype=DataType.JSON)
|
|
92
|
+
schema.add_field(field_name="record_id", datatype=DataType.VARCHAR, max_length=200)
|
|
94
93
|
|
|
95
94
|
index_params = self.client.prepare_index_params()
|
|
96
95
|
index_params.add_index(
|
|
@@ -112,6 +111,32 @@ class MilvusDestination(Destination):
|
|
|
112
111
|
|
|
113
112
|
def write(self, data: List[Dict[str, Any]], metadata: Dict[str, Any]) -> bool:
|
|
114
113
|
try:
|
|
114
|
+
# 如果 metadata 中有 record_id,先删除相同 record_id 的现有记录
|
|
115
|
+
record_id = metadata.get('record_id')
|
|
116
|
+
if record_id:
|
|
117
|
+
try:
|
|
118
|
+
# 删除相同 record_id 的所有记录
|
|
119
|
+
# MilvusClient.delete 返回删除的记录数(可能是 int 或 dict)
|
|
120
|
+
result = self.client.delete(
|
|
121
|
+
collection_name=self.collection_name,
|
|
122
|
+
filter=f'record_id == "{record_id}"'
|
|
123
|
+
)
|
|
124
|
+
# 处理返回值:可能是数字或字典
|
|
125
|
+
deleted_count = result if isinstance(result, int) else result.get('delete_count', 0) if isinstance(result, dict) else 0
|
|
126
|
+
if deleted_count > 0:
|
|
127
|
+
print(f" ✓ 删除现有记录: record_id={record_id}, 删除 {deleted_count} 条")
|
|
128
|
+
logger.info(f"删除 Milvus 现有记录: record_id={record_id}, 删除 {deleted_count} 条")
|
|
129
|
+
else:
|
|
130
|
+
print(f" → 未找到现有记录: record_id={record_id}")
|
|
131
|
+
except Exception as e:
|
|
132
|
+
print(f" ! 删除现有记录失败: {str(e)}")
|
|
133
|
+
logger.warning(f"删除 Milvus 现有记录失败: record_id={record_id}, {str(e)}")
|
|
134
|
+
# 继续执行写入,不因为删除失败而中断
|
|
135
|
+
else:
|
|
136
|
+
print(f" → 没有 record_id")
|
|
137
|
+
logger.warning(f"没有 record_id")
|
|
138
|
+
return
|
|
139
|
+
|
|
115
140
|
insert_data = []
|
|
116
141
|
for item in data:
|
|
117
142
|
# 获取元素级别的 metadata
|
|
@@ -125,7 +150,7 @@ class MilvusDestination(Destination):
|
|
|
125
150
|
'embeddings': item['embeddings'],
|
|
126
151
|
'text': item.get('text', ''),
|
|
127
152
|
'element_id': element_id,
|
|
128
|
-
'record_id':
|
|
153
|
+
'record_id': record_id
|
|
129
154
|
}
|
|
130
155
|
|
|
131
156
|
# 合并文件级别的 metadata 和元素级别的 metadata
|
|
@@ -179,8 +204,8 @@ class LocalDestination(Destination):
|
|
|
179
204
|
|
|
180
205
|
def write(self, data: List[Dict[str, Any]], metadata: Dict[str, Any]) -> bool:
|
|
181
206
|
try:
|
|
182
|
-
|
|
183
|
-
base_name = Path(
|
|
207
|
+
filename = metadata.get('filename', 'output')
|
|
208
|
+
base_name = Path(filename).stem
|
|
184
209
|
stage = metadata.get('stage') # 用于区分中间结果的阶段
|
|
185
210
|
|
|
186
211
|
# 如果是中间结果,在文件名中添加阶段标识
|
|
@@ -248,8 +273,8 @@ class S3Destination(Destination):
|
|
|
248
273
|
|
|
249
274
|
def write(self, data: List[Dict[str, Any]], metadata: Dict[str, Any]) -> bool:
|
|
250
275
|
try:
|
|
251
|
-
|
|
252
|
-
base_name = Path(
|
|
276
|
+
filename = metadata.get('filename', 'output')
|
|
277
|
+
base_name = Path(filename).stem
|
|
253
278
|
object_key = f"{self.prefix}/{base_name}.json" if self.prefix else f"{base_name}.json"
|
|
254
279
|
|
|
255
280
|
json_data = json.dumps(data, ensure_ascii=False, indent=2)
|
|
@@ -79,13 +79,13 @@ class Pipeline:
|
|
|
79
79
|
print(f" Pipeline Config: 中间结果保存已启用")
|
|
80
80
|
print("=" * 60)
|
|
81
81
|
|
|
82
|
-
def _call_pipeline_api(self, file_bytes: bytes,
|
|
82
|
+
def _call_pipeline_api(self, file_bytes: bytes, filename: str, data_source: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
83
83
|
url = f"{self.api_base_url}/pipeline"
|
|
84
84
|
max_retries = 3
|
|
85
85
|
|
|
86
86
|
for try_count in range(max_retries):
|
|
87
87
|
try:
|
|
88
|
-
files = {'file': (
|
|
88
|
+
files = {'file': (filename or 'file', file_bytes)}
|
|
89
89
|
form_data = {}
|
|
90
90
|
|
|
91
91
|
# 将 stages 转换为 API 格式
|
|
@@ -107,26 +107,55 @@ class Pipeline:
|
|
|
107
107
|
|
|
108
108
|
if response.status_code == 200:
|
|
109
109
|
result = response.json()
|
|
110
|
-
|
|
110
|
+
x_request_id = result.get('x_request_id', '')
|
|
111
|
+
print(f" ✓ Pipeline 接口返回 x_request_id: {x_request_id}")
|
|
111
112
|
if result.get('code') == 200 and 'data' in result:
|
|
112
113
|
return result.get('data')
|
|
114
|
+
# 如果 code 不是 200,打印错误信息
|
|
115
|
+
error_msg = result.get('message', result.get('msg', '未知错误'))
|
|
116
|
+
print(f" ✗ Pipeline 接口返回错误: code={result.get('code')}, message={error_msg}, x_request_id={x_request_id}")
|
|
117
|
+
logger.error(f"Pipeline 接口返回错误: code={result.get('code')}, message={error_msg}, x_request_id={x_request_id}")
|
|
113
118
|
return None
|
|
114
119
|
else:
|
|
115
|
-
|
|
116
|
-
|
|
120
|
+
# 尝试解析响应获取 x_request_id 和错误信息
|
|
121
|
+
x_request_id = ''
|
|
122
|
+
error_msg = ''
|
|
123
|
+
try:
|
|
124
|
+
result = response.json()
|
|
125
|
+
x_request_id = result.get('x_request_id', '')
|
|
126
|
+
error_msg = result.get('message', result.get('msg', response.text[:200]))
|
|
127
|
+
except:
|
|
128
|
+
error_msg = response.text[:200] if response.text else f'HTTP {response.status_code}'
|
|
129
|
+
|
|
130
|
+
print(f" ✗ API 错误 {response.status_code}: {error_msg}, x_request_id={x_request_id}, 重试 {try_count + 1}/{max_retries}")
|
|
131
|
+
logger.warning(f"API 错误 {response.status_code}: {error_msg}, x_request_id={x_request_id}, 重试 {try_count + 1}/{max_retries}")
|
|
117
132
|
|
|
118
133
|
except Exception as e:
|
|
119
|
-
|
|
120
|
-
|
|
134
|
+
# 如果是 requests 异常,尝试从响应中获取 x_request_id
|
|
135
|
+
x_request_id = ''
|
|
136
|
+
error_msg = str(e)
|
|
137
|
+
try:
|
|
138
|
+
if hasattr(e, 'response') and e.response is not None:
|
|
139
|
+
try:
|
|
140
|
+
result = e.response.json()
|
|
141
|
+
x_request_id = result.get('x_request_id', '')
|
|
142
|
+
error_msg = result.get('message', result.get('msg', error_msg))
|
|
143
|
+
except:
|
|
144
|
+
pass
|
|
145
|
+
except:
|
|
146
|
+
pass
|
|
147
|
+
|
|
148
|
+
print(f" ✗ 请求异常: {error_msg}, x_request_id={x_request_id}, 重试 {try_count + 1}/{max_retries}")
|
|
149
|
+
logger.error(f"API 请求异常 pipeline: {error_msg}, x_request_id={x_request_id}")
|
|
121
150
|
|
|
122
151
|
if try_count < max_retries - 1:
|
|
123
152
|
time.sleep(2)
|
|
124
153
|
|
|
125
154
|
return None
|
|
126
155
|
|
|
127
|
-
def process_with_pipeline(self, file_bytes: bytes,
|
|
128
|
-
print(f" → 调用 Pipeline 接口: {
|
|
129
|
-
result = self._call_pipeline_api(file_bytes,
|
|
156
|
+
def process_with_pipeline(self, file_bytes: bytes, filename: str, data_source: Dict[str, Any]) -> Optional[Tuple[List[Dict[str, Any]], PipelineStats]]:
|
|
157
|
+
print(f" → 调用 Pipeline 接口: {filename}")
|
|
158
|
+
result = self._call_pipeline_api(file_bytes, filename, data_source)
|
|
130
159
|
|
|
131
160
|
if result and 'elements' in result and 'stats' in result:
|
|
132
161
|
elements = result['elements']
|
|
@@ -136,31 +165,32 @@ class Pipeline:
|
|
|
136
165
|
original_elements=stats_data.get('original_elements', 0),
|
|
137
166
|
chunked_elements=stats_data.get('chunked_elements', 0),
|
|
138
167
|
embedded_elements=stats_data.get('embedded_elements', 0),
|
|
139
|
-
stages=self.stages # 使用实际执行的 stages
|
|
168
|
+
stages=self.stages, # 使用实际执行的 stages
|
|
169
|
+
record_id=stats_data.get('record_id') # 从 API 响应中获取 record_id
|
|
140
170
|
)
|
|
141
171
|
|
|
142
172
|
# 如果启用了中间结果保存,处理中间结果
|
|
143
173
|
if self.pipeline_config.include_intermediate_results and 'intermediate_results' in result:
|
|
144
|
-
self._save_intermediate_results(result['intermediate_results'],
|
|
174
|
+
self._save_intermediate_results(result['intermediate_results'], filename, data_source)
|
|
145
175
|
|
|
146
176
|
print(f" ✓ Pipeline 完成:")
|
|
147
177
|
print(f" - 原始元素: {stats.original_elements}")
|
|
148
178
|
print(f" - 分块后: {stats.chunked_elements}")
|
|
149
179
|
print(f" - 向量化: {stats.embedded_elements}")
|
|
150
|
-
logger.info(f"Pipeline 完成: {
|
|
180
|
+
logger.info(f"Pipeline 完成: {filename}, {stats.embedded_elements} 个向量")
|
|
151
181
|
|
|
152
182
|
return elements, stats
|
|
153
183
|
else:
|
|
154
184
|
print(f" ✗ Pipeline 失败")
|
|
155
|
-
logger.error(f"Pipeline 失败: {
|
|
185
|
+
logger.error(f"Pipeline 失败: {filename}")
|
|
156
186
|
return None
|
|
157
187
|
|
|
158
|
-
def _save_intermediate_results(self, intermediate_results: List[Dict[str, Any]],
|
|
188
|
+
def _save_intermediate_results(self, intermediate_results: List[Dict[str, Any]], filename: str, data_source: Dict[str, Any]) -> None:
|
|
159
189
|
"""保存中间结果
|
|
160
190
|
|
|
161
191
|
Args:
|
|
162
192
|
intermediate_results: 中间结果数组,每个元素包含 stage 和 elements 字段
|
|
163
|
-
|
|
193
|
+
filename: 文件名
|
|
164
194
|
data_source: 数据源信息
|
|
165
195
|
"""
|
|
166
196
|
try:
|
|
@@ -174,7 +204,7 @@ class Pipeline:
|
|
|
174
204
|
elements = result_item['elements']
|
|
175
205
|
|
|
176
206
|
metadata = {
|
|
177
|
-
'
|
|
207
|
+
'filename': filename,
|
|
178
208
|
'stage': stage,
|
|
179
209
|
'total_elements': len(elements),
|
|
180
210
|
'processed_at': datetime.now().isoformat(),
|
|
@@ -183,11 +213,11 @@ class Pipeline:
|
|
|
183
213
|
|
|
184
214
|
self.pipeline_config.intermediate_results_destination.write(elements, metadata)
|
|
185
215
|
print(f" ✓ 保存 {stage.upper()} 中间结果: {len(elements)} 个元素")
|
|
186
|
-
logger.info(f"保存 {stage.upper()} 中间结果成功: {
|
|
216
|
+
logger.info(f"保存 {stage.upper()} 中间结果成功: {filename}")
|
|
187
217
|
|
|
188
218
|
except Exception as e:
|
|
189
219
|
print(f" ✗ 保存中间结果失败: {str(e)}")
|
|
190
|
-
logger.error(f"保存中间结果失败: {
|
|
220
|
+
logger.error(f"保存中间结果失败: {filename}, {str(e)}")
|
|
191
221
|
|
|
192
222
|
def process_file(self, file_path: str) -> bool:
|
|
193
223
|
print(f"\n{'=' * 60}")
|
|
@@ -214,6 +244,10 @@ class Pipeline:
|
|
|
214
244
|
'filename': file_path,
|
|
215
245
|
'processed_at': str(timestamp_ms),
|
|
216
246
|
}
|
|
247
|
+
|
|
248
|
+
# 如果 stats 中有 record_id,添加到 metadata 中
|
|
249
|
+
if stats.record_id:
|
|
250
|
+
metadata['record_id'] = stats.record_id
|
|
217
251
|
|
|
218
252
|
success = self.destination.write(embedded_data, metadata)
|
|
219
253
|
|
|
@@ -294,12 +328,14 @@ def create_pipeline_from_config(config: Dict[str, Any]) -> Pipeline:
|
|
|
294
328
|
bucket=source_config['bucket'],
|
|
295
329
|
prefix=source_config.get('prefix', ''),
|
|
296
330
|
region=source_config.get('region', 'us-east-1'),
|
|
297
|
-
pattern=source_config.get('pattern', '*')
|
|
331
|
+
pattern=source_config.get('pattern', '*'),
|
|
332
|
+
recursive=source_config.get('recursive', False)
|
|
298
333
|
)
|
|
299
334
|
elif source_config['type'] == 'local':
|
|
300
335
|
source = LocalSource(
|
|
301
336
|
directory=source_config['directory'],
|
|
302
|
-
pattern=source_config.get('pattern', '*')
|
|
337
|
+
pattern=source_config.get('pattern', '*'),
|
|
338
|
+
recursive=source_config.get('recursive', False)
|
|
303
339
|
)
|
|
304
340
|
elif source_config['type'] == 'ftp':
|
|
305
341
|
source = FtpSource(
|
|
@@ -307,7 +343,8 @@ def create_pipeline_from_config(config: Dict[str, Any]) -> Pipeline:
|
|
|
307
343
|
port=source_config['port'],
|
|
308
344
|
username=source_config['username'],
|
|
309
345
|
password=source_config['password'],
|
|
310
|
-
pattern=source_config.get('pattern', '*')
|
|
346
|
+
pattern=source_config.get('pattern', '*'),
|
|
347
|
+
recursive=source_config.get('recursive', False)
|
|
311
348
|
)
|
|
312
349
|
elif source_config['type'] == 'smb':
|
|
313
350
|
source = SmbSource(
|
|
@@ -318,7 +355,8 @@ def create_pipeline_from_config(config: Dict[str, Any]) -> Pipeline:
|
|
|
318
355
|
domain=source_config.get('domain', ''),
|
|
319
356
|
port=source_config.get('port', 445),
|
|
320
357
|
path=source_config.get('path', ''),
|
|
321
|
-
pattern=source_config.get('pattern', '*')
|
|
358
|
+
pattern=source_config.get('pattern', '*'),
|
|
359
|
+
recursive=source_config.get('recursive', False)
|
|
322
360
|
)
|
|
323
361
|
else:
|
|
324
362
|
raise ValueError(f"未知的 source 类型: {source_config['type']}")
|
|
@@ -62,11 +62,12 @@ class S3Source(Source):
|
|
|
62
62
|
"""S3/MinIO 数据源"""
|
|
63
63
|
|
|
64
64
|
def __init__(self, endpoint: str, access_key: str, secret_key: str,
|
|
65
|
-
bucket: str, prefix: str = '', region: str = 'us-east-1', pattern: str = '*'):
|
|
65
|
+
bucket: str, prefix: str = '', region: str = 'us-east-1', pattern: str = '*', recursive: bool = False):
|
|
66
66
|
self.endpoint = endpoint
|
|
67
67
|
self.bucket = bucket
|
|
68
68
|
self.prefix = prefix
|
|
69
69
|
self.pattern = pattern or '*'
|
|
70
|
+
self.recursive = recursive
|
|
70
71
|
|
|
71
72
|
if self.endpoint == 'https://textin-minio-api.ai.intsig.net':
|
|
72
73
|
config = Config(signature_version='s3v4')
|
|
@@ -97,6 +98,9 @@ class S3Source(Source):
|
|
|
97
98
|
params = {'Bucket': self.bucket}
|
|
98
99
|
if self.prefix:
|
|
99
100
|
params['Prefix'] = self.prefix
|
|
101
|
+
if not self.recursive:
|
|
102
|
+
# 非递归模式:使用 Delimiter 只列出当前目录下的文件
|
|
103
|
+
params['Delimiter'] = '/'
|
|
100
104
|
|
|
101
105
|
for page in paginator.paginate(**params):
|
|
102
106
|
if 'Contents' in page:
|
|
@@ -106,6 +110,11 @@ class S3Source(Source):
|
|
|
106
110
|
continue
|
|
107
111
|
if fnmatch(key, self.pattern):
|
|
108
112
|
files.append(key)
|
|
113
|
+
|
|
114
|
+
# 非递归模式下,CommonPrefixes 包含子目录,我们忽略它们
|
|
115
|
+
if not self.recursive and 'CommonPrefixes' in page:
|
|
116
|
+
# 这些是子目录,在非递归模式下忽略
|
|
117
|
+
pass
|
|
109
118
|
|
|
110
119
|
print(f"✓ S3 找到 {len(files)} 个文件")
|
|
111
120
|
return files
|
|
@@ -115,7 +124,9 @@ class S3Source(Source):
|
|
|
115
124
|
file_bytes = response['Body'].read()
|
|
116
125
|
|
|
117
126
|
headers = response.get('ResponseMetadata', {}).get('HTTPHeaders', {})
|
|
118
|
-
version =
|
|
127
|
+
version = headers.get('etag') or ""
|
|
128
|
+
if version.startswith('"') and version.endswith('"'):
|
|
129
|
+
version = version[1:-1]
|
|
119
130
|
last_modified = headers.get('last-modified')
|
|
120
131
|
server = headers.get('server') or "unknown"
|
|
121
132
|
date_modified = None
|
|
@@ -145,9 +156,10 @@ class S3Source(Source):
|
|
|
145
156
|
class LocalSource(Source):
|
|
146
157
|
"""本地文件系统数据源"""
|
|
147
158
|
|
|
148
|
-
def __init__(self, directory: str, pattern: str = '*'):
|
|
159
|
+
def __init__(self, directory: str, pattern: str = '*', recursive: bool = False):
|
|
149
160
|
self.directory = Path(directory)
|
|
150
161
|
self.pattern = pattern or '*'
|
|
162
|
+
self.recursive = recursive
|
|
151
163
|
|
|
152
164
|
if not self.directory.exists():
|
|
153
165
|
raise ValueError(f"目录不存在: {directory}")
|
|
@@ -156,11 +168,20 @@ class LocalSource(Source):
|
|
|
156
168
|
logger.info(f"本地目录: {self.directory}")
|
|
157
169
|
|
|
158
170
|
def list_files(self) -> List[str]:
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
171
|
+
if self.recursive:
|
|
172
|
+
# 递归模式:使用 rglob
|
|
173
|
+
files = [
|
|
174
|
+
str(f.relative_to(self.directory))
|
|
175
|
+
for f in self.directory.rglob(self.pattern)
|
|
176
|
+
if f.is_file()
|
|
177
|
+
]
|
|
178
|
+
else:
|
|
179
|
+
# 非递归模式:只列出根目录下的文件,使用 glob
|
|
180
|
+
files = [
|
|
181
|
+
str(f.relative_to(self.directory))
|
|
182
|
+
for f in self.directory.glob(self.pattern)
|
|
183
|
+
if f.is_file()
|
|
184
|
+
]
|
|
164
185
|
print(f"✓ 本地找到 {len(files)} 个文件")
|
|
165
186
|
return files
|
|
166
187
|
|
|
@@ -196,12 +217,13 @@ class LocalSource(Source):
|
|
|
196
217
|
class FtpSource(Source):
|
|
197
218
|
"""FTP 数据源"""
|
|
198
219
|
|
|
199
|
-
def __init__(self, host: str, port: int, username: str, password: str, pattern: str = '*'):
|
|
220
|
+
def __init__(self, host: str, port: int, username: str, password: str, pattern: str = '*', recursive: bool = False):
|
|
200
221
|
self.host = host
|
|
201
222
|
self.port = port
|
|
202
223
|
self.username = username
|
|
203
224
|
self.password = password
|
|
204
225
|
self.pattern = pattern or '*'
|
|
226
|
+
self.recursive = recursive
|
|
205
227
|
|
|
206
228
|
self.client = ftplib.FTP()
|
|
207
229
|
self.client.connect(self.host, self.port)
|
|
@@ -211,8 +233,139 @@ class FtpSource(Source):
|
|
|
211
233
|
logger.info(f"FTP 连接成功: {self.host}:{self.port}")
|
|
212
234
|
|
|
213
235
|
def list_files(self) -> List[str]:
|
|
214
|
-
|
|
215
|
-
|
|
236
|
+
if self.recursive:
|
|
237
|
+
# 递归模式:递归列出所有文件
|
|
238
|
+
files = []
|
|
239
|
+
current_dir = self.client.pwd()
|
|
240
|
+
|
|
241
|
+
def _list_recursive(path=''):
|
|
242
|
+
try:
|
|
243
|
+
# 保存当前目录
|
|
244
|
+
original_dir = self.client.pwd()
|
|
245
|
+
if path:
|
|
246
|
+
try:
|
|
247
|
+
self.client.cwd(path)
|
|
248
|
+
except:
|
|
249
|
+
return
|
|
250
|
+
|
|
251
|
+
items = []
|
|
252
|
+
try:
|
|
253
|
+
# 尝试使用 MLSD 命令(更可靠)
|
|
254
|
+
items = []
|
|
255
|
+
for item in self.client.mlsd():
|
|
256
|
+
items.append(item)
|
|
257
|
+
except:
|
|
258
|
+
# 如果不支持 MLSD,使用 LIST 命令
|
|
259
|
+
try:
|
|
260
|
+
lines = []
|
|
261
|
+
self.client.retrlines('LIST', lines.append)
|
|
262
|
+
for line in lines:
|
|
263
|
+
parts = line.split()
|
|
264
|
+
if len(parts) >= 9:
|
|
265
|
+
# 解析 LIST 输出,第一个字符表示文件类型
|
|
266
|
+
item_name = ' '.join(parts[8:])
|
|
267
|
+
is_dir = parts[0].startswith('d')
|
|
268
|
+
items.append((item_name, {'type': 'dir' if is_dir else 'file'}))
|
|
269
|
+
except:
|
|
270
|
+
# 最后回退到 nlst,但无法区分文件和目录
|
|
271
|
+
for item_name in self.client.nlst():
|
|
272
|
+
items.append((item_name, {'type': 'unknown'}))
|
|
273
|
+
|
|
274
|
+
for item_name, item_info in items:
|
|
275
|
+
if item_name in ['.', '..']:
|
|
276
|
+
continue
|
|
277
|
+
|
|
278
|
+
item_type = item_info.get('type', 'unknown')
|
|
279
|
+
full_path = f"{path}/{item_name}" if path else item_name
|
|
280
|
+
|
|
281
|
+
if item_type == 'dir' or item_type == 'unknown':
|
|
282
|
+
# 尝试切换目录来判断是否为目录
|
|
283
|
+
try:
|
|
284
|
+
self.client.cwd(item_name)
|
|
285
|
+
self.client.cwd('..')
|
|
286
|
+
# 是目录,递归处理
|
|
287
|
+
_list_recursive(full_path)
|
|
288
|
+
except:
|
|
289
|
+
# 不是目录,是文件
|
|
290
|
+
relative_path = full_path.lstrip('/')
|
|
291
|
+
if fnmatch(relative_path, self.pattern):
|
|
292
|
+
files.append(relative_path)
|
|
293
|
+
else:
|
|
294
|
+
# 是文件
|
|
295
|
+
relative_path = full_path.lstrip('/')
|
|
296
|
+
if fnmatch(relative_path, self.pattern):
|
|
297
|
+
files.append(relative_path)
|
|
298
|
+
|
|
299
|
+
# 恢复原始目录
|
|
300
|
+
self.client.cwd(original_dir)
|
|
301
|
+
except Exception as e:
|
|
302
|
+
logger.warning(f"FTP 列出路径失败 {path}: {str(e)}")
|
|
303
|
+
try:
|
|
304
|
+
self.client.cwd(current_dir)
|
|
305
|
+
except:
|
|
306
|
+
pass
|
|
307
|
+
|
|
308
|
+
_list_recursive()
|
|
309
|
+
# 确保回到原始目录
|
|
310
|
+
try:
|
|
311
|
+
self.client.cwd(current_dir)
|
|
312
|
+
except:
|
|
313
|
+
pass
|
|
314
|
+
else:
|
|
315
|
+
# 非递归模式:只列出当前目录下的文件(排除目录)
|
|
316
|
+
files = []
|
|
317
|
+
current_dir = self.client.pwd()
|
|
318
|
+
|
|
319
|
+
try:
|
|
320
|
+
# 尝试使用 MLSD 命令(更可靠)
|
|
321
|
+
items = []
|
|
322
|
+
for item_name, item_info in self.client.mlsd():
|
|
323
|
+
if item_name in ['.', '..']:
|
|
324
|
+
continue
|
|
325
|
+
item_type = item_info.get('type', 'unknown')
|
|
326
|
+
# 只添加文件,排除目录
|
|
327
|
+
if item_type == 'file' or (item_type == 'unknown' and not item_info.get('type', '').startswith('dir')):
|
|
328
|
+
if fnmatch(item_name, self.pattern):
|
|
329
|
+
files.append(item_name)
|
|
330
|
+
except:
|
|
331
|
+
# 如果不支持 MLSD,使用 LIST 命令
|
|
332
|
+
try:
|
|
333
|
+
lines = []
|
|
334
|
+
self.client.retrlines('LIST', lines.append)
|
|
335
|
+
for line in lines:
|
|
336
|
+
parts = line.split()
|
|
337
|
+
if len(parts) >= 9:
|
|
338
|
+
# 解析 LIST 输出,第一个字符表示文件类型
|
|
339
|
+
item_name = ' '.join(parts[8:])
|
|
340
|
+
if item_name in ['.', '..']:
|
|
341
|
+
continue
|
|
342
|
+
is_dir = parts[0].startswith('d')
|
|
343
|
+
# 只添加文件,排除目录
|
|
344
|
+
if not is_dir and fnmatch(item_name, self.pattern):
|
|
345
|
+
files.append(item_name)
|
|
346
|
+
except:
|
|
347
|
+
# 最后回退到 nlst,通过尝试切换目录来判断是否为目录
|
|
348
|
+
raw_items = self.client.nlst()
|
|
349
|
+
for item_name in raw_items:
|
|
350
|
+
if item_name in ['.', '..']:
|
|
351
|
+
continue
|
|
352
|
+
# 尝试切换目录来判断是否为目录
|
|
353
|
+
try:
|
|
354
|
+
self.client.cwd(item_name)
|
|
355
|
+
self.client.cwd('..')
|
|
356
|
+
# 能切换成功,说明是目录,跳过
|
|
357
|
+
continue
|
|
358
|
+
except:
|
|
359
|
+
# 不能切换,说明是文件
|
|
360
|
+
if fnmatch(item_name, self.pattern):
|
|
361
|
+
files.append(item_name)
|
|
362
|
+
|
|
363
|
+
# 确保回到原始目录
|
|
364
|
+
try:
|
|
365
|
+
self.client.cwd(current_dir)
|
|
366
|
+
except:
|
|
367
|
+
pass
|
|
368
|
+
|
|
216
369
|
print(f"✓ FTP 找到 {len(files)} 个文件 (匹配 pattern)")
|
|
217
370
|
return files
|
|
218
371
|
|
|
@@ -232,11 +385,12 @@ class FtpSource(Source):
|
|
|
232
385
|
logger.debug(f"FTP 获取文件时间失败 {file_path}: {exc}")
|
|
233
386
|
|
|
234
387
|
normalized_path = file_path.lstrip('/')
|
|
388
|
+
version = _to_millis_timestamp_string(date_modified)
|
|
235
389
|
data_source = {
|
|
236
390
|
'url': f"ftp://{self.host}:{self.port}/{normalized_path}",
|
|
237
|
-
'version':
|
|
238
|
-
'date_created':
|
|
239
|
-
'date_modified':
|
|
391
|
+
'version': version,
|
|
392
|
+
'date_created': version,
|
|
393
|
+
'date_modified': version,
|
|
240
394
|
'record_locator': {
|
|
241
395
|
'server': f"{self.host}:{self.port}",
|
|
242
396
|
'protocol': 'ftp',
|
|
@@ -251,7 +405,7 @@ class SmbSource(Source):
|
|
|
251
405
|
"""SMB/CIFS 数据源"""
|
|
252
406
|
|
|
253
407
|
def __init__(self, host: str, share_name: str, username: str, password: str,
|
|
254
|
-
domain: str = '', port: int = 445, path: str = '', pattern: str = '*'):
|
|
408
|
+
domain: str = '', port: int = 445, path: str = '', pattern: str = '*', recursive: bool = False):
|
|
255
409
|
self.host = host
|
|
256
410
|
self.share_name = share_name
|
|
257
411
|
self.username = username
|
|
@@ -260,6 +414,7 @@ class SmbSource(Source):
|
|
|
260
414
|
self.port = port
|
|
261
415
|
self.path = path.strip('/').strip('\\') if path else ''
|
|
262
416
|
self.pattern = pattern or '*'
|
|
417
|
+
self.recursive = recursive
|
|
263
418
|
|
|
264
419
|
self.conn = SMBConnection(
|
|
265
420
|
username,
|
|
@@ -291,7 +446,10 @@ class SmbSource(Source):
|
|
|
291
446
|
item_path = f"{current_path.rstrip('/')}/{item.filename}" if current_path != '/' else f"/{item.filename}"
|
|
292
447
|
relative_path = item_path[len(base_path):].lstrip('/')
|
|
293
448
|
if item.isDirectory:
|
|
294
|
-
|
|
449
|
+
if self.recursive:
|
|
450
|
+
# 递归模式:继续递归子目录
|
|
451
|
+
_list_recursive(conn, share, item_path)
|
|
452
|
+
# 非递归模式:忽略子目录
|
|
295
453
|
else:
|
|
296
454
|
if fnmatch(relative_path, self.pattern):
|
|
297
455
|
files.append(relative_path)
|
|
@@ -334,7 +492,7 @@ class SmbSource(Source):
|
|
|
334
492
|
smb_url = f"smb://{self.host}/{self.share_name}{full_path}"
|
|
335
493
|
data_source = {
|
|
336
494
|
'url': smb_url,
|
|
337
|
-
'version':
|
|
495
|
+
'version': _to_millis_timestamp_string(date_modified),
|
|
338
496
|
'date_created': _to_millis_timestamp_string(date_created),
|
|
339
497
|
'date_modified': _to_millis_timestamp_string(date_modified),
|
|
340
498
|
'record_locator': {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: xparse-client
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.7
|
|
4
4
|
Summary: 面向Agent和RAG的新一代文档处理 AI Infra
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
Project-URL: Homepage, https://gitlab.intsig.net/xparse1/xparse-pipeline
|
|
@@ -323,12 +323,16 @@ source = SmbSource(
|
|
|
323
323
|
)
|
|
324
324
|
```
|
|
325
325
|
|
|
326
|
-
>
|
|
326
|
+
> 注 1:所有 Source 均支持 `pattern` 参数,使用 Shell 通配符(`*.pdf`、`**/*.txt` 等)来过滤需要处理的文件;默认为 `*`,即处理全部文件。
|
|
327
|
+
|
|
328
|
+
> 注 2:所有 Source 均支持 `recursive` 参数,表示是否递归遍历,默认为 `False`。
|
|
327
329
|
|
|
328
330
|
### Destination 配置
|
|
329
331
|
|
|
330
332
|
#### 本地 Milvus 向量存储
|
|
331
333
|
|
|
334
|
+
collection 中至少需要包含 `element_id`,`text`,`embeddings`,`record_id` 四个字段。
|
|
335
|
+
|
|
332
336
|
```python
|
|
333
337
|
destination = MilvusDestination(
|
|
334
338
|
db_path='./milvus_pipeline.db', # 本地数据库文件
|
|
@@ -339,6 +343,8 @@ destination = MilvusDestination(
|
|
|
339
343
|
|
|
340
344
|
#### Zilliz 向量存储
|
|
341
345
|
|
|
346
|
+
collection 中至少需要包含 `element_id`,`text`,`embeddings`,`record_id` 四个字段。
|
|
347
|
+
|
|
342
348
|
```python
|
|
343
349
|
destination = MilvusDestination(
|
|
344
350
|
db_path='https://xxxxxxx.serverless.xxxxxxx.cloud.zilliz.com.cn', # zilliz连接地址
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
example/run_pipeline.py,sha256=ijws5q_vMmV0-bMHuFtOUMrEnxnL1LvOBCtcCD2c8zc,15366
|
|
2
|
+
example/run_pipeline_test.py,sha256=uIU09FTv_VnTQS1Lc94ydc3kaD86eHkaHQbVXpsGEcA,14861
|
|
3
|
+
xparse_client/__init__.py,sha256=je1ena3HwLL4CRtLU4r6EAzoOIJthlPjTwshxZnzQDM,1677
|
|
4
|
+
xparse_client/pipeline/__init__.py,sha256=TVlb2AGCNKP0jrv3p4ZLZCPKp68hTVMFi00DTdi6QAo,49
|
|
5
|
+
xparse_client/pipeline/config.py,sha256=FFYq2a0dBWBEj70s2aInXOiQ5MwwHimd6SI2_tkp52w,4138
|
|
6
|
+
xparse_client/pipeline/destinations.py,sha256=F0z1AgVIBOn0m32i4l7LCMkJE0IbBdlpykO_at_wLaE,11931
|
|
7
|
+
xparse_client/pipeline/pipeline.py,sha256=pHw32eo-bRegzDvkuVUu0CjMXMejJ64dDXH7esGMXjg,20379
|
|
8
|
+
xparse_client/pipeline/sources.py,sha256=UeVbWv6n0wQkIZIBBhrFCiyydQX7cvwmkoMgcf12p9g,19940
|
|
9
|
+
xparse_client-0.2.7.dist-info/licenses/LICENSE,sha256=ckIP-MbocsP9nqYnta5KgfAicYF196B5TNdHIR6kOO0,1075
|
|
10
|
+
xparse_client-0.2.7.dist-info/METADATA,sha256=qMHiAq2qdH4vfW5zktrYrh9Kj72JxBDERVht8KYerl0,26805
|
|
11
|
+
xparse_client-0.2.7.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
12
|
+
xparse_client-0.2.7.dist-info/top_level.txt,sha256=bfX8BWo1sEEQVsI4Ql4Uu80vrfEh5zfajU9YqFTzxMo,22
|
|
13
|
+
xparse_client-0.2.7.dist-info/RECORD,,
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
example/run_pipeline.py,sha256=6gavTizAIqD62g4n9Pjq2-yW57ItZMJOOw8GEKm0Byk,15125
|
|
2
|
-
example/run_pipeline_test.py,sha256=uIU09FTv_VnTQS1Lc94ydc3kaD86eHkaHQbVXpsGEcA,14861
|
|
3
|
-
xparse_client/__init__.py,sha256=je1ena3HwLL4CRtLU4r6EAzoOIJthlPjTwshxZnzQDM,1677
|
|
4
|
-
xparse_client/pipeline/__init__.py,sha256=TVlb2AGCNKP0jrv3p4ZLZCPKp68hTVMFi00DTdi6QAo,49
|
|
5
|
-
xparse_client/pipeline/config.py,sha256=gkhAF-55PNvPPyfTZ0HkP95XB_K0HKCyYl6R4PTQLhI,4045
|
|
6
|
-
xparse_client/pipeline/destinations.py,sha256=dXtsYw6xu_pBH8GKu9zKRzD6qP6Krgg-l1zCTzj8PhU,10475
|
|
7
|
-
xparse_client/pipeline/pipeline.py,sha256=nWebrMGJjxTKF1de-7DeNtyozuUOkh3zbAqv-Q78Ev4,18039
|
|
8
|
-
xparse_client/pipeline/sources.py,sha256=NdME4mTSzC7JXXhaw985Tt_nc0y_aRUl2NEALm8xLII,12484
|
|
9
|
-
xparse_client-0.2.5.dist-info/licenses/LICENSE,sha256=ckIP-MbocsP9nqYnta5KgfAicYF196B5TNdHIR6kOO0,1075
|
|
10
|
-
xparse_client-0.2.5.dist-info/METADATA,sha256=iN0qG5s4bc1hAueNx0VucDekicwdF-kQ5IzUWH2tJd4,26500
|
|
11
|
-
xparse_client-0.2.5.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
12
|
-
xparse_client-0.2.5.dist-info/top_level.txt,sha256=bfX8BWo1sEEQVsI4Ql4Uu80vrfEh5zfajU9YqFTzxMo,22
|
|
13
|
-
xparse_client-0.2.5.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|