metapost-workshops
clone your own copy | download snapshot

Snapshots | iceberg

Inside this repository

api.py
text/x-python

Download raw (2.3 KB)

#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from datetime import datetime
import subprocess
import time
import os.path
import shutil
import random
from flask import Flask, Response, app, request, render_template
import sys
from hpgl_output_adapted import HpglOutputAdapted

speed = 15
force = 1
# Todo make penCount argument of the script
penCount = 1  # change this variable to the amount of pens in the plotter


def cm(l):
    return l * 400


def mm(l):
    return l * 40


# position of label in mm
labelposition = [mm(15), mm(15)]
labelsize = [0.2, 0.3]  # Character width, height in centimeters
lineheight = cm(labelsize[1] * 1.75)

cache_dir = "../hpgl"


def svg_to_hpgl(svgfile, speed=15, force=1, penCount=1):
    e = HpglOutputAdapted()
    e.affect([
        '--orientation', '0',
        '--force', '0',
        '--overcut', '0',
        '--precut', 'false',
        '--flat', '4',
        '--toolOffset', '0',
        '--autoAlign', 'false',
        '--speed', '{}'.format(speed),
        '--penCount', '{}'.format(penCount),
        '--force', '{}'.format(force),
        svgfile], False)

    return e.hpgl


def make_cache_file(hpgl):
    filename = os.path.join(
        cache_dir, '{}-{}.hpgl'.format(int(time.time()), random.randint(0, 1000)))

    with open(filename, 'w') as h:
        h.write(hpgl)

    h.close()


app = Flask(__name__)


@app.route("/api/plot/")
def plot():
    timestamp = int(time.time())
    charnum = int(request.args.get('charcode'))
    svgfile = 'svg/{}.svg'.format(charnum)
    svgsnap = 'svg/snaps/{}-{}.svg'.format(charnum, timestamp)

    mpfile = 'mpost/{}.mp'.format(charnum)
    mpsnap = 'mpost/snaps/{}-{}.mp'.format(charnum, timestamp)

    shutil.copy(svgfile, svgsnap)
    shutil.copy(mpfile, mpsnap)

    hpgl = svg_to_hpgl(svgsnap, speed, force, penCount)
    hpgl += ';PU;SP1;SI{},{};'.format(labelsize[0], labelsize[1])
    hpgl += 'PA{},{};'.format(labelposition[0], labelposition[1])
    hpgl += 'LB{}{}'.format(os.path.basename(svgfile), chr(3))
    hpgl += 'PA{},{};'.format(labelposition[0],
                              labelposition[1] - lineheight)
    hpgl += 'LB{}{};'.format(datetime.now().strftime("%d-%m-%Y %H:%M"), chr(3))

    make_cache_file(hpgl)

    return '100'


if __name__ == "__main__":
    app.run(host="localhost", port=5555, debug=True)