data_processor.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """
  2. OCR 数据处理
  3. """
  4. import sys
  5. from pathlib import Path
  6. from typing import List, Dict, Tuple
  7. # 添加父目录到路径
  8. sys.path.insert(0, str(Path(__file__).parent.parent))
  9. try:
  10. from table_line_generator import TableLineGenerator
  11. except ImportError:
  12. from ..table_line_generator import TableLineGenerator
  13. def parse_ocr_data(raw_data: Dict, tool: str = "ppstructv3") -> Tuple[List[int], List[Dict]]:
  14. """
  15. 解析 OCR 数据(根据工具类型自动选择解析方法)
  16. Args:
  17. raw_data: 原始 OCR 结果
  18. tool: 工具类型 ("ppstructv3" 或 "mineru")
  19. Returns:
  20. (table_bbox, ocr_data): 表格边界框和文本框列表
  21. """
  22. if tool.lower() == "mineru":
  23. # 使用 MinerU 专用解析方法
  24. table_bbox, structure = TableLineGenerator.parse_mineru_table_result(raw_data)
  25. # 🔑 将结构转换为 ocr_data 格式(兼容现有逻辑)
  26. ocr_data = []
  27. for row in structure['rows']:
  28. for bbox in row['bboxes']:
  29. ocr_data.append({
  30. 'bbox': bbox,
  31. 'text': '' # MinerU 可能没有文本,或需要从 table_cells 提取
  32. })
  33. return table_bbox, ocr_data
  34. elif tool.lower() == "ppstructv3":
  35. # 🔑 PPStructure V3 格式
  36. return TableLineGenerator.parse_ppstructure_result(raw_data)
  37. else:
  38. raise ValueError(f"不支持的工具类型: {tool},支持的类型: ppstructv3, mineru")
  39. def get_structure_from_ocr(
  40. raw_data: Dict,
  41. tool: str = "ppstructv3"
  42. ) -> Tuple[List[int], Dict]:
  43. """
  44. 从 OCR 数据直接生成表格结构
  45. Args:
  46. raw_data: 原始 OCR 结果
  47. tool: 工具类型
  48. Returns:
  49. (table_bbox, structure): 表格边界框和结构信息
  50. """
  51. if tool.lower() == "mineru":
  52. # 🔑 MinerU:直接传入完整 JSON,方法内部会提取 table
  53. return TableLineGenerator.parse_mineru_table_result(raw_data)
  54. elif tool.lower() == "ppstructv3" or tool.lower() == "ppstructure":
  55. # 🔑 PPStructure V3:需要先解析再分析
  56. table_bbox, ocr_data = TableLineGenerator.parse_ppstructure_result(raw_data)
  57. # 使用临时生成器分析结构
  58. from PIL import Image
  59. dummy_image = Image.new('RGB', (2000, 3000), 'white')
  60. generator = TableLineGenerator(dummy_image, ocr_data)
  61. structure = generator.analyze_table_structure()
  62. return table_bbox, structure
  63. else:
  64. raise ValueError(f"不支持的工具类型: {tool}")