|
| 1 | +# coding: utf-8 |
| 2 | +# 2024/3/5 @ yuheng |
| 3 | +import json |
| 4 | +import requests |
| 5 | +from EduNLP.utils import image2base64 |
| 6 | + |
| 7 | + |
| 8 | +class FormulaRecognitionError(Exception): |
| 9 | + """Exception raised when formula recognition fails.""" |
| 10 | + def __init__(self, message="Formula recognition failed"): |
| 11 | + self.message = message |
| 12 | + super().__init__(self.message) |
| 13 | + |
| 14 | + |
| 15 | +def ocr_formula_figure(image_PIL_or_base64, is_base64=False): |
| 16 | + """ |
| 17 | + Recognizes mathematical formulas in an image and returns their LaTeX representation. |
| 18 | +
|
| 19 | + Parameters |
| 20 | + ---------- |
| 21 | + image_PIL_or_base64 : PngImageFile or str |
| 22 | + The PngImageFile if is_base64 is False, or the base64 encoded string of the image if is_base64 is True. |
| 23 | + is_base64 : bool, optional |
| 24 | + Indicates whether the image_PIL_or_base64 parameter is an PngImageFile or a base64 encoded string. |
| 25 | +
|
| 26 | + Returns |
| 27 | + ------- |
| 28 | + latex : str |
| 29 | + The LaTeX representation of the mathematical formula recognized in the image. |
| 30 | + Raises an exception if the image is not recognized as containing a mathematical formula. |
| 31 | +
|
| 32 | + Raises |
| 33 | + ------ |
| 34 | + FormulaRecognitionError |
| 35 | + If the HTTP request does not return a 200 status code, |
| 36 | + if there is an error processing the response, |
| 37 | + if the image is not recognized as a mathematical formula. |
| 38 | +
|
| 39 | + Examples |
| 40 | + -------- |
| 41 | + >>> import os |
| 42 | + >>> from PIL import Image |
| 43 | + >>> from EduNLP.utils import abs_current_dir, path_append |
| 44 | + >>> img_dir = os.path.abspath(path_append(abs_current_dir(__file__), "..", "..", "..", "asset", "_static")) |
| 45 | + >>> image_PIL = Image.open(path_append(img_dir, "item_ocr_formula.png", to_str=True)) |
| 46 | + >>> print(ocr_formula_figure(image_PIL)) |
| 47 | + f(x)=\\left (\\frac {1}{3}\\right )^{x}-\\sqrt {x}} |
| 48 | + >>> import os |
| 49 | + >>> from PIL import Image |
| 50 | + >>> from EduNLP.utils import abs_current_dir, path_append, image2base64 |
| 51 | + >>> img_dir = os.path.abspath(path_append(abs_current_dir(__file__), "..", "..", "..", "asset", "_static")) |
| 52 | + >>> image_PIL = Image.open(path_append(img_dir, "item_ocr_formula.png", to_str=True)) |
| 53 | + >>> image_base64 = image2base64(image_PIL) |
| 54 | + >>> print(ocr_formula_figure(image_base64, is_base64=True)) |
| 55 | + f(x)=\\left (\\frac {1}{3}\\right )^{x}-\\sqrt {x}} |
| 56 | +
|
| 57 | + Notes |
| 58 | + ----- |
| 59 | + This function relies on an external service "https://formula-recognition-service-47-production.env.iai.bdaa.pro/v1", |
| 60 | + and the `requests` library to make HTTP requests. Make sure the required libraries are installed before use. |
| 61 | + """ |
| 62 | + url = "https://formula-recognition-service-47-production.env.iai.bdaa.pro/v1" |
| 63 | + |
| 64 | + if is_base64: |
| 65 | + image = image_PIL_or_base64 |
| 66 | + else: |
| 67 | + image = image2base64(image_PIL_or_base64) |
| 68 | + |
| 69 | + data = [{ |
| 70 | + 'qid': 0, |
| 71 | + 'image': image |
| 72 | + }] |
| 73 | + |
| 74 | + resp = requests.post(url, data=json.dumps(data)) |
| 75 | + |
| 76 | + if resp.status_code != 200: |
| 77 | + raise FormulaRecognitionError(f"HTTP error {resp.status_code}: {resp.text}") |
| 78 | + |
| 79 | + try: |
| 80 | + res = json.loads(resp.content) |
| 81 | + except Exception as e: |
| 82 | + raise FormulaRecognitionError(f"Error processing response: {e}") |
| 83 | + |
| 84 | + res = json.loads(resp.content) |
| 85 | + data = res['data'] |
| 86 | + if data['success'] == 1 and data['is_formula'] == 1 and data['detect_formula'] == 1: |
| 87 | + latex = data['latex'] |
| 88 | + else: |
| 89 | + latex = None |
| 90 | + raise FormulaRecognitionError("Image is not recognized as a formula") |
| 91 | + |
| 92 | + return latex |
| 93 | + |
| 94 | + |
| 95 | +def ocr(src, is_base64=False, figure_instances: dict = None): |
| 96 | + """ |
| 97 | + Recognizes mathematical formulas within figures from a given source, |
| 98 | + which can be either a base64 string or an identifier for a figure within a provided dictionary. |
| 99 | +
|
| 100 | + Parameters |
| 101 | + ---------- |
| 102 | + src : str |
| 103 | + The source from which the figure is to be recognized. |
| 104 | + It can be a base64 encoded string of the image if is_base64 is True, |
| 105 | + or an identifier for the figure if is_base64 is False. |
| 106 | + is_base64 : bool, optional |
| 107 | + Indicates whether the src parameter is a base64 encoded string or an identifier, by default False. |
| 108 | + figure_instances : dict, optional |
| 109 | + A dictionary mapping figure identifiers to their corresponding PngImageFile, by default None. |
| 110 | + This is only required and used if is_base64 is False. |
| 111 | +
|
| 112 | + Returns |
| 113 | + ------- |
| 114 | + forumla_figure_latex : str or None |
| 115 | + The LaTeX representation of the mathematical formula recognized within the figure. |
| 116 | + Returns None if no formula is recognized or |
| 117 | + if the figure_instances dictionary does not contain the specified figure identifier when is_base64 is False. |
| 118 | +
|
| 119 | + Examples |
| 120 | + -------- |
| 121 | + >>> import os |
| 122 | + >>> from PIL import Image |
| 123 | + >>> from EduNLP.utils import abs_current_dir, path_append |
| 124 | + >>> img_dir = os.path.abspath(path_append(abs_current_dir(__file__), "..", "..", "..", "asset", "_static")) |
| 125 | + >>> image_PIL = Image.open(path_append(img_dir, "item_ocr_formula.png", to_str=True)) |
| 126 | + >>> figure_instances = {"1": image_PIL} |
| 127 | + >>> src_id = r"$\\FormFigureID{1}$" |
| 128 | + >>> print(ocr(src_id[1:-1], figure_instances=figure_instances)) |
| 129 | + f(x)=\\left (\\frac {1}{3}\\right )^{x}-\\sqrt {x}} |
| 130 | + >>> import os |
| 131 | + >>> from PIL import Image |
| 132 | + >>> from EduNLP.utils import abs_current_dir, path_append, image2base64 |
| 133 | + >>> img_dir = os.path.abspath(path_append(abs_current_dir(__file__), "..", "..", "..", "asset", "_static")) |
| 134 | + >>> image_PIL = Image.open(path_append(img_dir, "item_ocr_formula.png", to_str=True)) |
| 135 | + >>> image_base64 = image2base64(image_PIL) |
| 136 | + >>> src_base64 = r"$\\FormFigureBase64{%s}$" % (image_base64) |
| 137 | + >>> print(ocr(src_base64[1:-1], is_base64=True, figure_instances=True)) |
| 138 | + f(x)=\\left (\\frac {1}{3}\\right )^{x}-\\sqrt {x}} |
| 139 | +
|
| 140 | + Notes |
| 141 | + ----- |
| 142 | + This function relies on `ocr_formula_figure` for the actual OCR (Optical Character Recognition) process. |
| 143 | + Ensure that `ocr_formula_figure` is correctly implemented and can handle base64 encoded strings and PngImageFile. |
| 144 | + """ |
| 145 | + forumla_figure_latex = None |
| 146 | + if is_base64: |
| 147 | + figure = src[len(r"\FormFigureBase64") + 1: -1] |
| 148 | + if figure_instances is not None: |
| 149 | + forumla_figure_latex = ocr_formula_figure(figure, is_base64) |
| 150 | + else: |
| 151 | + figure = src[len(r"\FormFigureID") + 1: -1] |
| 152 | + if figure_instances is not None: |
| 153 | + figure = figure_instances[figure] |
| 154 | + forumla_figure_latex = ocr_formula_figure(figure, is_base64) |
| 155 | + |
| 156 | + return forumla_figure_latex |
0 commit comments