feat(pre_process_file):解决hxops上传excel行截断的问题,由markdown换为命中更好的key=value的方式;dify同步custom;行间\n\n,数据行单独成块;

This commit is contained in:
super committed 2026-06-11 11:19:21 +08:00
1 parent a18a07ef1a
commit 67d08924a4
25 files changed
+655 -25

No files matched your search

@@ -16,6 +16,30 @@ from app.services.db_sequence import add_and_flush_with_sequence_retry
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
_EXCEL_SOURCE_EXTENSIONS = frozenset({'xlsx', 'xls', 'csv'})
def _decode_separator(value: str) -> str:
"""Turn env/AppSetting escape sequences into real separator characters."""
return str(value or '').replace('\\n', '\n').replace('\\t', '\t')
def _as_bool_setting(value: str | None) -> bool:
return str(value or '').strip().lower() in ('true', '1', 'yes', 'on')
def resolve_source_file_ext(version: KbDocumentVersion) -> str | None:
"""Lowercase extension without dot, e.g. xlsx."""
ext = str(version.source_file_ext or '').strip().lower().lstrip('.')
if ext:
return ext
name = str(version.source_file_name or '').strip()
if not name:
return None
suffix = Path(name).suffix.lower().lstrip('.')
return suffix or None
class KbDifySyncError(RuntimeError):
pass
@@ -29,8 +53,44 @@ class KbDifySyncService:
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
self.process_mode = str(settings.get('KB_DIFY_PROCESS_MODE') or 'automatic').strip().lower()
self.process_mode_excel = str(settings.get('KB_DIFY_PROCESS_MODE_EXCEL') or 'custom').strip().lower()
self.segment_separator = _decode_separator(str(settings.get('KB_DIFY_SEGMENT_SEPARATOR') or '\\n\\n'))
self.segment_separator_excel = _decode_separator(
str(settings.get('KB_DIFY_SEGMENT_SEPARATOR_EXCEL') or '\\n\\n')
)
self.segment_max_tokens = int(str(settings.get('KB_DIFY_SEGMENT_MAX_TOKENS') or '800'))
self.segment_chunk_overlap = int(str(settings.get('KB_DIFY_SEGMENT_CHUNK_OVERLAP') or '50'))
self.remove_urls_emails = _as_bool_setting(settings.get('KB_DIFY_REMOVE_URLS'))
self.timeout = 60
def _build_process_rule(self, source_ext: str | None = None) -> dict:
ext = str(source_ext or '').strip().lower().lstrip('.')
if ext in _EXCEL_SOURCE_EXTENSIONS:
mode = self.process_mode_excel
separator = self.segment_separator_excel
else:
mode = self.process_mode
separator = self.segment_separator
if mode != 'custom':
return {'mode': 'automatic'}
return {
'mode': 'custom',
'rules': {
'pre_processing_rules': [
{'id': 'remove_extra_spaces', 'enabled': True},
{'id': 'remove_urls_emails', 'enabled': self.remove_urls_emails},
],
'segmentation': {
'separator': separator,
'max_tokens': self.segment_max_tokens,
'chunk_overlap': self.segment_chunk_overlap,
},
},
}
def _headers(self) -> dict[str, str]:
if not self.base_url:
raise KbDifySyncError('DIFY_API_BASE 未配置')
@@ -100,21 +160,36 @@ class KbDifySyncService:
db.session.commit()
return group.dify_dataset_id, group.dify_dataset_name
def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict:
def create_document_by_text(
self,
*,
dataset_id: str,
name: str,
text: str,
source_ext: str | None = None,
) -> dict:
payload = {
'name': name,
'text': text,
'indexing_technique': self.indexing_technique,
'doc_form': self.doc_form,
'process_rule': {'mode': 'automatic'},
'process_rule': self._build_process_rule(source_ext),
}
return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload)
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
def update_document_by_text(
self,
*,
dataset_id: str,
document_id: str,
name: str,
text: str,
source_ext: str | None = None,
) -> dict:
payload = {
'name': name,
'text': text,
'process_rule': {'mode': 'automatic'},
'process_rule': self._build_process_rule(source_ext),
}
return self._request(
'POST',
@@ -175,6 +250,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
service = KbDifySyncService()
dataset_id, dataset_name = service.ensure_dataset(group)
source_ext = resolve_source_file_ext(version)
existing_record = (
db.session.query(KbDifySyncRecord)
@@ -204,6 +280,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
dataset_id=dataset_id,
name=upload_name,
text=text,
source_ext=source_ext,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or upload_name
@@ -214,6 +291,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
document_id=existing_record.remote_document_id,
name=upload_name,
text=text,
source_ext=source_ext,
)
except KbDifySyncError as exc:
if not _is_remote_document_missing(str(exc)):
@@ -222,6 +300,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
dataset_id=dataset_id,
name=upload_name,
text=text,
source_ext=source_ext,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
remote_document_name = payload.get('document', {}).get('name') or upload_name
@@ -230,6 +309,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
dataset_id=dataset_id,
name=upload_name,
text=text,
source_ext=source_ext,
)
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
remote_document_name = payload.get('document', {}).get('name') or upload_name
@@ -52,6 +52,42 @@ def _find_generated_preview_markdown(output_root: Path) -> Path | None:
return candidates[0]
def _find_generated_chunks_jsonl(output_root: Path) -> Path | None:
candidates = [path for path in output_root.rglob('04_chunks.jsonl') if path.is_file()]
if not candidates:
return None
candidates.sort(key=lambda item: len(item.parts))
return candidates[0]
def _count_jsonl_lines(path: Path) -> int:
count = 0
with path.open(encoding='utf-8', errors='ignore') as handle:
for line in handle:
if line.strip():
count += 1
return count
def _persist_debug_chunks(output_root: Path, target_dir: Path) -> tuple[str | None, int | None]:
"""Copy edkb chunk artifacts into the KB version directory for local debugging."""
chunks_source = _find_generated_chunks_jsonl(output_root)
if not chunks_source or not chunks_source.exists():
return None, None
chunks_target = target_dir / '04_chunks.jsonl'
shutil.copy2(chunks_source, chunks_target)
chunks_dir_source = chunks_source.parent / 'chunks'
chunks_dir_target = target_dir / 'chunks'
if chunks_dir_source.is_dir():
if chunks_dir_target.exists():
shutil.rmtree(chunks_dir_target)
shutil.copytree(chunks_dir_source, chunks_dir_target)
return str(chunks_target), _count_jsonl_lines(chunks_target)
def _rewrite_preview_markdown_if_needed(preview_path: Path, target_dir: Path) -> None:
content = preview_path.read_text(encoding='utf-8', errors='ignore')
if 'data:image/' not in content:
@@ -141,10 +177,13 @@ def build_clean_result(source_path: Path, target_dir: Path) -> dict:
shutil.copytree(preview_images_dir, target_preview_images_dir)
_rewrite_preview_markdown_if_needed(preview_path, target_dir)
content = cleaned_path.read_text(encoding='utf-8', errors='ignore')
chunks_file_path, chunks_count = _persist_debug_chunks(output_dir, target_dir)
return {
'mode': 'edkb_system',
'cleaned_file_path': str(cleaned_path),
'cleaned_preview_path': str(preview_path),
'word_count': len(content.split()),
'chunks_file_path': chunks_file_path,
'chunks_count': chunks_count,
}
@@ -20,6 +20,13 @@ SETTING_DEFAULTS = {
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
'KB_DIFY_DOC_FORM': 'text_model',
'KB_DIFY_PROCESS_MODE': 'automatic',
'KB_DIFY_PROCESS_MODE_EXCEL': 'custom',
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
'KB_DIFY_SEGMENT_MAX_TOKENS': '800',
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '50',
'KB_DIFY_REMOVE_URLS': 'false',
}
@@ -0,0 +1,4 @@
source_file=su_schedule_4.xlsx
source_size=5980
clean_status=placeholder_success
fallback_reason=No module named 'pydantic'
@@ -0,0 +1,5 @@
su_schedule_5
## Sheet: result
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
@@ -0,0 +1,5 @@
su_schedule_5
## Sheet: result
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
@@ -0,0 +1,4 @@
source_file=su_schedule_5.xlsx
source_size=5980
clean_status=placeholder_success
fallback_reason=[Errno 1] Operation not permitted
@@ -0,0 +1,5 @@
su_schedule_5
## Sheet: result
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
@@ -0,0 +1,5 @@
su_schedule_5
## Sheet: result
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
@@ -0,0 +1,5 @@
su_schedule_5
## Sheet: result
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
@@ -0,0 +1,5 @@
su_schedule_6
## Sheet: result
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
@@ -0,0 +1,5 @@
su_schedule_7
## Sheet: result
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=PC6842;材质名称=标签;第三方编码=SHAEC25020186401;检测项目=RoHS十项+卤素;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2025-08-14 00:00:00;报告有效截止日期=2026-08-14 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/本色磨砂PC-有害物质报告-20250814-英文_1779086818095.pdf;chm_id=17790867106401639770;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101008E;检测项目=卤素;铅(Pb)=NA;镉(Cd)=NA;汞(Hg)=NA;六价铬(Cr6+)=NA;多溴联苯(PBBs)=NA;多溴二苯醚(PBDEs)=NA;邻苯二甲酸二丁酯(DBP)=NA;邻苯二甲酸丁苄酯(BBP)=NA;邻苯二甲酸二(2-乙基己)酯(DEHP)=NA;邻苯二甲酸二异丁酯(DIBP)=NA;氯(Cl)=N.D;溴(Br)=N.D;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色HF_1774832573760.pdf;chm_id=17790869056412507491;检核结果=合格;检核说明=;回写SRM=True;回写错误=。
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;物料名称=标签;材质=Black ink;材质名称=标签;第三方编码=A2260184574101001E;检测项目=RoHS十项;铅(Pb)=N.D;镉(Cd)=N.D;汞(Hg)=N.D;六价铬(Cr6+)=N.D;多溴联苯(PBBs)=N.D;多溴二苯醚(PBDEs)=N.D;邻苯二甲酸二丁酯(DBP)=N.D;邻苯二甲酸丁苄酯(BBP)=N.D;邻苯二甲酸二(2-乙基己)酯(DEHP)=N.D;邻苯二甲酸二异丁酯(DIBP)=N.D;氯(Cl)=NA;溴(Br)=NA;检测日期=2026-03-18 00:00:00;报告有效截止日期=2027-03-18 00:00:00;附件地址=http://srm.well-trust.com:8090/hexin-boot/sys/common/static/temp/2026-黑色ROHS_1774832608199.pdf;chm_id=17790870063173449273;检核结果=人工判定;检核说明=返回值异常:空;回写SRM=True;回写错误=。
+4
View File
@@ -235,6 +235,8 @@ def _normalize_path_for_match(p: Path | str) -> str:
_WORD_TIMEOUT_EXTS = {".doc", ".docx"}
# Excel/CSV are fast and in-process; skip spawn timeout wrapper (macOS/gevent safe).
_FAST_PATH_EXTS = {".xlsx", ".xls", ".csv", ".txt", ".md"}
def _parse_timeout_env(name: str, default: str = "0") -> int | None:
@@ -248,6 +250,8 @@ def _parse_timeout_env(name: str, default: str = "0") -> int | None:
def _file_timeout_sec(file_path: Path | None = None) -> int | None:
suffix = str(getattr(file_path, "suffix", "") or "").lower()
if suffix in _FAST_PATH_EXTS:
return None
if suffix in _WORD_TIMEOUT_EXTS:
specific = _parse_timeout_env("EDKB_WORD_FILE_TIMEOUT_SEC")
if specific:
+57 -21
View File
@@ -7,6 +7,9 @@ COND_KWS = ["条件", "判定", "if", "IF"]
ACT_KWS = ["处理", "动作", "措施", "结果", "输出"]
OWN_KWS = ["责任", "负责人", "部门", "岗位"]
# Wide tables use row text blocks so Dify custom segmentation stays row-aligned.
WIDE_TABLE_COLS = 8
def _find_col(headers: list[str], kws: list[str]) -> int | None:
for i, h in enumerate(headers):
@@ -16,40 +19,73 @@ def _find_col(headers: list[str], kws: list[str]) -> int | None:
return None
def _to_table_md(headers: list[str], rows: list[list[str]]) -> str:
def _to_table_md_loose(headers: list[str], rows: list[list[str]]) -> str:
"""Markdown header block plus one pipe row per chunk, separated by blank lines."""
hs = [h or "-" for h in headers]
out = ["| " + " | ".join(hs) + " |", "| " + " | ".join(["---"] * len(hs)) + " |"]
for r in rows:
vals = [r[i] if i < len(r) else "" for i in range(len(hs))]
out.append("| " + " | ".join(vals) + " |")
return "\n".join(out)
header_block = "\n".join(
[
"| " + " | ".join(hs) + " |",
"| " + " | ".join(["---"] * len(hs)) + " |",
]
)
data_blocks: list[str] = []
for row in rows:
vals = [row[i] if i < len(row) else "" for i in range(len(hs))]
data_blocks.append("| " + " | ".join(vals) + " |")
if not data_blocks:
return header_block
return header_block + "\n\n" + "\n\n".join(data_blocks)
def _to_row_text_md(headers: list[str], rows: list[list[str]]) -> str:
"""Wide-table fallback: one bullet per row for stable chunk boundaries."""
hs = [h or "-" for h in headers]
blocks: list[str] = []
for row in rows:
pairs = []
for i, header in enumerate(hs):
val = row[i] if i < len(row) else ""
pairs.append(f"{header}={val}")
blocks.append("- 【行】" + ";".join(pairs) + "。")
return "\n\n".join(blocks)
def run(input_data: list[dict] | dict, context: Context) -> str:
tables = input_data if isinstance(input_data, list) else [input_data]
parts: list[str] = []
for t in tables:
headers = [str(x).strip() for x in t.get("headers", [])]
rows = [[str(c).strip() for c in row] for row in t.get("rows", [])]
parts.append(f"## Sheet: {t.get('sheet', 'Sheet1')}")
for table in tables:
headers = [str(x).strip() for x in table.get("headers", [])]
rows = [[str(c).strip() for c in row] for row in table.get("rows", [])]
sheet_blocks: list[str] = [f"## Sheet: {table.get('sheet', 'Sheet1')}"]
cidx = _find_col(headers, COND_KWS)
aidx = _find_col(headers, ACT_KWS)
oidx = _find_col(headers, OWN_KWS)
if cidx is not None and aidx is not None:
cond_idx = _find_col(headers, COND_KWS)
act_idx = _find_col(headers, ACT_KWS)
owner_idx = _find_col(headers, OWN_KWS)
if cond_idx is not None and act_idx is not None:
bullets: list[str] = []
for row in rows:
cond = row[cidx] if cidx < len(row) else "满足条件"
act = row[aidx] if aidx < len(row) else "执行处理"
cond = row[cond_idx] if cond_idx < len(row) else "满足条件"
act = row[act_idx] if act_idx < len(row) else "执行处理"
owner = (
row[oidx] if oidx is not None and oidx < len(row) else "相关责任方"
row[owner_idx]
if owner_idx is not None and owner_idx < len(row)
else "相关责任方"
)
parts.append(
bullets.append(
f"- 当 {cond or '满足条件'} 时,{owner or '相关责任方'} 执行 {act or '执行处理'}。"
)
if bullets:
sheet_blocks.append("\n\n".join(bullets))
elif len(headers) > WIDE_TABLE_COLS:
content = _to_row_text_md(headers, rows)
if content:
sheet_blocks.append(content)
else:
parts.append(_to_table_md(headers, rows))
content = _to_table_md_loose(headers, rows)
if content:
sheet_blocks.append(content)
parts.append("")
parts.append("\n\n".join(sheet_blocks))
return "\n".join(parts).strip() + "\n"
return "\n\n".join(parts).strip() + "\n"
@@ -0,0 +1,86 @@
"""Tests for Dify sync process_rule selection (Excel custom vs default automatic)."""
from __future__ import annotations
from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module
def _make_service(monkeypatch, **overrides):
settings = {
'DIFY_API_BASE': 'http://dify.example/v1',
'DIFY_API_KEY': 'dataset-test-key',
'KB_DIFY_PERMISSION': 'only_me',
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
'KB_DIFY_DOC_FORM': 'text_model',
'KB_DIFY_PROCESS_MODE': 'automatic',
'KB_DIFY_PROCESS_MODE_EXCEL': 'custom',
'KB_DIFY_SEGMENT_SEPARATOR': '\\n\\n',
'KB_DIFY_SEGMENT_SEPARATOR_EXCEL': '\\n\\n',
'KB_DIFY_SEGMENT_MAX_TOKENS': '800',
'KB_DIFY_SEGMENT_CHUNK_OVERLAP': '50',
'KB_DIFY_REMOVE_URLS': 'false',
}
settings.update(overrides)
monkeypatch.setattr(dify_sync_module, 'get_kb_dify_settings', lambda: settings)
return dify_sync_module.KbDifySyncService()
def test_build_process_rule_xlsx_uses_custom_segmentation(monkeypatch):
service = _make_service(monkeypatch)
rule = service._build_process_rule('xlsx')
assert rule['mode'] == 'custom'
assert rule['rules']['segmentation']['separator'] == '\n\n'
assert rule['rules']['segmentation']['max_tokens'] == 800
assert rule['rules']['segmentation']['chunk_overlap'] == 50
assert rule['rules']['pre_processing_rules'][1]['enabled'] is False
def test_build_process_rule_docx_defaults_to_automatic(monkeypatch):
service = _make_service(monkeypatch)
rule = service._build_process_rule('docx')
assert rule == {'mode': 'automatic'}
def test_create_document_by_text_xlsx_posts_custom_process_rule(monkeypatch):
service = _make_service(monkeypatch)
captured: dict = {}
def fake_request(method, path, **kwargs):
captured['method'] = method
captured['path'] = path
captured['json'] = kwargs.get('json')
return {'document': {'id': 'doc-1', 'name': 'demo.xlsx'}}
monkeypatch.setattr(service, '_request', fake_request)
service.create_document_by_text(
dataset_id='ds-1',
name='demo.xlsx',
text='row one\n\nrow two',
source_ext='xlsx',
)
assert captured['method'] == 'POST'
assert captured['path'] == '/datasets/ds-1/document/create-by-text'
process_rule = captured['json']['process_rule']
assert process_rule['mode'] == 'custom'
assert process_rule['rules']['segmentation']['separator'] == '\n\n'
assert process_rule['rules']['segmentation']['max_tokens'] == 800
def test_remove_urls_emails_respects_kb_dify_remove_urls_true(monkeypatch):
service = _make_service(monkeypatch, KB_DIFY_REMOVE_URLS='true')
rule = service._build_process_rule('csv')
remove_urls = next(
item for item in rule['rules']['pre_processing_rules']
if item['id'] == 'remove_urls_emails'
)
assert remove_urls['enabled'] is True
def test_resolve_source_file_ext_from_filename():
class _Version:
source_file_ext = None
source_file_name = 'report.XLSX'
assert dify_sync_module.resolve_source_file_ext(_Version()) == 'xlsx'
+62
View File
@@ -0,0 +1,62 @@
"""Tests for persisting edkb 04_chunks.jsonl into KB version directories."""
from __future__ import annotations
from pathlib import Path
from app.services.knowledge_cleaning import edkb_adapter
def _fake_build_knowledge(file_path: Path, output_dir: Path, config, cache_dir):
out_sub = output_dir / 'sample'
out_sub.mkdir(parents=True, exist_ok=True)
(out_sub / '03_clean.md').write_text(
'## Sheet: Data\n\n| A | B |\n| --- | --- |\n\n| 1 | 2 |\n',
encoding='utf-8',
)
(out_sub / '04_chunks.jsonl').write_text(
'{"id":"chunk-0","text":"row one"}\n{"id":"chunk-1","text":"row two"}\n',
encoding='utf-8',
)
chunks_dir = out_sub / 'chunks'
chunks_dir.mkdir()
(chunks_dir / 'chunk_0000.md').write_text('row one\n', encoding='utf-8')
(chunks_dir / 'chunk_0001.md').write_text('row two\n', encoding='utf-8')
return [{'status': 'success', 'file': str(file_path)}]
def test_build_clean_result_persists_chunks_jsonl(monkeypatch, tmp_path):
source_path = tmp_path / 'sample.xlsx'
source_path.write_bytes(b'fake-xlsx-content')
target_dir = tmp_path / 'output'
monkeypatch.setattr('edkb_system.controller.build_knowledge', _fake_build_knowledge)
class _FakeConfig:
@staticmethod
def load(_path):
return _FakeConfig()
monkeypatch.setattr('edkb_system.config.SystemConfig', _FakeConfig)
result = edkb_adapter.build_clean_result(source_path, target_dir)
chunks_path = target_dir / '04_chunks.jsonl'
assert chunks_path.exists()
assert (target_dir / 'document.md').exists()
assert (target_dir / 'chunks' / 'chunk_0000.md').exists()
assert (target_dir / 'chunks' / 'chunk_0001.md').exists()
assert result['chunks_file_path'] == str(chunks_path)
assert result['chunks_count'] == 2
def test_persist_debug_chunks_skips_missing_jsonl(tmp_path):
output_root = tmp_path / 'output'
output_root.mkdir()
target_dir = tmp_path / 'target'
target_dir.mkdir()
chunks_file_path, chunks_count = edkb_adapter._persist_debug_chunks(output_root, target_dir)
assert chunks_file_path is None
assert chunks_count is None
assert not (target_dir / '04_chunks.jsonl').exists()
+23
View File
@@ -0,0 +1,23 @@
"""Tests for edkb per-file timeout selection."""
from __future__ import annotations
from pathlib import Path
from edkb_system.controller import _file_timeout_sec
def test_excel_skips_spawn_timeout_wrapper(monkeypatch):
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180')
assert _file_timeout_sec(Path('report.xlsx')) is None
assert _file_timeout_sec(Path('data.csv')) is None
def test_word_still_uses_word_timeout(monkeypatch):
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180')
monkeypatch.setenv('EDKB_WORD_FILE_TIMEOUT_SEC', '420')
assert _file_timeout_sec(Path('manual.docx')) == 420
def test_other_formats_use_global_timeout(monkeypatch):
monkeypatch.setenv('EDKB_FILE_TIMEOUT_SEC', '180')
assert _file_timeout_sec(Path('slides.pptx')) == 180
+3
View File
@@ -27,8 +27,11 @@ def test_build_clean_result_generates_markdown_for_xlsx(tmp_path):
assert result['cleaned_preview_path'] == str(cleaned_path)
content = cleaned_path.read_text(encoding='utf-8')
assert content.strip()
assert '供应链' in content
assert '能耗' in content
# Narrow Excel tables should expose Dify-friendly row boundaries.
assert '\n\n|' in content or '| 供应链 | 能耗 |' in content
def test_normalized_source_filename_infers_xlsx_extension(tmp_path):
+70
View File
@@ -0,0 +1,70 @@
"""Tests for Excel table linearization chunk boundaries."""
from __future__ import annotations
from edkb_system.contracts import Context
from edkb_system.skills import table_linearize
def test_condition_action_table_uses_double_newline_between_bullets():
tables = [
{
'sheet': 'Rules',
'headers': ['条件', '处理', '责任'],
'rows': [
['库存不足', '补货', '采购部'],
['价格变动', '更新报价', '销售部'],
],
}
]
output = table_linearize.run(tables, Context())
assert '\n\n- 当' in output
assert output.count('- 当') == 2
assert output.startswith('## Sheet: Rules')
def test_narrow_table_separates_data_rows_with_double_newline():
tables = [
{
'sheet': 'Data',
'headers': ['A', 'B', 'C'],
'rows': [
['1', '2', '3'],
['4', '5', '6'],
],
}
]
output = table_linearize.run(tables, Context())
assert '| --- | --- | --- |' in output
assert '\n\n|' in output
assert '| 1 | 2 | 3 |' in output
assert '| 4 | 5 | 6 |' in output
assert '【行】' not in output
def test_wide_table_uses_row_text_blocks():
headers = [f'列{i}' for i in range(1, 11)]
rows = [[str(i * 10 + j) for j in range(10)] for i in range(1, 4)]
tables = [{'sheet': 'Wide', 'headers': headers, 'rows': rows}]
output = table_linearize.run(tables, Context())
assert '【行】' in output
assert '\n\n' in output
assert output.count('【行】') == 3
assert '列1=10' in output
assert '|' not in output.split('## Sheet: Wide')[-1]
def test_multiple_sheets_separated_by_double_newline():
tables = [
{'sheet': 'S1', 'headers': ['X'], 'rows': [['a']]},
{'sheet': 'S2', 'headers': ['Y'], 'rows': [['b']]},
]
output = table_linearize.run(tables, Context())
assert '## Sheet: S1' in output
assert '## Sheet: S2' in output
assert output.index('## Sheet: S2') > output.index('## Sheet: S1')
assert '\n\n## Sheet: S2' in output