OmniDocBench_DotsOCR_multthreads.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. """
  2. 批量处理 OmniDocBench 图片并生成符合评测要求的预测结果
  3. 根据 OmniDocBench 评测要求:
  4. - 输入:OpenDataLab___OmniDocBench/images 下的所有 .jpg 图片
  5. - 输出:每个图片对应的 .md、.json 和带标注的 layout 图片文件
  6. - 输出目录:用于后续的 end2end 评测
  7. """
  8. import os
  9. import sys
  10. import json
  11. import tempfile
  12. import uuid
  13. import shutil
  14. import time
  15. import traceback
  16. import warnings
  17. from pathlib import Path
  18. from typing import List, Dict, Any
  19. from PIL import Image
  20. from tqdm import tqdm
  21. import argparse
  22. # 导入 dots.ocr 相关模块
  23. from dots_ocr.parser import DotsOCRParser
  24. from dots_ocr.utils import dict_promptmode_to_prompt
  25. from dots_ocr.utils.consts import MIN_PIXELS, MAX_PIXELS
  26. # 导入工具函数
  27. from utils import (
  28. get_image_files_from_dir,
  29. get_image_files_from_list,
  30. get_image_files_from_csv,
  31. collect_pid_files
  32. )
  33. class DotsOCRProcessor:
  34. """DotsOCR 处理器"""
  35. def __init__(self,
  36. ip: str = "127.0.0.1",
  37. port: int = 8101,
  38. model_name: str = "DotsOCR",
  39. prompt_mode: str = "prompt_layout_all_en",
  40. dpi: int = 200,
  41. min_pixels: int = MIN_PIXELS,
  42. max_pixels: int = MAX_PIXELS):
  43. """
  44. 初始化处理器
  45. Args:
  46. ip: vLLM 服务器 IP
  47. port: vLLM 服务器端口
  48. model_name: 模型名称
  49. prompt_mode: 提示模式
  50. dpi: PDF 处理 DPI
  51. min_pixels: 最小像素数
  52. max_pixels: 最大像素数
  53. """
  54. self.ip = ip
  55. self.port = port
  56. self.model_name = model_name
  57. self.prompt_mode = prompt_mode
  58. self.dpi = dpi
  59. self.min_pixels = min_pixels
  60. self.max_pixels = max_pixels
  61. # 初始化解析器
  62. self.parser = DotsOCRParser(
  63. ip=ip,
  64. port=port,
  65. dpi=dpi,
  66. min_pixels=min_pixels,
  67. max_pixels=max_pixels,
  68. model_name=model_name
  69. )
  70. print(f"DotsOCR Parser 初始化完成:")
  71. print(f" - 服务器: {ip}:{port}")
  72. print(f" - 模型: {model_name}")
  73. print(f" - 提示模式: {prompt_mode}")
  74. print(f" - 像素范围: {min_pixels} - {max_pixels}")
  75. def create_temp_session_dir(self) -> tuple:
  76. """创建临时会话目录"""
  77. session_id = uuid.uuid4().hex[:8]
  78. temp_dir = os.path.join(tempfile.gettempdir(), f"omnidocbench_batch_{session_id}")
  79. os.makedirs(temp_dir, exist_ok=True)
  80. return temp_dir, session_id
  81. def save_results_to_output_dir(self, result: Dict, image_name: str, output_dir: str) -> Dict[str, str]:
  82. """
  83. 将处理结果保存到输出目录
  84. Args:
  85. result: 解析结果
  86. image_name: 图片文件名(不含扩展名)
  87. output_dir: 输出目录
  88. Returns:
  89. dict: 保存的文件路径
  90. """
  91. saved_files = {}
  92. try:
  93. # 1. 保存 Markdown 文件(OmniDocBench 评测必需)
  94. output_md_path = os.path.join(output_dir, f"{image_name}.md")
  95. md_content = ""
  96. # 优先使用无页眉页脚的版本(符合 OmniDocBench 评测要求)
  97. if 'md_content_nohf_path' in result and os.path.exists(result['md_content_nohf_path']):
  98. with open(result['md_content_nohf_path'], 'r', encoding='utf-8') as f:
  99. md_content = f.read()
  100. elif 'md_content_path' in result and os.path.exists(result['md_content_path']):
  101. with open(result['md_content_path'], 'r', encoding='utf-8') as f:
  102. md_content = f.read()
  103. else:
  104. md_content = "# 解析失败\n\n未能提取到有效的文档内容。"
  105. with open(output_md_path, 'w', encoding='utf-8') as f:
  106. f.write(md_content)
  107. saved_files['md'] = output_md_path
  108. # 2. 保存 JSON 文件
  109. output_json_path = os.path.join(output_dir, f"{image_name}.json")
  110. json_data = {}
  111. if 'layout_info_path' in result and os.path.exists(result['layout_info_path']):
  112. with open(result['layout_info_path'], 'r', encoding='utf-8') as f:
  113. json_data = json.load(f)
  114. else:
  115. json_data = {
  116. "error": "未能提取到有效的布局信息",
  117. "cells": []
  118. }
  119. with open(output_json_path, 'w', encoding='utf-8') as f:
  120. json.dump(json_data, f, ensure_ascii=False, indent=2)
  121. saved_files['json'] = output_json_path
  122. # 3. 保存带标注的布局图片
  123. output_layout_image_path = os.path.join(output_dir, f"{image_name}_layout.jpg")
  124. if 'layout_image_path' in result and os.path.exists(result['layout_image_path']):
  125. # 直接复制布局图片
  126. shutil.copy2(result['layout_image_path'], output_layout_image_path)
  127. saved_files['layout_image'] = output_layout_image_path
  128. else:
  129. # 如果没有布局图片,使用原始图片作为占位符
  130. try:
  131. original_image = Image.open(result.get('original_image_path', ''))
  132. original_image.save(output_layout_image_path, 'JPEG', quality=95)
  133. saved_files['layout_image'] = output_layout_image_path
  134. except Exception as e:
  135. saved_files['layout_image'] = None
  136. # # 4. 可选:保存原始图片副本
  137. # output_original_image_path = os.path.join(output_dir, f"{image_name}_original.jpg")
  138. # if 'original_image_path' in result and os.path.exists(result['original_image_path']):
  139. # shutil.copy2(result['original_image_path'], output_original_image_path)
  140. # saved_files['original_image'] = output_original_image_path
  141. except Exception as e:
  142. print(f"Error saving results for {image_name}: {e}")
  143. return saved_files
  144. def process_single_image(self, image_path: str, output_dir: str) -> Dict[str, Any]:
  145. """
  146. 处理单张图片
  147. Args:
  148. image_path: 图片路径
  149. output_dir: 输出目录
  150. Returns:
  151. dict: 处理结果
  152. """
  153. start_time = time.time()
  154. image_name = Path(image_path).stem
  155. result_info = {
  156. "image_path": image_path,
  157. "processing_time": 0,
  158. "success": False,
  159. "device": f"{self.ip}:{self.port}",
  160. "error": None,
  161. "output_files": {}
  162. }
  163. try:
  164. # 检查输出文件是否已存在
  165. output_md_path = os.path.join(output_dir, f"{image_name}.md")
  166. output_json_path = os.path.join(output_dir, f"{image_name}.json")
  167. output_layout_path = os.path.join(output_dir, f"{image_name}_layout.jpg")
  168. if all(os.path.exists(p) for p in [output_md_path, output_json_path, output_layout_path]):
  169. result_info.update({
  170. "success": True,
  171. "processing_time": 0,
  172. "output_files": {
  173. "md": output_md_path,
  174. "json": output_json_path,
  175. "layout_image": output_layout_path
  176. },
  177. "skipped": True
  178. })
  179. return result_info
  180. # 创建临时会话目录
  181. temp_dir, session_id = self.create_temp_session_dir()
  182. try:
  183. # 读取图片
  184. image = Image.open(image_path)
  185. # 使用 DotsOCRParser 处理图片
  186. filename = f"omnidocbench_{session_id}"
  187. results = self.parser.parse_image(
  188. input_path=image,
  189. filename=filename,
  190. prompt_mode=self.prompt_mode,
  191. save_dir=temp_dir,
  192. fitz_preprocess=True # 对图片使用 fitz 预处理
  193. )
  194. # 解析结果
  195. if not results:
  196. raise Exception("未返回解析结果")
  197. result = results[0] # parse_image 返回单个结果的列表
  198. # 添加原始图片路径到结果中
  199. # result['original_image_path'] = image_path
  200. # 保存所有结果文件到输出目录
  201. saved_files = self.save_results_to_output_dir(result, image_name, output_dir)
  202. # 验证保存结果
  203. success_count = sum(1 for path in saved_files.values() if path and os.path.exists(path))
  204. if success_count >= 2: # 至少保存了 md 和 json
  205. result_info.update({
  206. "success": True,
  207. "output_files": saved_files
  208. })
  209. else:
  210. raise Exception(f"保存文件不完整 ({success_count}/3)")
  211. finally:
  212. # 清理临时目录
  213. if os.path.exists(temp_dir):
  214. shutil.rmtree(temp_dir, ignore_errors=True)
  215. except Exception as e:
  216. result_info["error"] = str(e)
  217. print(f"❌ Error processing {image_name}: {e}")
  218. finally:
  219. result_info["processing_time"] = time.time() - start_time
  220. return result_info
  221. def process_images_single_process(image_paths: List[str],
  222. processor: DotsOCRProcessor,
  223. batch_size: int = 1,
  224. output_dir: str = "./output") -> List[Dict[str, Any]]:
  225. """
  226. 单进程版本的图像处理函数
  227. Args:
  228. image_paths: 图像路径列表
  229. processor: DotsOCR处理器实例
  230. batch_size: 批处理大小
  231. output_dir: 输出目录
  232. Returns:
  233. 处理结果列表
  234. """
  235. # 创建输出目录
  236. output_path = Path(output_dir)
  237. output_path.mkdir(parents=True, exist_ok=True)
  238. all_results = []
  239. total_images = len(image_paths)
  240. print(f"Processing {total_images} images with batch size {batch_size}")
  241. # 使用tqdm显示进度,添加更多统计信息
  242. with tqdm(total=total_images, desc="Processing images", unit="img",
  243. bar_format='{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]') as pbar:
  244. # 按批次处理图像(DotsOCR通常单张处理)
  245. for i in range(0, total_images, batch_size):
  246. batch = image_paths[i:i + batch_size]
  247. batch_start_time = time.time()
  248. batch_results = []
  249. try:
  250. # 处理批次中的每张图片
  251. for image_path in batch:
  252. try:
  253. result = processor.process_single_image(image_path, output_dir)
  254. batch_results.append(result)
  255. except Exception as e:
  256. print(f"Error processing {image_path}: {e}", file=sys.stderr)
  257. traceback.print_exc()
  258. batch_results.append({
  259. "image_path": image_path,
  260. "processing_time": 0,
  261. "success": False,
  262. "device": f"{processor.ip}:{processor.port}",
  263. "error": str(e)
  264. })
  265. batch_processing_time = time.time() - batch_start_time
  266. all_results.extend(batch_results)
  267. # 更新进度条
  268. success_count = sum(1 for r in batch_results if r.get('success', False))
  269. skipped_count = sum(1 for r in batch_results if r.get('skipped', False))
  270. total_success = sum(1 for r in all_results if r.get('success', False))
  271. total_skipped = sum(1 for r in all_results if r.get('skipped', False))
  272. avg_time = batch_processing_time / len(batch)
  273. pbar.update(len(batch))
  274. pbar.set_postfix({
  275. 'batch_time': f"{batch_processing_time:.2f}s",
  276. 'avg_time': f"{avg_time:.2f}s/img",
  277. 'success': f"{total_success}/{len(all_results)}",
  278. 'skipped': f"{total_skipped}",
  279. 'rate': f"{total_success/len(all_results)*100:.1f}%"
  280. })
  281. except Exception as e:
  282. print(f"Error processing batch {[Path(p).name for p in batch]}: {e}", file=sys.stderr)
  283. traceback.print_exc()
  284. # 为批次中的所有图像添加错误结果
  285. error_results = []
  286. for img_path in batch:
  287. error_results.append({
  288. "image_path": str(img_path),
  289. "processing_time": 0,
  290. "success": False,
  291. "device": f"{processor.ip}:{processor.port}",
  292. "error": str(e)
  293. })
  294. all_results.extend(error_results)
  295. pbar.update(len(batch))
  296. return all_results
  297. def process_images_concurrent(image_paths: List[str],
  298. processor: DotsOCRProcessor,
  299. batch_size: int = 1,
  300. output_dir: str = "./output",
  301. max_workers: int = 3) -> List[Dict[str, Any]]:
  302. """并发版本的图像处理函数"""
  303. from concurrent.futures import ThreadPoolExecutor, as_completed
  304. Path(output_dir).mkdir(parents=True, exist_ok=True)
  305. def process_batch(batch_images):
  306. """处理一批图像"""
  307. batch_results = []
  308. for image_path in batch_images:
  309. try:
  310. result = processor.process_single_image(image_path, output_dir)
  311. batch_results.append(result)
  312. except Exception as e:
  313. batch_results.append({
  314. "image_path": image_path,
  315. "processing_time": 0,
  316. "success": False,
  317. "device": f"{processor.ip}:{processor.port}",
  318. "error": str(e)
  319. })
  320. return batch_results
  321. # 将图像分批
  322. batches = [image_paths[i:i + batch_size] for i in range(0, len(image_paths), batch_size)]
  323. all_results = []
  324. with ThreadPoolExecutor(max_workers=max_workers) as executor:
  325. # 提交所有批次
  326. future_to_batch = {executor.submit(process_batch, batch): batch for batch in batches}
  327. # 使用 tqdm 显示进度
  328. with tqdm(total=len(image_paths), desc="Processing images") as pbar:
  329. for future in as_completed(future_to_batch):
  330. try:
  331. batch_results = future.result()
  332. all_results.extend(batch_results)
  333. # 更新进度
  334. success_count = sum(1 for r in batch_results if r.get('success', False))
  335. pbar.update(len(batch_results))
  336. pbar.set_postfix({'batch_success': f"{success_count}/{len(batch_results)}"})
  337. except Exception as e:
  338. batch = future_to_batch[future]
  339. # 为批次中的所有图像添加错误结果
  340. error_results = [
  341. {
  342. "image_path": img_path,
  343. "processing_time": 0,
  344. "success": False,
  345. "device": f"{processor.ip}:{processor.port}",
  346. "error": str(e)
  347. }
  348. for img_path in batch
  349. ]
  350. all_results.extend(error_results)
  351. pbar.update(len(batch))
  352. return all_results
  353. def main():
  354. """主函数"""
  355. parser = argparse.ArgumentParser(description="DotsOCR OmniDocBench Processing")
  356. # 输入参数组
  357. input_group = parser.add_mutually_exclusive_group(required=True)
  358. input_group.add_argument("--input_dir", type=str, help="Input directory")
  359. input_group.add_argument("--input_file_list", type=str, help="Input file list (one file per line)")
  360. input_group.add_argument("--input_csv", type=str, help="Input CSV file with image_path and status columns")
  361. # 输出参数
  362. parser.add_argument("--output_dir", type=str, help="Output directory")
  363. # DotsOCR 参数
  364. parser.add_argument("--ip", type=str, default="127.0.0.1", help="vLLM server IP")
  365. parser.add_argument("--port", type=int, default=8101, help="vLLM server port")
  366. parser.add_argument("--model_name", type=str, default="DotsOCR", help="Model name")
  367. parser.add_argument("--prompt_mode", type=str, default="prompt_layout_all_en",
  368. choices=list(dict_promptmode_to_prompt.keys()), help="Prompt mode")
  369. parser.add_argument("--min_pixels", type=int, default=MIN_PIXELS, help="Minimum pixels")
  370. parser.add_argument("--max_pixels", type=int, default=MAX_PIXELS, help="Maximum pixels")
  371. parser.add_argument("--dpi", type=int, default=200, help="PDF processing DPI")
  372. # 处理参数
  373. parser.add_argument("--batch_size", type=int, default=1, help="Batch size")
  374. parser.add_argument("--input_pattern", type=str, default="*", help="Input file pattern")
  375. parser.add_argument("--test_mode", action="store_true", help="Test mode (process only 10 images)")
  376. parser.add_argument("--collect_results", type=str, help="收集处理结果到指定CSV文件")
  377. # 并发参数
  378. parser.add_argument("--max_workers", type=int, default=3,
  379. help="Maximum number of concurrent workers (should match vLLM data-parallel-size)")
  380. parser.add_argument("--use_threading", action="store_true",
  381. help="Use multi-threading")
  382. args = parser.parse_args()
  383. try:
  384. # 获取图像文件列表
  385. if args.input_csv:
  386. # 从CSV文件读取
  387. image_files = get_image_files_from_csv(args.input_csv, "fail")
  388. print(f"📊 Loaded {len(image_files)} files from CSV with status filter: fail")
  389. elif args.input_file_list:
  390. # 从文件列表读取
  391. image_files = get_image_files_from_list(args.input_file_list)
  392. else:
  393. # 从目录读取
  394. input_dir = Path(args.input_dir).resolve()
  395. print(f"📁 Input dir: {input_dir}")
  396. if not input_dir.exists():
  397. print(f"❌ Input directory does not exist: {input_dir}")
  398. return 1
  399. image_files = get_image_files_from_dir(input_dir, args.input_pattern)
  400. output_dir = Path(args.output_dir).resolve()
  401. print(f"📁 Output dir: {output_dir}")
  402. print(f"📊 Found {len(image_files)} image files")
  403. if args.test_mode:
  404. image_files = image_files[:10]
  405. print(f"🧪 Test mode: processing only {len(image_files)} images")
  406. print(f"🌐 Using server: {args.ip}:{args.port}")
  407. print(f"📦 Batch size: {args.batch_size}")
  408. print(f"🎯 Prompt mode: {args.prompt_mode}")
  409. # 创建处理器
  410. processor = DotsOCRProcessor(
  411. ip=args.ip,
  412. port=args.port,
  413. model_name=args.model_name,
  414. prompt_mode=args.prompt_mode,
  415. dpi=args.dpi,
  416. min_pixels=args.min_pixels,
  417. max_pixels=args.max_pixels
  418. )
  419. # 开始处理
  420. start_time = time.time()
  421. # 选择处理方式
  422. if args.use_threading:
  423. results = process_images_concurrent(
  424. image_files,
  425. processor,
  426. args.batch_size,
  427. str(output_dir),
  428. args.max_workers
  429. )
  430. else:
  431. results = process_images_single_process(
  432. image_files,
  433. processor,
  434. args.batch_size,
  435. str(output_dir)
  436. )
  437. total_time = time.time() - start_time
  438. # 统计结果
  439. success_count = sum(1 for r in results if r.get('success', False))
  440. skipped_count = sum(1 for r in results if r.get('skipped', False))
  441. error_count = len(results) - success_count
  442. print(f"\n" + "="*60)
  443. print(f"✅ Processing completed!")
  444. print(f"📊 Statistics:")
  445. print(f" Total files: {len(image_files)}")
  446. print(f" Successful: {success_count}")
  447. print(f" Skipped: {skipped_count}")
  448. print(f" Failed: {error_count}")
  449. if len(image_files) > 0:
  450. print(f" Success rate: {success_count / len(image_files) * 100:.2f}%")
  451. print(f"⏱️ Performance:")
  452. print(f" Total time: {total_time:.2f} seconds")
  453. if total_time > 0:
  454. print(f" Throughput: {len(image_files) / total_time:.2f} images/second")
  455. print(f" Avg time per image: {total_time / len(image_files):.2f} seconds")
  456. # 保存结果统计
  457. stats = {
  458. "total_files": len(image_files),
  459. "success_count": success_count,
  460. "skipped_count": skipped_count,
  461. "error_count": error_count,
  462. "success_rate": success_count / len(image_files) if len(image_files) > 0 else 0,
  463. "total_time": total_time,
  464. "throughput": len(image_files) / total_time if total_time > 0 else 0,
  465. "avg_time_per_image": total_time / len(image_files) if len(image_files) > 0 else 0,
  466. "batch_size": args.batch_size,
  467. "server": f"{args.ip}:{args.port}",
  468. "model": args.model_name,
  469. "prompt_mode": args.prompt_mode,
  470. "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
  471. }
  472. # 保存最终结果
  473. output_file_name = Path(output_dir).name
  474. output_file = os.path.join(output_dir, f"{output_file_name}_results.json")
  475. final_results = {
  476. "stats": stats,
  477. "results": results
  478. }
  479. with open(output_file, 'w', encoding='utf-8') as f:
  480. json.dump(final_results, f, ensure_ascii=False, indent=2)
  481. print(f"💾 Results saved to: {output_file}")
  482. # 收集处理结果
  483. if args.collect_results:
  484. processed_files = collect_pid_files(output_file)
  485. output_file_processed = Path(args.collect_results).resolve()
  486. with open(output_file_processed, 'w', encoding='utf-8') as f:
  487. f.write("image_path,status\n")
  488. for file_path, status in processed_files:
  489. f.write(f"{file_path},{status}\n")
  490. print(f"💾 Processed files saved to: {output_file_processed}")
  491. return 0
  492. except Exception as e:
  493. print(f"❌ Processing failed: {e}", file=sys.stderr)
  494. traceback.print_exc()
  495. return 1
  496. if __name__ == "__main__":
  497. print(f"🚀 启动DotsOCR单进程程序...")
  498. print(f"🔧 CUDA_VISIBLE_DEVICES: {os.environ.get('CUDA_VISIBLE_DEVICES', 'Not set')}")
  499. if len(sys.argv) == 1:
  500. # 如果没有命令行参数,使用默认配置运行
  501. print("ℹ️ No command line arguments provided. Running with default configuration...")
  502. # 默认配置
  503. default_config = {
  504. "input_dir": "../../OmniDocBench/OpenDataLab___OmniDocBench/images",
  505. "output_dir": "./OmniDocBench_DotsOCR_Results",
  506. "ip": "10.192.72.11",
  507. "port": "8101",
  508. "model_name": "DotsOCR",
  509. "prompt_mode": "prompt_layout_all_en",
  510. "batch_size": "1",
  511. "max_workers": "3",
  512. "collect_results": "./OmniDocBench_DotsOCR_Results/processed_files.csv",
  513. }
  514. # 如果需要处理失败的文件,可以使用这个配置
  515. # default_config = {
  516. # "input_csv": "./OmniDocBench_DotsOCR_Results/processed_files.csv",
  517. # "output_dir": "./OmniDocBench_DotsOCR_Results",
  518. # "ip": "127.0.0.1",
  519. # "port": "8101",
  520. # "collect_results": f"./OmniDocBench_DotsOCR_Results/processed_files_{time.strftime('%Y%m%d_%H%M%S')}.csv",
  521. # }
  522. # 构造参数
  523. sys.argv = [sys.argv[0]]
  524. for key, value in default_config.items():
  525. sys.argv.extend([f"--{key}", str(value)])
  526. # 测试模式
  527. sys.argv.append("--use_threading")
  528. # sys.argv.append("--test_mode")
  529. sys.exit(main())