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