image_batch_sampler.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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.download import download
  19. from ....utils.cache import CACHE_DIR
  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. SUFFIX = ["jpg", "png", "jpeg", "JPEG", "JPG", "bmp"]
  34. def __init__(self, *args, **kwargs):
  35. super().__init__(*args, **kwargs)
  36. self.pdf_reader = PDFReader()
  37. # XXX: auto download for url
  38. def _download_from_url(self, in_path):
  39. file_name = Path(in_path).name
  40. save_path = Path(CACHE_DIR) / "predict_input" / file_name
  41. download(in_path, save_path, overwrite=True)
  42. return save_path.as_posix()
  43. def _get_files_list(self, fp):
  44. file_list = []
  45. if fp is None or not os.path.exists(fp):
  46. raise Exception(f"Not found any img file in path: {fp}")
  47. if os.path.isfile(fp) and fp.split(".")[-1] in self.SUFFIX:
  48. file_list.append(fp)
  49. elif os.path.isdir(fp):
  50. for root, dirs, files in os.walk(fp):
  51. for single_file in files:
  52. if single_file.split(".")[-1] in self.SUFFIX:
  53. file_list.append(os.path.join(root, single_file))
  54. if len(file_list) == 0:
  55. raise Exception("Not found any file in {}".format(fp))
  56. file_list = sorted(file_list)
  57. return file_list
  58. def sample(self, inputs):
  59. if not isinstance(inputs, list):
  60. inputs = [inputs]
  61. batch = ImgBatch()
  62. for input in inputs:
  63. if isinstance(input, np.ndarray):
  64. batch.append(input, None, None)
  65. if len(batch) == self.batch_size:
  66. yield batch
  67. batch.reset()
  68. elif isinstance(input, str) and input.split(".")[-1] in ("PDF", "pdf"):
  69. file_path = (
  70. self._download_from_url(input)
  71. if input.startswith("http")
  72. else input
  73. )
  74. for page_idx, page_img in enumerate(self.pdf_reader.read(file_path)):
  75. batch.append(page_img, file_path, page_idx)
  76. if len(batch) == self.batch_size:
  77. yield batch
  78. batch.reset()
  79. elif isinstance(input, str):
  80. file_path = (
  81. self._download_from_url(input)
  82. if input.startswith("http")
  83. else input
  84. )
  85. file_list = self._get_files_list(file_path)
  86. for file_path in file_list:
  87. batch.append(file_path, file_path, None)
  88. if len(batch) == self.batch_size:
  89. yield batch
  90. batch.reset()
  91. else:
  92. logging.warning(
  93. f"Not supported input data type! Only `numpy.ndarray` and `str` are supported! So has been ignored: {input}."
  94. )
  95. if len(batch) > 0:
  96. yield batch