data_processor.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import streamlit as st
  2. import json
  3. # 当直接运行时
  4. import sys
  5. from pathlib import Path
  6. sys.path.insert(0, str(Path(__file__).parent.parent))
  7. from table_line_generator import TableLineGenerator # 上级目录
  8. def parse_ocr_data(ocr_data):
  9. """解析OCR数据,支持多种格式"""
  10. # 如果是字符串,尝试解析
  11. if isinstance(ocr_data, str):
  12. try:
  13. ocr_data = json.loads(ocr_data)
  14. except json.JSONDecodeError:
  15. st.error("❌ JSON 格式错误,无法解析")
  16. return []
  17. # 检查是否为 PPStructure V3 格式
  18. if isinstance(ocr_data, dict) and 'parsing_res_list' in ocr_data and 'overall_ocr_res' in ocr_data:
  19. st.info("🔍 检测到 PPStructure V3 格式")
  20. try:
  21. table_bbox, text_boxes = TableLineGenerator.parse_ppstructure_result(ocr_data)
  22. st.success(f"✅ 表格区域: {table_bbox}")
  23. st.success(f"✅ 表格内文本框: {len(text_boxes)} 个")
  24. return text_boxes
  25. except Exception as e:
  26. st.error(f"❌ 解析 PPStructure 结果失败: {e}")
  27. return []
  28. # 确保是列表
  29. if not isinstance(ocr_data, list):
  30. st.error(f"❌ OCR 数据应该是列表,实际类型: {type(ocr_data)}")
  31. return []
  32. if not ocr_data:
  33. st.warning("⚠️ OCR 数据为空")
  34. return []
  35. first_item = ocr_data[0]
  36. if not isinstance(first_item, dict):
  37. st.error(f"❌ OCR 数据项应该是字典,实际类型: {type(first_item)}")
  38. return []
  39. if 'bbox' not in first_item:
  40. st.error("❌ OCR 数据缺少 'bbox' 字段")
  41. st.info("💡 支持的格式示例:\n```json\n[\n {\n \"text\": \"文本\",\n \"bbox\": [x1, y1, x2, y2]\n }\n]\n```")
  42. return []
  43. return ocr_data