Chaos0818 commited on
Commit
be7b677
·
1 Parent(s): d2b2451

[feat] finish pdf extract pipline

Browse files
Files changed (2) hide show
  1. main.py +122 -23
  2. ocr/doc2x.py +1 -1
main.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from llms.kimi import KimiAgent
2
  from ocr.doc2x import PDFProcessor
3
  import os
@@ -10,9 +11,12 @@ import yaml
10
  import logging
11
  import io
12
  from threading import Thread
 
13
 
 
 
 
14
 
15
- # todo 显示完成状态
16
  # todo 性能优化 并发?
17
 
18
 
@@ -20,6 +24,18 @@ from threading import Thread
20
  realtime_log_capture = RealTimeLogCapture(__name__)
21
 
22
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def update_ocr_interface(file_type):
24
  if file_type == "JSON":
25
  return (
@@ -53,6 +69,10 @@ def llm_extract_question(file_path, llm):
53
 
54
  jsonl_data = []
55
  for idx, que in enumerate(question_groups, 1):
 
 
 
 
56
  realtime_logger.info(f"处理第 {idx}/{len(question_groups)} 组题目...")
57
 
58
  # 处理每个部分题目
@@ -83,22 +103,29 @@ def process_files_core(json_files, pdf_files, file_type, ocr_choice, llm_choice)
83
  global models
84
  realtime_logger = logging.getLogger(__name__)
85
 
86
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
87
- temp_dir = os.path.join("temp_files", timestamp)
88
- out_dir = os.path.join(temp_dir, "out")
 
 
89
 
90
- # 中间流程
91
- os.makedirs(temp_dir, exist_ok=True)
92
- # 交付目录
93
- os.makedirs(out_dir, exist_ok=True)
94
 
95
- realtime_logger.info(f"开始新的处理...")
96
- realtime_logger.info(f"时间戳目录: {temp_dir}")
97
 
98
- try:
99
  if file_type == "JSON" and json_files is not None:
 
 
 
100
  realtime_logger.info(f"处理 {len(json_files)} 个JSON文件")
101
  for idx, json_file in enumerate(json_files, 1):
 
 
 
102
  dest_path = os.path.join(temp_dir, os.path.basename(json_file.name))
103
  shutil.copy2(json_file.name, dest_path)
104
  realtime_logger.info(
@@ -106,10 +133,16 @@ def process_files_core(json_files, pdf_files, file_type, ocr_choice, llm_choice)
106
  )
107
 
108
  elif file_type == "PDF" and pdf_files is not None:
 
 
 
109
  realtime_logger.info(f"处理 {len(pdf_files)} 个PDF文件")
110
  processed_files = []
111
 
112
  for idx, pdf_file in enumerate(pdf_files, 1):
 
 
 
113
  dest_path = os.path.join(temp_dir, os.path.basename(pdf_file.name))
114
  shutil.copy2(pdf_file.name, dest_path)
115
  processed_files.append(dest_path)
@@ -118,17 +151,23 @@ def process_files_core(json_files, pdf_files, file_type, ocr_choice, llm_choice)
118
  )
119
 
120
  if processed_files:
 
121
  realtime_logger.info(f"开始OCR处理,使用接口: {ocr_choice}")
122
  models["ocr"][ocr_choice].process_pdf_files(
123
  pdf_files=processed_files, output_path=temp_dir
124
  )
125
  realtime_logger.info("OCR处理完成")
126
 
 
127
  realtime_logger.info(f"开始LLM处理,使用模型: {llm_choice}")
128
 
129
  if file_type == "JSON" and json_files is not None:
130
  for idx, json_file in enumerate(json_files, 1):
131
  filename, file_ext = os.path.splitext(os.path.basename(json_file.name))
 
 
 
 
132
  realtime_logger.info(
133
  f"[{idx}/{len(json_files)}] 开���LLM处理: {filename}"
134
  )
@@ -141,6 +180,10 @@ def process_files_core(json_files, pdf_files, file_type, ocr_choice, llm_choice)
141
  elif file_type == "PDF" and pdf_files is not None:
142
  for idx, pdf_file in enumerate(pdf_files, 1):
143
  filename, file_ext = os.path.splitext(os.path.basename(pdf_file.name))
 
 
 
 
144
  realtime_logger.info(
145
  f"[{idx}/{len(pdf_files)}] 开始LLM处理: {filename}"
146
  )
