修复es重复入库的问题和文档分块字符串计算包括空格和换行符的问题
This commit is contained in:
parent
df993defcc
commit
53fb9f6319
Binary file not shown.
|
|
@ -86,14 +86,14 @@ def search_content(
|
|||
top_k: int = Body(2, description="匹配文档数"),
|
||||
)-> List[Document]:
|
||||
print("kb_doc_api search_content")
|
||||
docs=[]
|
||||
kb = KBServiceFactory.get_service_by_name(knowledge_base_name)
|
||||
if kb is not None:
|
||||
if query:
|
||||
docs = kb.search_content(query, top_k)
|
||||
print(f"search_content, docs:{docs}")
|
||||
return docs
|
||||
else:
|
||||
return None
|
||||
return docs
|
||||
|
||||
def update_docs_by_id(
|
||||
knowledge_base_name: str = Body(..., description="知识库名称", examples=["samples"]),
|
||||
|
|
@ -334,6 +334,7 @@ def update_docs(
|
|||
chunk_overlap=chunk_overlap,
|
||||
zh_title_enhance=zh_title_enhance):
|
||||
if status:
|
||||
print(f"kb_doc_api update_docs 文件生成docs并向量化,filename:{file_name}")
|
||||
kb_name, file_name, new_docs = result
|
||||
kb_file = KnowledgeFile(filename=file_name,
|
||||
knowledge_base_name=knowledge_base_name)
|
||||
|
|
@ -346,6 +347,7 @@ def update_docs(
|
|||
# 将自定义的docs进行向量化
|
||||
for file_name, v in docs.items():
|
||||
try:
|
||||
print(f"kb_doc_api update_docs 自定义的docs 向量化,filename:{file_name}")
|
||||
v = [x if isinstance(x, Document) else Document(**x) for x in v]
|
||||
kb_file = KnowledgeFile(filename=file_name, knowledge_base_name=knowledge_base_name)
|
||||
kb.update_doc(kb_file, docs=v, not_refresh_vs_cache=True)
|
||||
|
|
@ -358,6 +360,7 @@ def update_docs(
|
|||
if not not_refresh_vs_cache:
|
||||
kb.save_vector_store()
|
||||
|
||||
print(f"kb_doc_api update_docs before finishing, failed_files:{failed_files}")
|
||||
return BaseResponse(code=200, msg=f"更新文档完成", data={"failed_files": failed_files})
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -127,7 +127,9 @@ class KBService(ABC):
|
|||
except Exception as e:
|
||||
print(f"cannot convert absolute path ({source}) to relative path. error is : {e}")
|
||||
self.delete_doc(kb_file)
|
||||
print(f"add_doc filepath:{kb_file.filepath},将要执行do_add_doc")
|
||||
doc_infos = self.do_add_doc(docs, **kwargs)
|
||||
print(f"add_doc filepath:{kb_file.filepath} 将要执行dd_file_to_db")
|
||||
status = add_file_to_db(kb_file,
|
||||
custom_docs=custom_docs,
|
||||
docs_count=len(docs),
|
||||
|
|
@ -140,6 +142,7 @@ class KBService(ABC):
|
|||
"""
|
||||
从知识库删除文件
|
||||
"""
|
||||
print(f"delete_doc filepath:{kb_file.filepath}")
|
||||
self.do_delete_doc(kb_file, **kwargs)
|
||||
status = delete_file_from_db(kb_file)
|
||||
if delete_content and os.path.exists(kb_file.filepath):
|
||||
|
|
@ -160,6 +163,7 @@ class KBService(ABC):
|
|||
如果指定了docs,则使用自定义docs,并将数据库对应条目标为custom_docs=True
|
||||
"""
|
||||
if os.path.exists(kb_file.filepath):
|
||||
print(f"{kb_file.filename} exists")
|
||||
self.delete_doc(kb_file, **kwargs)
|
||||
return self.add_doc(kb_file, docs=docs, **kwargs)
|
||||
|
||||
|
|
|
|||
|
|
@ -50,7 +50,8 @@ class ESKBService(KBService):
|
|||
}
|
||||
self.es_client_python.indices.create(index=self.index_name, mappings=mappings)
|
||||
except BadRequestError as e:
|
||||
logger.error("创建索引失败,重新" + e)
|
||||
logger.error("创建索引失败,重新")
|
||||
logger.error(e)
|
||||
|
||||
try:
|
||||
# langchain ES 连接、创建索引
|
||||
|
|
@ -115,7 +116,20 @@ class ESKBService(KBService):
|
|||
# 将docs写入到ES中
|
||||
try:
|
||||
# 连接 + 同时写入文档
|
||||
#使用self.db_init,modified by weiweiwang
|
||||
if self.user != "" and self.password != "":
|
||||
# self.db_init.from_documents(
|
||||
# documents=docs,
|
||||
# embedding=embed_model,
|
||||
# es_url= f"http://{self.IP}:{self.PORT}",
|
||||
# index_name=self.index_name,
|
||||
# distance_strategy="COSINE",
|
||||
# query_field="context",
|
||||
# vector_query_field="dense_vector",
|
||||
# verify_certs=False,
|
||||
# es_user=self.user,
|
||||
# es_password=self.password
|
||||
# )
|
||||
self.db = ElasticsearchStore.from_documents(
|
||||
documents=docs,
|
||||
embedding=embed_model,
|
||||
|
|
@ -199,8 +213,10 @@ class ESKBService(KBService):
|
|||
}
|
||||
print(f"***do_delete_doc: kb_file.filepath:{kb_file.filepath}, base_file_name:{base_file_name}")
|
||||
# 注意设置size,默认返回10个。
|
||||
search_results = self.es_client_python.search(body=query, size=50)
|
||||
search_results = self.es_client_python.search(index=self.index_name, body=query,size=200)
|
||||
delete_list = [hit["_id"] for hit in search_results['hits']['hits']]
|
||||
size = len(delete_list)
|
||||
print(f"***do_delete_doc: 删除的size:{size}, {delete_list}")
|
||||
if len(delete_list) == 0:
|
||||
return None
|
||||
else:
|
||||
|
|
@ -234,10 +250,12 @@ class ESKBService(KBService):
|
|||
}
|
||||
}
|
||||
}
|
||||
search_results = self.es_client_python.search(body=query)
|
||||
search_results = self.es_client_python.search(index=self.index_name, body=query,size=200)
|
||||
if len(search_results["hits"]["hits"]) == 0:
|
||||
raise ValueError("召回元素个数为0")
|
||||
info_docs = [{"id":hit["_id"], "metadata": hit["_source"]["metadata"]} for hit in search_results["hits"]["hits"]]
|
||||
size = len(info_docs)
|
||||
print(f"do_add_doc 召回元素个数:{size}")
|
||||
return info_docs
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import re
|
|||
from typing import List, Optional, Any
|
||||
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
||||
import logging
|
||||
#import PyPDF2
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
|
@ -28,6 +27,9 @@ def _split_text_with_regex_from_end(
|
|||
splits = list(text)
|
||||
return [s for s in splits if s != ""]
|
||||
|
||||
def customerLen(text:str)->int:
|
||||
length = len(re.sub(r'[\s\n]+', '', text))
|
||||
return length
|
||||
|
||||
class ChineseRecursiveTextSplitter(RecursiveCharacterTextSplitter):
|
||||
def __init__(
|
||||
|
|
@ -53,10 +55,12 @@ class ChineseRecursiveTextSplitter(RecursiveCharacterTextSplitter):
|
|||
]
|
||||
self._is_separator_regex = is_separator_regex
|
||||
self.is_recursive = False
|
||||
self._length_function = customerLen
|
||||
|
||||
|
||||
def _split_text(self, text: str, separators: List[str]) -> List[str]:
|
||||
"""Split incoming text and return chunks."""
|
||||
print(f"***********************************ChineseRecursiveTextSplitter***********************************")
|
||||
#print(f"***********************************ChineseRecursiveTextSplitter***********************************")
|
||||
final_chunks = []
|
||||
# Get appropriate separator to use
|
||||
separator = separators[-1]
|
||||
|
|
@ -173,8 +177,8 @@ if __name__ == "__main__":
|
|||
text_splitter = ChineseRecursiveTextSplitter(
|
||||
keep_separator=True,
|
||||
is_separator_regex=True,
|
||||
chunk_size=300,
|
||||
chunk_overlap=30
|
||||
chunk_size=400,
|
||||
chunk_overlap=0
|
||||
)
|
||||
#ls = [
|
||||
# """中国对外贸易形势报告(75页)。前 10 个月,一般贸易进出口 19.5 万亿元,增长 25.1%, 比整体进出口增速高出 2.9 个百分点,占进出口总额的 61.7%,较去年同期提升 1.6 个百分点。其中,一般贸易出口 10.6 万亿元,增长 25.3%,占出口总额的 60.9%,提升 1.5 个百分点;进口8.9万亿元,增长24.9%,占进口总额的62.7%, \n1.1 提升 1.8 个百分点。加工贸易进出口 6.8 万亿元,增长 11.8%, 占进出口总额的 21.5%,减少 2.0 个百分点。其中,出口增 长 10.4%,占出口总额的 24.3%,减少 2.6 个百分点;进口增 长 14.2%,占进口总额的 18.0%,减少 1.2 个百分点。此外, 以保税物流方式进出口 3.96 万亿元,增长 27.9%。其中,出 口 1.47 万亿元,增长 38.9%;进口 2.49 万亿元,增长 22.2%。前三季度,中国服务贸易继续保持快速增长态势。服务 进出口总额 37834.3 亿元,增长 11.6%;其中服务出口 17820.9 亿元,增长 27.3%;进口 20013.4 亿元,增长 0.5%,进口增 速实现了疫情以来的首次转正。服务出口增幅大于进口 26.8 个百分点,带动服务贸易逆差下降 62.9%至 2192.5 亿元。服 务贸易结构持续优化,知识密集型服务进出口 16917.7 亿元, 增长 13.3%,占服务进出口总额的比重达到 44.7%,提升 0.7 个百分点。 二、中国对外贸易发展环境分析和展望 全球疫情起伏反复,经济复苏分化加剧,大宗商品价格 上涨、能源紧缺、运力紧张及发达经济体政策调整外溢等风 险交织叠加。\n1.2同时也要看到,我国经济长期向好的趋势没有 改变,外贸企业韧性和活力不断增强,新业态新模式加快发 展,创新转型步伐提速。产业链供应链面临挑战。美欧等加快出台制造业回迁计 划,加速产业链供应链本土布局,跨国公司调整产业链供应 链,全球双链面临新一轮重构,区域化、近岸化、本土化、 短链化趋势凸显。疫苗供应不足,制造业“缺芯”、物流受限、 运价高企,全球产业链供应链面临压力。 全球通胀持续高位运行。能源价格上涨加大主要经济体 的通胀压力,增加全球经济复苏的不确定性。世界银行今年 10 月发布《大宗商品市场展望》指出,能源价格在 2021 年 大涨逾 80%,并且仍将在 2022 年小幅上涨。IMF 指出,全 球通胀上行风险加剧,通胀前景存在巨大不确定性。""",
|
||||
|
|
@ -182,27 +186,17 @@ if __name__ == "__main__":
|
|||
# ]
|
||||
# text1 = """中国对外贸易形势报告(75页)。前 10 个月,一般贸易进出口 19.5 万亿元,增长 25.1%, 比整体进出口增速高出 2.9 个百分点,占进出口总额的 61.7%,较去年同期提升 1.6 个百分点。其中,一般贸易出口 10.6 万亿元,增长 25.3%,占出口总额的 60.9%,提升 1.5 个百分点;进口8.9万亿元,增长24.9%,占进口总额的62.7%, \n1.1 提升 1.8 个百分点。加工贸易进出口 6.8 万亿元,增长 11.8%, 占进出口总额的 21.5%,减少 2.0 个百分点。其中,出口增 长 10.4%,占出口总额的 24.3%,减少 2.6 个百分点;进口增 长 14.2%,占进口总额的 18.0%,减少 1.2 个百分点。此外, 以保税物流方式进出口 3.96 万亿元,增长 27.9%。其中,出 口 1.47 万亿元,增长 38.9%;进口 2.49 万亿元,增长 22.2%。前三季度,中国服务贸易继续保持快速增长态势。服务 进出口总额 37834.3 亿元,增长 11.6%;其中服务出口 17820.9 亿元,增长 27.3%;进口 20013.4 亿元,增长 0.5%,进口增 速实现了疫情以来的首次转正。服务出口增幅大于进口 26.8 个百分点,带动服务贸易逆差下降 62.9%至 2192.5 亿元。服 务贸易结构持续优化,知识密集型服务进出口 16917.7 亿元, 增长 13.3%,占服务进出口总额的比重达到 44.7%,提升 0.7 个百分点。 二、中国对外贸易发展环境分析和展望 全球疫情起伏反复,经济复苏分化加剧,大宗商品价格 上涨、能源紧缺、运力紧张及发达经济体政策调整外溢等风 险交织叠加。\n1.2同时也要看到,我国经济长期向好的趋势没有 改变,外贸企业韧性和活力不断增强,新业态新模式加快发 展,创新转型步伐提速。产业链供应链面临挑战。美欧等加快出台制造业回迁计 划,加速产业链供应链本土布局,跨国公司调整产业链供应 链,全球双链面临新一轮重构,区域化、近岸化、本土化、 短链化趋势凸显。疫苗供应不足,制造业“缺芯”、物流受限、 运价高企,全球产业链供应链面临压力。 全球通胀持续高位运行。能源价格上涨加大主要经济体 的通胀压力,增加全球经济复苏的不确定性。世界银行今年 10 月发布《大宗商品市场展望》指出,能源价格在 2021 年 大涨逾 80%,并且仍将在 2022 年小幅上涨。IMF 指出,全 球通胀上行风险加剧,通胀前景存在巨大不确定性。"""
|
||||
ls=["""
|
||||
|
||||
|
||||
4.1 保护装置
|
||||
4.1.1 换流变应按GB20838—2007 等有关标准及厂家规定装设保护装置。
|
||||
4.1.2 换流变的安全保护装置、油保护装置应符合相应标准的要求。
|
||||
4.1.3 换流变气体继电器安装时应使油管沿气体继电器油流方向有1%~1.5%的升高坡度(制造厂有规 定的按制造厂规定安装)。换流变气体继电器应配置采用耐腐蚀、防老化材质的防雨罩,二次电缆进入 气体继电器前应设置滴水弯,避免接点受潮误动。
|
||||
4.1.4 换流变应装用防震型气体继电器。
|
||||
4.1.5 气体继电器不应采用悬臂梁式安装结构。
|
||||
4.1.6 换流变采用两个及以上有载分接开关并联,且所有有载分接开关共用一个有载分接开关储油柜 时,每个有载分接开关应分别装设油流继电器或压力继电器作为主保护跳闸。有载分接开关油流继电 器安装时应使油流继电器连接的支路油管沿油流继电器油流方向有1%~3%的升高坡度(制造厂有规 定的按制造厂规定安装)。
|
||||
4.1.7 换流变的保护跳闸功能宜采用三取“逻辑。
|
||||
4.1.8 当换流变所在系统的实际短路视在容量大于GB/T1094.5—2008 中表2规定值时,应在订货时向 制造广提出要求。对运行中的换流变应采取限制短路电流的措施。换流变保护动作的时间应小于承受 短路耐热能力的持续时间。
|
||||
4.1.9 压力释放装置的安装应保证事故喷油畅通,避免喷入电缆沟、母线及其他设备上,必要时应予 以遮挡,事故放油阀应安装在换流变下部,且放油口朝下。
|
||||
4.2 测量装置
|
||||
4.2.1 换流变应按有关标准及广家规定装设测量装置。
|
||||
4.2.2 换流变温度测量装置应符合下列规定: a) 有测量顶层油温的温度计;
|
||||
b) 有测量绕组温度的温度计;
|
||||
c) 将信号温度计接远方信号;
|
||||
d) 测温时,温度计管座内应充有绝缘油;
|
||||
e) 温度计可指示运行期间的最高温度。
|
||||
4.2.3 若换流变采用充气式套管,气体压力信号应传至后台,应装设密度继电器,密度继电器安装位置 应便于观察。
|
||||
4.2.4 换流变上安装的在线监测装置应可靠接地。采集油中溶解气样的装置,应能避免污染油箱本体
|
||||
5 技术要求
|
||||
5.1 一般要求
|
||||
5.1.1 智能安全帽应符合GB 2811 中的基本性能要求。
|
||||
5.1.2 智能模块与安全帽本体之间的连接应牢固可靠,且不得影响安全帽佩戴的稳定性及 正常防护功能。
|
||||
5.1.3 智能模块的外壳防护等级应符合 GB/T 4208 中 IP54 的要求。
|
||||
5.1.4 智能模块重量基础型不宜超过300g。
|
||||
5.1.5 智能模块应能存储不低于8h 的采集回传的位置信息文件。
|
||||
5.1.6 智能模块应具有低电量报警功能,电量低于20%应能给出清晰的报警提示。
|
||||
5.1.7 电池应符合GB 31241中的相关要求。支持智能模块持续工作时间不得小于8h。
|
||||
5.1.8 无线通信应符合 GB 21288 中电磁辐射局部暴露限值的规定。
|
||||
5.1.9 智能安全帽应配合管理系统使用。管理系统的功能应符合附录B的要求。
|
||||
"""]
|
||||
#
|
||||
|
||||
|
|
|
|||
|
|
@ -158,20 +158,20 @@ def zh_third_title_enhance(docs: Document) -> Document:
|
|||
print(f"zh_third_title_enhance ....")
|
||||
if len(docs) > 0:
|
||||
for doc in docs:
|
||||
print(f"zh_third_title_enhance: {doc}")
|
||||
#print(f"zh_third_title_enhance: {doc}")
|
||||
third_title = get_third_level_title(doc.page_content)
|
||||
if third_title:
|
||||
title = third_title
|
||||
print(f"title: {title}")
|
||||
#print(f"title: {title}")
|
||||
elif title:
|
||||
print(f"title is not none")
|
||||
#print(f"title is not none")
|
||||
temp_fourth_content = is_fourth_level_content(doc.page_content)
|
||||
if temp_fourth_content:
|
||||
print(f"is_fourth_level_content : {temp_fourth_content}")
|
||||
#print(f"is_fourth_level_content : {temp_fourth_content}")
|
||||
doc.page_content = f"{title} {doc.page_content}"
|
||||
else:
|
||||
title = None
|
||||
print(f"final title: {title}")
|
||||
#print(f"final title: {title}")
|
||||
return docs
|
||||
else:
|
||||
print("zh_third_title_enhance 文件不存在")
|
||||
|
|
@ -181,20 +181,20 @@ def zh_second_title_enhance(docs: Document) -> Document:
|
|||
title = None
|
||||
if len(docs) > 0:
|
||||
for doc in docs:
|
||||
print(f"zh_second_title_enhance: {doc}")
|
||||
#print(f"zh_second_title_enhance: {doc}")
|
||||
second_title = get_second_level_title(doc.page_content)
|
||||
if second_title:
|
||||
title = second_title
|
||||
print(f"title: {title}")
|
||||
#print(f"title: {title}")
|
||||
elif title:
|
||||
print(f"title is not none")
|
||||
#print(f"title is not none")
|
||||
temp_third_content = is_third_level_content(doc.page_content)
|
||||
if temp_third_content:
|
||||
print(f"is_third_level_content : {temp_third_content}")
|
||||
#print(f"is_third_level_content : {temp_third_content}")
|
||||
doc.page_content = f"{title} {doc.page_content}"
|
||||
else:
|
||||
title = None
|
||||
print(f"final title: {title}")
|
||||
#print(f"final title: {title}")
|
||||
return docs
|
||||
else:
|
||||
print("zh_second_title_enhance 文件不存在")
|
||||
|
|
@ -204,19 +204,19 @@ def zh_first_title_enhance(docs: Document) -> Document:
|
|||
title = None
|
||||
if len(docs) > 0:
|
||||
for doc in docs:
|
||||
print(f"zh_first_title_enhance: {doc}")
|
||||
#print(f"zh_first_title_enhance: {doc}")
|
||||
first_title = get_fist_level_title(doc.page_content)
|
||||
if first_title:
|
||||
title = first_title
|
||||
print(f"title: {title}")
|
||||
#print(f"title: {title}")
|
||||
elif title:
|
||||
temp_second_content = is_second_level_content(doc.page_content)
|
||||
if temp_second_content:
|
||||
print(f"is_second_level_content : {temp_second_content}")
|
||||
#print(f"is_second_level_content : {temp_second_content}")
|
||||
doc.page_content = f"{title} {doc.page_content}"
|
||||
else:
|
||||
title = None
|
||||
print(f"final title: {title}")
|
||||
#print(f"final title: {title}")
|
||||
return docs
|
||||
else:
|
||||
print("zh_first_title_enhance 文件不存在")
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Loading…
Reference in New Issue