pp_structure_v2.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import random
  2. from loguru import logger
  3. try:
  4. from paddleocr import PPStructure
  5. except ImportError:
  6. logger.error('paddleocr not installed, please install by "pip install magic-pdf[lite]"')
  7. exit(1)
  8. def region_to_bbox(region):
  9. x0 = region[0][0]
  10. y0 = region[0][1]
  11. x1 = region[2][0]
  12. y1 = region[2][1]
  13. return [x0, y0, x1, y1]
  14. class CustomPaddleModel:
  15. def __init__(self, ocr: bool = False, show_log: bool = False):
  16. self.model = PPStructure(table=False, ocr=ocr, show_log=show_log)
  17. def __call__(self, img):
  18. try:
  19. import cv2
  20. except ImportError:
  21. logger.error("opencv-python not installed, please install by pip.")
  22. exit(1)
  23. # 将RGB图片转换为BGR格式适配paddle
  24. img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
  25. result = self.model(img)
  26. spans = []
  27. for line in result:
  28. line.pop("img")
  29. """
  30. 为paddle输出适配type no.
  31. title: 0 # 标题
  32. text: 1 # 文本
  33. header: 2 # abandon
  34. footer: 2 # abandon
  35. reference: 1 # 文本 or abandon
  36. equation: 8 # 行间公式 block
  37. equation: 14 # 行间公式 text
  38. figure: 3 # 图片
  39. figure_caption: 4 # 图片描述
  40. table: 5 # 表格
  41. table_caption: 6 # 表格描述
  42. """
  43. if line["type"] == "title":
  44. line["category_id"] = 0
  45. elif line["type"] in ["text", "reference"]:
  46. line["category_id"] = 1
  47. elif line["type"] == "figure":
  48. line["category_id"] = 3
  49. elif line["type"] == "figure_caption":
  50. line["category_id"] = 4
  51. elif line["type"] == "table":
  52. line["category_id"] = 5
  53. elif line["type"] == "table_caption":
  54. line["category_id"] = 6
  55. elif line["type"] == "equation":
  56. line["category_id"] = 8
  57. elif line["type"] in ["header", "footer"]:
  58. line["category_id"] = 2
  59. else:
  60. logger.warning(f"unknown type: {line['type']}")
  61. # 兼容不输出score的paddleocr版本
  62. if line.get("score") is None:
  63. line["score"] = 0.5 + random.random() * 0.5
  64. res = line.pop("res", None)
  65. if res is not None and len(res) > 0:
  66. for span in res:
  67. new_span = {
  68. "category_id": 15,
  69. "bbox": region_to_bbox(span["text_region"]),
  70. "score": span["confidence"],
  71. "text": span["text"],
  72. }
  73. spans.append(new_span)
  74. if len(spans) > 0:
  75. result.extend(spans)
  76. return result