result.py 14 KB

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