@@ -149,9 +192,13 @@ def process_files_core(json_files, pdf_files, file_type, ocr_choice, llm_choice)
149
  os.makedirs(os.path.join(out_dir, filename), exist_ok=True)
150
 
151
  # 解析jsonl
 
 
 
152
  realtime_logger.info(f"提取题目中: {filename}")
153
  md_jsonl = llm_extract_question(md_path, models["llm"][llm_choice])
154
 
 
155
  realtime_logger.info(f"保存JSONL文件: {filename}.jsonl")
156
  dump_jsonl(
157
  os.path.join(out_dir, filename, f"{filename}.jsonl"), md_jsonl
@@ -160,12 +207,20 @@ def process_files_core(json_files, pdf_files, file_type, ocr_choice, llm_choice)
160
  # 移动img到交付目录
161
  img_dir = os.path.join(temp_dir, filename, "images")
162
  if os.path.exists(img_dir):
 
 
 
163
  dest_img_dir = os.path.join(out_dir, filename, "images")
164
  os.makedirs(dest_img_dir, exist_ok=True)
165
  img_files = os.listdir(img_dir)
166
  realtime_logger.info(f"移动 {len(img_files)} 个图片文件到输出目录")
167
 
168
  for img_idx, img in enumerate(img_files, 1):
 
 
 
 
 
169
  shutil.copy2(
170
  os.path.join(img_dir, img), os.path.join(dest_img_dir, img)
171
  )
@@ -180,12 +235,28 @@ def process_files_core(json_files, pdf_files, file_type, ocr_choice, llm_choice)
180
  f"[{idx}/{len(pdf_files)}] PDF处理完成: {filename}"
181
  )
182
 
183
- realtime_logger.info("所有文件处理完成!")
 
 
 
 
 
 
 
184
 
185
- # 上传到阿里云盘 output和tmp
186
  # 判断上传完成后删除缓存文件
 
 
 
 
 
 
 
 
 
187
 
188
  except Exception as e:
 
189
  realtime_logger.error(f"处理出错: {str(e)}")
190
  raise
191
 
