check_dataset.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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. import os.path as osp
  16. from collections import defaultdict
  17. from PIL import Image, ImageOps
  18. import json
  19. import numpy as np
  20. from .....utils.errors import DatasetFileNotFoundError, CheckFailedError
  21. def check(
  22. dataset_dir, output, dataset_type="MSTextRecDataset", mode="fast", sample_num=10
  23. ):
  24. """check dataset"""
  25. if dataset_type == "SimpleDataSet" or "MSTextRecDataset" or "LaTeXOCRDataset":
  26. # Custom dataset
  27. if not osp.exists(dataset_dir) or not osp.isdir(dataset_dir):
  28. raise DatasetFileNotFoundError(file_path=dataset_dir)
  29. tags = ["train", "val"]
  30. delim = "\t"
  31. valid_num_parts = 2
  32. max_recorded_sample_cnts = 50
  33. sample_cnts = dict()
  34. sample_paths = defaultdict(list)
  35. if dataset_type == "LaTeXOCRDataset":
  36. dict_file = osp.join(dataset_dir, "latex_ocr_tokenizer.json")
  37. if not osp.exists(dict_file):
  38. raise DatasetFileNotFoundError(
  39. file_path=dict_file,
  40. solution=f"Ensure that `latex_ocr_tokenizer.json` exist in {dataset_dir}",
  41. )
  42. else:
  43. dict_file = osp.join(dataset_dir, "dict.txt")
  44. if not osp.exists(dict_file):
  45. raise DatasetFileNotFoundError(
  46. file_path=dict_file,
  47. solution=f"Ensure that `dict.txt` exist in {dataset_dir}",
  48. )
  49. for tag in tags:
  50. file_list = osp.join(dataset_dir, f"{tag}.txt")
  51. if not osp.exists(file_list):
  52. if tag in ("train", "val"):
  53. # train and val file lists must exist
  54. raise DatasetFileNotFoundError(
  55. file_path=file_list,
  56. solution=f"Ensure that both `train.txt` and `val.txt` exist in {dataset_dir}",
  57. )
  58. else:
  59. # tag == 'test'
  60. continue
  61. else:
  62. with open(file_list, "r", encoding="utf-8") as f:
  63. all_lines = f.readlines()
  64. sample_cnts[tag] = len(all_lines)
  65. for line in all_lines:
  66. substr = line.strip("\n").split(delim)
  67. if len(line.strip("\n")) < 1:
  68. continue
  69. if len(substr) != valid_num_parts and len(line.strip("\n")) > 1:
  70. raise CheckFailedError(
  71. f"Error in {line}, The number of delimiter-separated items in each row "
  72. "in {file_list} should be {valid_num_parts} (current delimiter is '{delim}')."
  73. )
  74. file_name = substr[0]
  75. img_path = osp.join(dataset_dir, file_name)
  76. if not os.path.exists(img_path):
  77. raise DatasetFileNotFoundError(file_path=img_path)
  78. vis_save_dir = osp.join(output, "demo_img")
  79. if not osp.exists(vis_save_dir):
  80. os.makedirs(vis_save_dir)
  81. if len(sample_paths[tag]) < sample_num:
  82. img = Image.open(img_path)
  83. img = ImageOps.exif_transpose(img)
  84. vis_path = osp.join(vis_save_dir, osp.basename(file_name))
  85. img.save(vis_path)
  86. sample_path = osp.join(
  87. "check_dataset", os.path.relpath(vis_path, output)
  88. )
  89. sample_paths[tag].append(sample_path)
  90. meta = {}
  91. meta["train_samples"] = sample_cnts["train"]
  92. meta["train_sample_paths"] = sample_paths["train"][:sample_num]
  93. meta["val_samples"] = sample_cnts["val"]
  94. meta["val_sample_paths"] = sample_paths["val"][:sample_num]
  95. # meta['dict_file'] = dict_file
  96. return meta