result.py 14 KB

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