<commit_before>#!/usr/bin/env python3
"""A program (bot) for rendering short snippets of LaTeX code as an image.
A LaTeX distribution needs to be installed on the machine where this code
is ran."""

import sys
from io import BytesIO
from tempfile import NamedTemporaryFile
from os.path import basename
import re

from sympy import preview
from flask import Flask, request, abort, send_file

app = Flask(__name__)
app.config.from_pyfile('latexbot.cfg')


def render(latex_source, mode, image_name=None, output_buffer=None):
    """Renders the given LaTeX source and outputs it in a PNG image
    with the given name. Returns True on success and False otherwise."""
    try:
        if mode == 'link':
            preview(latex_source, euler=False, viewer='file', filename=image_name)
        else:
            preview(latex_source, euler=False, output='png', viewer='BytesIO',
                    outputbuffer=output_buffer)
    except RuntimeError as err:
        print('Got Latex error: {}'.format(err), file=sys.stderr)
        return False
    return True


# Routes
@app.route('/', methods=['GET'])
def index():
    """Index route."""
    if 'mode' in request.args:
        mode = request.args['mode']
    else:
        mode = app.config['OUTPUT_MODE']

    if 'render' not in request.args:
        abort(400)

    # Hack to generate a temporary filename
    with NamedTemporaryFile(dir='/tmp', prefix='latexbot_', suffix='.png', delete=True) as tmpfile:
        tmpfile_name = tmpfile.name

    if mode == 'link':
        if not render(request.args['render'], mode, image_name=tmpfile_name):
            abort(400)

        return '{}get/{}'.format(request.url_root,
                                 re.search(r'latexbot_(\w+)\.png',
                                           basename(tmpfile_name)).group(1))
    else:
        out_buffer = BytesIO()
        if not render(request.args['render'], mode, output_buffer=out_buffer):
            abort(400)

        out_buffer.seek(0)
        return send_file(out_buffer, mimetype='image/png')


if __name__ == '__main__':
    app.run(host='0.0.0.0')<commit_msg>Add image fetching with an ID<commit_after>#!/usr/bin/env python3
"""A program (bot) for rendering short snippets of LaTeX code as an image.
A LaTeX distribution needs to be installed on the machine where this code
is ran."""

import sys
from io import BytesIO
from tempfile import NamedTemporaryFile
from os.path import basename
import re

from sympy import preview
from flask import Flask, request, abort, send_file

app = Flask(__name__)
app.config.from_pyfile('latexbot.cfg')


def render(latex_source, mode, image_name=None, output_buffer=None):
    """Renders the given LaTeX source and outputs it in a PNG image
    with the given name. Returns True on success and False otherwise."""
    try:
        if mode == 'link':
            preview(latex_source, euler=False, viewer='file', filename=image_name)
        else:
            preview(latex_source, euler=False, output='png', viewer='BytesIO',
                    outputbuffer=output_buffer)
    except RuntimeError as err:
        print('Got Latex error: {}'.format(err), file=sys.stderr)
        return False
    return True


# Routes
@app.route('/', methods=['GET'])
def index():
    """Index route."""
    if 'mode' in request.args:
        mode = request.args['mode']
    else:
        mode = app.config['OUTPUT_MODE']

    if 'render' not in request.args:
        abort(404)

    # Hack to generate a temporary filename
    with NamedTemporaryFile(dir='/tmp', prefix='latexbot_', suffix='.png', delete=True) as tmpfile:
        tmpfile_name = tmpfile.name

    if mode == 'link':
        if not render(request.args['render'], mode, image_name=tmpfile_name):
            abort(404)

        return '{}image/{}'.format(request.url_root,
                                   re.search(r'latexbot_(\w+)\.png',
                                             basename(tmpfile_name)).group(1))
    else:
        out_buffer = BytesIO()
        if not render(request.args['render'], mode, output_buffer=out_buffer):
            abort(404)

        out_buffer.seek(0)
        return send_file(out_buffer, mimetype='image/png')


@app.route('/image/<image_id>', methods=['GET'])
def get_image(image_id):
    """Returns the image referred by the given ID."""
    try:
        image = open('/tmp/latexbot_{}.png'.format(image_id), 'rb')
    except FileNotFoundError:
        print('Tried to access non-existent image: {}'.format(image_id),
              file=sys.stderr)
        abort(404)
    return send_file(image, mimetype='image/png')


if __name__ == '__main__':
    app.run(host='0.0.0.0')
{'fraction_non_alphanumeric': 0.12124463519313304, 'fraction_numerical': 0.0075107296137339056, 'mean_word_length': 2.8204918032786885, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7502535', 'n_tokens_mistral': 1434, 'n_tokens_neox': 1381, 'n_words': 397}