convert_dataset.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 math
  15. import os
  16. import pickle
  17. from collections import defaultdict
  18. import imagesize
  19. from tqdm import tqdm
  20. from .....utils.errors import ConvertFailedError
  21. def check_src_dataset(root_dir, dataset_type):
  22. """check src dataset format validity"""
  23. if dataset_type in ("MSTextRecDataset"):
  24. pass
  25. else:
  26. raise ConvertFailedError(
  27. message=f"数据格式转换失败!不支持{dataset_type}格式数据集。当前仅支持 MSTextRecDataset 格式。"
  28. )
  29. err_msg_prefix = f"数据格式转换失败!请参考上述`{dataset_type}格式数据集示例`检查待转换数据集格式。"
  30. for anno in ["train.txt", "val.txt", "latex_ocr_tokenizer.json"]:
  31. src_anno_path = os.path.join(root_dir, anno)
  32. if not os.path.exists(src_anno_path):
  33. raise ConvertFailedError(
  34. message=f"{err_msg_prefix}保证{src_anno_path}文件存在。"
  35. )
  36. return None
  37. def convert(dataset_type, input_dir):
  38. """convert dataset to pkl format"""
  39. # check format validity
  40. check_src_dataset(input_dir, dataset_type)
  41. if dataset_type in ("MSTextRecDataset"):
  42. convert_pkl_dataset(input_dir)
  43. else:
  44. raise ConvertFailedError(
  45. message=f"数据格式转换失败!不支持{dataset_type}格式数据集。当前仅支持 MSTextRecDataset 格式。"
  46. )
  47. def convert_pkl_dataset(root_dir):
  48. for anno in ["train.txt", "val.txt"]:
  49. src_img_dir = root_dir
  50. src_anno_path = os.path.join(root_dir, anno)
  51. txt2pickle(src_img_dir, src_anno_path, root_dir)
  52. def txt2pickle(images, equations, save_dir):
  53. phase = os.path.basename(equations).replace(".txt", "")
  54. save_p = os.path.join(save_dir, "latexocr_{}.pkl".format(phase))
  55. min_dimensions = (32, 32)
  56. max_dimensions = (672, 192)
  57. data = defaultdict(lambda: [])
  58. pic_num = 0
  59. if images is not None and equations is not None:
  60. with open(equations, "r") as f:
  61. lines = f.readlines()
  62. for l in tqdm(lines, total=len(lines)):
  63. l = l.strip()
  64. img_name, equation = l.split("\t")
  65. img_path = os.path.join(images, img_name)
  66. width, height = imagesize.get(img_path)
  67. if (
  68. min_dimensions[0] <= width <= max_dimensions[0]
  69. and min_dimensions[1] <= height <= max_dimensions[1]
  70. ):
  71. divide_h = math.ceil(height / 16) * 16
  72. divide_w = math.ceil(width / 16) * 16
  73. data[(divide_w, divide_h)].append((equation, img_name))
  74. pic_num += 1
  75. data = dict(data)
  76. with open(save_p, "wb") as file:
  77. pickle.dump(data, file)