Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

t_recognizer.py 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. #
  13. import logging
  14. import os
  15. import sys
  16. sys.path.insert(
  17. 0,
  18. os.path.abspath(
  19. os.path.join(
  20. os.path.dirname(
  21. os.path.abspath(__file__)),
  22. '../../')))
  23. from deepdoc.vision.seeit import draw_box
  24. from deepdoc.vision import LayoutRecognizer, TableStructureRecognizer, OCR, init_in_out, Recognizer
  25. import argparse
  26. import re
  27. import numpy as np
  28. def main(args):
  29. images, outputs = init_in_out(args)
  30. if args.mode.lower() == "layout":
  31. detr = LayoutRecognizer("layout")
  32. layouts = super(Recognizer, detr)(images, thr=float(args.threshold))
  33. if args.mode.lower() == "tsr":
  34. labels = TableStructureRecognizer.labels
  35. detr = TableStructureRecognizer()
  36. ocr = OCR()
  37. layouts = detr(images, thr=float(args.threshold))
  38. for i, lyt in enumerate(layouts):
  39. if args.mode.lower() == "tsr":
  40. #lyt = [t for t in lyt if t["type"] == "table column"]
  41. html = get_table_html(images[i], lyt, ocr)
  42. with open(outputs[i] + ".html", "w+", encoding='utf-8') as f:
  43. f.write(html)
  44. lyt = [{
  45. "type": t["label"],
  46. "bbox": [t["x0"], t["top"], t["x1"], t["bottom"]],
  47. "score": t["score"]
  48. } for t in lyt]
  49. img = draw_box(images[i], lyt, labels, float(args.threshold))
  50. img.save(outputs[i], quality=95)
  51. logging.info("save result to: " + outputs[i])
  52. def get_table_html(img, tb_cpns, ocr):
  53. boxes = ocr(np.array(img))
  54. boxes = LayoutRecognizer.sort_Y_firstly(
  55. [{"x0": b[0][0], "x1": b[1][0],
  56. "top": b[0][1], "text": t[0],
  57. "bottom": b[-1][1],
  58. "layout_type": "table",
  59. "page_number": 0} for b, t in boxes if b[0][0] <= b[1][0] and b[0][1] <= b[-1][1]],
  60. np.mean([b[-1][1] - b[0][1] for b, _ in boxes]) / 3
  61. )
  62. def gather(kwd, fzy=10, ption=0.6):
  63. nonlocal boxes
  64. eles = LayoutRecognizer.sort_Y_firstly(
  65. [r for r in tb_cpns if re.match(kwd, r["label"])], fzy)
  66. eles = LayoutRecognizer.layouts_cleanup(boxes, eles, 5, ption)
  67. return LayoutRecognizer.sort_Y_firstly(eles, 0)
  68. headers = gather(r".*header$")
  69. rows = gather(r".* (row|header)")
  70. spans = gather(r".*spanning")
  71. clmns = sorted([r for r in tb_cpns if re.match(
  72. r"table column$", r["label"])], key=lambda x: x["x0"])
  73. clmns = LayoutRecognizer.layouts_cleanup(boxes, clmns, 5, 0.5)
  74. for b in boxes:
  75. ii = LayoutRecognizer.find_overlapped_with_threashold(b, rows, thr=0.3)
  76. if ii is not None:
  77. b["R"] = ii
  78. b["R_top"] = rows[ii]["top"]
  79. b["R_bott"] = rows[ii]["bottom"]
  80. ii = LayoutRecognizer.find_overlapped_with_threashold(b, headers, thr=0.3)
  81. if ii is not None:
  82. b["H_top"] = headers[ii]["top"]
  83. b["H_bott"] = headers[ii]["bottom"]
  84. b["H_left"] = headers[ii]["x0"]
  85. b["H_right"] = headers[ii]["x1"]
  86. b["H"] = ii
  87. ii = LayoutRecognizer.find_horizontally_tightest_fit(b, clmns)
  88. if ii is not None:
  89. b["C"] = ii
  90. b["C_left"] = clmns[ii]["x0"]
  91. b["C_right"] = clmns[ii]["x1"]
  92. ii = LayoutRecognizer.find_overlapped_with_threashold(b, spans, thr=0.3)
  93. if ii is not None:
  94. b["H_top"] = spans[ii]["top"]
  95. b["H_bott"] = spans[ii]["bottom"]
  96. b["H_left"] = spans[ii]["x0"]
  97. b["H_right"] = spans[ii]["x1"]
  98. b["SP"] = ii
  99. html = """
  100. <html>
  101. <head>
  102. <style>
  103. ._table_1nkzy_11 {
  104. margin: auto;
  105. width: 70%%;
  106. padding: 10px;
  107. }
  108. ._table_1nkzy_11 p {
  109. margin-bottom: 50px;
  110. border: 1px solid #e1e1e1;
  111. }
  112. caption {
  113. color: #6ac1ca;
  114. font-size: 20px;
  115. height: 50px;
  116. line-height: 50px;
  117. font-weight: 600;
  118. margin-bottom: 10px;
  119. }
  120. ._table_1nkzy_11 table {
  121. width: 100%%;
  122. border-collapse: collapse;
  123. }
  124. th {
  125. color: #fff;
  126. background-color: #6ac1ca;
  127. }
  128. td:hover {
  129. background: #c1e8e8;
  130. }
  131. tr:nth-child(even) {
  132. background-color: #f2f2f2;
  133. }
  134. ._table_1nkzy_11 th,
  135. ._table_1nkzy_11 td {
  136. text-align: center;
  137. border: 1px solid #ddd;
  138. padding: 8px;
  139. }
  140. </style>
  141. </head>
  142. <body>
  143. %s
  144. </body>
  145. </html>
  146. """ % TableStructureRecognizer.construct_table(boxes, html=True)
  147. return html
  148. if __name__ == "__main__":
  149. parser = argparse.ArgumentParser()
  150. parser.add_argument('--inputs',
  151. help="Directory where to store images or PDFs, or a file path to a single image or PDF",
  152. required=True)
  153. parser.add_argument('--output_dir', help="Directory where to store the output images. Default: './layouts_outputs'",
  154. default="./layouts_outputs")
  155. parser.add_argument(
  156. '--threshold',
  157. help="A threshold to filter out detections. Default: 0.5",
  158. default=0.5)
  159. parser.add_argument('--mode', help="Task mode: layout recognition or table structure recognition", choices=["layout", "tsr"],
  160. default="layout")
  161. args = parser.parse_args()
  162. main(args)