processors.py 36 KB

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