Spaces:
Running
Running
Delete latex2bbox_color.py
Browse files- latex2bbox_color.py +0 -251
latex2bbox_color.py
DELETED
|
@@ -1,251 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import re
|
| 3 |
-
import cv2
|
| 4 |
-
import json
|
| 5 |
-
import shutil
|
| 6 |
-
import logging
|
| 7 |
-
import subprocess
|
| 8 |
-
import numpy as np
|
| 9 |
-
|
| 10 |
-
from threading import Timer
|
| 11 |
-
from PIL import Image, ImageDraw
|
| 12 |
-
from modules.latex_processor import (
|
| 13 |
-
normalize_latex,
|
| 14 |
-
token_add_color_RGB,
|
| 15 |
-
clean_latex
|
| 16 |
-
)
|
| 17 |
-
from modules.tokenize_latex.tokenize_latex import tokenize_latex
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
tabular_template = r"""
|
| 21 |
-
\documentclass[12pt]{article}
|
| 22 |
-
\usepackage[landscape]{geometry}
|
| 23 |
-
\usepackage{geometry}
|
| 24 |
-
\geometry{a<PaperSize>paper,scale=0.98}
|
| 25 |
-
\pagestyle{empty}
|
| 26 |
-
\usepackage{booktabs}
|
| 27 |
-
\usepackage{multirow}
|
| 28 |
-
\usepackage{amssymb}
|
| 29 |
-
\usepackage{upgreek}
|
| 30 |
-
\usepackage{amsmath}
|
| 31 |
-
\usepackage{xcolor}
|
| 32 |
-
\begin{document}
|
| 33 |
-
\makeatletter
|
| 34 |
-
\renewcommand*{\@textcolor}[3]{%%
|
| 35 |
-
\protect\leavevmode
|
| 36 |
-
\begingroup
|
| 37 |
-
\color#1{#2}#3%%
|
| 38 |
-
\endgroup
|
| 39 |
-
}
|
| 40 |
-
\makeatother
|
| 41 |
-
\begin{displaymath}
|
| 42 |
-
%s
|
| 43 |
-
\end{displaymath}
|
| 44 |
-
\end{document}
|
| 45 |
-
"""
|
| 46 |
-
|
| 47 |
-
formular_template = r"""
|
| 48 |
-
\documentclass[12pt]{article}
|
| 49 |
-
\usepackage[landscape]{geometry}
|
| 50 |
-
\usepackage{geometry}
|
| 51 |
-
\geometry{a<PaperSize>paper,scale=0.98}
|
| 52 |
-
\pagestyle{empty}
|
| 53 |
-
\usepackage{booktabs}
|
| 54 |
-
\usepackage{amsmath}
|
| 55 |
-
\usepackage{upgreek}
|
| 56 |
-
\usepackage{amssymb}
|
| 57 |
-
\usepackage{xcolor}
|
| 58 |
-
\begin{document}
|
| 59 |
-
\makeatletter
|
| 60 |
-
\renewcommand*{\@textcolor}[3]{%%
|
| 61 |
-
\protect\leavevmode
|
| 62 |
-
\begingroup
|
| 63 |
-
\color#1{#2}#3%%
|
| 64 |
-
\endgroup
|
| 65 |
-
}
|
| 66 |
-
\makeatother
|
| 67 |
-
\begin{displaymath}
|
| 68 |
-
%s
|
| 69 |
-
\end{displaymath}
|
| 70 |
-
\end{document}
|
| 71 |
-
"""
|
| 72 |
-
|
| 73 |
-
formular_template_zh = r"""
|
| 74 |
-
\documentclass[12pt]{article}
|
| 75 |
-
\usepackage[landscape]{geometry}
|
| 76 |
-
\usepackage{geometry}
|
| 77 |
-
\geometry{a<PaperSize>paper,scale=0.98}
|
| 78 |
-
\pagestyle{empty}
|
| 79 |
-
\usepackage{booktabs}
|
| 80 |
-
\usepackage{amsmath}
|
| 81 |
-
\usepackage{upgreek}
|
| 82 |
-
\usepackage{CJK}
|
| 83 |
-
\usepackage{amssymb}
|
| 84 |
-
\usepackage{xcolor}
|
| 85 |
-
\begin{document}
|
| 86 |
-
\makeatletter
|
| 87 |
-
\renewcommand*{\@textcolor}[3]{%%
|
| 88 |
-
\protect\leavevmode
|
| 89 |
-
\begingroup
|
| 90 |
-
\color#1{#2}#3%%
|
| 91 |
-
\endgroup
|
| 92 |
-
}
|
| 93 |
-
\makeatother
|
| 94 |
-
\begin{CJK}{UTF8}{gkai}
|
| 95 |
-
%s
|
| 96 |
-
\end{CJK}
|
| 97 |
-
\end{document}
|
| 98 |
-
"""
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
def run_cmd(cmd, timeout_sec=30):
|
| 102 |
-
proc = subprocess.Popen(cmd, shell=True)
|
| 103 |
-
kill_proc = lambda p: p.kill()
|
| 104 |
-
timer = Timer(timeout_sec, kill_proc, [proc])
|
| 105 |
-
try:
|
| 106 |
-
timer.start()
|
| 107 |
-
stdout,stderr = proc.communicate()
|
| 108 |
-
finally:
|
| 109 |
-
timer.cancel()
|
| 110 |
-
|
| 111 |
-
def convert_pdf2img(pdf_filename, png_filename):
|
| 112 |
-
cmd = "magick -density 200 -quality 100 %s %s"%(pdf_filename, png_filename)
|
| 113 |
-
os.system(cmd)
|
| 114 |
-
|
| 115 |
-
def crop_image(image_path, pad=8):
|
| 116 |
-
img = Image.open(image_path).convert("L")
|
| 117 |
-
img_data = np.asarray(img, dtype=np.uint8)
|
| 118 |
-
nnz_inds = np.where(img_data!=255)
|
| 119 |
-
if len(nnz_inds[0]) == 0:
|
| 120 |
-
y_min = 0
|
| 121 |
-
y_max = 10
|
| 122 |
-
x_min = 0
|
| 123 |
-
x_max = 10
|
| 124 |
-
else:
|
| 125 |
-
y_min = np.min(nnz_inds[0])
|
| 126 |
-
y_max = np.max(nnz_inds[0])
|
| 127 |
-
x_min = np.min(nnz_inds[1])
|
| 128 |
-
x_max = np.max(nnz_inds[1])
|
| 129 |
-
|
| 130 |
-
img = Image.open(image_path).convert("RGB").crop((x_min-pad, y_min-pad, x_max+pad, y_max+pad))
|
| 131 |
-
img.save(image_path)
|
| 132 |
-
|
| 133 |
-
def extrac_bbox_from_color_image(image_path, color_list):
|
| 134 |
-
img = cv2.imread(image_path)
|
| 135 |
-
bbox_list = []
|
| 136 |
-
for target_color in color_list:
|
| 137 |
-
r, g, b = target_color
|
| 138 |
-
target_rgb = np.array([b, g, r], dtype=np.uint8)
|
| 139 |
-
mask = np.all(img == target_rgb, axis=2)
|
| 140 |
-
coords = np.argwhere(mask)
|
| 141 |
-
if coords.size > 0:
|
| 142 |
-
x_min, y_min = coords[:, 1].min(), coords[:, 0].min()
|
| 143 |
-
x_max, y_max = coords[:, 1].max(), coords[:, 0].max()
|
| 144 |
-
bbox_list.append([int(x_min-1), int(y_min-1), int(x_max+1), int(y_max+1)])
|
| 145 |
-
else:
|
| 146 |
-
bbox_list.append([])
|
| 147 |
-
|
| 148 |
-
img = Image.open(image_path).convert("RGB").convert("L")
|
| 149 |
-
img_bw = img.point(lambda x: 255 if x == 255 else 0, '1')
|
| 150 |
-
img_bw.convert("RGB").save(image_path)
|
| 151 |
-
return bbox_list
|
| 152 |
-
|
| 153 |
-
def contains_chinese(text):
|
| 154 |
-
# 匹配中文字符的正则表达式范围
|
| 155 |
-
return re.search(r'[\u4e00-\u9fff]', text) is not None
|
| 156 |
-
|
| 157 |
-
def latex2bbox_color(input_arg):
|
| 158 |
-
latex, basename, output_path, temp_dir, total_color_list = input_arg
|
| 159 |
-
if "tabular" in latex:
|
| 160 |
-
template = tabular_template
|
| 161 |
-
else:
|
| 162 |
-
if contains_chinese(latex):
|
| 163 |
-
template = formular_template_zh
|
| 164 |
-
latex = latex.replace(",", ", ").replace(":", ": ").replace(";", "; ")
|
| 165 |
-
else:
|
| 166 |
-
template = formular_template
|
| 167 |
-
output_bbox_path = os.path.join(output_path, 'bbox', basename+'.jsonl')
|
| 168 |
-
output_vis_path = os.path.join(output_path, 'vis', basename+'.png')
|
| 169 |
-
output_base_path = os.path.join(output_path, 'vis', basename+'_base.png')
|
| 170 |
-
|
| 171 |
-
if os.path.exists(output_bbox_path) and os.path.exists(output_vis_path) and os.path.exists(output_base_path):
|
| 172 |
-
return
|
| 173 |
-
|
| 174 |
-
try:
|
| 175 |
-
latex = latex.replace("\n", " ")
|
| 176 |
-
ret, new_latex = tokenize_latex(latex, middle_file=os.path.join(temp_dir, basename+'.txt'))
|
| 177 |
-
if not(ret and new_latex):
|
| 178 |
-
log = f"ERROR, Tokenize latex failed: {basename}."
|
| 179 |
-
logging.info(log)
|
| 180 |
-
new_latex = latex
|
| 181 |
-
latex = normalize_latex(new_latex)
|
| 182 |
-
token_list = []
|
| 183 |
-
l_split = latex.strip().split(' ')
|
| 184 |
-
color_list = total_color_list[0:len(l_split)]
|
| 185 |
-
idx = 0
|
| 186 |
-
while idx < len(l_split):
|
| 187 |
-
l_split, idx, token_list = token_add_color_RGB(l_split, idx, token_list)
|
| 188 |
-
|
| 189 |
-
rgb_latex = " ".join(l_split)
|
| 190 |
-
for idx, color in enumerate(color_list):
|
| 191 |
-
R, G, B = color
|
| 192 |
-
rgb_latex = rgb_latex.replace(f"<color_{idx}>", f"{R},{G},{B}")
|
| 193 |
-
|
| 194 |
-
if len(token_list) > 1300:
|
| 195 |
-
paper_size = 3
|
| 196 |
-
elif len(token_list) > 600:
|
| 197 |
-
paper_size = 4
|
| 198 |
-
else:
|
| 199 |
-
paper_size = 5
|
| 200 |
-
final_latex = template.replace("<PaperSize>", str(paper_size)) % rgb_latex
|
| 201 |
-
|
| 202 |
-
except Exception as e:
|
| 203 |
-
log = f"ERROR, Preprocess latex failed: {basename}; {e}."
|
| 204 |
-
logging.info(log)
|
| 205 |
-
return
|
| 206 |
-
|
| 207 |
-
pre_name = output_path.replace('/', '_').replace('.','_') + '_' + basename
|
| 208 |
-
tex_filename = os.path.join(temp_dir, pre_name+'.tex')
|
| 209 |
-
log_filename = os.path.join(temp_dir, pre_name+'.log')
|
| 210 |
-
aux_filename = os.path.join(temp_dir, pre_name+'.aux')
|
| 211 |
-
|
| 212 |
-
with open(tex_filename, "w") as w:
|
| 213 |
-
print(final_latex, file=w)
|
| 214 |
-
run_cmd(f"pdflatex -interaction=nonstopmode -output-directory={temp_dir} {tex_filename} >/dev/null")
|
| 215 |
-
try:
|
| 216 |
-
os.remove(tex_filename)
|
| 217 |
-
os.remove(log_filename)
|
| 218 |
-
os.remove(aux_filename)
|
| 219 |
-
except:
|
| 220 |
-
pass
|
| 221 |
-
pdf_filename = tex_filename[:-4]+'.pdf'
|
| 222 |
-
if not os.path.exists(pdf_filename):
|
| 223 |
-
log = f"ERROR, Compile pdf failed: {pdf_filename}"
|
| 224 |
-
logging.info(log)
|
| 225 |
-
else:
|
| 226 |
-
convert_pdf2img(pdf_filename, output_base_path)
|
| 227 |
-
os.remove(pdf_filename)
|
| 228 |
-
|
| 229 |
-
crop_image(output_base_path)
|
| 230 |
-
bbox_list = extrac_bbox_from_color_image(output_base_path, color_list)
|
| 231 |
-
vis = Image.open(output_base_path)
|
| 232 |
-
draw = ImageDraw.Draw(vis)
|
| 233 |
-
|
| 234 |
-
with open(output_bbox_path, 'w', encoding='utf-8') as f:
|
| 235 |
-
for token, box in zip(token_list, bbox_list):
|
| 236 |
-
item = {
|
| 237 |
-
"bbox": box,
|
| 238 |
-
"token": token
|
| 239 |
-
}
|
| 240 |
-
f.write(json.dumps(item, ensure_ascii=False)+'\n')
|
| 241 |
-
|
| 242 |
-
if not box:
|
| 243 |
-
continue
|
| 244 |
-
x_min, y_min, x_max, y_max = box
|
| 245 |
-
draw.rectangle([x_min, y_min, x_max, y_max], fill=None, outline=(0,250,0), width=1)
|
| 246 |
-
try:
|
| 247 |
-
draw.text((x_min, y_min), token, (250,0,0))
|
| 248 |
-
except:
|
| 249 |
-
pass
|
| 250 |
-
|
| 251 |
-
vis.save(output_vis_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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