batch_process_pdf.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  1. #!/usr/bin/env python3
  2. """
  3. PDF 批量处理脚本
  4. 支持多种处理器,配置文件驱动
  5. 支持自动切换虚拟环境
  6. """
  7. import os
  8. import sys
  9. import argparse
  10. import subprocess
  11. import json
  12. import yaml
  13. from pathlib import Path
  14. from datetime import datetime
  15. from typing import List, Dict, Optional, Any
  16. from dataclasses import dataclass, field
  17. import logging
  18. from tqdm import tqdm
  19. import time
  20. # ============================================================================
  21. # 数据类定义
  22. # ============================================================================
  23. @dataclass
  24. class ProcessorConfig:
  25. """处理器配置"""
  26. name: str
  27. script: str
  28. input_arg: str = "--input_file"
  29. output_arg: str = "--output_dir"
  30. extra_args: List[str] = field(default_factory=list)
  31. output_subdir: str = "results"
  32. venv: Optional[str] = None # 虚拟环境激活命令
  33. description: str = ""
  34. @dataclass
  35. class ProcessResult:
  36. """处理结果"""
  37. pdf_file: str
  38. success: bool
  39. duration: float
  40. error_message: str = ""
  41. # ============================================================================
  42. # 配置管理
  43. # ============================================================================
  44. class ConfigManager:
  45. """配置管理器"""
  46. DEFAULT_CONFIG = {
  47. 'processors': {
  48. 'paddleocr_vl_single_process': {
  49. 'script': '/Users/zhch158/workspace/repository.git/PaddleX/zhch/paddleocr_vl_single_process.py',
  50. 'input_arg': '--input_file',
  51. 'output_arg': '--output_dir',
  52. 'extra_args': [
  53. '--pipeline=/Users/zhch158/workspace/repository.git/PaddleX/zhch/my_config/PaddleOCR-VL-Client-RT-DETR-H_layout_17cls.yaml',
  54. '--no-adapter'
  55. ],
  56. 'output_subdir': 'paddleocr_vl_results',
  57. 'venv': 'source /Users/zhch158/workspace/repository.git/PaddleX/paddle_env/bin/activate',
  58. 'description': 'PaddleOCR-VL 处理器'
  59. },
  60. 'ppstructurev3_single_process': {
  61. 'script': '/Users/zhch158/workspace/repository.git/PaddleX/zhch/ppstructurev3_single_process.py',
  62. 'input_arg': '--input_file',
  63. 'output_arg': '--output_dir',
  64. 'extra_args': [
  65. '--pipeline=/Users/zhch158/workspace/repository.git/PaddleX/zhch/my_config/PP-StructureV3.yaml'
  66. ],
  67. 'output_subdir': 'ppstructurev3_results',
  68. 'venv': 'conda activate paddle',
  69. 'description': 'PP-StructureV3 处理器'
  70. },
  71. 'ppstructurev3_single_client': {
  72. 'script': '/Users/zhch158/workspace/repository.git/PaddleX/zhch/ppstructurev3_single_client.py',
  73. 'input_arg': '--input_file',
  74. 'output_arg': '--output_dir',
  75. 'extra_args': [
  76. '--api_url=http://10.192.72.11:8111/layout-parsing',
  77. '--timeout=300'
  78. ],
  79. 'output_subdir': 'ppstructurev3_client_results',
  80. 'venv': 'source /Users/zhch158/workspace/repository.git/PaddleX/paddle_env/bin/activate',
  81. 'description': 'PP-StructureV3 HTTP API 客户端'
  82. },
  83. 'mineru_vllm': {
  84. 'script': '/Users/zhch158/workspace/repository.git/MinerU/zhch/mineru2_vllm_multthreads.py',
  85. 'input_arg': '--input_file',
  86. 'output_arg': '--output_dir',
  87. 'extra_args': [
  88. '--server_url=http://10.192.72.11:8121',
  89. '--timeout=300',
  90. '--batch_size=1'
  91. ],
  92. 'output_subdir': 'mineru_vllm_results',
  93. 'venv': 'conda activate mineru2',
  94. 'description': 'MinerU vLLM 处理器'
  95. },
  96. 'dotsocr_vllm': {
  97. 'script': '/Users/zhch158/workspace/repository.git/dots.ocr/zhch/dotsocr_vllm_multthreads.py',
  98. 'input_arg': '--input_file',
  99. 'output_arg': '--output_dir',
  100. 'extra_args': [
  101. '--ip=10.192.72.11',
  102. '--port=8101',
  103. '--model_name=DotsOCR',
  104. '--prompt_mode=prompt_layout_all_en',
  105. '--batch_size=1',
  106. '--max_workers=1',
  107. '--dpi=200'
  108. ],
  109. 'output_subdir': 'dotsocr_vllm_results',
  110. 'venv': 'conda activate py312',
  111. 'description': 'DotsOCR vLLM 处理器 - 支持PDF和图片'
  112. }
  113. },
  114. 'global': {
  115. 'base_dir': '/Users/zhch158/workspace/data/流水分析',
  116. 'output_subdir': 'results'
  117. }
  118. }
  119. def __init__(self, config_file: Optional[str] = None):
  120. self.config_file = config_file
  121. self.config = self._load_config()
  122. def _load_config(self) -> Dict:
  123. """加载配置文件"""
  124. if self.config_file and Path(self.config_file).exists():
  125. with open(self.config_file, 'r', encoding='utf-8') as f:
  126. if self.config_file.endswith('.yaml') or self.config_file.endswith('.yml'):
  127. return yaml.safe_load(f)
  128. else:
  129. return json.load(f)
  130. return self.DEFAULT_CONFIG.copy()
  131. def get_processor_config(self, processor_name: str) -> ProcessorConfig:
  132. """获取处理器配置"""
  133. if processor_name not in self.config['processors']:
  134. raise ValueError(f"处理器 '{processor_name}' 不存在")
  135. proc_config = self.config['processors'][processor_name]
  136. return ProcessorConfig(
  137. name=processor_name,
  138. script=proc_config['script'],
  139. input_arg=proc_config.get('input_arg', '--input_file'),
  140. output_arg=proc_config.get('output_arg', '--output_dir'),
  141. extra_args=proc_config.get('extra_args', []),
  142. output_subdir=proc_config.get('output_subdir', processor_name + '_results'),
  143. venv=proc_config.get('venv'),
  144. description=proc_config.get('description', '')
  145. )
  146. def get_global_config(self, key: str, default=None):
  147. """获取全局配置"""
  148. return self.config.get('global', {}).get(key, default)
  149. def list_processors(self) -> List[str]:
  150. """列出所有可用的处理器"""
  151. return list(self.config['processors'].keys())
  152. # ============================================================================
  153. # PDF 文件查找器
  154. # ============================================================================
  155. class PDFFileFinder:
  156. """PDF 文件查找器"""
  157. def __init__(self, base_dir: str):
  158. self.base_dir = Path(base_dir)
  159. def from_file_list(self, list_file: str) -> List[Path]:
  160. """从文件列表读取"""
  161. pdf_files = []
  162. with open(list_file, 'r', encoding='utf-8') as f:
  163. for line in f:
  164. # 跳过空行和注释
  165. line = line.strip()
  166. if not line or line.startswith('#'):
  167. continue
  168. # 构建完整路径
  169. pdf_path = self._resolve_path(line)
  170. if pdf_path:
  171. pdf_files.append(pdf_path)
  172. return pdf_files
  173. def from_list(self, pdf_list: List[str]) -> List[Path]:
  174. """从列表读取"""
  175. pdf_files = []
  176. for pdf in pdf_list:
  177. pdf_path = self._resolve_path(pdf.strip())
  178. if pdf_path:
  179. pdf_files.append(pdf_path)
  180. return pdf_files
  181. def find_all(self) -> List[Path]:
  182. """查找基础目录下所有 PDF"""
  183. return sorted(self.base_dir.rglob('*.pdf'))
  184. def _resolve_path(self, path_str: str) -> Optional[Path]:
  185. """解析路径"""
  186. path = Path(path_str)
  187. # 绝对路径
  188. if path.is_absolute():
  189. return path if path.exists() else path # 返回路径,即使不存在
  190. # 相对路径
  191. # 1. 尝试完整相对路径
  192. candidate1 = self.base_dir / path
  193. if candidate1.exists():
  194. return candidate1
  195. # 2. 尝试在同名子目录下查找
  196. if '/' not in path_str:
  197. pdf_name = path.stem
  198. candidate2 = self.base_dir / pdf_name / path.name
  199. if candidate2.exists():
  200. return candidate2
  201. # 3. 使用 glob 搜索
  202. matches = list(self.base_dir.rglob(path.name))
  203. if matches:
  204. return matches[0]
  205. # 返回候选路径(即使不存在)
  206. return candidate1
  207. # ============================================================================
  208. # PDF 批处理器
  209. # ============================================================================
  210. class PDFBatchProcessor:
  211. """PDF 批处理器"""
  212. def __init__(
  213. self,
  214. processor_config: ProcessorConfig,
  215. output_subdir: Optional[str] = None,
  216. dry_run: bool = False
  217. ):
  218. self.processor_config = processor_config
  219. # 如果指定了output_subdir,使用指定的;否则使用处理器配置中的
  220. self.output_subdir = output_subdir or processor_config.output_subdir
  221. self.dry_run = dry_run
  222. # 设置日志
  223. self.logger = self._setup_logger()
  224. # 统计信息
  225. self.results: List[ProcessResult] = []
  226. def _setup_logger(self) -> logging.Logger:
  227. """设置日志"""
  228. logger = logging.getLogger('PDFBatchProcessor')
  229. logger.setLevel(logging.INFO)
  230. # 避免重复添加handler
  231. if not logger.handlers:
  232. # 控制台输出
  233. console_handler = logging.StreamHandler()
  234. console_handler.setLevel(logging.INFO)
  235. console_format = logging.Formatter(
  236. '%(asctime)s - %(levelname)s - %(message)s',
  237. datefmt='%Y-%m-%d %H:%M:%S'
  238. )
  239. console_handler.setFormatter(console_format)
  240. logger.addHandler(console_handler)
  241. return logger
  242. def process_files(self, pdf_files: List[Path]) -> Dict[str, Any]:
  243. """批量处理文件"""
  244. self.logger.info(f"开始处理 {len(pdf_files)} 个文件")
  245. self.logger.info(f"处理器: {self.processor_config.description}")
  246. self.logger.info(f"脚本: {self.processor_config.script}")
  247. self.logger.info(f"输出目录: {self.output_subdir}")
  248. if self.processor_config.venv:
  249. self.logger.info(f"虚拟环境: {self.processor_config.venv}")
  250. start_time = time.time()
  251. # 使用进度条
  252. with tqdm(total=len(pdf_files), desc="处理进度", unit="file") as pbar:
  253. for pdf_file in pdf_files:
  254. result = self._process_single_file(pdf_file)
  255. self.results.append(result)
  256. pbar.update(1)
  257. # 更新进度条描述
  258. success_count = sum(1 for r in self.results if r.success)
  259. pbar.set_postfix({
  260. 'success': success_count,
  261. 'failed': len(self.results) - success_count
  262. })
  263. total_duration = time.time() - start_time
  264. # 生成统计信息
  265. stats = self._generate_stats(total_duration)
  266. # 保存日志
  267. self._save_log(stats)
  268. return stats
  269. def _process_single_file(self, pdf_file: Path) -> ProcessResult:
  270. """处理单个文件"""
  271. self.logger.info(f"处理: {pdf_file}")
  272. # 检查文件是否存在
  273. if not pdf_file.exists():
  274. self.logger.warning(f"跳过: 文件不存在 - {pdf_file}")
  275. return ProcessResult(
  276. pdf_file=str(pdf_file),
  277. success=False,
  278. duration=0,
  279. error_message="文件不存在"
  280. )
  281. # 确定输出目录
  282. output_dir = pdf_file.parent / pdf_file.stem / self.output_subdir
  283. # 构建命令
  284. cmd = self._build_command(pdf_file, output_dir)
  285. self.logger.debug(f"执行命令: {cmd if isinstance(cmd, str) else ' '.join(cmd)}")
  286. if self.dry_run:
  287. self.logger.info(f"[DRY RUN] 将执行: {cmd if isinstance(cmd, str) else ' '.join(cmd)}")
  288. return ProcessResult(
  289. pdf_file=str(pdf_file),
  290. success=True,
  291. duration=0,
  292. error_message=""
  293. )
  294. # 执行命令
  295. start_time = time.time()
  296. try:
  297. # 如果是 shell 命令(包含 venv),使用 shell=True
  298. if isinstance(cmd, str):
  299. result = subprocess.run(
  300. cmd,
  301. shell=True,
  302. executable='/bin/bash', # 使用 bash
  303. capture_output=True,
  304. text=True,
  305. check=True
  306. )
  307. else:
  308. result = subprocess.run(
  309. cmd,
  310. capture_output=True,
  311. text=True,
  312. check=True
  313. )
  314. duration = time.time() - start_time
  315. self.logger.info(f"✓ 成功 (耗时: {duration:.2f}秒)")
  316. return ProcessResult(
  317. pdf_file=str(pdf_file),
  318. success=True,
  319. duration=duration,
  320. error_message=""
  321. )
  322. except subprocess.CalledProcessError as e:
  323. duration = time.time() - start_time
  324. error_msg = e.stderr if e.stderr else str(e)
  325. self.logger.error(f"✗ 失败 (耗时: {duration:.2f}秒)")
  326. self.logger.error(f"错误信息: {error_msg}")
  327. return ProcessResult(
  328. pdf_file=str(pdf_file),
  329. success=False,
  330. duration=duration,
  331. error_message=error_msg
  332. )
  333. def _build_command(self, pdf_file: Path, output_dir: Path):
  334. """构建执行命令
  335. Returns:
  336. 如果配置了 venv,返回 shell 命令字符串
  337. 否则返回命令列表
  338. """
  339. # 构建基础 Python 命令
  340. base_cmd = [
  341. 'python', # 使用虚拟环境中的 python
  342. self.processor_config.script,
  343. self.processor_config.input_arg, str(pdf_file),
  344. self.processor_config.output_arg, str(output_dir)
  345. ]
  346. # 添加额外参数
  347. base_cmd.extend(self.processor_config.extra_args)
  348. # 如果配置了虚拟环境,构建 shell 命令
  349. if self.processor_config.venv:
  350. # 转义参数中的特殊字符
  351. escaped_cmd = []
  352. for arg in base_cmd:
  353. if ' ' in arg or '"' in arg or "'" in arg:
  354. # 使用单引号包裹,内部单引号转义
  355. arg = arg.replace("'", "'\\''")
  356. escaped_cmd.append(f"'{arg}'")
  357. else:
  358. escaped_cmd.append(arg)
  359. python_cmd = ' '.join(escaped_cmd)
  360. # 检查是否使用 conda
  361. if 'conda activate' in self.processor_config.venv:
  362. # 获取 conda 基础路径
  363. # 对于 conda,需要先 source conda.sh,然后 conda activate
  364. conda_init = """
  365. eval "$(conda shell.bash hook)"
  366. """.strip()
  367. shell_cmd = f"{conda_init} && {self.processor_config.venv} && {python_cmd}"
  368. else:
  369. # 对于 source 激活的虚拟环境
  370. shell_cmd = f"{self.processor_config.venv} && {python_cmd}"
  371. return shell_cmd
  372. else:
  373. # 没有虚拟环境,使用当前 Python 解释器
  374. base_cmd[0] = sys.executable
  375. return base_cmd
  376. def _generate_stats(self, total_duration: float) -> Dict[str, Any]:
  377. """生成统计信息"""
  378. success_count = sum(1 for r in self.results if r.success)
  379. failed_count = len(self.results) - success_count
  380. failed_files = [r.pdf_file for r in self.results if not r.success]
  381. stats = {
  382. 'total': len(self.results),
  383. 'success': success_count,
  384. 'failed': failed_count,
  385. 'total_duration': total_duration,
  386. 'failed_files': failed_files,
  387. 'results': [
  388. {
  389. 'file': r.pdf_file,
  390. 'success': r.success,
  391. 'duration': r.duration,
  392. 'error': r.error_message
  393. }
  394. for r in self.results
  395. ]
  396. }
  397. return stats
  398. def _save_log(self, stats: Dict[str, Any]):
  399. """保存日志"""
  400. timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
  401. log_file = f"batch_process_{self.processor_config.name}_{timestamp}.log"
  402. with open(log_file, 'w', encoding='utf-8') as f:
  403. f.write("PDF 批量处理日志\n")
  404. f.write("=" * 80 + "\n\n")
  405. f.write(f"处理器: {self.processor_config.description}\n")
  406. f.write(f"处理器名称: {self.processor_config.name}\n")
  407. f.write(f"脚本: {self.processor_config.script}\n")
  408. f.write(f"输出目录: {self.output_subdir}\n")
  409. if self.processor_config.venv:
  410. f.write(f"虚拟环境: {self.processor_config.venv}\n")
  411. f.write(f"开始时间: {datetime.now()}\n")
  412. f.write(f"总耗时: {stats['total_duration']:.2f} 秒\n\n")
  413. f.write("统计信息:\n")
  414. f.write(f" 总文件数: {stats['total']}\n")
  415. f.write(f" 成功: {stats['success']}\n")
  416. f.write(f" 失败: {stats['failed']}\n\n")
  417. if stats['failed_files']:
  418. f.write("失败的文件:\n")
  419. for file in stats['failed_files']:
  420. f.write(f" - {file}\n")
  421. f.write("\n")
  422. f.write("详细结果:\n")
  423. for result in stats['results']:
  424. status = "✓" if result['success'] else "✗"
  425. f.write(f"{status} {result['file']} ({result['duration']:.2f}s)\n")
  426. if result['error']:
  427. f.write(f" 错误: {result['error']}\n")
  428. self.logger.info(f"日志已保存: {log_file}")
  429. # ============================================================================
  430. # 命令行接口
  431. # ============================================================================
  432. def create_parser() -> argparse.ArgumentParser:
  433. """创建命令行参数解析器"""
  434. parser = argparse.ArgumentParser(
  435. description='PDF 批量处理工具 (支持虚拟环境自动切换)',
  436. formatter_class=argparse.RawDescriptionHelpFormatter,
  437. epilog="""
  438. 示例用法:
  439. 1. 使用配置文件中的处理器 (自动切换虚拟环境):
  440. python batch_process_pdf.py -p paddleocr_vl_single_process -f pdf_list.txt
  441. 2. 使用 DotsOCR 处理器 (自动切换到 py312 环境):
  442. python batch_process_pdf.py -p dotsocr_vllm -f pdf_list.txt
  443. 3. 使用 MinerU 处理器 (自动切换到 mineru2 环境):
  444. python batch_process_pdf.py -p mineru_vllm -f pdf_list.txt
  445. 4. 处理指定目录下所有 PDF:
  446. python batch_process_pdf.py -p ppstructurev3_single_client -d /path/to/pdfs
  447. 5. 列出所有可用的处理器:
  448. python batch_process_pdf.py --list-processors
  449. 6. 手动指定虚拟环境:
  450. python batch_process_pdf.py -p paddleocr_vl_single_process -f pdf_list.txt --venv "conda activate paddle"
  451. """
  452. )
  453. # 处理器选择
  454. parser.add_argument(
  455. '-p', '--processor',
  456. help='处理器名称'
  457. )
  458. # 配置文件
  459. parser.add_argument(
  460. '-c', '--config',
  461. default='processor_configs.yaml',
  462. help='配置文件路径 (默认: processor_configs.yaml)'
  463. )
  464. # 手动指定脚本
  465. parser.add_argument(
  466. '-s', '--script',
  467. help='Python 脚本路径 (覆盖配置文件)'
  468. )
  469. # 目录和文件
  470. parser.add_argument(
  471. '-d', '--base-dir',
  472. help='PDF 文件基础目录'
  473. )
  474. parser.add_argument(
  475. '-o', '--output-subdir',
  476. help='输出子目录名称 (覆盖处理器默认配置)'
  477. )
  478. parser.add_argument(
  479. '-f', '--file-list',
  480. help='PDF 文件列表文件路径'
  481. )
  482. parser.add_argument(
  483. '-l', '--pdf-list',
  484. nargs='+',
  485. help='PDF 文件列表 (空格分隔)'
  486. )
  487. # 额外参数
  488. parser.add_argument(
  489. '-e', '--extra-args',
  490. help='额外参数 (覆盖配置文件)'
  491. )
  492. # 虚拟环境
  493. parser.add_argument(
  494. '--venv',
  495. help='虚拟环境激活命令 (覆盖配置文件)'
  496. )
  497. # 工具选项
  498. parser.add_argument(
  499. '--list-processors',
  500. action='store_true',
  501. help='列出所有可用的处理器'
  502. )
  503. parser.add_argument(
  504. '--show-config',
  505. action='store_true',
  506. help='显示配置文件内容'
  507. )
  508. parser.add_argument(
  509. '--dry-run',
  510. action='store_true',
  511. help='模拟运行,不实际执行'
  512. )
  513. parser.add_argument(
  514. '-v', '--verbose',
  515. action='store_true',
  516. help='详细输出'
  517. )
  518. return parser
  519. def main():
  520. """主函数"""
  521. parser = create_parser()
  522. args = parser.parse_args()
  523. # 设置日志级别
  524. if args.verbose:
  525. logging.getLogger().setLevel(logging.DEBUG)
  526. # 加载配置
  527. config_manager = ConfigManager(args.config if Path(args.config).exists() else None)
  528. # 列出处理器
  529. if args.list_processors:
  530. print("可用的处理器:")
  531. for name in config_manager.list_processors():
  532. proc_config = config_manager.get_processor_config(name)
  533. print(f" • {name}")
  534. print(f" 描述: {proc_config.description}")
  535. print(f" 脚本: {proc_config.script}")
  536. print(f" 输出目录: {proc_config.output_subdir}")
  537. if proc_config.venv:
  538. print(f" 虚拟环境: {proc_config.venv}")
  539. print()
  540. return 0
  541. # 显示配置
  542. if args.show_config:
  543. print(yaml.dump(config_manager.config, allow_unicode=True))
  544. return 0
  545. # 获取处理器配置
  546. if args.processor:
  547. processor_config = config_manager.get_processor_config(args.processor)
  548. elif args.script:
  549. # 手动指定脚本
  550. processor_config = ProcessorConfig(
  551. name='manual',
  552. script=args.script,
  553. extra_args=args.extra_args.split() if args.extra_args else [],
  554. output_subdir=args.output_subdir or 'manual_results',
  555. venv=args.venv
  556. )
  557. else:
  558. parser.error("必须指定 -p 或 -s 参数")
  559. # 覆盖额外参数
  560. if args.extra_args and args.processor:
  561. processor_config.extra_args = args.extra_args.split()
  562. # 覆盖虚拟环境
  563. if args.venv:
  564. processor_config.venv = args.venv
  565. # 获取基础目录
  566. base_dir = args.base_dir or config_manager.get_global_config('base_dir')
  567. if not base_dir:
  568. parser.error("必须指定 -d 参数或在配置文件中设置 base_dir")
  569. # 查找 PDF 文件
  570. finder = PDFFileFinder(base_dir)
  571. if args.file_list:
  572. pdf_files = finder.from_file_list(args.file_list)
  573. elif args.pdf_list:
  574. pdf_files = finder.from_list(args.pdf_list)
  575. else:
  576. pdf_files = finder.find_all()
  577. if not pdf_files:
  578. print("❌ 未找到任何 PDF 文件")
  579. return 1
  580. # 显示找到的文件
  581. valid_file_paths = [f.as_posix() for f in pdf_files if f.exists()]
  582. if valid_file_paths:
  583. print("\n".join(valid_file_paths))
  584. # 验证文件
  585. valid_files = [f for f in pdf_files if f.exists()]
  586. invalid_files = [f for f in pdf_files if not f.exists()]
  587. if invalid_files:
  588. print(f"\n⚠️ 警告: {len(invalid_files)} 个文件不存在:")
  589. for f in invalid_files[:5]:
  590. print(f" - {f}")
  591. if len(invalid_files) > 5:
  592. print(f" ... 还有 {len(invalid_files) - 5} 个")
  593. # 确认执行
  594. if not args.dry_run and valid_files:
  595. venv_info = f" (虚拟环境: {processor_config.venv})" if processor_config.venv else ""
  596. confirm = input(f"\n是否继续处理 {len(valid_files)} 个文件{venv_info}? [Y/n]: ")
  597. if confirm.lower() not in ['', 'y', 'yes']:
  598. print("已取消")
  599. return 0
  600. # 批量处理
  601. processor = PDFBatchProcessor(
  602. processor_config=processor_config,
  603. output_subdir=args.output_subdir,
  604. dry_run=args.dry_run
  605. )
  606. stats = processor.process_files(valid_files)
  607. # 显示统计信息
  608. print("\n" + "=" * 80)
  609. print("处理完成")
  610. print("=" * 80)
  611. print(f"\n📊 统计信息:")
  612. print(f" 处理器: {processor_config.description}")
  613. print(f" 输出目录: {processor.output_subdir}")
  614. if stats.get('venv'):
  615. print(f" 虚拟环境: {stats['venv']}")
  616. print(f" 总文件数: {stats['total']}")
  617. print(f" ✓ 成功: {stats['success']}")
  618. print(f" ✗ 失败: {stats['failed']}")
  619. print(f" ⏱️ 总耗时: {stats['total_duration']:.2f} 秒")
  620. if stats['failed_files']:
  621. print(f"\n失败的文件:")
  622. for file in stats['failed_files']:
  623. print(f" ✗ {file}")
  624. return 0 if stats['failed'] == 0 else 1
  625. if __name__ == '__main__':
  626. sys.exit(main())