video_batch_sampler.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. from ....utils import logging
  17. from ....utils.cache import CACHE_DIR
  18. from ....utils.download import download
  19. from .base_batch_sampler import BaseBatchSampler
  20. class VideoBatchSampler(BaseBatchSampler):
  21. SUFFIX = ["mp4", "avi", "mkv", "webm"]
  22. # XXX: auto download for url
  23. def _download_from_url(self, in_path):
  24. file_name = Path(in_path).name
  25. save_path = Path(CACHE_DIR) / "predict_input" / file_name
  26. download(in_path, save_path, overwrite=True)
  27. return save_path.as_posix()
  28. def _get_files_list(self, fp):
  29. file_list = []
  30. if fp is None or not os.path.exists(fp):
  31. raise Exception(f"Not found any video file in path: {fp}")
  32. if os.path.isfile(fp) and fp.split(".")[-1] in self.SUFFIX:
  33. file_list.append(fp)
  34. elif os.path.isdir(fp):
  35. for root, dirs, files in os.walk(fp):
  36. for single_file in files:
  37. if single_file.split(".")[-1] in self.SUFFIX:
  38. file_list.append(os.path.join(root, single_file))
  39. if len(file_list) == 0:
  40. raise Exception("Not found any file in {}".format(fp))
  41. file_list = sorted(file_list)
  42. return file_list
  43. def sample(self, inputs):
  44. if not isinstance(inputs, list):
  45. inputs = [inputs]
  46. batch = []
  47. for input in inputs:
  48. if isinstance(input, str):
  49. file_path = (
  50. self._download_from_url(input)
  51. if input.startswith("http")
  52. else input
  53. )
  54. file_list = self._get_files_list(file_path)
  55. for file_path in file_list:
  56. batch.append(file_path)
  57. if len(batch) == self.batch_size:
  58. yield batch
  59. batch = []
  60. else:
  61. logging.warning(
  62. f"Not supported input data type! Only `str` are supported! So has been ignored: {input}."
  63. )
  64. if len(batch) > 0:
  65. yield batch