text_rec.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. import re
  17. import numpy as np
  18. from PIL import Image
  19. import cv2
  20. import math
  21. import lazy_paddle as paddle
  22. import json
  23. import tempfile
  24. from tokenizers import Tokenizer as TokenizerFast
  25. from ....utils import logging
  26. from ..base import BaseComponent
  27. __all__ = [
  28. "OCRReisizeNormImg",
  29. # "LaTeXOCRReisizeNormImg",
  30. "CTCLabelDecode",
  31. # "LaTeXOCRDecode",
  32. ]
  33. class OCRReisizeNormImg(BaseComponent):
  34. """for ocr image resize and normalization"""
  35. INPUT_KEYS = ["img", "img_size"]
  36. OUTPUT_KEYS = ["img"]
  37. DEAULT_INPUTS = {"img": "img", "img_size": "img_size"}
  38. DEAULT_OUTPUTS = {"img": "img"}
  39. def __init__(self, rec_image_shape=[3, 48, 320]):
  40. super().__init__()
  41. self.rec_image_shape = rec_image_shape
  42. def resize_norm_img(self, img, max_wh_ratio):
  43. """resize and normalize the img"""
  44. imgC, imgH, imgW = self.rec_image_shape
  45. assert imgC == img.shape[2]
  46. imgW = int((imgH * max_wh_ratio))
  47. h, w = img.shape[:2]
  48. ratio = w / float(h)
  49. if math.ceil(imgH * ratio) > imgW:
  50. resized_w = imgW
  51. else:
  52. resized_w = int(math.ceil(imgH * ratio))
  53. resized_image = cv2.resize(img, (resized_w, imgH))
  54. resized_image = resized_image.astype("float32")
  55. resized_image = resized_image.transpose((2, 0, 1)) / 255
  56. resized_image -= 0.5
  57. resized_image /= 0.5
  58. padding_im = np.zeros((imgC, imgH, imgW), dtype=np.float32)
  59. padding_im[:, :, 0:resized_w] = resized_image
  60. return padding_im
  61. def apply(self, img, img_size):
  62. """apply"""
  63. imgC, imgH, imgW = self.rec_image_shape
  64. max_wh_ratio = imgW / imgH
  65. w, h = img_size[:2]
  66. wh_ratio = w * 1.0 / h
  67. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  68. img = self.resize_norm_img(img, max_wh_ratio)
  69. return {"img": img}
  70. # class LaTeXOCRReisizeNormImg(BaseComponent):
  71. # """for ocr image resize and normalization"""
  72. # def __init__(self, rec_image_shape=[3, 48, 320]):
  73. # super().__init__()
  74. # self.rec_image_shape = rec_image_shape
  75. # def pad_(self, img, divable=32):
  76. # threshold = 128
  77. # data = np.array(img.convert("LA"))
  78. # if data[..., -1].var() == 0:
  79. # data = (data[..., 0]).astype(np.uint8)
  80. # else:
  81. # data = (255 - data[..., -1]).astype(np.uint8)
  82. # data = (data - data.min()) / (data.max() - data.min()) * 255
  83. # if data.mean() > threshold:
  84. # # To invert the text to white
  85. # gray = 255 * (data < threshold).astype(np.uint8)
  86. # else:
  87. # gray = 255 * (data > threshold).astype(np.uint8)
  88. # data = 255 - data
  89. # coords = cv2.findNonZero(gray) # Find all non-zero points (text)
  90. # a, b, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box
  91. # rect = data[b : b + h, a : a + w]
  92. # im = Image.fromarray(rect).convert("L")
  93. # dims = []
  94. # for x in [w, h]:
  95. # div, mod = divmod(x, divable)
  96. # dims.append(divable * (div + (1 if mod > 0 else 0)))
  97. # padded = Image.new("L", dims, 255)
  98. # padded.paste(im, (0, 0, im.size[0], im.size[1]))
  99. # return padded
  100. # def minmax_size_(
  101. # self,
  102. # img,
  103. # max_dimensions,
  104. # min_dimensions,
  105. # ):
  106. # if max_dimensions is not None:
  107. # ratios = [a / b for a, b in zip(img.size, max_dimensions)]
  108. # if any([r > 1 for r in ratios]):
  109. # size = np.array(img.size) // max(ratios)
  110. # img = img.resize(tuple(size.astype(int)), Image.BILINEAR)
  111. # if min_dimensions is not None:
  112. # # hypothesis: there is a dim in img smaller than min_dimensions, and return a proper dim >= min_dimensions
  113. # padded_size = [
  114. # max(img_dim, min_dim)
  115. # for img_dim, min_dim in zip(img.size, min_dimensions)
  116. # ]
  117. # if padded_size != list(img.size): # assert hypothesis
  118. # padded_im = Image.new("L", padded_size, 255)
  119. # padded_im.paste(img, img.getbbox())
  120. # img = padded_im
  121. # return img
  122. # def norm_img_latexocr(self, img):
  123. # # CAN only predict gray scale image
  124. # shape = (1, 1, 3)
  125. # mean = [0.7931, 0.7931, 0.7931]
  126. # std = [0.1738, 0.1738, 0.1738]
  127. # scale = np.float32(1.0 / 255.0)
  128. # min_dimensions = [32, 32]
  129. # max_dimensions = [672, 192]
  130. # mean = np.array(mean).reshape(shape).astype("float32")
  131. # std = np.array(std).reshape(shape).astype("float32")
  132. # im_h, im_w = img.shape[:2]
  133. # if (
  134. # min_dimensions[0] <= im_w <= max_dimensions[0]
  135. # and min_dimensions[1] <= im_h <= max_dimensions[1]
  136. # ):
  137. # pass
  138. # else:
  139. # img = Image.fromarray(np.uint8(img))
  140. # img = self.minmax_size_(self.pad_(img), max_dimensions, min_dimensions)
  141. # img = np.array(img)
  142. # im_h, im_w = img.shape[:2]
  143. # img = np.dstack([img, img, img])
  144. # img = (img.astype("float32") * scale - mean) / std
  145. # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  146. # divide_h = math.ceil(im_h / 16) * 16
  147. # divide_w = math.ceil(im_w / 16) * 16
  148. # img = np.pad(
  149. # img, ((0, divide_h - im_h), (0, divide_w - im_w)), constant_values=(1, 1)
  150. # )
  151. # img = img[:, :, np.newaxis].transpose(2, 0, 1)
  152. # img = img.astype("float32")
  153. # return img
  154. # def apply(self, data):
  155. # """apply"""
  156. # data[K.IMAGE] = self.norm_img_latexocr(data[K.IMAGE])
  157. # return data
  158. # @classmethod
  159. # def get_input_keys(cls):
  160. # """get input keys"""
  161. # return [K.IMAGE, K.ORI_IM_SIZE]
  162. # @classmethod
  163. # def get_output_keys(cls):
  164. # """get output keys"""
  165. # return [K.IMAGE]
  166. class BaseRecLabelDecode(BaseComponent):
  167. """Convert between text-label and text-index"""
  168. INPUT_KEYS = ["pred"]
  169. OUTPUT_KEYS = ["rec_text", "rec_score"]
  170. DEAULT_INPUTS = {"pred": "pred"}
  171. DEAULT_OUTPUTS = {"rec_text": "rec_text", "rec_score": "rec_score"}
  172. ENABLE_BATCH = True
  173. def __init__(self, character_str=None, use_space_char=True):
  174. super().__init__()
  175. self.reverse = False
  176. character_list = (
  177. list(character_str)
  178. if character_str is not None
  179. else list("0123456789abcdefghijklmnopqrstuvwxyz")
  180. )
  181. if use_space_char:
  182. character_list.append(" ")
  183. character_list = self.add_special_char(character_list)
  184. self.dict = {}
  185. for i, char in enumerate(character_list):
  186. self.dict[char] = i
  187. self.character = character_list
  188. def pred_reverse(self, pred):
  189. """pred_reverse"""
  190. pred_re = []
  191. c_current = ""
  192. for c in pred:
  193. if not bool(re.search("[a-zA-Z0-9 :*./%+-]", c)):
  194. if c_current != "":
  195. pred_re.append(c_current)
  196. pred_re.append(c)
  197. c_current = ""
  198. else:
  199. c_current += c
  200. if c_current != "":
  201. pred_re.append(c_current)
  202. return "".join(pred_re[::-1])
  203. def add_special_char(self, character_list):
  204. """add_special_char"""
  205. return character_list
  206. def decode(self, text_index, text_prob=None, is_remove_duplicate=False):
  207. """convert text-index into text-label."""
  208. result_list = []
  209. ignored_tokens = self.get_ignored_tokens()
  210. batch_size = len(text_index)
  211. for batch_idx in range(batch_size):
  212. selection = np.ones(len(text_index[batch_idx]), dtype=bool)
  213. if is_remove_duplicate:
  214. selection[1:] = text_index[batch_idx][1:] != text_index[batch_idx][:-1]
  215. for ignored_token in ignored_tokens:
  216. selection &= text_index[batch_idx] != ignored_token
  217. char_list = [
  218. self.character[text_id] for text_id in text_index[batch_idx][selection]
  219. ]
  220. if text_prob is not None:
  221. conf_list = text_prob[batch_idx][selection]
  222. else:
  223. conf_list = [1] * len(selection)
  224. if len(conf_list) == 0:
  225. conf_list = [0]
  226. text = "".join(char_list)
  227. if self.reverse: # for arabic rec
  228. text = self.pred_reverse(text)
  229. result_list.append((text, np.mean(conf_list).tolist()))
  230. return result_list
  231. def get_ignored_tokens(self):
  232. """get_ignored_tokens"""
  233. return [0] # for ctc blank
  234. def apply(self, pred):
  235. """apply"""
  236. preds = np.array(pred)
  237. if isinstance(preds, tuple) or isinstance(preds, list):
  238. preds = preds[-1]
  239. preds_idx = preds.argmax(axis=2)
  240. preds_prob = preds.max(axis=2)
  241. text = self.decode(preds_idx, preds_prob, is_remove_duplicate=True)
  242. return [{"rec_text": t[0], "rec_score": t[1]} for t in text]
  243. class CTCLabelDecode(BaseRecLabelDecode):
  244. """Convert between text-label and text-index"""
  245. def __init__(self, character_list=None, use_space_char=True):
  246. super().__init__(character_list, use_space_char=use_space_char)
  247. def apply(self, pred):
  248. """apply"""
  249. preds = np.array(pred[0])
  250. preds_idx = preds.argmax(axis=2)
  251. preds_prob = preds.max(axis=2)
  252. text = self.decode(preds_idx, preds_prob, is_remove_duplicate=True)
  253. return [{"rec_text": t[0], "rec_score": t[1]} for t in text]
  254. def add_special_char(self, character_list):
  255. """add_special_char"""
  256. character_list = ["blank"] + character_list
  257. return character_list
  258. # class LaTeXOCRDecode(object):
  259. # """Convert between latex-symbol and symbol-index"""
  260. # def __init__(self, post_process_cfg=None, **kwargs):
  261. # assert post_process_cfg["name"] == "LaTeXOCRDecode"
  262. # super(LaTeXOCRDecode, self).__init__()
  263. # character_list = post_process_cfg["character_dict"]
  264. # temp_path = tempfile.gettempdir()
  265. # rec_char_dict_path = os.path.join(temp_path, "latexocr_tokenizer.json")
  266. # try:
  267. # with open(rec_char_dict_path, "w") as f:
  268. # json.dump(character_list, f)
  269. # except Exception as e:
  270. # print(f"创建 latexocr_tokenizer.json 文件失败, 原因{str(e)}")
  271. # self.tokenizer = TokenizerFast.from_file(rec_char_dict_path)
  272. # def post_process(self, s):
  273. # text_reg = r"(\\(operatorname|mathrm|text|mathbf)\s?\*? {.*?})"
  274. # letter = "[a-zA-Z]"
  275. # noletter = "[\W_^\d]"
  276. # names = [x[0].replace(" ", "") for x in re.findall(text_reg, s)]
  277. # s = re.sub(text_reg, lambda match: str(names.pop(0)), s)
  278. # news = s
  279. # while True:
  280. # s = news
  281. # news = re.sub(r"(?!\\ )(%s)\s+?(%s)" % (noletter, noletter), r"\1\2", s)
  282. # news = re.sub(r"(?!\\ )(%s)\s+?(%s)" % (noletter, letter), r"\1\2", news)
  283. # news = re.sub(r"(%s)\s+?(%s)" % (letter, noletter), r"\1\2", news)
  284. # if news == s:
  285. # break
  286. # return s
  287. # def decode(self, tokens):
  288. # if len(tokens.shape) == 1:
  289. # tokens = tokens[None, :]
  290. # dec = [self.tokenizer.decode(tok) for tok in tokens]
  291. # dec_str_list = [
  292. # "".join(detok.split(" "))
  293. # .replace("Ġ", " ")
  294. # .replace("[EOS]", "")
  295. # .replace("[BOS]", "")
  296. # .replace("[PAD]", "")
  297. # .strip()
  298. # for detok in dec
  299. # ]
  300. # return [str(self.post_process(dec_str)) for dec_str in dec_str_list]
  301. # def __call__(self, data):
  302. # preds = data[K.REC_PROBS]
  303. # text = self.decode(preds)
  304. # data[K.REC_TEXT] = text[0]
  305. # return data
  306. # class SaveTextRecResults(BaseComponent):
  307. # """SaveTextRecResults"""
  308. # _TEXT_REC_RES_SUFFIX = "_text_rec"
  309. # _FILE_EXT = ".txt"
  310. # def __init__(self, save_dir):
  311. # super().__init__()
  312. # self.save_dir = save_dir
  313. # # We use python backend to save text object
  314. # self._writer = TextWriter(backend="python")
  315. # def apply(self, data):
  316. # """apply"""
  317. # ori_path = data[K.IM_PATH]
  318. # file_name = os.path.basename(ori_path)
  319. # file_name = self._replace_ext(file_name, self._FILE_EXT)
  320. # text_rec_res_save_path = os.path.join(self.save_dir, file_name)
  321. # rec_res = ""
  322. # for text, score in zip(data[K.REC_TEXT], data[K.REC_SCORE]):
  323. # line = text + "\t" + str(score) + "\n"
  324. # rec_res += line
  325. # text_rec_res_save_path = self._add_suffix(
  326. # text_rec_res_save_path, self._TEXT_REC_RES_SUFFIX
  327. # )
  328. # self._write_txt(text_rec_res_save_path, rec_res)
  329. # return data
  330. # @classmethod
  331. # def get_input_keys(cls):
  332. # """get_input_keys"""
  333. # return [K.IM_PATH, K.REC_TEXT, K.REC_SCORE]
  334. # @classmethod
  335. # def get_output_keys(cls):
  336. # """get_output_keys"""
  337. # return []
  338. # def _write_txt(self, path, txt_str):
  339. # """_write_txt"""
  340. # if os.path.exists(path):
  341. # logging.warning(f"{path} already exists. Overwriting it.")
  342. # self._writer.write(path, txt_str)
  343. # @staticmethod
  344. # def _add_suffix(path, suffix):
  345. # """_add_suffix"""
  346. # stem, ext = os.path.splitext(path)
  347. # return stem + suffix + ext
  348. # @staticmethod
  349. # def _replace_ext(path, new_ext):
  350. # """_replace_ext"""
  351. # stem, _ = os.path.splitext(path)
  352. # return stem + new_ext
  353. # class PrintResult(BaseComponent):
  354. # """Print Result Transform"""
  355. # def apply(self, data):
  356. # """apply"""
  357. # logging.info("The prediction result is:")
  358. # logging.info(data[K.REC_TEXT])
  359. # return data
  360. # @classmethod
  361. # def get_input_keys(cls):
  362. # """get input keys"""
  363. # return [K.REC_TEXT]
  364. # @classmethod
  365. # def get_output_keys(cls):
  366. # """get output keys"""
  367. # return []