image_batch_sampler.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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 files in path: {fp}")
  47. if os.path.isfile(fp):
  48. return [fp]
  49. file_list = []
  50. if os.path.isdir(fp):
  51. for root, dirs, files in os.walk(fp):
  52. for single_file in files:
  53. if (
  54. single_file.split(".")[-1].lower()
  55. in self.IMG_SUFFIX + self.PDF_SUFFIX
  56. ):
  57. file_list.append(os.path.join(root, single_file))
  58. if len(file_list) == 0:
  59. raise Exception("Not found any file in {}".format(fp))
  60. file_list = sorted(file_list)
  61. return file_list
  62. def sample(self, inputs):
  63. if not isinstance(inputs, list):
  64. inputs = [inputs]
  65. batch = ImgBatch()
  66. for input in inputs:
  67. if isinstance(input, np.ndarray):
  68. batch.append(input, None, None)
  69. if len(batch) == self.batch_size:
  70. yield batch
  71. batch = ImgBatch()
  72. elif isinstance(input, str):
  73. suffix = input.split(".")[-1].lower()
  74. if suffix in self.PDF_SUFFIX:
  75. file_path = (
  76. self._download_from_url(input)
  77. if input.startswith("http")
  78. else input
  79. )
  80. for page_idx, page_img in enumerate(
  81. self.pdf_reader.read(file_path)
  82. ):
  83. batch.append(page_img, file_path, page_idx)
  84. if len(batch) == self.batch_size:
  85. yield batch
  86. batch = ImgBatch()
  87. elif suffix in self.IMG_SUFFIX:
  88. file_path = (
  89. self._download_from_url(input)
  90. if input.startswith("http")
  91. else input
  92. )
  93. batch.append(file_path, file_path, None)
  94. if len(batch) == self.batch_size:
  95. yield batch
  96. batch = ImgBatch()
  97. else:
  98. file_list = self._get_files_list(input)
  99. yield from self.sample(file_list)
  100. else:
  101. logging.warning(
  102. f"Not supported input data type! Only `numpy.ndarray` and `str` are supported! So has been ignored: {input}."
  103. )
  104. if len(batch) > 0:
  105. yield batch