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

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