markdown_batch_sampler.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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 ...utils.io import MarkDownReader
  20. from .base_batch_sampler import BaseBatchSampler, Batch
  21. class MarkDownBatchSampler(BaseBatchSampler):
  22. """Batch sampler for markdown data, supporting markdown file inputs."""
  23. SUFFIX = ["md", "markdown", "mdown", "mkd"]
  24. def __init__(self, *args, **kwargs):
  25. super().__init__(*args, **kwargs)
  26. self.md_reader = MarkDownReader()
  27. def _download_from_url(self, in_path: str) -> str:
  28. """Download a file from a URL to a cache directory.
  29. Args:
  30. in_path (str): URL of the file to be downloaded.
  31. Returns:
  32. str: Path to the downloaded file.
  33. """
  34. file_name = Path(in_path).name
  35. save_path = Path(CACHE_DIR) / "predict_input" / file_name
  36. download(in_path, save_path, overwrite=True)
  37. return save_path.as_posix()
  38. def _get_files_list(self, fp: str) -> list:
  39. """Get a list of markdown files from a directory or a single file path.
  40. Args:
  41. fp (str): Path to a directory or a single markdown file.
  42. Returns:
  43. list: Sorted list of markdown file paths.
  44. Raises:
  45. Exception: If no markdown file is found in the path.
  46. """
  47. file_list = []
  48. if fp is None or not os.path.exists(fp):
  49. raise Exception(f"Not found any markdown file in path: {fp}")
  50. if os.path.isfile(fp) and fp.split(".")[-1] in self.SUFFIX:
  51. file_list.append(fp)
  52. elif os.path.isdir(fp):
  53. for root, dirs, files in os.walk(fp):
  54. for single_file in files:
  55. if single_file.split(".")[-1] in self.SUFFIX:
  56. file_list.append(os.path.join(root, single_file))
  57. if len(file_list) == 0:
  58. raise Exception("Not found any file in {}".format(fp))
  59. file_list = sorted(file_list)
  60. return file_list
  61. def sample(self, inputs: list) -> list:
  62. """Generate batches of data from inputs, which can only be file paths.
  63. Args:
  64. inputs (list): List of markdown file paths.
  65. Yields:
  66. list: A batch of data which is a list of markdown file paths.
  67. """
  68. if not isinstance(inputs, list):
  69. inputs = [inputs]
  70. batch = Batch()
  71. for input in inputs:
  72. if isinstance(input, str):
  73. suffix = input.split(".")[-1].lower()
  74. file_path = (
  75. self._download_from_url(input)
  76. if input.startswith("http")
  77. else input
  78. )
  79. if suffix in self.SUFFIX:
  80. markdown_text = self.md_reader.read(file_path)
  81. batch.append(markdown_text, file_path)
  82. if len(batch) == self.batch_size:
  83. yield batch
  84. batch = Batch()
  85. else:
  86. file_list = self._get_files_list(file_path)
  87. for file_path in file_list:
  88. markdown_text = self.md_reader.read(file_path)
  89. batch.append(markdown_text, file_path)
  90. if len(batch) == self.batch_size:
  91. yield batch
  92. batch = Batch()
  93. else:
  94. logging.warning(
  95. f"Not supported input data type! Only `str` is supported! So has been ignored: {input}."
  96. )
  97. if len(batch) > 0:
  98. yield batch