Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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