October 2024 - LaTeX Formula Generator

I've not been able to justify posting the physics/math series for short while now, mainly because I'm not feeling the motivation to copy/paste the LaTeX formulas into the converter website I've been using one by one. In theory, making a script that reads the formulas out of a file and gives a series of images can't be that difficult. That's what we're building this month, and maybe posting those finished entries won't be quite as painful anymore.

The idea is as follows:

A normal text file should hold all the relevant formulas, separated by two empty lines. The script saves them as an array of strings, hopefully escaping all the odd LaTeX backslashes. For each entry of the array, the script finds attempts (!) to create an image, and when it's successful it saves the graphic as {index}.png. It tells the user which ones failed, and doesn't attempt to create a graphic for them.

This should be mostly easy - except for the LaTeX part. I have no idea how that works, but knowing the python community, there's likely a library for doing this. The tricky thing here is the style I usually go for, which includes a transparent background. That will be a LaTeX issue that I will have to investigate before I get to coding.

I've seen Sympy around during studies, but never got good at using it. I don't need it personally, because I can live with cli results, and these auto-generated texts just don't look good yet, so I've always written the documents I had to hand in by hand. Now though, it might turn out useful. The first lead I found to solve my problem was sympy.preview, which displays the generated LaTeX snippet in whatever image format I need it.

The rest turns out to be mostly dealing with a package called "dvipng". All my images are usually in png, and sympy delegates the png export to dvipng, which gets its own set of pythonic options, passed as a string-array. What's left to do now is the usual argparse stuff, and make the small adjustments to the workflow (i.e. the try-except brackets, and printing/exporting for errors)

Here’s the full script:

from sympy import preview
import argparse

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description="LaTeX Helper")
    parser.add_argument('fpath', type=str, help='Input File, separated by "\\n\\n"')
    parser.add_argument('outlog', type=str, help='Output File, separated by "\\n\\n"')
    args = parser.parse_args()

    fpath = args.fpath
    out = args.outlog
    counter = 0
    errstr = ''
    with open(fpath) as f:
        form_arr = f.read().split('\\n\\n')
        for i in form_arr: 
            try:
                preview(r"\begin{align} %s \end{align}" % (i), 
                        filename=f'{counter}.png', output='png', viewer='file', 
                        dvioptions=["-fg", "Green", "-bg", "Transparent", "-D 1000"])
            except:
                errstr += i + "\\n\\n\n"

            counter += 1

    print(errstr)

    with open(out, 'w') as f:
        f.write(errstr)

Now all that’s left is to initiate this script into my bins so I don’t have to keep finding the script in my system - but that’s something everybody will have to do by themselves. I, for one, like having all my script-kiddy products in one directory, and just write a quick bash script in my bin directory. Some people might have better ideas on that though.

Previous
Previous

November 2024 - Rebuilding My Scheduler

Next
Next

September 2024 - Creating a Pen & Paper System