utility.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. # Copyright (c) 2020 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 logging
  15. import os
  16. import imghdr
  17. import cv2
  18. import random
  19. import numpy as np
  20. import paddle
  21. def print_dict(d, logger, delimiter=0):
  22. """
  23. Recursively visualize a dict and
  24. indenting acrrording by the relationship of keys.
  25. """
  26. for k, v in sorted(d.items()):
  27. if isinstance(v, dict):
  28. logger.info("{}{} : ".format(delimiter * " ", str(k)))
  29. print_dict(v, logger, delimiter + 4)
  30. elif isinstance(v, list) and len(v) >= 1 and isinstance(v[0], dict):
  31. logger.info("{}{} : ".format(delimiter * " ", str(k)))
  32. for value in v:
  33. print_dict(value, logger, delimiter + 4)
  34. else:
  35. logger.info("{}{} : {}".format(delimiter * " ", k, v))
  36. def get_check_global_params(mode):
  37. check_params = ['use_gpu', 'max_text_length', 'image_shape', \
  38. 'image_shape', 'character_type', 'loss_type']
  39. if mode == "train_eval":
  40. check_params = check_params + [ \
  41. 'train_batch_size_per_card', 'test_batch_size_per_card']
  42. elif mode == "test":
  43. check_params = check_params + ['test_batch_size_per_card']
  44. return check_params
  45. def _check_image_file(path):
  46. img_end = {'jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif', 'tiff', 'gif', 'pdf'}
  47. return any([path.lower().endswith(e) for e in img_end])
  48. def get_image_file_list(img_file):
  49. imgs_lists = []
  50. if img_file is None or not os.path.exists(img_file):
  51. raise Exception("not found any img file in {}".format(img_file))
  52. img_end = {'jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif', 'tiff', 'gif', 'pdf'}
  53. if os.path.isfile(img_file) and _check_image_file(img_file):
  54. imgs_lists.append(img_file)
  55. elif os.path.isdir(img_file):
  56. for single_file in os.listdir(img_file):
  57. file_path = os.path.join(img_file, single_file)
  58. if os.path.isfile(file_path) and _check_image_file(file_path):
  59. imgs_lists.append(file_path)
  60. if len(imgs_lists) == 0:
  61. raise Exception("not found any img file in {}".format(img_file))
  62. imgs_lists = sorted(imgs_lists)
  63. return imgs_lists
  64. def check_and_read(img_path):
  65. if os.path.basename(img_path)[-3:] in ['gif', 'GIF']:
  66. gif = cv2.VideoCapture(img_path)
  67. ret, frame = gif.read()
  68. if not ret:
  69. logger = logging.getLogger('ppocr')
  70. logger.info("Cannot read {}. This gif image maybe corrupted.")
  71. return None, False
  72. if len(frame.shape) == 2 or frame.shape[-1] == 1:
  73. frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)
  74. imgvalue = frame[:, :, ::-1]
  75. return imgvalue, True, False
  76. elif os.path.basename(img_path)[-3:] in ['pdf']:
  77. import fitz
  78. from PIL import Image
  79. imgs = []
  80. with fitz.open(img_path) as pdf:
  81. for pg in range(0, pdf.pageCount):
  82. page = pdf[pg]
  83. mat = fitz.Matrix(2, 2)
  84. pm = page.getPixmap(matrix=mat, alpha=False)
  85. # if width or height > 2000 pixels, don't enlarge the image
  86. if pm.width > 2000 or pm.height > 2000:
  87. pm = page.getPixmap(matrix=fitz.Matrix(1, 1), alpha=False)
  88. img = Image.frombytes("RGB", [pm.width, pm.height], pm.samples)
  89. img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
  90. imgs.append(img)
  91. return imgs, False, True
  92. return None, False, False
  93. def load_vqa_bio_label_maps(label_map_path):
  94. with open(label_map_path, "r", encoding='utf-8') as fin:
  95. lines = fin.readlines()
  96. old_lines = [line.strip() for line in lines]
  97. lines = ["O"]
  98. for line in old_lines:
  99. # "O" has already been in lines
  100. if line.upper() in ["OTHER", "OTHERS", "IGNORE"]:
  101. continue
  102. lines.append(line)
  103. labels = ["O"]
  104. for line in lines[1:]:
  105. labels.append("B-" + line)
  106. labels.append("I-" + line)
  107. label2id_map = {label.upper(): idx for idx, label in enumerate(labels)}
  108. id2label_map = {idx: label.upper() for idx, label in enumerate(labels)}
  109. return label2id_map, id2label_map
  110. def set_seed(seed=1024):
  111. random.seed(seed)
  112. np.random.seed(seed)
  113. paddle.seed(seed)
  114. class AverageMeter:
  115. def __init__(self):
  116. self.reset()
  117. def reset(self):
  118. """reset"""
  119. self.val = 0
  120. self.avg = 0
  121. self.sum = 0
  122. self.count = 0
  123. def update(self, val, n=1):
  124. """update"""
  125. self.val = val
  126. self.sum += val * n
  127. self.count += n
  128. self.avg = self.sum / self.count