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.

__init__.py 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 io
  17. import sys
  18. import threading
  19. import pdfplumber
  20. from .ocr import OCR
  21. from .recognizer import Recognizer
  22. from .layout_recognizer import LayoutRecognizer4YOLOv10 as LayoutRecognizer
  23. from .table_structure_recognizer import TableStructureRecognizer
  24. LOCK_KEY_pdfplumber = "global_shared_lock_pdfplumber"
  25. if LOCK_KEY_pdfplumber not in sys.modules:
  26. sys.modules[LOCK_KEY_pdfplumber] = threading.Lock()
  27. def init_in_out(args):
  28. from PIL import Image
  29. import os
  30. import traceback
  31. from api.utils.file_utils import traversal_files
  32. images = []
  33. outputs = []
  34. if not os.path.exists(args.output_dir):
  35. os.mkdir(args.output_dir)
  36. def pdf_pages(fnm, zoomin=3):
  37. nonlocal outputs, images
  38. with sys.modules[LOCK_KEY_pdfplumber]:
  39. pdf = pdfplumber.open(fnm)
  40. images = [p.to_image(resolution=72 * zoomin).annotated for i, p in
  41. enumerate(pdf.pages)]
  42. for i, page in enumerate(images):
  43. outputs.append(os.path.split(fnm)[-1] + f"_{i}.jpg")
  44. pdf.close()
  45. def images_and_outputs(fnm):
  46. nonlocal outputs, images
  47. if fnm.split(".")[-1].lower() == "pdf":
  48. pdf_pages(fnm)
  49. return
  50. try:
  51. fp = open(fnm, 'rb')
  52. binary = fp.read()
  53. fp.close()
  54. images.append(Image.open(io.BytesIO(binary)).convert('RGB'))
  55. outputs.append(os.path.split(fnm)[-1])
  56. except Exception:
  57. traceback.print_exc()
  58. if os.path.isdir(args.inputs):
  59. for fnm in traversal_files(args.inputs):
  60. images_and_outputs(fnm)
  61. else:
  62. images_and_outputs(args.inputs)
  63. for i in range(len(outputs)):
  64. outputs[i] = os.path.join(args.output_dir, outputs[i])
  65. return images, outputs
  66. __all__ = [
  67. "OCR",
  68. "Recognizer",
  69. "LayoutRecognizer",
  70. "TableStructureRecognizer",
  71. "init_in_out",
  72. ]