utility.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import random
  15. import ast
  16. from PIL import Image, ImageDraw, ImageFont
  17. import numpy as np
  18. from tools.infer.utility import draw_ocr_box_txt, str2bool, init_args as infer_args
  19. def init_args():
  20. parser = infer_args()
  21. # params for output
  22. parser.add_argument("--output", type=str, default='./output')
  23. # params for table structure
  24. parser.add_argument("--table_max_len", type=int, default=488)
  25. parser.add_argument("--table_algorithm", type=str, default='TableAttn')
  26. parser.add_argument("--table_model_dir", type=str)
  27. parser.add_argument(
  28. "--merge_no_span_structure", type=str2bool, default=True)
  29. parser.add_argument(
  30. "--table_char_dict_path",
  31. type=str,
  32. default="../ppocr/utils/dict/table_structure_dict_ch.txt")
  33. # params for layout
  34. parser.add_argument("--layout_model_dir", type=str)
  35. parser.add_argument(
  36. "--layout_dict_path",
  37. type=str,
  38. default="../ppocr/utils/dict/layout_dict/layout_publaynet_dict.txt")
  39. parser.add_argument(
  40. "--layout_score_threshold",
  41. type=float,
  42. default=0.5,
  43. help="Threshold of score.")
  44. parser.add_argument(
  45. "--layout_nms_threshold",
  46. type=float,
  47. default=0.5,
  48. help="Threshold of nms.")
  49. # params for kie
  50. parser.add_argument("--kie_algorithm", type=str, default='LayoutXLM')
  51. parser.add_argument("--ser_model_dir", type=str)
  52. parser.add_argument("--re_model_dir", type=str)
  53. parser.add_argument("--use_visual_backbone", type=str2bool, default=True)
  54. parser.add_argument(
  55. "--ser_dict_path",
  56. type=str,
  57. default="../train_data/XFUND/class_list_xfun.txt")
  58. # need to be None or tb-yx
  59. parser.add_argument("--ocr_order_method", type=str, default=None)
  60. # params for inference
  61. parser.add_argument(
  62. "--mode",
  63. type=str,
  64. choices=['structure', 'kie'],
  65. default='structure',
  66. help='structure and kie is supported')
  67. parser.add_argument(
  68. "--image_orientation",
  69. type=bool,
  70. default=False,
  71. help='Whether to enable image orientation recognition')
  72. parser.add_argument(
  73. "--layout",
  74. type=str2bool,
  75. default=True,
  76. help='Whether to enable layout analysis')
  77. parser.add_argument(
  78. "--table",
  79. type=str2bool,
  80. default=True,
  81. help='In the forward, whether the table area uses table recognition')
  82. parser.add_argument(
  83. "--ocr",
  84. type=str2bool,
  85. default=True,
  86. help='In the forward, whether the non-table area is recognition by ocr')
  87. # param for recovery
  88. parser.add_argument(
  89. "--recovery",
  90. type=str2bool,
  91. default=False,
  92. help='Whether to enable layout of recovery')
  93. parser.add_argument(
  94. "--use_pdf2docx_api",
  95. type=str2bool,
  96. default=False,
  97. help='Whether to use pdf2docx api')
  98. return parser
  99. def parse_args():
  100. parser = init_args()
  101. return parser.parse_args()
  102. def draw_structure_result(image, result, font_path):
  103. if isinstance(image, np.ndarray):
  104. image = Image.fromarray(image)
  105. boxes, txts, scores = [], [], []
  106. img_layout = image.copy()
  107. draw_layout = ImageDraw.Draw(img_layout)
  108. text_color = (255, 255, 255)
  109. text_background_color = (80, 127, 255)
  110. catid2color = {}
  111. font_size = 15
  112. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  113. for region in result:
  114. if region['type'] not in catid2color:
  115. box_color = (random.randint(0, 255), random.randint(0, 255),
  116. random.randint(0, 255))
  117. catid2color[region['type']] = box_color
  118. else:
  119. box_color = catid2color[region['type']]
  120. box_layout = region['bbox']
  121. draw_layout.rectangle(
  122. [(box_layout[0], box_layout[1]), (box_layout[2], box_layout[3])],
  123. outline=box_color,
  124. width=3)
  125. text_w, text_h = font.getsize(region['type'])
  126. draw_layout.rectangle(
  127. [(box_layout[0], box_layout[1]),
  128. (box_layout[0] + text_w, box_layout[1] + text_h)],
  129. fill=text_background_color)
  130. draw_layout.text(
  131. (box_layout[0], box_layout[1]),
  132. region['type'],
  133. fill=text_color,
  134. font=font)
  135. if region['type'] == 'table':
  136. pass
  137. else:
  138. for text_result in region['res']:
  139. boxes.append(np.array(text_result['text_region']))
  140. txts.append(text_result['text'])
  141. scores.append(text_result['confidence'])
  142. im_show = draw_ocr_box_txt(
  143. img_layout, boxes, txts, scores, font_path=font_path, drop_score=0)
  144. return im_show