result.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import copy
  15. import math
  16. import os
  17. import re
  18. import subprocess
  19. import tempfile
  20. from pathlib import Path
  21. from typing import List, Optional
  22. import numpy as np
  23. import PIL
  24. from PIL import Image, ImageDraw, ImageFont
  25. from ....utils import logging
  26. from ....utils.deps import function_requires_deps, is_dep_available
  27. from ....utils.file_interface import custom_open
  28. from ....utils.fonts import PINGFANG_FONT_FILE_PATH
  29. from ...common.result import BaseCVResult, JsonMixin
  30. if is_dep_available("opencv-contrib-python"):
  31. import cv2
  32. if is_dep_available("pypdfium2"):
  33. import pypdfium2 as pdfium
  34. class FormulaRecResult(BaseCVResult):
  35. def _get_input_fn(self):
  36. fn = super()._get_input_fn()
  37. if (page_idx := self["page_index"]) is not None:
  38. fp = Path(fn)
  39. stem, suffix = fp.stem, fp.suffix
  40. return f"{stem}_{page_idx}{suffix}"
  41. else:
  42. return fn
  43. def _to_str(self, *args, **kwargs):
  44. data = copy.deepcopy(self)
  45. data.pop("input_img")
  46. _str = JsonMixin._to_str(data, *args, **kwargs)["res"]
  47. return {"res": _str}
  48. def _to_json(self, *args, **kwargs):
  49. data = copy.deepcopy(self)
  50. data.pop("input_img")
  51. return JsonMixin._to_json(data, *args, **kwargs)
  52. def _to_img(
  53. self,
  54. ) -> Image.Image:
  55. """
  56. Draws a recognized formula on an image.
  57. This method processes an input image to recognize and render a LaTeX formula.
  58. It overlays the rendered formula onto the input image and returns the combined image.
  59. If the LaTeX rendering engine is not installed or a syntax error is detected,
  60. it logs a warning and returns the original image.
  61. Returns:
  62. Image.Image: An image with the recognized formula rendered alongside the original image.
  63. """
  64. image = Image.fromarray(self["input_img"])
  65. try:
  66. env_valid()
  67. except subprocess.CalledProcessError as e:
  68. logging.warning(
  69. "Please refer to 2.3 Formula Recognition Pipeline Visualization in Formula Recognition Pipeline Tutorial to install the LaTeX rendering engine at first."
  70. )
  71. return {"res": image}
  72. rec_formula = str(self["rec_formula"])
  73. image = np.array(image.convert("RGB"))
  74. xywh = crop_white_area(image)
  75. if xywh is not None:
  76. x, y, w, h = xywh
  77. image = image[y : y + h, x : x + w]
  78. image = Image.fromarray(image)
  79. image_width, image_height = image.size
  80. box = [[0, 0], [image_width, 0], [image_width, image_height], [0, image_height]]
  81. try:
  82. img_formula = draw_formula_module(
  83. image.size, box, rec_formula, is_debug=False
  84. )
  85. img_formula = Image.fromarray(img_formula)
  86. render_width, render_height = img_formula.size
  87. resize_height = render_height
  88. resize_width = int(resize_height * image_width / image_height)
  89. image = image.resize((resize_width, resize_height), Image.LANCZOS)
  90. new_image_width = image.width + int(render_width) + 10
  91. new_image = Image.new(
  92. "RGB", (new_image_width, render_height), (255, 255, 255)
  93. )
  94. new_image.paste(image, (0, 0))
  95. new_image.paste(img_formula, (image.width + 10, 0))
  96. return {"res": new_image}
  97. except subprocess.CalledProcessError as e:
  98. logging.warning("Syntax error detected in formula, rendering failed.")
  99. return {"res": image}
  100. def get_align_equation(equation: str) -> str:
  101. """
  102. Wraps an equation in LaTeX environment tags if not already aligned.
  103. This function checks if a given LaTeX equation contains any alignment tags (`align` or `align*`).
  104. If the equation does not contain these tags, it wraps the equation in `equation` and `nonumber` tags.
  105. Args:
  106. equation (str): The LaTeX equation to be checked and potentially modified.
  107. Returns:
  108. str: The modified equation with appropriate LaTeX tags for alignment.
  109. """
  110. is_align = False
  111. equation = str(equation) + "\n"
  112. begin_dict = [
  113. r"begin{align}",
  114. r"begin{align*}",
  115. ]
  116. for begin_sym in begin_dict:
  117. if begin_sym in equation:
  118. is_align = True
  119. break
  120. if not is_align:
  121. equation = (
  122. r"\begin{equation}"
  123. + "\n"
  124. + equation.strip()
  125. + r"\nonumber"
  126. + "\n"
  127. + r"\end{equation}"
  128. + "\n"
  129. )
  130. return equation
  131. def add_text_for_zh_formula(formula: str) -> str:
  132. pattern = re.compile(r"([^\x00-\x7F]+)")
  133. def replacer(match):
  134. return f"\\text{{{match.group(1)}}}"
  135. replaced_formula = pattern.sub(replacer, formula)
  136. return replaced_formula
  137. def generate_tex_file(tex_file_path: str, equation: str) -> None:
  138. """
  139. Generates a LaTeX file containing a specific equation.
  140. This function creates a LaTeX file at the specified file path, writing the necessary
  141. LaTeX preamble and wrapping the provided equation in a document structure. The equation
  142. is processed to ensure it includes alignment tags if necessary.
  143. Args:
  144. tex_file_path (str): The file path where the LaTeX file will be saved.
  145. equation (str): The LaTeX equation to be written into the file.
  146. """
  147. with custom_open(tex_file_path, "w") as fp:
  148. start_template = (
  149. r"\documentclass[varwidth]{standalone}" + "\n"
  150. r"\usepackage{cite}" + "\n"
  151. r"\usepackage{amsmath,amssymb,amsfonts,upgreek}" + "\n"
  152. r"\usepackage{graphicx}" + "\n"
  153. r"\usepackage{textcomp}" + "\n"
  154. r"\usepackage{xeCJK}" + "\n"
  155. r"\DeclareMathSizes{14}{14}{9.8}{7}" + "\n"
  156. r"\pagestyle{empty}" + "\n"
  157. r"\begin{document}" + "\n"
  158. r"\begin{large}" + "\n"
  159. )
  160. fp.write(start_template)
  161. equation = add_text_for_zh_formula(equation)
  162. equation = get_align_equation(equation)
  163. fp.write(equation)
  164. end_template = r"\end{large}" + "\n" r"\end{document}" + "\n"
  165. fp.write(end_template)
  166. def generate_pdf_file(
  167. tex_path: str, pdf_dir: str, is_debug: bool = False
  168. ) -> Optional[bool]:
  169. """
  170. Generates a PDF file from a LaTeX file using pdflatex.
  171. This function checks if the specified LaTeX file exists, and then runs pdflatex to generate a PDF file
  172. in the specified directory. It can run in debug mode to show detailed output or in silent mode.
  173. Args:
  174. tex_path (str): The path to the LaTeX file.
  175. pdf_dir (str): The directory where the PDF file will be saved.
  176. is_debug (bool, optional): If True, runs pdflatex with detailed output. Defaults to False.
  177. Returns:
  178. Optional[bool]: Returns True if the PDF was generated successfully, False if the LaTeX file does not exist,
  179. and None if an error occurred during the pdflatex execution.
  180. """
  181. if os.path.exists(tex_path):
  182. command = "xelatex -interaction=nonstopmode -halt-on-error -output-directory={} {}".format(
  183. pdf_dir, tex_path
  184. )
  185. if is_debug:
  186. subprocess.check_call(command, shell=True)
  187. else:
  188. custom_open(os.devnull, "w")
  189. subprocess.check_call(
  190. command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True
  191. )
  192. @function_requires_deps("opencv-contrib-python")
  193. def crop_white_area(image: np.ndarray) -> Optional[List[int]]:
  194. """
  195. Finds and returns the bounding box of the non-white area in an image.
  196. This function converts an image to grayscale and uses binary thresholding to
  197. find contours. It then calculates the bounding rectangle around the non-white
  198. areas of the image.
  199. Args:
  200. image (np.ndarray): The input image as a NumPy array.
  201. Returns:
  202. Optional[List[int]]: A list [x, y, w, h] representing the bounding box of
  203. the non-white area, or None if no such area is found.
  204. """
  205. image = np.array(image).astype("uint8")
  206. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  207. _, thresh = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)
  208. contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  209. if len(contours) > 0:
  210. x, y, w, h = cv2.boundingRect(np.concatenate(contours))
  211. return [x, y, w, h]
  212. else:
  213. return None
  214. @function_requires_deps("pypdfium2", "opencv-contrib-python")
  215. def pdf2img(pdf_path: str, img_path: str, is_padding: bool = False):
  216. """
  217. Converts a single-page PDF to an image, optionally cropping white areas and adding padding.
  218. Args:
  219. pdf_path (str): The path to the PDF file.
  220. img_path (str): The path where the image will be saved.
  221. is_padding (bool): If True, adds a 30-pixel white padding around the image.
  222. Returns:
  223. np.ndarray: The resulting image as a NumPy array, or None if the PDF is not single-page.
  224. """
  225. pdfDoc = pdfium.PdfDocument(pdf_path)
  226. if len(pdfDoc) != 1:
  227. return None
  228. for page in pdfDoc:
  229. rotate = int(0)
  230. zoom = 2
  231. img = page.render(scale=zoom, rotation=rotate).to_pil()
  232. img = img.convert("RGB")
  233. img = np.array(img)
  234. img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
  235. xywh = crop_white_area(img)
  236. if xywh is not None:
  237. x, y, w, h = xywh
  238. img = img[y : y + h, x : x + w]
  239. if is_padding:
  240. img = cv2.copyMakeBorder(
  241. img, 30, 30, 30, 30, cv2.BORDER_CONSTANT, value=(255, 255, 255)
  242. )
  243. return img
  244. return None
  245. def draw_formula_module(
  246. img_size: tuple, box: list, formula: str, is_debug: bool = False
  247. ):
  248. """
  249. Draw box formula for module.
  250. Args:
  251. img_size (tuple): The size of the image as (width, height).
  252. box (list): The coordinates for the bounding box.
  253. formula (str): The LaTeX formula to render.
  254. is_debug (bool): If True, retains intermediate files for debugging purposes.
  255. Returns:
  256. np.ndarray: The resulting image with the formula or an error message.
  257. """
  258. box_width, box_height = img_size
  259. with tempfile.TemporaryDirectory() as td:
  260. tex_file_path = os.path.join(td, "temp.tex")
  261. pdf_file_path = os.path.join(td, "temp.pdf")
  262. img_file_path = os.path.join(td, "temp.jpg")
  263. generate_tex_file(tex_file_path, formula)
  264. if os.path.exists(tex_file_path):
  265. generate_pdf_file(tex_file_path, td, is_debug)
  266. formula_img = None
  267. if os.path.exists(pdf_file_path):
  268. formula_img = pdf2img(pdf_file_path, img_file_path, is_padding=False)
  269. if formula_img is not None:
  270. return formula_img
  271. else:
  272. img_right_text = draw_box_txt_fine(
  273. img_size, box, "Rendering Failed", PINGFANG_FONT_FILE_PATH
  274. )
  275. return img_right_text
  276. def env_valid() -> bool:
  277. """
  278. Validates if the environment is correctly set up to convert LaTeX formulas to images.
  279. Returns:
  280. bool: True if the environment is valid and the conversion is successful, False otherwise.
  281. """
  282. with tempfile.TemporaryDirectory() as td:
  283. tex_file_path = os.path.join(td, "temp.tex")
  284. pdf_file_path = os.path.join(td, "temp.pdf")
  285. img_file_path = os.path.join(td, "temp.jpg")
  286. formula = "a+b=c"
  287. is_debug = False
  288. generate_tex_file(tex_file_path, formula)
  289. if os.path.exists(tex_file_path):
  290. generate_pdf_file(tex_file_path, td, is_debug)
  291. if os.path.exists(pdf_file_path):
  292. formula_img = pdf2img(pdf_file_path, img_file_path, is_padding=False)
  293. @function_requires_deps("opencv-contrib-python")
  294. def draw_box_txt_fine(img_size: tuple, box: list, txt: str, font_path: str):
  295. """
  296. Draw box text.
  297. Args:
  298. img_size (tuple): Size of the image as (width, height).
  299. box (list): List of four points defining the box, each point is a tuple (x, y).
  300. txt (str): The text to draw inside the box.
  301. font_path (str): Path to the font file to be used for drawing text.
  302. Returns:
  303. np.ndarray: Image array with the text drawn and transformed to fit the box.
  304. """
  305. box_height = int(
  306. math.sqrt((box[0][0] - box[3][0]) ** 2 + (box[0][1] - box[3][1]) ** 2)
  307. )
  308. box_width = int(
  309. math.sqrt((box[0][0] - box[1][0]) ** 2 + (box[0][1] - box[1][1]) ** 2)
  310. )
  311. if box_height > 2 * box_width and box_height > 30:
  312. img_text = Image.new("RGB", (box_height, box_width), (255, 255, 255))
  313. draw_text = ImageDraw.Draw(img_text)
  314. if txt:
  315. font = create_font(txt, (box_height, box_width), font_path)
  316. draw_text.text([0, 0], txt, fill=(0, 0, 0), font=font)
  317. img_text = img_text.transpose(Image.ROTATE_270)
  318. else:
  319. img_text = Image.new("RGB", (box_width, box_height), (255, 255, 255))
  320. draw_text = ImageDraw.Draw(img_text)
  321. if txt:
  322. font = create_font(txt, (box_width, box_height), font_path)
  323. draw_text.text([0, 0], txt, fill=(0, 0, 0), font=font)
  324. pts1 = np.float32(
  325. [[0, 0], [box_width, 0], [box_width, box_height], [0, box_height]]
  326. )
  327. pts2 = np.array(box, dtype=np.float32)
  328. M = cv2.getPerspectiveTransform(pts1, pts2)
  329. img_text = np.array(img_text, dtype=np.uint8)
  330. img_right_text = cv2.warpPerspective(
  331. img_text,
  332. M,
  333. img_size,
  334. flags=cv2.INTER_NEAREST,
  335. borderMode=cv2.BORDER_CONSTANT,
  336. borderValue=(255, 255, 255),
  337. )
  338. return img_right_text
  339. def create_font(txt: str, sz: tuple, font_path: str) -> ImageFont.FreeTypeFont:
  340. """
  341. Creates a font object with a size that ensures the text fits within the specified dimensions.
  342. Args:
  343. txt (str): The text to fit.
  344. sz (tuple): The target size as (width, height).
  345. font_path (str): The path to the font file.
  346. Returns:
  347. ImageFont.FreeTypeFont: A PIL font object at the appropriate size.
  348. """
  349. font_size = int(sz[1] * 0.8)
  350. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  351. if int(PIL.__version__.split(".")[0]) < 10:
  352. length = font.getsize(txt)[0]
  353. else:
  354. length = font.getlength(txt)
  355. if length > sz[0]:
  356. font_size = int(font_size * sz[0] / length)
  357. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  358. return font