result.py 14 KB

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