main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. #!/usr/bin/env python3
  2. """
  3. 批量处理图片/PDF文件并生成符合评测要求的预测结果(MinerU版本)
  4. 根据 MinerU demo.py 框架调用方式:
  5. - 输入:支持 PDF 和各种图片格式(统一使用 --input 参数)
  6. - 输出:每个文件对应的 .md、.json 文件,所有图片保存为单独的图片文件
  7. - 调用方式:通过 vlm-http-client 连接到 MinerU vLLM 服务器
  8. 使用方法:
  9. python main.py --input document.pdf --output_dir ./output
  10. python main.py --input ./images/ --output_dir ./output
  11. python main.py --input file_list.txt --output_dir ./output
  12. python main.py --input results.csv --output_dir ./output --dry_run
  13. """
  14. import os
  15. import sys
  16. import json
  17. import time
  18. import traceback
  19. from pathlib import Path
  20. from typing import List, Dict, Any
  21. from tqdm import tqdm
  22. import argparse
  23. from loguru import logger
  24. # 导入 MinerU 核心组件
  25. from mineru.cli.common import read_fn, convert_pdf_bytes_to_bytes_by_pypdfium2
  26. # 导入 ocr_utils
  27. ocr_platform_root = Path(__file__).parents[2]
  28. if str(ocr_platform_root) not in sys.path:
  29. sys.path.insert(0, str(ocr_platform_root))
  30. from ocr_utils import (
  31. get_input_files,
  32. collect_pid_files,
  33. PDFUtils,
  34. setup_logging
  35. )
  36. # 导入处理器
  37. try:
  38. from .processor import MinerUVLLMProcessor
  39. except ImportError:
  40. from processor import MinerUVLLMProcessor
  41. def process_images_single_process(
  42. image_paths: List[str],
  43. processor: MinerUVLLMProcessor,
  44. batch_size: int = 1,
  45. output_dir: str = "./output"
  46. ) -> List[Dict[str, Any]]:
  47. """
  48. 单进程版本的图像处理函数
  49. Args:
  50. image_paths: 图像文件路径列表
  51. processor: MinerU vLLM 处理器
  52. batch_size: 批次大小
  53. output_dir: 输出目录
  54. Returns:
  55. 处理结果列表
  56. """
  57. # 创建输出目录
  58. output_path = Path(output_dir)
  59. output_path.mkdir(parents=True, exist_ok=True)
  60. all_results = []
  61. total_images = len(image_paths)
  62. logger.info(f"Processing {total_images} images with batch size {batch_size}")
  63. with tqdm(total=total_images, desc="Processing images", unit="img",
  64. bar_format='{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]') as pbar:
  65. for i in range(0, total_images, batch_size):
  66. batch = image_paths[i:i + batch_size]
  67. batch_start_time = time.time()
  68. batch_results = []
  69. try:
  70. for image_path in batch:
  71. try:
  72. result = processor.process_single_image(image_path, output_dir)
  73. batch_results.append(result)
  74. except Exception as e:
  75. logger.error(f"Error processing {image_path}: {e}")
  76. batch_results.append({
  77. "image_path": image_path,
  78. "processing_time": 0,
  79. "success": False,
  80. "server": processor.server_url,
  81. "error": str(e)
  82. })
  83. batch_processing_time = time.time() - batch_start_time
  84. all_results.extend(batch_results)
  85. # 更新进度条
  86. success_count = sum(1 for r in batch_results if r.get('success', False))
  87. skipped_count = sum(1 for r in batch_results if r.get('skipped', False))
  88. total_success = sum(1 for r in all_results if r.get('success', False))
  89. total_skipped = sum(1 for r in all_results if r.get('skipped', False))
  90. avg_time = batch_processing_time / len(batch) if len(batch) > 0 else 0
  91. total_blocks = sum(r.get('extraction_stats', {}).get('total_blocks', 0) for r in batch_results)
  92. pbar.update(len(batch))
  93. pbar.set_postfix({
  94. 'batch_time': f"{batch_processing_time:.2f}s",
  95. 'avg_time': f"{avg_time:.2f}s/img",
  96. 'success': f"{total_success}/{len(all_results)}",
  97. 'skipped': f"{total_skipped}",
  98. 'blocks': f"{total_blocks}",
  99. 'rate': f"{total_success/len(all_results)*100:.1f}%" if len(all_results) > 0 else "0%"
  100. })
  101. except Exception as e:
  102. logger.error(f"Error processing batch {[Path(p).name for p in batch]}: {e}")
  103. error_results = []
  104. for img_path in batch:
  105. error_results.append({
  106. "image_path": str(img_path),
  107. "processing_time": 0,
  108. "success": False,
  109. "server": processor.server_url,
  110. "error": str(e)
  111. })
  112. all_results.extend(error_results)
  113. pbar.update(len(batch))
  114. return all_results
  115. def main():
  116. """主函数"""
  117. parser = argparse.ArgumentParser(
  118. description="MinerU vLLM Batch Processing (demo.py framework)",
  119. formatter_class=argparse.RawDescriptionHelpFormatter,
  120. epilog="""
  121. 示例:
  122. # 处理单个PDF文件
  123. python main.py --input document.pdf --output_dir ./output
  124. # 处理图片目录
  125. python main.py --input ./images/ --output_dir ./output
  126. # 处理文件列表
  127. python main.py --input file_list.txt --output_dir ./output
  128. # 处理CSV文件(失败的文件)
  129. python main.py --input results.csv --output_dir ./output
  130. # 指定页面范围(仅PDF)
  131. python main.py --input document.pdf --output_dir ./output --pages "1-5,7"
  132. # 启用调试模式
  133. python main.py --input document.pdf --output_dir ./output --debug
  134. # 仅验证配置(dry run)
  135. python main.py --input document.pdf --output_dir ./output --dry_run
  136. """
  137. )
  138. # 输入参数(统一使用 --input)
  139. parser.add_argument(
  140. "--input", "-i",
  141. required=True,
  142. type=str,
  143. help="输入路径(支持PDF文件、图片文件、图片目录、文件列表.txt、CSV文件)"
  144. )
  145. # 输出参数
  146. parser.add_argument(
  147. "--output_dir", "-o",
  148. type=str,
  149. required=True,
  150. help="输出目录"
  151. )
  152. # MinerU vLLM 参数
  153. parser.add_argument(
  154. "--server_url",
  155. type=str,
  156. default="http://127.0.0.1:20006",
  157. help="MinerU vLLM server URL"
  158. )
  159. parser.add_argument(
  160. "--timeout",
  161. type=int,
  162. default=300,
  163. help="Request timeout in seconds"
  164. )
  165. parser.add_argument(
  166. "--pdf_dpi",
  167. type=int,
  168. default=200,
  169. help="DPI for PDF to image conversion"
  170. )
  171. parser.add_argument(
  172. '--no-normalize',
  173. action='store_true',
  174. help='禁用数字标准化'
  175. )
  176. parser.add_argument(
  177. '--debug',
  178. action='store_true',
  179. help='启用调试模式'
  180. )
  181. # 处理参数
  182. parser.add_argument(
  183. "--batch_size",
  184. type=int,
  185. default=1,
  186. help="Batch size"
  187. )
  188. parser.add_argument(
  189. "--pages", "-p",
  190. type=str,
  191. help="页面范围(PDF和图片目录有效),如: '1-5,7,9-12', '1-', '-10'"
  192. )
  193. parser.add_argument(
  194. "--collect_results",
  195. type=str,
  196. help="收集处理结果到指定CSV文件"
  197. )
  198. # 日志参数
  199. parser.add_argument(
  200. "--log_level",
  201. default="INFO",
  202. choices=["DEBUG", "INFO", "WARNING", "ERROR"],
  203. help="日志级别(默认: INFO)"
  204. )
  205. parser.add_argument(
  206. "--log_file",
  207. type=str,
  208. help="日志文件路径"
  209. )
  210. # Dry run 参数
  211. parser.add_argument(
  212. "--dry_run",
  213. action="store_true",
  214. help="仅验证配置和输入,不执行实际处理"
  215. )
  216. args = parser.parse_args()
  217. # 设置日志
  218. setup_logging(args.log_level, args.log_file)
  219. try:
  220. # 创建参数对象(用于 get_input_files)
  221. class Args:
  222. def __init__(self, input_path, output_dir, pdf_dpi):
  223. self.input = input_path
  224. self.output_dir = output_dir
  225. self.pdf_dpi = pdf_dpi
  226. args_obj = Args(args.input, args.output_dir, args.pdf_dpi)
  227. # 获取并预处理输入文件(页面范围过滤已在 get_input_files 中处理)
  228. logger.info("🔄 Preprocessing input files...")
  229. if args.pages:
  230. logger.info(f"📄 页面范围: {args.pages}")
  231. image_files = get_input_files(args_obj, page_range=args.pages)
  232. if not image_files:
  233. logger.error("❌ No input files found or processed")
  234. return 1
  235. output_dir = Path(args.output_dir).resolve()
  236. logger.info(f"📁 Output dir: {output_dir}")
  237. logger.info(f"📊 Found {len(image_files)} image files to process")
  238. # Dry run 模式
  239. if args.dry_run:
  240. logger.info("🔍 Dry run mode: 仅验证配置,不执行处理")
  241. logger.info(f"📋 配置信息:")
  242. logger.info(f" - 输入: {args.input}")
  243. logger.info(f" - 输出目录: {output_dir}")
  244. logger.info(f" - 服务器: {args.server_url}")
  245. logger.info(f" - 超时: {args.timeout}s")
  246. logger.info(f" - 批次大小: {args.batch_size}")
  247. logger.info(f" - PDF DPI: {args.pdf_dpi}")
  248. logger.info(f" - 数字标准化: {not args.no_normalize}")
  249. logger.info(f" - 调试模式: {args.debug}")
  250. if args.pages:
  251. logger.info(f" - 页面范围: {args.pages}")
  252. logger.info(f"📋 将要处理的文件 ({len(image_files)} 个):")
  253. for i, img_file in enumerate(image_files[:20], 1): # 只显示前20个
  254. logger.info(f" {i}. {img_file}")
  255. if len(image_files) > 20:
  256. logger.info(f" ... 还有 {len(image_files) - 20} 个文件")
  257. logger.info("✅ Dry run 完成:配置验证通过")
  258. return 0
  259. logger.info(f"🌐 Using server: {args.server_url}")
  260. logger.info(f"📦 Batch size: {args.batch_size}")
  261. logger.info(f"⏱️ Timeout: {args.timeout}s")
  262. # 创建处理器
  263. processor = MinerUVLLMProcessor(
  264. server_url=args.server_url,
  265. timeout=args.timeout,
  266. normalize_numbers=not args.no_normalize,
  267. debug=args.debug
  268. )
  269. # 开始处理
  270. start_time = time.time()
  271. results = process_images_single_process(
  272. image_files,
  273. processor,
  274. args.batch_size,
  275. str(output_dir)
  276. )
  277. total_time = time.time() - start_time
  278. # 统计结果
  279. success_count = sum(1 for r in results if r.get('success', False))
  280. skipped_count = sum(1 for r in results if r.get('skipped', False))
  281. error_count = len(results) - success_count
  282. pdf_page_count = sum(1 for r in results if r.get('is_pdf_page', False))
  283. # 统计提取的块信息
  284. total_blocks = sum(r.get('extraction_stats', {}).get('total_blocks', 0) for r in results)
  285. block_type_stats = {}
  286. for result in results:
  287. if 'extraction_stats' in result and 'block_types' in result['extraction_stats']:
  288. for block_type, count in result['extraction_stats']['block_types'].items():
  289. block_type_stats[block_type] = block_type_stats.get(block_type, 0) + count
  290. print(f"\n" + "="*60)
  291. print(f"✅ Processing completed!")
  292. print(f"📊 Statistics:")
  293. print(f" Total files processed: {len(image_files)}")
  294. print(f" PDF pages processed: {pdf_page_count}")
  295. print(f" Regular images processed: {len(image_files) - pdf_page_count}")
  296. print(f" Successful: {success_count}")
  297. print(f" Skipped: {skipped_count}")
  298. print(f" Failed: {error_count}")
  299. if len(image_files) > 0:
  300. print(f" Success rate: {success_count / len(image_files) * 100:.2f}%")
  301. print(f"📋 Content Extraction:")
  302. print(f" Total blocks extracted: {total_blocks}")
  303. if block_type_stats:
  304. print(f" Block types:")
  305. for block_type, count in sorted(block_type_stats.items()):
  306. print(f" {block_type}: {count}")
  307. print(f"⏱️ Performance:")
  308. print(f" Total time: {total_time:.2f} seconds")
  309. if total_time > 0:
  310. print(f" Throughput: {len(image_files) / total_time:.2f} images/second")
  311. print(f" Avg time per image: {total_time / len(image_files):.2f} seconds")
  312. print(f"\n📁 Output Structure (demo.py compatible):")
  313. print(f" output_dir/")
  314. print(f" ├── filename.md # Markdown content")
  315. print(f" ├── filename.json # Content list")
  316. print(f" ├── filename_layout.pdf # Debug: layout bbox")
  317. print(f" └── images/ # Extracted images")
  318. print(f" └── filename.png")
  319. if args.debug:
  320. print(f" ├── filename_middle.json # Debug: middle JSON")
  321. print(f" └── filename_model.json # Debug: model output")
  322. # 保存结果统计
  323. stats = {
  324. "total_files": len(image_files),
  325. "pdf_pages": pdf_page_count,
  326. "regular_images": len(image_files) - pdf_page_count,
  327. "success_count": success_count,
  328. "skipped_count": skipped_count,
  329. "error_count": error_count,
  330. "success_rate": success_count / len(image_files) if len(image_files) > 0 else 0,
  331. "total_time": total_time,
  332. "throughput": len(image_files) / total_time if total_time > 0 else 0,
  333. "avg_time_per_image": total_time / len(image_files) if len(image_files) > 0 else 0,
  334. "batch_size": args.batch_size,
  335. "server": args.server_url,
  336. "backend": "vlm-http-client",
  337. "timeout": args.timeout,
  338. "pdf_dpi": args.pdf_dpi,
  339. "total_blocks": total_blocks,
  340. "block_type_stats": block_type_stats,
  341. "normalization_enabled": not args.no_normalize,
  342. "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
  343. }
  344. # 保存最终结果
  345. output_file_name = Path(output_dir).name
  346. output_file = output_dir / f"{output_file_name}_results.json"
  347. final_results = {
  348. "stats": stats,
  349. "results": results
  350. }
  351. with open(output_file, 'w', encoding='utf-8') as f:
  352. json.dump(final_results, f, ensure_ascii=False, indent=2)
  353. logger.info(f"💾 Results saved to: {output_file}")
  354. # 收集处理结果
  355. if not args.collect_results:
  356. output_file_processed = output_dir / f"processed_files_{time.strftime('%Y%m%d_%H%M%S')}.csv"
  357. else:
  358. output_file_processed = Path(args.collect_results).resolve()
  359. processed_files = collect_pid_files(str(output_file))
  360. with open(output_file_processed, 'w', encoding='utf-8') as f:
  361. f.write("image_path,status\n")
  362. for file_path, status in processed_files:
  363. f.write(f"{file_path},{status}\n")
  364. logger.info(f"💾 Processed files saved to: {output_file_processed}")
  365. return 0
  366. except Exception as e:
  367. logger.error(f"Processing failed: {e}")
  368. traceback.print_exc()
  369. return 1
  370. if __name__ == "__main__":
  371. logger.info(f"🚀 启动MinerU vLLM统一PDF/图像处理程序...")
  372. logger.info(f"🔧 CUDA_VISIBLE_DEVICES: {os.environ.get('CUDA_VISIBLE_DEVICES', 'Not set')}")
  373. if len(sys.argv) == 1:
  374. # 如果没有命令行参数,使用默认配置运行
  375. logger.info("ℹ️ No command line arguments provided. Running with default configuration...")
  376. # 默认配置
  377. default_config = {
  378. "input": "/Users/zhch158/workspace/data/流水分析/马公账流水_工商银行.pdf",
  379. "output_dir": "./output",
  380. "server_url": "http://10.192.72.11:20006",
  381. "timeout": "300",
  382. "batch_size": "1",
  383. "pdf_dpi": "200",
  384. "pages": "-1",
  385. }
  386. # 构造参数
  387. sys.argv = [sys.argv[0]]
  388. for key, value in default_config.items():
  389. sys.argv.extend([f"--{key}", str(value)])
  390. # 调试模式
  391. sys.argv.append("--debug")
  392. sys.exit(main())