2022-04-14

Server API for PIC Scripts

Pic is a language for drawing simple box-and-arrow diagrams, intended as troff preprocessor, a pic script can be translated with pic2plot to SVG or PNG formats. The program pic2plot is included in GNU plotutils and it's either pre-installed or can be easily installed on Linux OS (less so for a Windows machine).

The pic script below (json.pic) represents a typical client-server diagram:

    .PS 8
    VIM:    box "VIM"
            arrow <-> "JSON REQUEST" above "RESPONSE" below
    SERVER: box "SERVER" "bottle micro-framework"
            arrow -> "SVG" above "PNG" below
    STATIC: ellipse "SERVER" "STATIC FILES"
    .PE
    

that can be serialized into a base64 string with:

   cat json.pic |base64 

As previously described here, I can send a JSON request to a server API and display the response directly from VIM.

A simple Bottle micro-framework endpoint that can compile the previous pic script would look something like this:

    @post('/pic2plot')
    def pic2plot():
        import re
        import os
        import tempfile
        import json
        from subprocess import run
        import base64
        from datetime import datetime
        fmt  = request.json.get("fmt")
        pic  = request.json.get("pic")
        filename = "".join([x for x in str(datetime.now()).split(".")[0] if x.isnumeric()])
        pic2plot_exe="/home/tessarinseve/bin/pic2plot"
        tmp = tempfile.mktemp()
        with open(tmp,"w") as tf:
            tf.write(base64.b64decode(pic).decode('utf-8'))

        out=run([f"{pic2plot_exe} -T {fmt} {tmp} > /home/tessarinseve/pic/{filename}.{fmt}"],check=False, capture_output=True,shell=True).stdout
        return f"\nhttps://tessarinseve.pythonanywhere.com/pic/{filename}.{fmt}"
        

Finally, the diagram can be downloaded locally with:

   wget https://tessarinseve.pythonanywhere.com/pic/20220417115035.svg