@@ -197,6 +268,9 @@ def process_files_with_realtime_logs(
197
  # 清空之前的日志
198
  realtime_log_capture.clear_logs()
199
 
 
 
 
200
  # 在单独线程中运行核心处理逻辑
201
  task_thread = Thread(
202
  target=process_files_core,
@@ -206,7 +280,7 @@ def process_files_with_realtime_logs(
206
 
207
  current_logs = ""
208
 
209
- # 实时获取并yield日志
210
  while task_thread.is_alive():
211
  # 获取当前日志内容
212
  log_contents = realtime_log_capture.get_logs()
@@ -214,7 +288,7 @@ def process_files_with_realtime_logs(
214
  # 如果有新日志,则更新
215
  if log_contents != current_logs:
216
  current_logs = log_contents
217
- yield current_logs
218
 
219
  time.sleep(0.5) # 每0.5秒检查一次新日志
220
 
@@ -223,10 +297,16 @@ def process_files_with_realtime_logs(
223
  final_logs = realtime_log_capture.get_logs()
224
 
225
  if final_logs != current_logs:
226
- yield final_logs
227
-
228
- # 添加完成标记
229
- yield final_logs + "\n" + "=" * 50 + "\n处理完成!\n" + "=" * 50
 
 
 
 
 
 
230
 
231
 
232
  def update_file_inputs(file_type):
@@ -235,6 +315,12 @@ def update_file_inputs(file_type):
235
  return gr.update(visible=False), gr.update(visible=True)
236
 
237
 
 
 
 
 
 
 
238
  if __name__ == "__main__":
239
  os.makedirs("temp_files", exist_ok=True)
240
 
@@ -245,13 +331,18 @@ if __name__ == "__main__":
245
  # Initialize services with API keys from config
246
  doc2x = PDFProcessor(config["ocr"]["doc2x"]["API_KEY"])
247
  kimi = KimiAgent(api_key=config["llm"]["kimi"]["API_KEY"])
 
 
 
 
 
248
 
249
  # Initialize global models
250
  global models
251
- models = dict(ocr=dict(doc2x=doc2x), llm=dict(kimi=kimi))
252
 
253
  with gr.Blocks(title="文件处理系统") as demo:
254
- gr.Markdown("# 文件处理系统 - 实时日志版本")
255
 
256
  # Top section
257
  with gr.Row():
@@ -287,9 +378,12 @@ if __name__ == "__main__":
287
 
288
  # Control section
289
  with gr.Row():
290
- status_text = gr.Textbox(label="运行状态", interactive=False)
 
 
291
  process_btn = gr.Button("开始处理", variant="primary", size="lg")
292
  clear_log_btn = gr.Button("清空日志", variant="secondary")
 
293
 
294
  # Log output section - 放在最下面,占据更多空间
295
  gr.Markdown("### 实时处理日志")
@@ -323,10 +417,15 @@ if __name__ == "__main__":
323
  ocr_choice,
324
  llm_choice,
325
  ],
326
- outputs=[log_output],
327
  show_progress=True,
328
  )
329
 
330
  clear_log_btn.click(fn=lambda: "", outputs=[log_output])
331
 
 
 
 
 
 
332
  demo.launch()
 
1
+ from storage.ali_drive import AligoUploader
2
  from llms.kimi import KimiAgent
3
  from ocr.doc2x import PDFProcessor
4
  import os
 
11
  import logging
12
  import io
13
  from threading import Thread
14
+ from status import *
15
 
16
+ # 全局状态变量
17
+ current_status = ProcessStatus.IDLE
18
+ status_detail = ""
19
 
 
20
  # todo 性能优化 并发?
21
 
22
 
 
24
  realtime_log_capture = RealTimeLogCapture(__name__)
25
 
26
 
27
+ def update_status(status: ProcessStatus, detail: str = ""):
28
+ """更新全局状态"""
29
+ global current_status, status_detail
30
+ current_status = status
31
+ status_detail = detail
32
+
33
+
34
+ def get_current_status_display():
35
+ """获取当前状态的显示格式"""
36
+ return format_status_display(current_status, status_detail)
37
+
38
+
39
  def update_ocr_interface(file_type):
40
  if file_type == "JSON":
41
  return (
 
69
 
70
  jsonl_data = []
71
  for idx, que in enumerate(question_groups, 1):
72
+ update_status(
73
+ ProcessStatus.EXTRACTING_QUESTIONS,
74
+ f"处理第 {idx}/{len(question_groups)} 组题目",
75
+ )
76
  realtime_logger.info(f"处理第 {idx}/{len(question_groups)} 组题目...")
77
 
78
  # 处理每个部分题目
 
103
  global models
104
  realtime_logger = logging.getLogger(__name__)
105
 
106
+ try:
107
+ update_status(ProcessStatus.INITIALIZING, "创建临时目录")
108
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
109
+ temp_dir = os.path.join("temp_files", timestamp)
110
+ out_dir = os.path.join(temp_dir, "out")
111
 
112
+ # 中间流程
113
+ os.makedirs(temp_dir, exist_ok=True)
114
+ # 交付目录
115
+ os.makedirs(out_dir, exist_ok=True)
116
 
117
+ realtime_logger.info(f"开始新的处理...")
118
+ realtime_logger.info(f"时间戳目录: {temp_dir}")
119
 
 
120
  if file_type == "JSON" and json_files is not None:
121
+ update_status(
122
+ ProcessStatus.COPYING_FILES, f"处理 {len(json_files)} 个JSON文件"
123
+ )
124
  realtime_logger.info(f"处理 {len(json_files)} 个JSON文件")
125
  for idx, json_file in enumerate(json_files, 1):
126
+ update_status(
127
+ ProcessStatus.COPYING_FILES, f"复制JSON文件 {idx}/{len(json_files)}"
128
+ )
129
  dest_path = os.path.join(temp_dir, os.path.basename(json_file.name))
130
  shutil.copy2(json_file.name, dest_path)
131
  realtime_logger.info(
 
133
  )
134
 
135
  elif file_type == "PDF" and pdf_files is not None:
136
+ update_status(
137
+ ProcessStatus.COPYING_FILES, f"处理 {len(pdf_files)} 个PDF文件"
138
+ )
139
  realtime_logger.info(f"处理 {len(pdf_files)} 个PDF文件")
140
  processed_files = []
141
 
142
  for idx, pdf_file in enumerate(pdf_files, 1):
143
+ update_status(
144
+ ProcessStatus.COPYING_FILES, f"复制PDF文件 {idx}/{len(pdf_files)}"
145
+ )
146
  dest_path = os.path.join(temp_dir, os.path.basename(pdf_file.name))
147
  shutil.copy2(pdf_file.name, dest_path)
148
  processed_files.append(dest_path)
 
151
  )
152
 
153
  if processed_files:
154
+ update_status(ProcessStatus.OCR_PROCESSING, f"使用接口: {ocr_choice}")
155
  realtime_logger.info(f"开始OCR处理,使用接口: {ocr_choice}")
156
  models["ocr"][ocr_choice].process_pdf_files(
157
  pdf_files=processed_files, output_path=temp_dir
158
  )
159
  realtime_logger.info("OCR处理完成")
160
 
161
+ update_status(ProcessStatus.LLM_PROCESSING, f"使用模型: {llm_choice}")
162
  realtime_logger.info(f"开始LLM处理,使用模型: {llm_choice}")
163
 
164
  if file_type == "JSON" and json_files is not None:
165
  for idx, json_file in enumerate(json_files, 1):
166
  filename, file_ext = os.path.splitext(os.path.basename(json_file.name))
167
+ update_status(
168
+ ProcessStatus.LLM_PROCESSING,
169
+ f"处理JSON {idx}/{len(json_files)}: {filename}",
170
+ )
171
  realtime_logger.info(
172
  f"[{idx}/{len(json_files)}] 开���LLM处理: {filename}"
173
  )
 
180
  elif file_type == "PDF" and pdf_files is not None:
181
  for idx, pdf_file in enumerate(pdf_files, 1):
182
  filename, file_ext = os.path.splitext(os.path.basename(pdf_file.name))
183
+ update_status(
184
+ ProcessStatus.LLM_PROCESSING,
185
+ f"处理PDF {idx}/{len(pdf_files)}: {filename}",
186
+ )
187
  realtime_logger.info(
188
  f"[{idx}/{len(pdf_files)}] 开始LLM处理: {filename}"
189
  )
 
192
  os.makedirs(os.path.join(out_dir, filename), exist_ok=True)
193
 
194
  # 解析jsonl
195
+ update_status(
196
+ ProcessStatus.EXTRACTING_QUESTIONS, f"提取题目: {filename}"
197
+ )
198
  realtime_logger.info(f"提取题目中: {filename}")
199
  md_jsonl = llm_extract_question(md_path, models["llm"][llm_choice])
200
 
201
+ update_status(ProcessStatus.SAVING_RESULTS, f"保存JSONL: {filename}")
202
  realtime_logger.info(f"保存JSONL文件: {filename}.jsonl")
203
  dump_jsonl(
204
  os.path.join(out_dir, filename, f"{filename}.jsonl"), md_jsonl
 
207
  # 移动img到交付目录
208
  img_dir = os.path.join(temp_dir, filename, "images")
209
  if os.path.exists(img_dir):
210
+ update_status(
211
+ ProcessStatus.MOVING_FILES, f"移动图片文件: {filename}"
212
+ )
213
  dest_img_dir = os.path.join(out_dir, filename, "images")
214
  os.makedirs(dest_img_dir, exist_ok=True)
215
  img_files = os.listdir(img_dir)
216
  realtime_logger.info(f"移动 {len(img_files)} 个图片文件到输出目录")
217
 
218
  for img_idx, img in enumerate(img_files, 1):
219
+ if img_idx % 10 == 0: # 每10个文件更新一次状态
220
+ update_status(
221
+ ProcessStatus.MOVING_FILES,
222
+ f"移动图片 {img_idx}/{len(img_files)}",
223
+ )
224
  shutil.copy2(
225
  os.path.join(img_dir, img), os.path.join(dest_img_dir, img)
226
  )
 
235
  f"[{idx}/{len(pdf_files)}] PDF处理完成: {filename}"
236
  )
237
 
238
+ # 上传到阿里云盘
239
+ ali_drive = models["storage"]["ali_drive"]
240
+ update_status(ProcessStatus.UPLOADING, "开始上传至存储")
241
+ # 上传文件夹
242
+ if os.path.exists(temp_dir):
243
+ upload_flag = ali_drive.upload_data(temp_dir)
244
+ else:
245
+ realtime_logger.info(f"路径 {temp_dir} 不存在")
246
 
 
247
  # 判断上传完成后删除缓存文件
248
+ if upload_flag:
249
+ update_status(ProcessStatus.IDLE, "上传完成,清理临时文件")
250
+ realtime_logger.info("上传完成,清理临时文件")
251
+ # 删除临时目录
252
+ shutil.rmtree(temp_dir, ignore_errors=True)
253
+ realtime_logger.info(f"已删除临时目录: {temp_dir}")
254
+
255
+ update_status(ProcessStatus.COMPLETED, "所有文件处理完成")
256
+ realtime_logger.info("所有文件处理完成!")
257
 
258
  except Exception as e:
259
+ update_status(ProcessStatus.ERROR, f"错误: {str(e)}")
260
  realtime_logger.error(f"处理出错: {str(e)}")
261
  raise
262
 
 
268
  # 清空之前的日志
269
  realtime_log_capture.clear_logs()
270
 
271
+ # 重置状态
272
+ update_status(ProcessStatus.INITIALIZING)
273
+
274
  # 在单独线程中运行核心处理逻辑
275
  task_thread = Thread(
276
  target=process_files_core,
 
280
 
281
  current_logs = ""
282
 
283
+ # 实时获取并yield日志和状态
284
  while task_thread.is_alive():
285
  # 获取当前日志内容
286
  log_contents = realtime_log_capture.get_logs()
 
288
  # 如果有新日志,则更新
289
  if log_contents != current_logs:
290
  current_logs = log_contents
291
+ yield current_logs, get_current_status_display()
292
 
293
  time.sleep(0.5) # 每0.5秒检查一次新日志
294
 
 
297
  final_logs = realtime_log_capture.get_logs()
298
 
299
  if final_logs != current_logs:
300
+ final_logs_with_completion = (
301
+ final_logs + "\n" + "=" * 50 + "\n处理完成!\n" + "=" * 50
302
+ )
303
+ yield final_logs_with_completion, get_current_status_display()
304
+ else:
305
+ # 添加完成标记
306
+ final_logs_with_completion = (
307
+ final_logs + "\n" + "=" * 50 + "\n处理完成!\n" + "=" * 50
308
+ )
309
+ yield final_logs_with_completion, get_current_status_display()
310
 
311
 
312
  def update_file_inputs(file_type):
 
315
  return gr.update(visible=False), gr.update(visible=True)
316
 
317
 
318
+ def reset_status():
319
+ """重置状态为待机"""
320
+ update_status(ProcessStatus.IDLE)
321
+ return get_current_status_display()
322
+
323
+
324
  if __name__ == "__main__":
325
  os.makedirs("temp_files", exist_ok=True)
326
 
 
331
  # Initialize services with API keys from config
332
  doc2x = PDFProcessor(config["ocr"]["doc2x"]["API_KEY"])
333
  kimi = KimiAgent(api_key=config["llm"]["kimi"]["API_KEY"])
334
+ ali_drive = AligoUploader(
335
+ email=config["storage"]["ali_drive"]["email"],
336
+ password=config["storage"]["ali_drive"]["pwd"],
337
+ name=config["storage"]["ali_drive"]["name"],
338
+ )
339
 
340
  # Initialize global models
341
  global models
342
+ models = dict(ocr=dict(doc2x=doc2x), llm=dict(kimi=kimi), storage=dict(ali_drive=ali_drive))
343
 
344
  with gr.Blocks(title="文件处理系统") as demo:
345
+ gr.Markdown("# 文件处理系统")
346
 
347
  # Top section
348
  with gr.Row():
 
378
 
379
  # Control section
380
  with gr.Row():
381
+ status_text = gr.HTML(
382
+ label="运行状态", value=get_current_status_display(), visible=True
383
+ )
384
  process_btn = gr.Button("开始处理", variant="primary", size="lg")
385
  clear_log_btn = gr.Button("清空日志", variant="secondary")
386
+ # reset_btn = gr.Button("重置状态", variant="secondary")
387
 
388
  # Log output section - 放在最下面,占据更多空间
389
  gr.Markdown("### 实时处理日志")
 
417
  ocr_choice,
418
  llm_choice,
419
  ],
420
+ outputs=[log_output, status_text],
421
  show_progress=True,
422
  )
423
 
424
  clear_log_btn.click(fn=lambda: "", outputs=[log_output])
425
 
426
+ # reset_btn.click(
427
+ # fn=reset_status,
428
+ # outputs=[status_text]
429
+ # )
430
+
431
  demo.launch()
ocr/doc2x.py CHANGED
@@ -13,7 +13,7 @@ class PDFProcessor:
13
  """
14
  Initialize Doc2X client
15
  """
16
- return Doc2X(apikey=apikey, debug=True)
17
 
18
  def pdf2md(self, pdf_file, output_path):
19
  """
 
13
  """
14
  Initialize Doc2X client
15
  """
16
+ return Doc2X(apikey=apikey, debug=True, full_speed=True)
17
 
18
  def pdf2md(self, pdf_file, output_path):
19
  """