|
import csv |
|
import os |
|
import io |
|
from PIL import Image |
|
|
|
from pnglatex import pnglatex |
|
from pdf2image import convert_from_path |
|
import jsonlines |
|
import json |
|
|
|
import numpy as np |
|
|
|
from pylatex import ( |
|
Alignat, |
|
Axis, |
|
Document, |
|
Figure, |
|
Math, |
|
Matrix, |
|
Plot, |
|
Section, |
|
Subsection, |
|
Tabular, |
|
TikZ, |
|
) |
|
from pylatex.utils import italic, NoEscape |
|
from pylatex.package import Package |
|
|
|
|
|
|
|
def generate_pdf(latex, name, pre=True): |
|
try: |
|
doc = Document(default_filepath=name, geometry_options=geometry_options) |
|
doc.packages.append(Package('amsmath')) |
|
doc.packages.append(Package('graphicx')) |
|
if pre: |
|
doc.append(NoEscape(latex)) |
|
else: |
|
is_text = True |
|
while r"\$" in latex: |
|
pos = latex.index(r"\$") |
|
if is_text: |
|
|
|
doc.append(latex[:pos]) |
|
is_text = False |
|
else: |
|
|
|
doc.append(NoEscape("$" + latex[:pos] + "$")) |
|
is_text = True |
|
latex = latex[pos+2:] |
|
|
|
doc.generate_pdf(name, clean=True, clean_tex=True, compiler="pdflatex", silent=True) |
|
except: |
|
print("pre-ran " + name) |
|
|
|
def latex_to_image(latex, name): |
|
|
|
while latex.index('\n') == 0: |
|
latex = latex[1:] |
|
|
|
generate_pdf(latex, name) |
|
generate_pdf(latex, name, False) |
|
|
|
images = convert_from_path(name + '.pdf') |
|
|
|
for i in range(len(images)): |
|
|
|
images[i].save(name + '_' + str(i) + '.jpg', 'JPEG') |
|
|
|
os.remove(name + ".pdf") |
|
|
|
if __name__=="__main__": |
|
print("STARTED") |
|
|
|
geometry_options = {"tmargin": "1cm", "lmargin": "1cm", "rmargin": "1cm", "bmargin": "1cm"} |
|
|
|
with jsonlines.open('dataset.jsonl') as reader_obj: |
|
count = 0 |
|
for row in reader_obj.iter(type=dict, skip_invalid=True): |
|
question_path = "output/" + row["id"] |
|
if not os.path.exists(question_path): |
|
os.makedirs(question_path) |
|
|
|
|
|
if count >= 27674: |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
try: |
|
latex_to_image(row["body"], question_path + "/question") |
|
except: |
|
print(count, question_path + "/question", " question could not generate") |
|
for i in range(len(row["answers"])): |
|
try: |
|
latex_to_image(row["answers"][i]["body"], question_path + "/" + row["answers"][i]["id"]) |
|
except: |
|
print(count, question_path + "/" + row["answers"][i]["id"], " answer could not generate") |
|
print(count, question_path) |
|
count += 1 |
|
print(count, end=" ") |