ppstructurev3_single_client.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. """PDF转图像后通过API统一处理"""
  2. import json
  3. import time
  4. import os
  5. import traceback
  6. import argparse
  7. import sys
  8. import warnings
  9. import base64
  10. from pathlib import Path
  11. from typing import List, Dict, Any, Union
  12. import requests
  13. from tqdm import tqdm
  14. from dotenv import load_dotenv
  15. load_dotenv(override=True)
  16. from utils import (
  17. get_image_files_from_dir,
  18. get_image_files_from_list,
  19. get_image_files_from_csv,
  20. collect_pid_files,
  21. load_images_from_pdf,
  22. normalize_financial_numbers,
  23. normalize_markdown_table
  24. )
  25. def convert_pdf_to_images(pdf_file: str, output_dir: str | None = None, dpi: int = 200) -> List[str]:
  26. """
  27. 将PDF转换为图像文件
  28. Args:
  29. pdf_file: PDF文件路径
  30. output_dir: 输出目录
  31. dpi: 图像分辨率
  32. Returns:
  33. 生成的图像文件路径列表
  34. """
  35. pdf_path = Path(pdf_file)
  36. if not pdf_path.exists() or pdf_path.suffix.lower() != '.pdf':
  37. print(f"❌ Invalid PDF file: {pdf_path}")
  38. return []
  39. # 如果没有指定输出目录,使用PDF同名目录
  40. if output_dir is None:
  41. output_path = pdf_path.parent / f"{pdf_path.stem}"
  42. else:
  43. output_path = Path(output_dir) / f"{pdf_path.stem}"
  44. output_path = output_path.resolve()
  45. output_path.mkdir(parents=True, exist_ok=True)
  46. try:
  47. # 使用doc_utils中的函数加载PDF图像
  48. images = load_images_from_pdf(str(pdf_path), dpi=dpi)
  49. image_paths = []
  50. for i, image in enumerate(images):
  51. # 生成图像文件名
  52. image_filename = f"{pdf_path.stem}_page_{i+1:03d}.png"
  53. image_path = output_path / image_filename
  54. # 保存图像
  55. image.save(str(image_path))
  56. image_paths.append(str(image_path))
  57. print(f"✅ Converted {len(images)} pages from {pdf_path.name} to images")
  58. return image_paths
  59. except Exception as e:
  60. print(f"❌ Error converting PDF {pdf_path}: {e}")
  61. traceback.print_exc()
  62. return []
  63. def get_input_files(args) -> List[str]:
  64. """
  65. 获取输入文件列表,统一处理PDF和图像文件
  66. Args:
  67. args: 命令行参数
  68. Returns:
  69. 处理后的图像文件路径列表
  70. """
  71. input_files = []
  72. # 获取原始输入文件
  73. if args.input_csv:
  74. raw_files = get_image_files_from_csv(args.input_csv, "fail")
  75. elif args.input_file_list:
  76. raw_files = get_image_files_from_list(args.input_file_list)
  77. elif args.input_file:
  78. raw_files = [Path(args.input_file).resolve()]
  79. else:
  80. input_dir = Path(args.input_dir).resolve()
  81. if not input_dir.exists():
  82. print(f"❌ Input directory does not exist: {input_dir}")
  83. return []
  84. # 获取所有支持的文件(图像和PDF)
  85. image_extensions = ['.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.tif']
  86. pdf_extensions = ['.pdf']
  87. raw_files = []
  88. for ext in image_extensions + pdf_extensions:
  89. raw_files.extend(list(input_dir.glob(f"*{ext}")))
  90. raw_files.extend(list(input_dir.glob(f"*{ext.upper()}")))
  91. raw_files = [str(f) for f in raw_files]
  92. # 分别处理PDF和图像文件
  93. pdf_count = 0
  94. image_count = 0
  95. for file_path in raw_files:
  96. file_path = Path(file_path)
  97. if file_path.suffix.lower() == '.pdf':
  98. # 转换PDF为图像
  99. print(f"📄 Processing PDF: {file_path.name}")
  100. pdf_images = convert_pdf_to_images(
  101. str(file_path),
  102. args.output_dir,
  103. dpi=args.pdf_dpi
  104. )
  105. input_files.extend(pdf_images)
  106. pdf_count += 1
  107. else:
  108. # 直接添加图像文件
  109. if file_path.exists():
  110. input_files.append(str(file_path))
  111. image_count += 1
  112. print(f"📊 Input summary:")
  113. print(f" PDF files processed: {pdf_count}")
  114. print(f" Image files found: {image_count}")
  115. print(f" Total image files to process: {len(input_files)}")
  116. return input_files
  117. def convert_api_result_to_json(api_result: Dict[str, Any],
  118. input_image_path: str,
  119. output_dir: str,
  120. filename: str,
  121. normalize_numbers: bool = True) -> tuple[str, Dict[str, Any]]:
  122. """
  123. 将API返回结果转换为标准JSON格式,并支持数字标准化
  124. """
  125. # 获取主要数据
  126. layout_parsing_results = api_result.get('layoutParsingResults', [])
  127. if not layout_parsing_results:
  128. print("⚠️ Warning: No layoutParsingResults found in API response")
  129. return {}
  130. # 取第一个结果(通常只有一个)
  131. main_result = layout_parsing_results[0]
  132. pruned_result = main_result.get('prunedResult', {})
  133. # 构造标准格式的JSON
  134. converted_json = {
  135. "input_path": input_image_path,
  136. "page_index": None,
  137. "model_settings": pruned_result.get('model_settings', {}),
  138. "parsing_res_list": pruned_result.get('parsing_res_list', []),
  139. "doc_preprocessor_res": {
  140. "input_path": None,
  141. "page_index": None,
  142. "model_settings": pruned_result.get('doc_preprocessor_res', {}).get('model_settings', {}),
  143. "angle": pruned_result.get('doc_preprocessor_res', {}).get('angle', 0)
  144. },
  145. "layout_det_res": {
  146. "input_path": None,
  147. "page_index": None,
  148. "boxes": pruned_result.get('layout_det_res', {}).get('boxes', [])
  149. },
  150. "overall_ocr_res": {
  151. "input_path": None,
  152. "page_index": None,
  153. "model_settings": pruned_result.get('overall_ocr_res', {}).get('model_settings', {}),
  154. "dt_polys": pruned_result.get('overall_ocr_res', {}).get('dt_polys', []),
  155. "text_det_params": pruned_result.get('overall_ocr_res', {}).get('text_det_params', {}),
  156. "text_type": pruned_result.get('overall_ocr_res', {}).get('text_type', 'general'),
  157. "textline_orientation_angles": pruned_result.get('overall_ocr_res', {}).get('textline_orientation_angles', []),
  158. "text_rec_score_thresh": pruned_result.get('overall_ocr_res', {}).get('text_rec_score_thresh', 0.0),
  159. "return_word_box": pruned_result.get('overall_ocr_res', {}).get('return_word_box', False),
  160. "rec_texts": pruned_result.get('overall_ocr_res', {}).get('rec_texts', []),
  161. "rec_scores": pruned_result.get('overall_ocr_res', {}).get('rec_scores', []),
  162. "rec_polys": pruned_result.get('overall_ocr_res', {}).get('rec_polys', []),
  163. "rec_boxes": pruned_result.get('overall_ocr_res', {}).get('rec_boxes', [])
  164. },
  165. "table_res_list": pruned_result.get('table_res_list', [])
  166. }
  167. # 数字标准化处理
  168. original_json = converted_json.copy()
  169. changes_count = 0
  170. if normalize_numbers:
  171. # 1. 标准化 parsing_res_list 中的文本内容
  172. for item in converted_json.get('parsing_res_list', []):
  173. if 'block_content' in item:
  174. original_content = item['block_content']
  175. normalized_content = original_content
  176. # 根据block_label类型选择标准化方法
  177. if item.get('block_label') == 'table':
  178. normalized_content = normalize_markdown_table(original_content)
  179. # else:
  180. # normalized_content = normalize_financial_numbers(original_content)
  181. if original_content != normalized_content:
  182. item['block_content'] = normalized_content
  183. changes_count += len([1 for o, n in zip(original_content, normalized_content) if o != n])
  184. # 2. 标准化 table_res_list 中的HTML表格
  185. for table_item in converted_json.get('table_res_list', []):
  186. if 'pred_html' in table_item:
  187. original_html = table_item['pred_html']
  188. normalized_html = normalize_markdown_table(original_html)
  189. if original_html != normalized_html:
  190. table_item['pred_html'] = normalized_html
  191. changes_count += len([1 for o, n in zip(original_html, normalized_html) if o != n])
  192. # 3. 标准化 overall_ocr_res 中的识别文本
  193. # ocr_res = converted_json.get('overall_ocr_res', {})
  194. # if 'rec_texts' in ocr_res:
  195. # original_texts = ocr_res['rec_texts'][:]
  196. # normalized_texts = []
  197. # for text in original_texts:
  198. # normalized_text = normalize_financial_numbers(text)
  199. # normalized_texts.append(normalized_text)
  200. # if text != normalized_text:
  201. # changes_count += len([1 for o, n in zip(text, normalized_text) if o != n])
  202. # ocr_res['rec_texts'] = normalized_texts
  203. # 添加标准化处理信息
  204. converted_json['processing_info'] = {
  205. "normalize_numbers": normalize_numbers,
  206. "changes_applied": changes_count > 0,
  207. "character_changes_count": changes_count
  208. }
  209. # if changes_count > 0:
  210. # print(f"🔧 已标准化 {changes_count} 个字符(全角→半角)")
  211. else:
  212. converted_json['processing_info'] = {
  213. "normalize_numbers": False,
  214. "changes_applied": False,
  215. "character_changes_count": 0
  216. }
  217. # 保存JSON文件
  218. output_path = Path(output_dir).resolve() / f"{filename}.json"
  219. output_path.parent.mkdir(parents=True, exist_ok=True)
  220. with open(output_path, 'w', encoding='utf-8') as f:
  221. json.dump(converted_json, f, ensure_ascii=False, indent=2)
  222. # 如果启用了标准化且有变化,保存原始版本用于对比
  223. if normalize_numbers and changes_count > 0:
  224. original_output_path = output_path.parent / f"{output_path.stem}_original.json"
  225. with open(original_output_path, 'w', encoding='utf-8') as f:
  226. json.dump(original_json, f, ensure_ascii=False, indent=2)
  227. return str(output_path), converted_json
  228. def save_markdown_content(api_result: Dict[str, Any], output_dir: str,
  229. filename: str, normalize_numbers: bool = True) -> str:
  230. """
  231. 保存Markdown内容,支持数字标准化
  232. """
  233. layout_parsing_results = api_result.get('layoutParsingResults', [])
  234. if not layout_parsing_results:
  235. return ""
  236. main_result = layout_parsing_results[0]
  237. markdown_data = main_result.get('markdown', {})
  238. output_path = Path(output_dir).resolve()
  239. output_path.mkdir(parents=True, exist_ok=True)
  240. # 保存Markdown文本
  241. markdown_text = markdown_data.get('text', '')
  242. # 数字标准化处理
  243. if normalize_numbers and markdown_text:
  244. original_markdown_text = markdown_text
  245. markdown_text = normalize_markdown_table(markdown_text)
  246. changes_count = len([1 for o, n in zip(original_markdown_text, markdown_text) if o != n])
  247. # if changes_count > 0:
  248. # print(f"🔧 Markdown中已标准化 {changes_count} 个字符(全角→半角)")
  249. md_file_path = output_path / f"{filename}.md"
  250. with open(md_file_path, 'w', encoding='utf-8') as f:
  251. f.write(markdown_text)
  252. # 如果启用了标准化且有变化,保存原始版本用于对比
  253. if normalize_numbers and changes_count > 0:
  254. original_output_path = output_path.parent / f"{output_path.stem}_original.json"
  255. with open(original_output_path, 'w', encoding='utf-8') as f:
  256. f.write(original_markdown_text)
  257. return str(md_file_path)
  258. def call_api_for_image(image_path: str, api_url: str, timeout: int = 300) -> Dict[str, Any]:
  259. """
  260. 为单个图像调用API
  261. Args:
  262. image_path: 图像文件路径
  263. api_url: API URL
  264. timeout: 超时时间(秒)
  265. Returns:
  266. API返回结果
  267. """
  268. try:
  269. # 对本地图像进行Base64编码
  270. with open(image_path, "rb") as file:
  271. image_bytes = file.read()
  272. image_data = base64.b64encode(image_bytes).decode("ascii")
  273. payload = {
  274. "file": image_data,
  275. "fileType": 1,
  276. }
  277. # 调用API
  278. response = requests.post(api_url, json=payload, timeout=timeout)
  279. response.raise_for_status()
  280. return response.json()["result"]
  281. except requests.exceptions.Timeout:
  282. raise Exception(f"API调用超时 ({timeout}秒)")
  283. except requests.exceptions.RequestException as e:
  284. raise Exception(f"API调用失败: {e}")
  285. except KeyError:
  286. raise Exception("API返回格式错误,缺少'result'字段")
  287. except Exception as e:
  288. raise Exception(f"处理图像时发生错误: {e}")
  289. def process_images_via_api(image_paths: List[str],
  290. api_url: str,
  291. output_dir: str = "./output",
  292. normalize_numbers: bool = True,
  293. timeout: int = 300) -> List[Dict[str, Any]]:
  294. """
  295. 通过API统一处理图像文件
  296. Args:
  297. image_paths: 图像路径列表
  298. api_url: API URL
  299. output_dir: 输出目录
  300. normalize_numbers: 是否标准化数字格式
  301. timeout: API调用超时时间
  302. Returns:
  303. 处理结果列表
  304. """
  305. # 创建输出目录
  306. output_path = Path(output_dir)
  307. output_path.mkdir(parents=True, exist_ok=True)
  308. all_results = []
  309. total_images = len(image_paths)
  310. print(f"Processing {total_images} images via API")
  311. # 使用tqdm显示进度
  312. with tqdm(total=total_images, desc="Processing images", unit="img",
  313. bar_format='{l_bar}{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]') as pbar:
  314. # 逐个处理图像
  315. for img_path in image_paths:
  316. start_time = time.time()
  317. try:
  318. # 调用API处理图像
  319. api_result = call_api_for_image(img_path, api_url, timeout)
  320. processing_time = time.time() - start_time
  321. # 处理API返回结果
  322. input_path = Path(img_path)
  323. # 生成输出文件名
  324. output_filename = input_path.stem
  325. # 转换并保存标准JSON格式
  326. json_output_path, converted_json = convert_api_result_to_json(
  327. api_result,
  328. str(input_path),
  329. output_dir,
  330. output_filename,
  331. normalize_numbers=normalize_numbers
  332. )
  333. # 保存Markdown内容
  334. md_output_path = save_markdown_content(
  335. api_result,
  336. output_dir,
  337. output_filename,
  338. normalize_numbers=normalize_numbers
  339. )
  340. # 记录处理结果
  341. all_results.append({
  342. "image_path": str(input_path),
  343. "processing_time": processing_time,
  344. "success": True,
  345. "api_url": api_url,
  346. "output_json": json_output_path,
  347. "output_md": md_output_path,
  348. "is_pdf_page": "_page_" in input_path.name, # 标记是否为PDF页面
  349. "processing_info": converted_json.get('processing_info', {})
  350. })
  351. # 更新进度条
  352. success_count = sum(1 for r in all_results if r.get('success', False))
  353. pbar.update(1)
  354. pbar.set_postfix({
  355. 'time': f"{processing_time:.2f}s",
  356. 'success': f"{success_count}/{len(all_results)}",
  357. 'rate': f"{success_count/len(all_results)*100:.1f}%"
  358. })
  359. except Exception as e:
  360. print(f"Error processing {Path(img_path).name}: {e}", file=sys.stderr)
  361. import traceback
  362. traceback.print_exc()
  363. # 添加错误结果
  364. all_results.append({
  365. "image_path": str(img_path),
  366. "processing_time": 0,
  367. "success": False,
  368. "api_url": api_url,
  369. "error": str(e),
  370. "is_pdf_page": "_page_" in Path(img_path).name
  371. })
  372. pbar.update(1)
  373. return all_results
  374. def main():
  375. """主函数"""
  376. parser = argparse.ArgumentParser(description="PaddleX PP-StructureV3 API Client - Unified PDF/Image Processor")
  377. # 参数定义
  378. input_group = parser.add_mutually_exclusive_group(required=True)
  379. input_group.add_argument("--input_file", type=str, help="Input file (supports both PDF and image file)")
  380. input_group.add_argument("--input_dir", type=str, help="Input directory (supports both PDF and image files)")
  381. input_group.add_argument("--input_file_list", type=str, help="Input file list (one file per line)")
  382. input_group.add_argument("--input_csv", type=str, help="Input CSV file with image_path and status columns")
  383. parser.add_argument("--output_dir", type=str, required=True, help="Output directory")
  384. parser.add_argument("--api_url", type=str, default="http://localhost:8080/layout-parsing", help="API URL")
  385. parser.add_argument("--pdf_dpi", type=int, default=200, help="DPI for PDF to image conversion")
  386. parser.add_argument("--timeout", type=int, default=300, help="API timeout in seconds")
  387. parser.add_argument("--no-normalize", action="store_true", help="禁用数字标准化")
  388. parser.add_argument("--test_mode", action="store_true", help="Test mode (process only 20 files)")
  389. parser.add_argument("--collect_results", type=str, help="收集处理结果到指定CSV文件")
  390. args = parser.parse_args()
  391. normalize_numbers = not args.no_normalize
  392. try:
  393. # 获取并预处理输入文件
  394. print("🔄 Preprocessing input files...")
  395. input_files = get_input_files(args)
  396. if not input_files:
  397. print("❌ No input files found or processed")
  398. return 1
  399. if args.test_mode:
  400. input_files = input_files[:20]
  401. print(f"Test mode: processing only {len(input_files)} images")
  402. print(f"🌐 Using API: {args.api_url}")
  403. print(f"🔧 数字标准化: {'启用' if normalize_numbers else '禁用'}")
  404. print(f"⏱️ Timeout: {args.timeout} seconds")
  405. # 开始处理
  406. start_time = time.time()
  407. results = process_images_via_api(
  408. input_files,
  409. args.api_url,
  410. args.output_dir,
  411. normalize_numbers=normalize_numbers,
  412. timeout=args.timeout
  413. )
  414. total_time = time.time() - start_time
  415. # 统计结果
  416. success_count = sum(1 for r in results if r.get('success', False))
  417. error_count = len(results) - success_count
  418. pdf_page_count = sum(1 for r in results if r.get('is_pdf_page', False))
  419. total_changes = sum(r.get('processing_info', {}).get('character_changes_count', 0) for r in results if 'processing_info' in r)
  420. print(f"\n" + "="*60)
  421. print(f"✅ API Processing completed!")
  422. print(f"📊 Statistics:")
  423. print(f" Total files processed: {len(input_files)}")
  424. print(f" PDF pages processed: {pdf_page_count}")
  425. print(f" Regular images processed: {len(input_files) - pdf_page_count}")
  426. print(f" Successful: {success_count}")
  427. print(f" Failed: {error_count}")
  428. if len(input_files) > 0:
  429. print(f" Success rate: {success_count / len(input_files) * 100:.2f}%")
  430. if normalize_numbers:
  431. print(f" 总标准化字符数: {total_changes}")
  432. print(f"⏱️ Performance:")
  433. print(f" Total time: {total_time:.2f} seconds")
  434. if total_time > 0:
  435. print(f" Throughput: {len(input_files) / total_time:.2f} files/second")
  436. print(f" Avg time per file: {total_time / len(input_files):.2f} seconds")
  437. # 保存结果统计
  438. stats = {
  439. "total_files": len(input_files),
  440. "pdf_pages": pdf_page_count,
  441. "regular_images": len(input_files) - pdf_page_count,
  442. "success_count": success_count,
  443. "error_count": error_count,
  444. "success_rate": success_count / len(input_files) if len(input_files) > 0 else 0,
  445. "total_time": total_time,
  446. "throughput": len(input_files) / total_time if total_time > 0 else 0,
  447. "avg_time_per_file": total_time / len(input_files) if len(input_files) > 0 else 0,
  448. "api_url": args.api_url,
  449. "pdf_dpi": args.pdf_dpi,
  450. "normalize_numbers": normalize_numbers,
  451. "total_character_changes": total_changes,
  452. "timestamp": time.strftime("%Y-%m-%d %H:%M:%S")
  453. }
  454. # 保存最终结果
  455. output_file_name = Path(args.output_dir).name
  456. output_file = os.path.join(args.output_dir, f"{output_file_name}_api_results.json")
  457. final_results = {
  458. "stats": stats,
  459. "results": results
  460. }
  461. with open(output_file, 'w', encoding='utf-8') as f:
  462. json.dump(final_results, f, ensure_ascii=False, indent=2)
  463. print(f"💾 Results saved to: {output_file}")
  464. # 如果没有收集结果的路径,使用缺省文件名,和output_dir同一路径
  465. if not args.collect_results:
  466. output_file_processed = Path(args.output_dir) / f"processed_files_{time.strftime('%Y%m%d_%H%M%S')}.csv"
  467. else:
  468. output_file_processed = Path(args.collect_results).resolve()
  469. processed_files = collect_pid_files(output_file)
  470. with open(output_file_processed, 'w', encoding='utf-8') as f:
  471. f.write("image_path,status\n")
  472. for file_path, status in processed_files:
  473. f.write(f"{file_path},{status}\n")
  474. print(f"💾 Processed files saved to: {output_file_processed}")
  475. return 0
  476. except Exception as e:
  477. print(f"❌ Processing failed: {e}", file=sys.stderr)
  478. traceback.print_exc()
  479. return 1
  480. if __name__ == "__main__":
  481. print(f"🚀 启动PP-StructureV3 API客户端...")
  482. print(f"🔧 环境变量检查: {os.environ.get('CUDA_VISIBLE_DEVICES', 'Not set')}")
  483. if len(sys.argv) == 1:
  484. # 如果没有命令行参数,使用默认配置运行
  485. print("ℹ️ No command line arguments provided. Running with default configuration...")
  486. # 默认配置
  487. default_config = {
  488. "input_dir": "../../OmniDocBench/OpenDataLab___OmniDocBench/images",
  489. "output_dir": "./OmniDocBench_API_Results",
  490. "api_url": "http://10.192.72.11:8111/layout-parsing",
  491. "timeout": "300",
  492. "collect_results": f"./OmniDocBench_API_Results/processed_files_{time.strftime('%Y%m%d_%H%M%S')}.csv",
  493. }
  494. # 构造参数
  495. sys.argv = [sys.argv[0]]
  496. for key, value in default_config.items():
  497. sys.argv.extend([f"--{key}", str(value)])
  498. # sys.argv.append("--no-normalize")
  499. # 测试模式
  500. # sys.argv.append("--test_mode")
  501. sys.exit(main())