aesthetics-of-the-commons
clone your own copy | download snapshot

Snapshots | iceberg

No images in this repository’s iceberg at this time

Inside this repository

scale.py
text/x-python

Download raw (2.7 KB)

#! /usr/bin/env python3


import argparse
import sys
import subprocess
import svgutils as su
import lxml.etree as et
from svg.path import parse_path


def getInfoPath(f, pattern):
    """returns the bounding box of the quadratin"""
    file = open(f, "r")
    elem = et.parse(file)
    root = elem.getroot()
    for child in root:
        for child in root:
            if child.tag == "{http://www.w3.org/2000/svg}path":
                if child.attrib["style"].startswith(pattern):
                    dparse = parse_path(child.attrib["d"])
                    x = dparse[1].start.real
                    y = dparse[2].end.imag * -1
                    h = dparse[1].start.imag
                    w = dparse[1].end.real
    return [x, y, w, h]


def generate(key):
    """generate svg from mpost. batchmode does not choke on errors"""
    Command = "mpost -interaction=batchmode mp/" + str(key) + ".mp"
    process = subprocess.Popen(Command.split(), stdout=subprocess.PIPE)
    output, error = process.communicate()


def main(
    word, outfile="cover/cover.svg", page_width=120, page_height=200, line_height=400
):
    """Compose an SVG cover from the given text"""
    trl_x = 0
    trl_y = 0
    t = []
    i = 0

    tree = su.transform.SVGFigure("{}mm".format(page_width), "{}mm".format(page_height))

    for c in word:
        # Retrieve letter code and generate svg from corresponding mp file
        key = ord(c)
        generate(key)

        if key == 47:  # line-break
            trl_y = trl_y + line_height
            trl_x = 0
        else:
            print(c, " -> ", key)
            svg = "svg/" + str(key) + ".svg"
            info = getInfoPath(svg, "stroke:rgb(100.000000%,0.000000%,0.000000%);")
            fig = su.transform.fromfile(svg)
            # scale = line_height / info[3] # en cours
            scale = 1
            t.append(fig.getroot())
            t[i].moveto((trl_x * scale), (trl_y * scale), scale=scale)
            trl_x = trl_x + info[2]
            tree.append(t[i])
            i = i + 1

    tree.save(outfile)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Generates a cover for Aesthetics of the Commons."
    )
    parser.add_argument(
        "text",
        nargs="?",
        default=sys.stdin,
        help="The text to compose",
    )
    parser.add_argument(
        "-o",
        "--outfile",
        default="cover/cover.svg",
        help="The path of the output file",
    )
    parser.add_argument(
        "-l",
        "--line-height",
        default="400",
        type=int,
        help="line height (default: 400)",
    )

    args = parser.parse_args()

    main(args.text, args.outfile, line_height=args.line_height)