You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

t_recognizer.py 5.8KB

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