MCPcopy Create free account
hub / github.com/KnowledgeXLab/LeanRAG / process_single_file

Function process_single_file

CommonKG/create_kg.py:147–329  ·  view source on GitHub ↗

处理单个文件的三元组抽取

(corpus_path, task_conf, llm_processer, output_dir="output")

Source from the content-addressed store, hash-verified

145
146
147def process_single_file(corpus_path, task_conf, llm_processer, output_dir="output"):
148 """处理单个文件的三元组抽取"""
149 start_time = time.time()
150 pedia_entity_path = task_conf["pedia_entity_path"] # 头实体路径
151
152 try:
153 # 动态生成输出路径
154 file_name = Path(corpus_path).stem
155 output_subdir = Path(output_dir) / file_name
156 if output_subdir.exists():
157 logger.info(f"Target files: {file_name} already exists, overwrite\n")
158 else:
159 output_subdir.mkdir(parents=True, exist_ok=True)
160 #移动chunk文件
161 shutil.copy(corpus_path, output_subdir)
162
163 # 初始化输出文件路径
164 result_triple_path = output_subdir / f"new_triples_{file_name}.jsonl"
165 next_layer_entities_path = output_subdir / f"next_layer_entities_{file_name}.txt"
166 all_entities_path = output_subdir / f"all_entities_{file_name}.txt"
167 match_words_path = output_subdir / f"match_words_{file_name}.jsonl" ## 匹配结果路径
168
169
170 # 当不跳过提取三元组时,进行多层次的实体匹配和三元组抽取
171 if not task_conf["skip_extract_triple"]:
172
173 # 加载到头实体路径进行处理,假设有第0层,那么头实体直接next_layer_entities_path来匹配
174 head_entities = read_txt(pedia_entity_path)
175 next_layer_entities = list(set([item.strip() for item in head_entities]))
176 write_txt(next_layer_entities_path, next_layer_entities, mode="w")
177 logger.info(f"Initialize next_layer_entities num: {len(next_layer_entities)}")
178
179 # 初始化实体和三元组文件
180 write_jsonl(data="", path=result_triple_path, mode="w")
181 write_txt(data="", path=all_entities_path, mode="w")
182 with open(corpus_path, "r") as f:
183 corpusfiles=json.load(f)
184 # 读取语料文件
185 # corpusfiles = read_jsonl(corpus_path)
186 logger.info(f"corpus paragraph num: {len(corpusfiles)}")
187
188 for iter in range(task_conf["level_num"]):
189 logger.info(f"Processing {file_name} | Iteration {iter+1}/{task_conf['level_num']}")
190 layer_head_cnt, layer_tail_cnt, layer_triple_cnt = 0, 0, 0
191
192 logger.info(f"[num_iteration]: {iter+1} ---------------------\n")
193 logger.info("[corpus matching]-----------------------------------\n")
194
195 # 检查文件是否存在,如果存在则删除
196 if os.path.exists(match_words_path):
197 os.remove(match_words_path)
198
199 next_layer_entities = read_txt(next_layer_entities_path)
200 next_layer_entities = [entity.strip("\n") for entity in next_layer_entities]
201
202 source_id = "hash_code"
203 text_key = "text"
204

Callers 1

mainFunction · 0.85

Calls 6

write_jsonlFunction · 0.90
read_jsonlFunction · 0.90
extract_descFunction · 0.85
triple_json_formatMethod · 0.80
read_txtFunction · 0.70
write_txtFunction · 0.70

Tested by

no test coverage detected