您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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