convert_dataset.py 3.4 KB

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