Skip to content

Commit

Permalink
Update files
Browse files Browse the repository at this point in the history
  • Loading branch information
SWHL committed Dec 21, 2023
1 parent cf54bc5 commit 89376eb
Show file tree
Hide file tree
Showing 13 changed files with 138 additions and 248 deletions.
17 changes: 1 addition & 16 deletions .github/workflows/auto_push_pypi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,17 +24,6 @@ jobs:
- name: Display Python version
run: python -c "import sys; print(sys.version)"

- name: Unit testings
run: |
pip install -r requirements.txt
pip install pytest
wget https://github.com/RapidAI/TableStructureRec/releases/download/v0.0.0/lineless_table_rec_models.zip
unzip lineless_table_rec_models.zip
mv lineless_table_rec_models/*.onnx lineless_table_rec/models/
pytest tests/test_lore.py
GenerateWHL_PushPyPi:
needs: UnitTesting
runs-on: ubuntu-latest
Expand All @@ -54,11 +43,7 @@ jobs:
python -m pip install --upgrade pip
pip install wheel get_pypi_latest_version
wget https://github.com/RapidAI/TableStructureRec/releases/download/v0.0.0/lineless_table_rec_models.zip
unzip lineless_table_rec_models.zip
mv lineless_table_rec_models/*.onnx lineless_table_rec/models/
python setup_lineless.py bdist_wheel ${{ github.event.head_commit.message }}
python setup.py bdist_wheel ${{ github.event.head_commit.message }}
# - name: Publish distribution 📦 to Test PyPI
# uses: pypa/[email protected]
Expand Down
44 changes: 27 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,41 @@
该仓库是用于将LaTeX的公式借助LaTeX工具转换为对应的图像。


### 安装
1. 安装texlive
- Ubuntu
```bash
# Ubuntu
sudo apt-get install texlive-full

# 确认是否安装成功
$ pdflatex --help
Usage: pdftex [OPTION]... [TEXNAME[.tex]] [COMMANDS]
or: pdftex [OPTION]... \FIRST-LINE
or: pdftex [OPTION]... &FMT ARGS
Run pdfTeX on TEXNAME, usually creating TEXNAME.pdf.
```
- MacOS
### 安装LaTeX编译环境
Ubuntu:
```bash
sudo apt-get install texlive-full

# 确认是否安装成功
$ xelatex --help
# Usage: pdftex [OPTION]... [TEXNAME[.tex]] [COMMANDS]
# or: pdftex [OPTION]... \FIRST-LINE
# or: pdftex [OPTION]... &FMT ARGS
# Run pdfTeX on TEXNAME, usually creating TEXNAME.pdf.
```

MacOS

推荐安装[MacTex](https://tug.org/mactex/mactex-download.html)

验证是否安装成功:
```bash
$ xelatex --help

2. 安装运行环境
# Usage: xetex [OPTION]... [TEXNAME[.tex]] [COMMANDS]
# or: xetex [OPTION]... \FIRST-LINE
# or: xetex [OPTION]... &FMT ARGS
# Run XeTeX on TEXNAME, usually creating TEXNAME.pdf.
```

### 安装运行环境
```bash
pip install latex_to_image
```

### 使用



### 参考代码
- [LaTeX-OCR](https://github.com/lukas-blecher/LaTeX-OCR/blob/main/pix2tex/dataset/latex2png.py)
- [latex2image](https://pypi.org/project/latex2image/#description)
7 changes: 3 additions & 4 deletions demo.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
from PIL import Image
import cv2

from latex_to_image import LaTeXToImg

render = LaTeXToImg()

formula = "x^2 + y ^2 = 1"

img_formula = render(formula)
img_formula = Image.fromarray(img_formula)
img_formula.save("res2.png")
img = render(formula)
cv2.imwrite("res.png", img)
print("ok")
1 change: 1 addition & 0 deletions docs/doc_whl.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
### See details for [latex_to_image](https://github.com/SWHL/latex_to_image)
26 changes: 25 additions & 1 deletion latex_to_image/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
import argparse
from typing import Optional

import cv2
import numpy as np

from .crop_img import CropByProject
Expand All @@ -14,9 +18,29 @@ def __init__(
self.cropper = CropByProject()
self.latex = RenderLaTeX()

def __call__(self, math: str) -> np.ndarray:
def __call__(self, math: Optional[str] = None) -> np.ndarray:
if len(math.strip()) <= 0 or math is None:
raise ValueError("The input of formula must have value.")

img = self.latex(math)
img = self.cropper(img)
return img


def main():
parser = argparse.ArgumentParser()
parser.add_argument("math", type=str, default=None)
parser.add_argument("save_path", type=str, default="res.png")
args = parser.parse_args()

render = LaTeXToImg()
img = render(args.math)
if img is not None:
cv2.imwrite(args.save_path, img)
print(f"The image has been saved in {args.save_path} .")
else:
print("The result of render formula is empty.")


if __name__ == "__main__":
main()
12 changes: 5 additions & 7 deletions latex_to_image/render_latex.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# -*- encoding: utf-8 -*-
# mostly taken from http://code.google.com/p/latexmath2png/
# install preview.sty
import io
import os
import re
import shlex
Expand All @@ -11,8 +10,7 @@
from pathlib import Path
from typing import Union

import numpy as np
from PIL import Image
import cv2


class RenderLaTeX:
Expand Down Expand Up @@ -52,15 +50,15 @@ def render_by_xelatex(self, work_dir, in_file) -> Path:
)
if flag:
return pdf_file
raise LatexError("xelatex meets error.")
raise LaTeXError("xelatex meets error.")

def convert_pdf_to_png(self, pdf_file):
png_file: Path = Path(pdf_file).with_suffix(".png")
cmd = f"convert -background white -flatten -density {self.dpi} -colorspace gray {pdf_file} -quality 90 {png_file}"
_, return_code = self.run_cmd(cmd)
if return_code != 0:
raise LatexError(f"PDF to png error\n{cmd}\n{pdf_file}")
img = np.array(Image.open(png_file))
raise LaTeXError(f"PDF to png error\n{cmd}\n{pdf_file}")
img = cv2.imread(str(png_file))
return img

@staticmethod
Expand Down Expand Up @@ -94,5 +92,5 @@ def clear_files(in_file: Union[str, Path]) -> None:
file_path.unlink()


class LatexError(Exception):
class LaTeXError(Exception):
pass
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
opencv_python_headless
Pillow
numpy
Binary file removed res2.png
Binary file not shown.
75 changes: 75 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# -*- encoding: utf-8 -*-
# @Author: SWHL
# @Contact: [email protected]
import sys
from pathlib import Path
from typing import List

import setuptools
from get_pypi_latest_version import GetPyPiLatestVersion


def read_txt(txt_path: str) -> List:
if not isinstance(txt_path, str):
txt_path = str(txt_path)

with open(txt_path, "r", encoding="utf-8") as f:
data = list(map(lambda x: x.rstrip("\n"), f))
return data


def get_readme() -> str:
root_dir = Path(__file__).resolve().parent
readme_path = str(root_dir / "docs" / "doc_whl.md")
with open(readme_path, "r", encoding="utf-8") as f:
readme = f.read()
return readme


MODULE_NAME = "latex_to_image"

obtainer = GetPyPiLatestVersion()
try:
latest_version = obtainer(MODULE_NAME)
except ValueError:
latest_version = "0.0.0"

VERSION_NUM = obtainer.version_add_one(latest_version)

if len(sys.argv) > 2:
match_str = " ".join(sys.argv[2:])
matched_versions = obtainer.extract_version(match_str)
if matched_versions:
VERSION_NUM = matched_versions
sys.argv = sys.argv[:2]

setuptools.setup(
name=MODULE_NAME,
version=VERSION_NUM,
platforms="Any",
description="Use LaTeX compilation tools to convert formulas in LaTeX format into corresponding images.",
long_description=get_readme(),
long_description_content_type="text/markdown",
author="SWHL",
author_email="[email protected]",
url="https://github.com/SWHL/CutVideo",
license="MIT",
include_package_data=True,
install_requires=read_txt("requirements.txt"),
packages=[MODULE_NAME],
keywords=["moviepy,crop_video"],
classifiers=[
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
],
python_requires=">=3.6,<3.12",
entry_points={
"console_scripts": [
f"latex_to_image={MODULE_NAME}.main:main",
],
},
)
Loading

0 comments on commit 89376eb

Please sign in to comment.