processors.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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, ImageOps, ImageDraw
  19. import cv2
  20. import math
  21. import json
  22. import tempfile
  23. from tokenizers import Tokenizer as TokenizerFast
  24. from tokenizers import AddedToken
  25. from typing import List, Tuple, Optional, Any, Dict, Union
  26. from ....utils import logging
  27. from ...utils.benchmark import benchmark
  28. @benchmark.timeit
  29. class MinMaxResize:
  30. """Class for resizing images to be within specified minimum and maximum dimensions, with padding and normalization."""
  31. def __init__(
  32. self,
  33. min_dimensions: Optional[List[int]] = [32, 32],
  34. max_dimensions: Optional[List[int]] = [672, 192],
  35. **kwargs,
  36. ) -> None:
  37. """Initializes the MinMaxResize class with minimum and maximum dimensions.
  38. Args:
  39. min_dimensions (list of int, optional): Minimum dimensions (width, height). Defaults to [32, 32].
  40. max_dimensions (list of int, optional): Maximum dimensions (width, height). Defaults to [672, 192].
  41. **kwargs: Additional keyword arguments for future expansion.
  42. """
  43. self.min_dimensions = min_dimensions
  44. self.max_dimensions = max_dimensions
  45. def pad_(self, img: Image.Image, divable: int = 32) -> Image.Image:
  46. """Pads the image to ensure its dimensions are divisible by a specified value.
  47. Args:
  48. img (PIL.Image.Image): The input image.
  49. divable (int, optional): The value by which the dimensions should be divisible. Defaults to 32.
  50. Returns:
  51. PIL.Image.Image: The padded image.
  52. """
  53. threshold = 128
  54. data = np.array(img.convert("LA"))
  55. if data[..., -1].var() == 0:
  56. data = (data[..., 0]).astype(np.uint8)
  57. else:
  58. data = (255 - data[..., -1]).astype(np.uint8)
  59. data = (data - data.min()) / (data.max() - data.min()) * 255
  60. if data.mean() > threshold:
  61. # To invert the text to white
  62. gray = 255 * (data < threshold).astype(np.uint8)
  63. else:
  64. gray = 255 * (data > threshold).astype(np.uint8)
  65. data = 255 - data
  66. coords = cv2.findNonZero(gray) # Find all non-zero points (text)
  67. a, b, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box
  68. rect = data[b : b + h, a : a + w]
  69. im = Image.fromarray(rect).convert("L")
  70. dims = []
  71. for x in [w, h]:
  72. div, mod = divmod(x, divable)
  73. dims.append(divable * (div + (1 if mod > 0 else 0)))
  74. padded = Image.new("L", dims, 255)
  75. padded.paste(im, (0, 0, im.size[0], im.size[1]))
  76. return padded
  77. def minmax_size_(
  78. self,
  79. img: Image.Image,
  80. max_dimensions: Optional[List[int]],
  81. min_dimensions: Optional[List[int]],
  82. ) -> Image.Image:
  83. """Resizes the image to be within the specified minimum and maximum dimensions.
  84. Args:
  85. img (PIL.Image.Image): The input image.
  86. max_dimensions (list of int or None): Maximum dimensions (width, height).
  87. min_dimensions (list of int or None): Minimum dimensions (width, height).
  88. Returns:
  89. PIL.Image.Image: The resized image.
  90. """
  91. if max_dimensions is not None:
  92. ratios = [a / b for a, b in zip(img.size, max_dimensions)]
  93. if any([r > 1 for r in ratios]):
  94. size = np.array(img.size) // max(ratios)
  95. img = img.resize(tuple(size.astype(int)), Image.BILINEAR)
  96. if min_dimensions is not None:
  97. # hypothesis: there is a dim in img smaller than min_dimensions, and return a proper dim >= min_dimensions
  98. padded_size = [
  99. max(img_dim, min_dim)
  100. for img_dim, min_dim in zip(img.size, min_dimensions)
  101. ]
  102. if padded_size != list(img.size): # assert hypothesis
  103. padded_im = Image.new("L", padded_size, 255)
  104. padded_im.paste(img, img.getbbox())
  105. img = padded_im
  106. return img
  107. def resize(self, img: np.ndarray) -> np.ndarray:
  108. """Resizes the input image according to the specified minimum and maximum dimensions.
  109. Args:
  110. img (np.ndarray): The input image as a numpy array.
  111. Returns:
  112. np.ndarray: The resized image as a numpy array with three channels.
  113. """
  114. h, w = img.shape[:2]
  115. if (
  116. self.min_dimensions[0] <= w <= self.max_dimensions[0]
  117. and self.min_dimensions[1] <= h <= self.max_dimensions[1]
  118. ):
  119. return img
  120. else:
  121. img = Image.fromarray(np.uint8(img))
  122. img = self.minmax_size_(
  123. self.pad_(img), self.max_dimensions, self.min_dimensions
  124. )
  125. img = np.array(img)
  126. img = np.dstack((img, img, img))
  127. return img
  128. def __call__(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
  129. """Applies the resize method to a list of images.
  130. Args:
  131. imgs (list of np.ndarray): The list of input images as numpy arrays.
  132. Returns:
  133. list of np.ndarray: The list of resized images as numpy arrays with three channels.
  134. """
  135. return [self.resize(img) for img in imgs]
  136. @benchmark.timeit
  137. class LatexTestTransform:
  138. """
  139. A transform class for processing images according to Latex test requirements.
  140. """
  141. def __init__(self, **kwargs) -> None:
  142. """
  143. Initialize the transform with default number of output channels.
  144. """
  145. super().__init__()
  146. self.num_output_channels = 3
  147. def transform(self, img: np.ndarray) -> np.ndarray:
  148. """
  149. Convert the input image to grayscale, squeeze it, and merge to create an output
  150. image with the specified number of output channels.
  151. Parameters:
  152. img (np.array): The input image.
  153. Returns:
  154. np.array: The transformed image.
  155. """
  156. grayscale_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  157. squeezed = np.squeeze(grayscale_image)
  158. return cv2.merge([squeezed] * self.num_output_channels)
  159. def __call__(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
  160. """
  161. Apply the transform to a list of images.
  162. Parameters:
  163. imgs (list of np.array): The list of input images.
  164. Returns:
  165. list of np.array: The list of transformed images.
  166. """
  167. return [self.transform(img) for img in imgs]
  168. @benchmark.timeit
  169. class LatexImageFormat:
  170. """Class for formatting images to a specific format suitable for LaTeX."""
  171. def __init__(self, **kwargs) -> None:
  172. """Initializes the LatexImageFormat class with optional keyword arguments."""
  173. super().__init__()
  174. def format(self, img: np.ndarray) -> np.ndarray:
  175. """Formats a single image to the LaTeX-compatible format.
  176. Args:
  177. img (numpy.ndarray): The input image as a numpy array.
  178. Returns:
  179. numpy.ndarray: The formatted image as a numpy array with an added dimension for color.
  180. """
  181. im_h, im_w = img.shape[:2]
  182. divide_h = math.ceil(im_h / 16) * 16
  183. divide_w = math.ceil(im_w / 16) * 16
  184. img = img[:, :, 0]
  185. img = np.pad(
  186. img, ((0, divide_h - im_h), (0, divide_w - im_w)), constant_values=(1, 1)
  187. )
  188. img_expanded = img[:, :, np.newaxis].transpose(2, 0, 1)
  189. return img_expanded[np.newaxis, :]
  190. def __call__(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
  191. """Applies the format method to a list of images.
  192. Args:
  193. imgs (list of numpy.ndarray): A list of input images as numpy arrays.
  194. Returns:
  195. list of numpy.ndarray: A list of formatted images as numpy arrays.
  196. """
  197. return [self.format(img) for img in imgs]
  198. @benchmark.timeit
  199. class NormalizeImage(object):
  200. """Normalize an image by subtracting the mean and dividing by the standard deviation.
  201. Args:
  202. scale (float or str): The scale factor to apply to the image. If a string is provided, it will be evaluated as a Python expression.
  203. mean (list of float): The mean values to subtract from each channel. Defaults to [0.485, 0.456, 0.406].
  204. std (list of float): The standard deviation values to divide by for each channel. Defaults to [0.229, 0.224, 0.225].
  205. order (str): The order of dimensions for the mean and std. 'chw' for channels-height-width, 'hwc' for height-width-channels. Defaults to 'chw'.
  206. **kwargs: Additional keyword arguments that may be used by subclasses.
  207. Attributes:
  208. scale (float): The scale factor applied to the image.
  209. mean (numpy.ndarray): The mean values reshaped according to the specified order.
  210. std (numpy.ndarray): The standard deviation values reshaped according to the specified order.
  211. """
  212. def __init__(
  213. self,
  214. scale: Optional[Union[float, str]] = None,
  215. mean: Optional[List[float]] = None,
  216. std: Optional[List[float]] = None,
  217. order: str = "chw",
  218. **kwargs,
  219. ) -> None:
  220. if isinstance(scale, str):
  221. scale = eval(scale)
  222. self.scale = np.float32(scale if scale is not None else 1.0 / 255.0)
  223. mean = mean if mean is not None else [0.485, 0.456, 0.406]
  224. std = std if std is not None else [0.229, 0.224, 0.225]
  225. shape = (3, 1, 1) if order == "chw" else (1, 1, 3)
  226. self.mean = np.array(mean).reshape(shape).astype("float32")
  227. self.std = np.array(std).reshape(shape).astype("float32")
  228. def normalize(self, img: Union[np.ndarray, Image.Image]) -> np.ndarray:
  229. from PIL import Image
  230. if isinstance(img, Image.Image):
  231. img = np.array(img)
  232. assert isinstance(img, np.ndarray), "invalid input 'img' in NormalizeImage"
  233. img = (img.astype("float32") * self.scale - self.mean) / self.std
  234. return img
  235. def __call__(self, imgs: List[Union[np.ndarray, Image.Image]]) -> List[np.ndarray]:
  236. """Apply normalization to a list of images."""
  237. return [self.normalize(img) for img in imgs]
  238. @benchmark.timeit
  239. class ToBatch(object):
  240. """A class for batching images."""
  241. def __init__(self, **kwargs) -> None:
  242. """Initializes the ToBatch object."""
  243. super(ToBatch, self).__init__()
  244. def __call__(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
  245. """Concatenates a list of images into a single batch.
  246. Args:
  247. imgs (list): A list of image arrays to be concatenated.
  248. Returns:
  249. list: A list containing the concatenated batch of images wrapped in another list (to comply with common batch processing formats).
  250. """
  251. batch_imgs = np.concatenate(imgs)
  252. batch_imgs = batch_imgs.copy()
  253. x = [batch_imgs]
  254. return x
  255. @benchmark.timeit
  256. class LaTeXOCRDecode(object):
  257. """Class for decoding LaTeX OCR tokens based on a provided character list."""
  258. def __init__(self, character_list: List[str], **kwargs) -> None:
  259. """Initializes the LaTeXOCRDecode object.
  260. Args:
  261. character_list (list): The list of characters to use for tokenization.
  262. **kwargs: Additional keyword arguments for initialization.
  263. """
  264. from tokenizers import Tokenizer as TokenizerFast
  265. super(LaTeXOCRDecode, self).__init__()
  266. temp_path = tempfile.gettempdir()
  267. rec_char_dict_path = os.path.join(temp_path, "latexocr_tokenizer.json")
  268. try:
  269. with open(rec_char_dict_path, "w") as f:
  270. json.dump(character_list, f)
  271. except Exception as e:
  272. print(f"创建 latexocr_tokenizer.json 文件失败, 原因{str(e)}")
  273. self.tokenizer = TokenizerFast.from_file(rec_char_dict_path)
  274. def post_process(self, s: str) -> str:
  275. """Post-processes the decoded LaTeX string.
  276. Args:
  277. s (str): The decoded LaTeX string to post-process.
  278. Returns:
  279. str: The post-processed LaTeX string.
  280. """
  281. text_reg = r"(\\(operatorname|mathrm|text|mathbf)\s?\*? {.*?})"
  282. letter = "[a-zA-Z]"
  283. noletter = "[\W_^\d]"
  284. names = [x[0].replace(" ", "") for x in re.findall(text_reg, s)]
  285. s = re.sub(text_reg, lambda match: str(names.pop(0)), s)
  286. news = s
  287. while True:
  288. s = news
  289. news = re.sub(r"(?!\\ )(%s)\s+?(%s)" % (noletter, noletter), r"\1\2", s)
  290. news = re.sub(r"(?!\\ )(%s)\s+?(%s)" % (noletter, letter), r"\1\2", news)
  291. news = re.sub(r"(%s)\s+?(%s)" % (letter, noletter), r"\1\2", news)
  292. if news == s:
  293. break
  294. return s
  295. def decode(self, tokens: np.ndarray) -> List[str]:
  296. """Decodes the provided tokens into LaTeX strings.
  297. Args:
  298. tokens (np.array): The tokens to decode.
  299. Returns:
  300. list: The decoded LaTeX strings.
  301. """
  302. if len(tokens.shape) == 1:
  303. tokens = tokens[None, :]
  304. dec = [self.tokenizer.decode(tok) for tok in tokens]
  305. dec_str_list = [
  306. "".join(detok.split(" "))
  307. .replace("Ġ", " ")
  308. .replace("[EOS]", "")
  309. .replace("[BOS]", "")
  310. .replace("[PAD]", "")
  311. .strip()
  312. for detok in dec
  313. ]
  314. return [self.post_process(dec_str) for dec_str in dec_str_list]
  315. def __call__(
  316. self,
  317. preds: np.ndarray,
  318. label: Optional[np.ndarray] = None,
  319. mode: str = "eval",
  320. *args,
  321. **kwargs,
  322. ) -> Tuple[List[str], List[str]]:
  323. """Calls the object with the provided predictions and label.
  324. Args:
  325. preds (np.array): The predictions to decode.
  326. label (np.array, optional): The labels to decode. Defaults to None.
  327. mode (str): The mode to run in, either 'train' or 'eval'. Defaults to 'eval'.
  328. *args: Positional arguments to pass.
  329. **kwargs: Keyword arguments to pass.
  330. Returns:
  331. tuple or list: The decoded text and optionally the decoded label.
  332. """
  333. if mode == "train":
  334. preds_idx = np.array(preds.argmax(axis=2))
  335. text = self.decode(preds_idx)
  336. else:
  337. text = self.decode(np.array(preds))
  338. if label is None:
  339. return text
  340. label = self.decode(np.array(label))
  341. return text, label
  342. @benchmark.timeit
  343. class UniMERNetImgDecode(object):
  344. """Class for decoding images for UniMERNet, including cropping margins, resizing, and padding."""
  345. def __init__(
  346. self, input_size: Tuple[int, int], random_padding: bool = False, **kwargs
  347. ) -> None:
  348. """Initializes the UniMERNetImgDecode class with input size and random padding options.
  349. Args:
  350. input_size (tuple): The desired input size for the images (height, width).
  351. random_padding (bool): Whether to use random padding for resizing.
  352. **kwargs: Additional keyword arguments."""
  353. self.input_size = input_size
  354. self.random_padding = random_padding
  355. def crop_margin(self, img: Image.Image) -> Image.Image:
  356. """Crops the margin of the image based on grayscale thresholding.
  357. Args:
  358. img (PIL.Image.Image): The input image.
  359. Returns:
  360. PIL.Image.Image: The cropped image."""
  361. data = np.array(img.convert("L"))
  362. data = data.astype(np.uint8)
  363. max_val = data.max()
  364. min_val = data.min()
  365. if max_val == min_val:
  366. return img
  367. data = (data - min_val) / (max_val - min_val) * 255
  368. gray = 255 * (data < 200).astype(np.uint8)
  369. coords = cv2.findNonZero(gray) # Find all non-zero points (text)
  370. a, b, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box
  371. return img.crop((a, b, w + a, h + b))
  372. def get_dimensions(self, img: Union[Image.Image, np.ndarray]) -> List[int]:
  373. """Gets the dimensions of the image.
  374. Args:
  375. img (PIL.Image.Image or numpy.ndarray): The input image.
  376. Returns:
  377. list: A list containing the number of channels, height, and width."""
  378. if hasattr(img, "getbands"):
  379. channels = len(img.getbands())
  380. else:
  381. channels = img.channels
  382. width, height = img.size
  383. return [channels, height, width]
  384. def _compute_resized_output_size(
  385. self,
  386. image_size: Tuple[int, int],
  387. size: Union[int, Tuple[int, int]],
  388. max_size: Optional[int] = None,
  389. ) -> List[int]:
  390. """Computes the resized output size of the image.
  391. Args:
  392. image_size (tuple): The original size of the image (height, width).
  393. size (int or tuple): The desired size for the smallest edge or both height and width.
  394. max_size (int, optional): The maximum allowed size for the longer edge.
  395. Returns:
  396. list: A list containing the new height and width."""
  397. if len(size) == 1: # specified size only for the smallest edge
  398. h, w = image_size
  399. short, long = (w, h) if w <= h else (h, w)
  400. requested_new_short = size if isinstance(size, int) else size[0]
  401. new_short, new_long = requested_new_short, int(
  402. requested_new_short * long / short
  403. )
  404. if max_size is not None:
  405. if max_size <= requested_new_short:
  406. raise ValueError(
  407. f"max_size = {max_size} must be strictly greater than the requested "
  408. f"size for the smaller edge size = {size}"
  409. )
  410. if new_long > max_size:
  411. new_short, new_long = int(max_size * new_short / new_long), max_size
  412. new_w, new_h = (new_short, new_long) if w <= h else (new_long, new_short)
  413. else: # specified both h and w
  414. new_w, new_h = size[1], size[0]
  415. return [new_h, new_w]
  416. def resize(
  417. self, img: Image.Image, size: Union[int, Tuple[int, int]]
  418. ) -> Image.Image:
  419. """Resizes the image to the specified size.
  420. Args:
  421. img (PIL.Image.Image): The input image.
  422. size (int or tuple): The desired size for the smallest edge or both height and width.
  423. Returns:
  424. PIL.Image.Image: The resized image."""
  425. _, image_height, image_width = self.get_dimensions(img)
  426. if isinstance(size, int):
  427. size = [size]
  428. max_size = None
  429. output_size = self._compute_resized_output_size(
  430. (image_height, image_width), size, max_size
  431. )
  432. img = img.resize(tuple(output_size[::-1]), resample=2)
  433. return img
  434. def img_decode(self, img: np.ndarray) -> Optional[np.ndarray]:
  435. """Decodes the image by cropping margins, resizing, and adding padding.
  436. Args:
  437. img (numpy.ndarray): The input image array.
  438. Returns:
  439. numpy.ndarray: The decoded image array."""
  440. try:
  441. img = self.crop_margin(Image.fromarray(img).convert("RGB"))
  442. except OSError:
  443. return
  444. if img.height == 0 or img.width == 0:
  445. return
  446. img = self.resize(img, min(self.input_size))
  447. img.thumbnail((self.input_size[1], self.input_size[0]))
  448. delta_width = self.input_size[1] - img.width
  449. delta_height = self.input_size[0] - img.height
  450. if self.random_padding:
  451. pad_width = np.random.randint(low=0, high=delta_width + 1)
  452. pad_height = np.random.randint(low=0, high=delta_height + 1)
  453. else:
  454. pad_width = delta_width // 2
  455. pad_height = delta_height // 2
  456. padding = (
  457. pad_width,
  458. pad_height,
  459. delta_width - pad_width,
  460. delta_height - pad_height,
  461. )
  462. return np.array(ImageOps.expand(img, padding))
  463. def __call__(self, imgs: List[np.ndarray]) -> List[Optional[np.ndarray]]:
  464. """Calls the img_decode method on a list of images.
  465. Args:
  466. imgs (list of numpy.ndarray): The list of input image arrays.
  467. Returns:
  468. list of numpy.ndarray: The list of decoded image arrays."""
  469. return [self.img_decode(img) for img in imgs]
  470. @benchmark.timeit
  471. class UniMERNetDecode(object):
  472. """Class for decoding tokenized inputs using UniMERNet tokenizer.
  473. Attributes:
  474. SPECIAL_TOKENS_ATTRIBUTES (List[str]): List of special token attributes.
  475. model_input_names (List[str]): List of model input names.
  476. max_seq_len (int): Maximum sequence length.
  477. pad_token_id (int): ID for the padding token.
  478. bos_token_id (int): ID for the beginning-of-sequence token.
  479. eos_token_id (int): ID for the end-of-sequence token.
  480. padding_side (str): Padding side, either 'left' or 'right'.
  481. pad_token (str): Padding token.
  482. pad_token_type_id (int): Type ID for the padding token.
  483. pad_to_multiple_of (Optional[int]): If set, pad to a multiple of this value.
  484. tokenizer (TokenizerFast): Fast tokenizer instance.
  485. Args:
  486. character_list (Dict[str, Any]): Dictionary containing tokenizer configuration.
  487. **kwargs: Additional keyword arguments.
  488. """
  489. SPECIAL_TOKENS_ATTRIBUTES = [
  490. "bos_token",
  491. "eos_token",
  492. "unk_token",
  493. "sep_token",
  494. "pad_token",
  495. "cls_token",
  496. "mask_token",
  497. "additional_special_tokens",
  498. ]
  499. def __init__(
  500. self,
  501. character_list: Dict[str, Any],
  502. **kwargs,
  503. ) -> None:
  504. """Initializes the UniMERNetDecode class.
  505. Args:
  506. character_list (Dict[str, Any]): Dictionary containing tokenizer configuration.
  507. **kwargs: Additional keyword arguments.
  508. """
  509. self._unk_token = "<unk>"
  510. self._bos_token = "<s>"
  511. self._eos_token = "</s>"
  512. self._pad_token = "<pad>"
  513. self._sep_token = None
  514. self._cls_token = None
  515. self._mask_token = None
  516. self._additional_special_tokens = []
  517. self.model_input_names = ["input_ids", "token_type_ids", "attention_mask"]
  518. self.max_seq_len = 2048
  519. self.pad_token_id = 1
  520. self.bos_token_id = 0
  521. self.eos_token_id = 2
  522. self.padding_side = "right"
  523. self.pad_token_id = 1
  524. self.pad_token = "<pad>"
  525. self.pad_token_type_id = 0
  526. self.pad_to_multiple_of = None
  527. temp_path = tempfile.gettempdir()
  528. fast_tokenizer_file = os.path.join(temp_path, "tokenizer.json")
  529. tokenizer_config_file = os.path.join(temp_path, "tokenizer_config.json")
  530. try:
  531. with open(fast_tokenizer_file, "w") as f:
  532. json.dump(character_list["fast_tokenizer_file"], f)
  533. with open(tokenizer_config_file, "w") as f:
  534. json.dump(character_list["tokenizer_config_file"], f)
  535. except Exception as e:
  536. print(
  537. f"创建 tokenizer.json 和 tokenizer_config.json 文件失败, 原因{str(e)}"
  538. )
  539. self.tokenizer = TokenizerFast.from_file(fast_tokenizer_file)
  540. added_tokens_decoder = {}
  541. added_tokens_map = {}
  542. if tokenizer_config_file is not None:
  543. with open(
  544. tokenizer_config_file, encoding="utf-8"
  545. ) as tokenizer_config_handle:
  546. init_kwargs = json.load(tokenizer_config_handle)
  547. if "added_tokens_decoder" in init_kwargs:
  548. for idx, token in init_kwargs["added_tokens_decoder"].items():
  549. if isinstance(token, dict):
  550. token = AddedToken(**token)
  551. if isinstance(token, AddedToken):
  552. added_tokens_decoder[int(idx)] = token
  553. added_tokens_map[str(token)] = token
  554. else:
  555. raise ValueError(
  556. f"Found a {token.__class__} in the saved `added_tokens_decoder`, should be a dictionary or an AddedToken instance"
  557. )
  558. init_kwargs["added_tokens_decoder"] = added_tokens_decoder
  559. added_tokens_decoder = init_kwargs.pop("added_tokens_decoder", {})
  560. tokens_to_add = [
  561. token
  562. for index, token in sorted(
  563. added_tokens_decoder.items(), key=lambda x: x[0]
  564. )
  565. if token not in added_tokens_decoder
  566. ]
  567. added_tokens_encoder = self.added_tokens_encoder(added_tokens_decoder)
  568. encoder = list(added_tokens_encoder.keys()) + [
  569. str(token) for token in tokens_to_add
  570. ]
  571. tokens_to_add += [
  572. token
  573. for token in self.all_special_tokens_extended
  574. if token not in encoder and token not in tokens_to_add
  575. ]
  576. if len(tokens_to_add) > 0:
  577. is_last_special = None
  578. tokens = []
  579. special_tokens = self.all_special_tokens
  580. for token in tokens_to_add:
  581. is_special = (
  582. (token.special or str(token) in special_tokens)
  583. if isinstance(token, AddedToken)
  584. else str(token) in special_tokens
  585. )
  586. if is_last_special is None or is_last_special == is_special:
  587. tokens.append(token)
  588. else:
  589. self._add_tokens(tokens, special_tokens=is_last_special)
  590. tokens = [token]
  591. is_last_special = is_special
  592. if tokens:
  593. self._add_tokens(tokens, special_tokens=is_last_special)
  594. def _add_tokens(
  595. self, new_tokens: List[Union[AddedToken, str]], special_tokens: bool = False
  596. ) -> List[Union[AddedToken, str]]:
  597. """Adds new tokens to the tokenizer.
  598. Args:
  599. new_tokens (List[Union[AddedToken, str]]): Tokens to be added.
  600. special_tokens (bool): Indicates whether the tokens are special tokens.
  601. Returns:
  602. List[Union[AddedToken, str]]: added tokens.
  603. """
  604. if special_tokens:
  605. return self.tokenizer.add_special_tokens(new_tokens)
  606. return self.tokenizer.add_tokens(new_tokens)
  607. def added_tokens_encoder(
  608. self, added_tokens_decoder: Dict[int, AddedToken]
  609. ) -> Dict[str, int]:
  610. """Creates an encoder dictionary from added tokens.
  611. Args:
  612. added_tokens_decoder (Dict[int, AddedToken]): Dictionary mapping token IDs to tokens.
  613. Returns:
  614. Dict[str, int]: Dictionary mapping token strings to IDs.
  615. """
  616. return {
  617. k.content: v
  618. for v, k in sorted(added_tokens_decoder.items(), key=lambda item: item[0])
  619. }
  620. @property
  621. def all_special_tokens(self) -> List[str]:
  622. """Retrieves all special tokens.
  623. Returns:
  624. List[str]: List of all special tokens as strings.
  625. """
  626. all_toks = [str(s) for s in self.all_special_tokens_extended]
  627. return all_toks
  628. @property
  629. def all_special_tokens_extended(self) -> List[Union[str, AddedToken]]:
  630. """Retrieves all special tokens, including extended ones.
  631. Returns:
  632. List[Union[str, AddedToken]]: List of all special tokens.
  633. """
  634. all_tokens = []
  635. seen = set()
  636. for value in self.special_tokens_map_extended.values():
  637. if isinstance(value, (list, tuple)):
  638. tokens_to_add = [token for token in value if str(token) not in seen]
  639. else:
  640. tokens_to_add = [value] if str(value) not in seen else []
  641. seen.update(map(str, tokens_to_add))
  642. all_tokens.extend(tokens_to_add)
  643. return all_tokens
  644. @property
  645. def special_tokens_map_extended(self) -> Dict[str, Union[str, List[str]]]:
  646. """Retrieves the extended map of special tokens.
  647. Returns:
  648. Dict[str, Union[str, List[str]]]: Dictionary mapping special token attributes to their values.
  649. """
  650. set_attr = {}
  651. for attr in self.SPECIAL_TOKENS_ATTRIBUTES:
  652. attr_value = getattr(self, "_" + attr)
  653. if attr_value:
  654. set_attr[attr] = attr_value
  655. return set_attr
  656. def convert_ids_to_tokens(
  657. self, ids: Union[int, List[int]], skip_special_tokens: bool = False
  658. ) -> Union[str, List[str]]:
  659. """Converts token IDs to token strings.
  660. Args:
  661. ids (Union[int, List[int]]): Token ID(s) to convert.
  662. skip_special_tokens (bool): Whether to skip special tokens during conversion.
  663. Returns:
  664. Union[str, List[str]]: Converted token string(s).
  665. """
  666. if isinstance(ids, int):
  667. return self.tokenizer.id_to_token(ids)
  668. tokens = []
  669. for index in ids:
  670. index = int(index)
  671. if skip_special_tokens and index in self.all_special_ids:
  672. continue
  673. tokens.append(self.tokenizer.id_to_token(index))
  674. return tokens
  675. def detokenize(self, tokens: List[List[int]]) -> List[List[str]]:
  676. """Detokenizes a list of token IDs back into strings.
  677. Args:
  678. tokens (List[List[int]]): List of token ID lists.
  679. Returns:
  680. List[List[str]]: List of detokenized strings.
  681. """
  682. self.tokenizer.bos_token = "<s>"
  683. self.tokenizer.eos_token = "</s>"
  684. self.tokenizer.pad_token = "<pad>"
  685. toks = [self.convert_ids_to_tokens(tok) for tok in tokens]
  686. for b in range(len(toks)):
  687. for i in reversed(range(len(toks[b]))):
  688. if toks[b][i] is None:
  689. toks[b][i] = ""
  690. toks[b][i] = toks[b][i].replace("Ġ", " ").strip()
  691. if toks[b][i] in (
  692. [
  693. self.tokenizer.bos_token,
  694. self.tokenizer.eos_token,
  695. self.tokenizer.pad_token,
  696. ]
  697. ):
  698. del toks[b][i]
  699. return toks
  700. def token2str(self, token_ids: List[List[int]]) -> List[str]:
  701. """Converts a list of token IDs to strings.
  702. Args:
  703. token_ids (List[List[int]]): List of token ID lists.
  704. Returns:
  705. List[str]: List of converted strings.
  706. """
  707. generated_text = []
  708. for tok_id in token_ids:
  709. end_idx = np.argwhere(tok_id == 2)
  710. if len(end_idx) > 0:
  711. end_idx = int(end_idx[0][0])
  712. tok_id = tok_id[: end_idx + 1]
  713. generated_text.append(
  714. self.tokenizer.decode(tok_id, skip_special_tokens=True)
  715. )
  716. generated_text = [self.post_process(text) for text in generated_text]
  717. return generated_text
  718. def normalize(self, s: str) -> str:
  719. """Normalizes a string by removing unnecessary spaces.
  720. Args:
  721. s (str): String to normalize.
  722. Returns:
  723. str: Normalized string.
  724. """
  725. text_reg = r"(\\(operatorname|mathrm|text|mathbf)\s?\*? {.*?})"
  726. letter = "[a-zA-Z]"
  727. noletter = "[\W_^\d]"
  728. names = [x[0].replace(" ", "") for x in re.findall(text_reg, s)]
  729. s = re.sub(text_reg, lambda match: str(names.pop(0)), s)
  730. news = s
  731. while True:
  732. s = news
  733. news = re.sub(r"(?!\\ )(%s)\s+?(%s)" % (noletter, noletter), r"\1\2", s)
  734. news = re.sub(r"(?!\\ )(%s)\s+?(%s)" % (noletter, letter), r"\1\2", news)
  735. news = re.sub(r"(%s)\s+?(%s)" % (letter, noletter), r"\1\2", news)
  736. if news == s:
  737. break
  738. return s
  739. def post_process(self, text: str) -> str:
  740. """Post-processes a string by fixing text and normalizing it.
  741. Args:
  742. text (str): String to post-process.
  743. Returns:
  744. str: Post-processed string.
  745. """
  746. from ftfy import fix_text
  747. text = fix_text(text)
  748. text = self.normalize(text)
  749. return text
  750. def __call__(
  751. self,
  752. preds: np.ndarray,
  753. label: Optional[np.ndarray] = None,
  754. mode: str = "eval",
  755. *args,
  756. **kwargs,
  757. ) -> Union[List[str], tuple]:
  758. """Processes predictions and optionally labels, returning the decoded text.
  759. Args:
  760. preds (np.ndarray): Model predictions.
  761. label (Optional[np.ndarray]): True labels, if available.
  762. mode (str): Mode of operation, either 'train' or 'eval'.
  763. Returns:
  764. Union[List[str], tuple]: Decoded text, optionally with labels.
  765. """
  766. if mode == "train":
  767. preds_idx = np.array(preds.argmax(axis=2))
  768. text = self.token2str(preds_idx)
  769. else:
  770. text = self.token2str(np.array(preds))
  771. if label is None:
  772. return text
  773. label = self.token2str(np.array(label))
  774. return text, label
  775. @benchmark.timeit
  776. class UniMERNetTestTransform:
  777. """
  778. A class for transforming images according to UniMERNet test specifications.
  779. """
  780. def __init__(self, **kwargs) -> None:
  781. """
  782. Initializes the UniMERNetTestTransform class.
  783. """
  784. super().__init__()
  785. self.num_output_channels = 3
  786. def transform(self, img: np.ndarray) -> np.ndarray:
  787. """
  788. Transforms a single image for UniMERNet testing.
  789. Args:
  790. img (numpy.ndarray): The input image.
  791. Returns:
  792. numpy.ndarray: The transformed image.
  793. """
  794. mean = [0.7931, 0.7931, 0.7931]
  795. std = [0.1738, 0.1738, 0.1738]
  796. scale = float(1 / 255.0)
  797. shape = (1, 1, 3)
  798. mean = np.array(mean).reshape(shape).astype("float32")
  799. std = np.array(std).reshape(shape).astype("float32")
  800. img = (img.astype("float32") * scale - mean) / std
  801. grayscale_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  802. squeezed = np.squeeze(grayscale_image)
  803. img = cv2.merge([squeezed] * self.num_output_channels)
  804. return img
  805. def __call__(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
  806. """
  807. Applies the transform to a list of images.
  808. Args:
  809. imgs (list of numpy.ndarray): The list of input images.
  810. Returns:
  811. list of numpy.ndarray: The list of transformed images.
  812. """
  813. return [self.transform(img) for img in imgs]
  814. @benchmark.timeit
  815. class UniMERNetImageFormat:
  816. """Class for formatting images to UniMERNet's required format."""
  817. def __init__(self, **kwargs) -> None:
  818. """Initializes the UniMERNetImageFormat instance."""
  819. # your init code
  820. pass
  821. def format(self, img: np.ndarray) -> np.ndarray:
  822. """Formats a single image to UniMERNet's required format.
  823. Args:
  824. img (numpy.ndarray): The input image to be formatted.
  825. Returns:
  826. numpy.ndarray: The formatted image.
  827. """
  828. im_h, im_w = img.shape[:2]
  829. divide_h = math.ceil(im_h / 32) * 32
  830. divide_w = math.ceil(im_w / 32) * 32
  831. img = img[:, :, 0]
  832. img = np.pad(
  833. img, ((0, divide_h - im_h), (0, divide_w - im_w)), constant_values=(1, 1)
  834. )
  835. img_expanded = img[:, :, np.newaxis].transpose(2, 0, 1)
  836. return img_expanded[np.newaxis, :]
  837. def __call__(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
  838. """Applies the format method to a list of images.
  839. Args:
  840. imgs (list of numpy.ndarray): The list of input images to be formatted.
  841. Returns:
  842. list of numpy.ndarray: The list of formatted images.
  843. """
  844. return [self.format(img) for img in imgs]