processors.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. import json
  2. import numpy as np
  3. import cv2
  4. import math
  5. import re
  6. from PIL import Image, ImageOps
  7. from typing import List, Optional, Tuple, Union, Dict, Any
  8. from tokenizers import AddedToken
  9. from tokenizers import Tokenizer as TokenizerFast
  10. class UniMERNetImgDecode(object):
  11. """Class for decoding images for UniMERNet, including cropping margins, resizing, and padding."""
  12. def __init__(
  13. self, input_size: Tuple[int, int], random_padding: bool = False, **kwargs
  14. ) -> None:
  15. """Initializes the UniMERNetImgDecode class with input size and random padding options.
  16. Args:
  17. input_size (tuple): The desired input size for the images (height, width).
  18. random_padding (bool): Whether to use random padding for resizing.
  19. **kwargs: Additional keyword arguments."""
  20. self.input_size = input_size
  21. self.random_padding = random_padding
  22. def crop_margin(self, img: Image.Image) -> Image.Image:
  23. """Crops the margin of the image based on grayscale thresholding.
  24. Args:
  25. img (PIL.Image.Image): The input image.
  26. Returns:
  27. PIL.Image.Image: The cropped image."""
  28. data = np.array(img.convert("L"))
  29. data = data.astype(np.uint8)
  30. max_val = data.max()
  31. min_val = data.min()
  32. if max_val == min_val:
  33. return img
  34. data = (data - min_val) / (max_val - min_val) * 255
  35. gray = 255 * (data < 200).astype(np.uint8)
  36. coords = cv2.findNonZero(gray) # Find all non-zero points (text)
  37. a, b, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box
  38. return img.crop((a, b, w + a, h + b))
  39. def get_dimensions(self, img: Union[Image.Image, np.ndarray]) -> List[int]:
  40. """Gets the dimensions of the image.
  41. Args:
  42. img (PIL.Image.Image or numpy.ndarray): The input image.
  43. Returns:
  44. list: A list containing the number of channels, height, and width."""
  45. if hasattr(img, "getbands"):
  46. channels = len(img.getbands())
  47. else:
  48. channels = img.channels
  49. width, height = img.size
  50. return [channels, height, width]
  51. def _compute_resized_output_size(
  52. self,
  53. image_size: Tuple[int, int],
  54. size: Union[int, Tuple[int, int]],
  55. max_size: Optional[int] = None,
  56. ) -> List[int]:
  57. """Computes the resized output size of the image.
  58. Args:
  59. image_size (tuple): The original size of the image (height, width).
  60. size (int or tuple): The desired size for the smallest edge or both height and width.
  61. max_size (int, optional): The maximum allowed size for the longer edge.
  62. Returns:
  63. list: A list containing the new height and width."""
  64. if len(size) == 1: # specified size only for the smallest edge
  65. h, w = image_size
  66. short, long = (w, h) if w <= h else (h, w)
  67. requested_new_short = size if isinstance(size, int) else size[0]
  68. new_short, new_long = requested_new_short, int(
  69. requested_new_short * long / short
  70. )
  71. if max_size is not None:
  72. if max_size <= requested_new_short:
  73. raise ValueError(
  74. f"max_size = {max_size} must be strictly greater than the requested "
  75. f"size for the smaller edge size = {size}"
  76. )
  77. if new_long > max_size:
  78. new_short, new_long = int(max_size * new_short / new_long), max_size
  79. new_w, new_h = (new_short, new_long) if w <= h else (new_long, new_short)
  80. else: # specified both h and w
  81. new_w, new_h = size[1], size[0]
  82. return [new_h, new_w]
  83. def resize(
  84. self, img: Image.Image, size: Union[int, Tuple[int, int]]
  85. ) -> Image.Image:
  86. """Resizes the image to the specified size.
  87. Args:
  88. img (PIL.Image.Image): The input image.
  89. size (int or tuple): The desired size for the smallest edge or both height and width.
  90. Returns:
  91. PIL.Image.Image: The resized image."""
  92. _, image_height, image_width = self.get_dimensions(img)
  93. if isinstance(size, int):
  94. size = [size]
  95. max_size = None
  96. output_size = self._compute_resized_output_size(
  97. (image_height, image_width), size, max_size
  98. )
  99. img = img.resize(tuple(output_size[::-1]), resample=2)
  100. return img
  101. def img_decode(self, img: np.ndarray) -> Optional[np.ndarray]:
  102. """Decodes the image by cropping margins, resizing, and adding padding.
  103. Args:
  104. img (numpy.ndarray): The input image array.
  105. Returns:
  106. numpy.ndarray: The decoded image array."""
  107. try:
  108. img = self.crop_margin(Image.fromarray(img).convert("RGB"))
  109. except OSError:
  110. return
  111. if img.height == 0 or img.width == 0:
  112. return
  113. img = self.resize(img, min(self.input_size))
  114. img.thumbnail((self.input_size[1], self.input_size[0]))
  115. delta_width = self.input_size[1] - img.width
  116. delta_height = self.input_size[0] - img.height
  117. if self.random_padding:
  118. pad_width = np.random.randint(low=0, high=delta_width + 1)
  119. pad_height = np.random.randint(low=0, high=delta_height + 1)
  120. else:
  121. pad_width = delta_width // 2
  122. pad_height = delta_height // 2
  123. padding = (
  124. pad_width,
  125. pad_height,
  126. delta_width - pad_width,
  127. delta_height - pad_height,
  128. )
  129. return np.array(ImageOps.expand(img, padding))
  130. def __call__(self, imgs: List[np.ndarray]) -> List[Optional[np.ndarray]]:
  131. """Calls the img_decode method on a list of images.
  132. Args:
  133. imgs (list of numpy.ndarray): The list of input image arrays.
  134. Returns:
  135. list of numpy.ndarray: The list of decoded image arrays."""
  136. return [self.img_decode(img) for img in imgs]
  137. class UniMERNetTestTransform:
  138. """
  139. A class for transforming images according to UniMERNet test specifications.
  140. """
  141. def __init__(self, **kwargs) -> None:
  142. """
  143. Initializes the UniMERNetTestTransform class.
  144. """
  145. super().__init__()
  146. self.num_output_channels = 3
  147. def transform(self, img: np.ndarray) -> np.ndarray:
  148. """
  149. Transforms a single image for UniMERNet testing.
  150. Args:
  151. img (numpy.ndarray): The input image.
  152. Returns:
  153. numpy.ndarray: The transformed image.
  154. """
  155. mean = [0.7931, 0.7931, 0.7931]
  156. std = [0.1738, 0.1738, 0.1738]
  157. scale = float(1 / 255.0)
  158. shape = (1, 1, 3)
  159. mean = np.array(mean).reshape(shape).astype("float32")
  160. std = np.array(std).reshape(shape).astype("float32")
  161. img = (img.astype("float32") * scale - mean) / std
  162. grayscale_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  163. squeezed = np.squeeze(grayscale_image)
  164. img = cv2.merge([squeezed] * self.num_output_channels)
  165. return img
  166. def __call__(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
  167. """
  168. Applies the transform to a list of images.
  169. Args:
  170. imgs (list of numpy.ndarray): The list of input images.
  171. Returns:
  172. list of numpy.ndarray: The list of transformed images.
  173. """
  174. return [self.transform(img) for img in imgs]
  175. class LatexImageFormat:
  176. """Class for formatting images to a specific format suitable for LaTeX."""
  177. def __init__(self, **kwargs) -> None:
  178. """Initializes the LatexImageFormat class with optional keyword arguments."""
  179. super().__init__()
  180. def format(self, img: np.ndarray) -> np.ndarray:
  181. """Formats a single image to the LaTeX-compatible format.
  182. Args:
  183. img (numpy.ndarray): The input image as a numpy array.
  184. Returns:
  185. numpy.ndarray: The formatted image as a numpy array with an added dimension for color.
  186. """
  187. im_h, im_w = img.shape[:2]
  188. divide_h = math.ceil(im_h / 16) * 16
  189. divide_w = math.ceil(im_w / 16) * 16
  190. img = img[:, :, 0]
  191. img = np.pad(
  192. img, ((0, divide_h - im_h), (0, divide_w - im_w)), constant_values=(1, 1)
  193. )
  194. img_expanded = img[:, :, np.newaxis].transpose(2, 0, 1)
  195. return img_expanded[np.newaxis, :]
  196. def __call__(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
  197. """Applies the format method to a list of images.
  198. Args:
  199. imgs (list of numpy.ndarray): A list of input images as numpy arrays.
  200. Returns:
  201. list of numpy.ndarray: A list of formatted images as numpy arrays.
  202. """
  203. return [self.format(img) for img in imgs]
  204. class ToBatch(object):
  205. """A class for batching images."""
  206. def __init__(self, **kwargs) -> None:
  207. """Initializes the ToBatch object."""
  208. super(ToBatch, self).__init__()
  209. def __call__(self, imgs: List[np.ndarray]) -> List[np.ndarray]:
  210. """Concatenates a list of images into a single batch.
  211. Args:
  212. imgs (list): A list of image arrays to be concatenated.
  213. Returns:
  214. list: A list containing the concatenated batch of images wrapped in another list (to comply with common batch processing formats).
  215. """
  216. batch_imgs = np.concatenate(imgs)
  217. batch_imgs = batch_imgs.copy()
  218. x = [batch_imgs]
  219. return x
  220. class UniMERNetDecode(object):
  221. """Class for decoding tokenized inputs using UniMERNet tokenizer.
  222. Attributes:
  223. SPECIAL_TOKENS_ATTRIBUTES (List[str]): List of special token attributes.
  224. model_input_names (List[str]): List of model input names.
  225. max_seq_len (int): Maximum sequence length.
  226. pad_token_id (int): ID for the padding token.
  227. bos_token_id (int): ID for the beginning-of-sequence token.
  228. eos_token_id (int): ID for the end-of-sequence token.
  229. padding_side (str): Padding side, either 'left' or 'right'.
  230. pad_token (str): Padding token.
  231. pad_token_type_id (int): Type ID for the padding token.
  232. pad_to_multiple_of (Optional[int]): If set, pad to a multiple of this value.
  233. tokenizer (TokenizerFast): Fast tokenizer instance.
  234. Args:
  235. character_list (Dict[str, Any]): Dictionary containing tokenizer configuration.
  236. **kwargs: Additional keyword arguments.
  237. """
  238. SPECIAL_TOKENS_ATTRIBUTES = [
  239. "bos_token",
  240. "eos_token",
  241. "unk_token",
  242. "sep_token",
  243. "pad_token",
  244. "cls_token",
  245. "mask_token",
  246. "additional_special_tokens",
  247. ]
  248. def __init__(
  249. self,
  250. character_list: Dict[str, Any],
  251. **kwargs,
  252. ) -> None:
  253. """Initializes the UniMERNetDecode class.
  254. Args:
  255. character_list (Dict[str, Any]): Dictionary containing tokenizer configuration.
  256. **kwargs: Additional keyword arguments.
  257. """
  258. self._unk_token = "<unk>"
  259. self._bos_token = "<s>"
  260. self._eos_token = "</s>"
  261. self._pad_token = "<pad>"
  262. self._sep_token = None
  263. self._cls_token = None
  264. self._mask_token = None
  265. self._additional_special_tokens = []
  266. self.model_input_names = ["input_ids", "token_type_ids", "attention_mask"]
  267. self.max_seq_len = 2048
  268. self.pad_token_id = 1
  269. self.bos_token_id = 0
  270. self.eos_token_id = 2
  271. self.padding_side = "right"
  272. self.pad_token_id = 1
  273. self.pad_token = "<pad>"
  274. self.pad_token_type_id = 0
  275. self.pad_to_multiple_of = None
  276. fast_tokenizer_str = json.dumps(character_list["fast_tokenizer_file"])
  277. fast_tokenizer_buffer = fast_tokenizer_str.encode("utf-8")
  278. self.tokenizer = TokenizerFast.from_buffer(fast_tokenizer_buffer)
  279. tokenizer_config = (
  280. character_list["tokenizer_config_file"]
  281. if "tokenizer_config_file" in character_list
  282. else None
  283. )
  284. added_tokens_decoder = {}
  285. added_tokens_map = {}
  286. if tokenizer_config is not None:
  287. init_kwargs = tokenizer_config
  288. if "added_tokens_decoder" in init_kwargs:
  289. for idx, token in init_kwargs["added_tokens_decoder"].items():
  290. if isinstance(token, dict):
  291. token = AddedToken(**token)
  292. if isinstance(token, AddedToken):
  293. added_tokens_decoder[int(idx)] = token
  294. added_tokens_map[str(token)] = token
  295. else:
  296. raise ValueError(
  297. f"Found a {token.__class__} in the saved `added_tokens_decoder`, should be a dictionary or an AddedToken instance"
  298. )
  299. init_kwargs["added_tokens_decoder"] = added_tokens_decoder
  300. added_tokens_decoder = init_kwargs.pop("added_tokens_decoder", {})
  301. tokens_to_add = [
  302. token
  303. for index, token in sorted(
  304. added_tokens_decoder.items(), key=lambda x: x[0]
  305. )
  306. if token not in added_tokens_decoder
  307. ]
  308. added_tokens_encoder = self.added_tokens_encoder(added_tokens_decoder)
  309. encoder = list(added_tokens_encoder.keys()) + [
  310. str(token) for token in tokens_to_add
  311. ]
  312. tokens_to_add += [
  313. token
  314. for token in self.all_special_tokens_extended
  315. if token not in encoder and token not in tokens_to_add
  316. ]
  317. if len(tokens_to_add) > 0:
  318. is_last_special = None
  319. tokens = []
  320. special_tokens = self.all_special_tokens
  321. for token in tokens_to_add:
  322. is_special = (
  323. (token.special or str(token) in special_tokens)
  324. if isinstance(token, AddedToken)
  325. else str(token) in special_tokens
  326. )
  327. if is_last_special is None or is_last_special == is_special:
  328. tokens.append(token)
  329. else:
  330. self._add_tokens(tokens, special_tokens=is_last_special)
  331. tokens = [token]
  332. is_last_special = is_special
  333. if tokens:
  334. self._add_tokens(tokens, special_tokens=is_last_special)
  335. def _add_tokens(
  336. self, new_tokens: "List[Union[AddedToken, str]]", special_tokens: bool = False
  337. ) -> "List[Union[AddedToken, str]]":
  338. """Adds new tokens to the tokenizer.
  339. Args:
  340. new_tokens (List[Union[AddedToken, str]]): Tokens to be added.
  341. special_tokens (bool): Indicates whether the tokens are special tokens.
  342. Returns:
  343. List[Union[AddedToken, str]]: added tokens.
  344. """
  345. if special_tokens:
  346. return self.tokenizer.add_special_tokens(new_tokens)
  347. return self.tokenizer.add_tokens(new_tokens)
  348. def added_tokens_encoder(
  349. self, added_tokens_decoder: "Dict[int, AddedToken]"
  350. ) -> Dict[str, int]:
  351. """Creates an encoder dictionary from added tokens.
  352. Args:
  353. added_tokens_decoder (Dict[int, AddedToken]): Dictionary mapping token IDs to tokens.
  354. Returns:
  355. Dict[str, int]: Dictionary mapping token strings to IDs.
  356. """
  357. return {
  358. k.content: v
  359. for v, k in sorted(added_tokens_decoder.items(), key=lambda item: item[0])
  360. }
  361. @property
  362. def all_special_tokens(self) -> List[str]:
  363. """Retrieves all special tokens.
  364. Returns:
  365. List[str]: List of all special tokens as strings.
  366. """
  367. all_toks = [str(s) for s in self.all_special_tokens_extended]
  368. return all_toks
  369. @property
  370. def all_special_tokens_extended(self) -> "List[Union[str, AddedToken]]":
  371. """Retrieves all special tokens, including extended ones.
  372. Returns:
  373. List[Union[str, AddedToken]]: List of all special tokens.
  374. """
  375. all_tokens = []
  376. seen = set()
  377. for value in self.special_tokens_map_extended.values():
  378. if isinstance(value, (list, tuple)):
  379. tokens_to_add = [token for token in value if str(token) not in seen]
  380. else:
  381. tokens_to_add = [value] if str(value) not in seen else []
  382. seen.update(map(str, tokens_to_add))
  383. all_tokens.extend(tokens_to_add)
  384. return all_tokens
  385. @property
  386. def special_tokens_map_extended(self) -> Dict[str, Union[str, List[str]]]:
  387. """Retrieves the extended map of special tokens.
  388. Returns:
  389. Dict[str, Union[str, List[str]]]: Dictionary mapping special token attributes to their values.
  390. """
  391. set_attr = {}
  392. for attr in self.SPECIAL_TOKENS_ATTRIBUTES:
  393. attr_value = getattr(self, "_" + attr)
  394. if attr_value:
  395. set_attr[attr] = attr_value
  396. return set_attr
  397. def convert_ids_to_tokens(
  398. self, ids: Union[int, List[int]], skip_special_tokens: bool = False
  399. ) -> Union[str, List[str]]:
  400. """Converts token IDs to token strings.
  401. Args:
  402. ids (Union[int, List[int]]): Token ID(s) to convert.
  403. skip_special_tokens (bool): Whether to skip special tokens during conversion.
  404. Returns:
  405. Union[str, List[str]]: Converted token string(s).
  406. """
  407. if isinstance(ids, int):
  408. return self.tokenizer.id_to_token(ids)
  409. tokens = []
  410. for index in ids:
  411. index = int(index)
  412. if skip_special_tokens and index in self.all_special_ids:
  413. continue
  414. tokens.append(self.tokenizer.id_to_token(index))
  415. return tokens
  416. def detokenize(self, tokens: List[List[int]]) -> List[List[str]]:
  417. """Detokenizes a list of token IDs back into strings.
  418. Args:
  419. tokens (List[List[int]]): List of token ID lists.
  420. Returns:
  421. List[List[str]]: List of detokenized strings.
  422. """
  423. self.tokenizer.bos_token = "<s>"
  424. self.tokenizer.eos_token = "</s>"
  425. self.tokenizer.pad_token = "<pad>"
  426. toks = [self.convert_ids_to_tokens(tok) for tok in tokens]
  427. for b in range(len(toks)):
  428. for i in reversed(range(len(toks[b]))):
  429. if toks[b][i] is None:
  430. toks[b][i] = ""
  431. toks[b][i] = toks[b][i].replace("Ġ", " ").strip()
  432. if toks[b][i] in (
  433. [
  434. self.tokenizer.bos_token,
  435. self.tokenizer.eos_token,
  436. self.tokenizer.pad_token,
  437. ]
  438. ):
  439. del toks[b][i]
  440. return toks
  441. def token2str(self, token_ids: List[List[int]]) -> List[str]:
  442. """Converts a list of token IDs to strings.
  443. Args:
  444. token_ids (List[List[int]]): List of token ID lists.
  445. Returns:
  446. List[str]: List of converted strings.
  447. """
  448. generated_text = []
  449. for tok_id in token_ids:
  450. end_idx = np.argwhere(tok_id == 2)
  451. if len(end_idx) > 0:
  452. end_idx = int(end_idx[0][0])
  453. tok_id = tok_id[: end_idx + 1]
  454. generated_text.append(
  455. self.tokenizer.decode(tok_id, skip_special_tokens=True)
  456. )
  457. generated_text = [self.post_process(text) for text in generated_text]
  458. return generated_text
  459. def normalize(self, s: str) -> str:
  460. """Normalizes a string by removing unnecessary spaces.
  461. Args:
  462. s (str): String to normalize.
  463. Returns:
  464. str: Normalized string.
  465. """
  466. text_reg = r"(\\(operatorname|mathrm|text|mathbf)\s?\*? {.*?})"
  467. letter = "[a-zA-Z]"
  468. noletter = r"[\W_^\d]"
  469. names = []
  470. for x in re.findall(text_reg, s):
  471. pattern = r"(\\[a-zA-Z]+)\s(?=\w)|\\[a-zA-Z]+\s(?=})"
  472. matches = re.findall(pattern, x[0])
  473. for m in matches:
  474. if (
  475. m
  476. not in [
  477. "\\operatorname",
  478. "\\mathrm",
  479. "\\text",
  480. "\\mathbf",
  481. ]
  482. and m.strip() != ""
  483. ):
  484. s = s.replace(m, m + "XXXXXXX")
  485. s = s.replace(" ", "")
  486. names.append(s)
  487. if len(names) > 0:
  488. s = re.sub(text_reg, lambda match: str(names.pop(0)), s)
  489. news = s
  490. while True:
  491. s = news
  492. news = re.sub(r"(?!\\ )(%s)\s+?(%s)" % (noletter, noletter), r"\1\2", s)
  493. news = re.sub(r"(?!\\ )(%s)\s+?(%s)" % (noletter, letter), r"\1\2", news)
  494. news = re.sub(r"(%s)\s+?(%s)" % (letter, noletter), r"\1\2", news)
  495. if news == s:
  496. break
  497. return s.replace("XXXXXXX", " ")
  498. def remove_chinese_text_wrapping(self, formula):
  499. pattern = re.compile(r"\\text\s*{\s*([^}]*?[\u4e00-\u9fff]+[^}]*?)\s*}")
  500. def replacer(match):
  501. return match.group(1)
  502. replaced_formula = pattern.sub(replacer, formula)
  503. return replaced_formula.replace('"', "")
  504. def post_process(self, text: str) -> str:
  505. """Post-processes a string by fixing text and normalizing it.
  506. Args:
  507. text (str): String to post-process.
  508. Returns:
  509. str: Post-processed string.
  510. """
  511. from ftfy import fix_text
  512. text = self.remove_chinese_text_wrapping(text)
  513. text = fix_text(text)
  514. text = self.normalize(text)
  515. return text
  516. def __call__(
  517. self,
  518. preds: np.ndarray,
  519. label: Optional[np.ndarray] = None,
  520. mode: str = "eval",
  521. *args,
  522. **kwargs,
  523. ) -> Union[List[str], tuple]:
  524. """Processes predictions and optionally labels, returning the decoded text.
  525. Args:
  526. preds (np.ndarray): Model predictions.
  527. label (Optional[np.ndarray]): True labels, if available.
  528. mode (str): Mode of operation, either 'train' or 'eval'.
  529. Returns:
  530. Union[List[str], tuple]: Decoded text, optionally with labels.
  531. """
  532. if mode == "train":
  533. preds_idx = np.array(preds.argmax(axis=2))
  534. text = self.token2str(preds_idx)
  535. else:
  536. text = self.token2str(np.array(preds))
  537. if label is None:
  538. return text
  539. label = self.token2str(np.array(label))
  540. return text, label