image_batch_sampler.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. from pathlib import Path
  16. import numpy as np
  17. from ....utils import logging
  18. from ....utils.cache import CACHE_DIR
  19. from ....utils.download import download
  20. from ...utils.io import PDFReader
  21. from .base_batch_sampler import BaseBatchSampler, Batch
  22. class ImgBatch(Batch):
  23. def __init__(self):
  24. super().__init__()
  25. self.page_indexes = []
  26. def append(self, instance, input_path, page_index):
  27. super().append(instance, input_path)
  28. self.page_indexes.append(page_index)
  29. def reset(self):
  30. super().reset()
  31. self.page_indexes = []
  32. class ImageBatchSampler(BaseBatchSampler):
  33. IMG_SUFFIX = ["jpg", "png", "jpeg", "bmp"]
  34. PDF_SUFFIX = ["pdf"]
  35. def __init__(self, *args, **kwargs):
  36. super().__init__(*args, **kwargs)
  37. self.pdf_reader = PDFReader()
  38. # XXX: auto download for url
  39. def _download_from_url(self, in_path):
  40. file_name = Path(in_path).name
  41. save_path = Path(CACHE_DIR) / "predict_input" / file_name
  42. download(in_path, save_path, overwrite=True)
  43. return save_path.as_posix()
  44. def _get_files_list(self, fp):
  45. if fp is None or not os.path.exists(fp):
  46. raise Exception(f"Not found any image files or pdf files in path: {fp}")
  47. file_list = []
  48. if os.path.isdir(fp):
  49. for root, dirs, files in os.walk(fp):
  50. for single_file in files:
  51. if (
  52. single_file.split(".")[-1].lower()
  53. in self.IMG_SUFFIX + self.PDF_SUFFIX
  54. ):
  55. file_list.append(os.path.join(root, single_file))
  56. if len(file_list) == 0:
  57. raise Exception("Not found any file in {}".format(fp))
  58. file_list = sorted(file_list)
  59. return file_list
  60. def sample(self, inputs):
  61. if not isinstance(inputs, list):
  62. inputs = [inputs]
  63. batch = ImgBatch()
  64. for input in inputs:
  65. if isinstance(input, np.ndarray):
  66. batch.append(input, None, None)
  67. if len(batch) == self.batch_size:
  68. yield batch
  69. batch = ImgBatch()
  70. elif isinstance(input, str):
  71. suffix = input.split(".")[-1].lower()
  72. if suffix in self.PDF_SUFFIX:
  73. file_path = (
  74. self._download_from_url(input)
  75. if input.startswith("http")
  76. else input
  77. )
  78. for page_idx, page_img in enumerate(
  79. self.pdf_reader.read(file_path)
  80. ):
  81. batch.append(page_img, file_path, page_idx)
  82. if len(batch) == self.batch_size:
  83. yield batch
  84. batch = ImgBatch()
  85. elif suffix in self.IMG_SUFFIX:
  86. file_path = (
  87. self._download_from_url(input)
  88. if input.startswith("http")
  89. else input
  90. )
  91. batch.append(file_path, file_path, None)
  92. if len(batch) == self.batch_size:
  93. yield batch
  94. batch = ImgBatch()
  95. else:
  96. file_list = self._get_files_list(input)
  97. yield from self.sample(file_list)
  98. else:
  99. logging.warning(
  100. f"Not supported input data type! Only `numpy.ndarray` and `str` are supported! So has been ignored: {input}."
  101. )
  102. if len(batch) > 0:
  103. yield batch