From 17984b91d82d6ebc0455fe0b9faacdb65cd0c155 Mon Sep 17 00:00:00 2001 From: Joscha Date: Sun, 5 May 2019 09:29:34 +0000 Subject: [PATCH] Add initial version of shape script --- shape/.gitignore | 5 +++++ shape/README.md | 4 ++++ shape/shape.py | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 shape/.gitignore create mode 100644 shape/README.md create mode 100644 shape/shape.py diff --git a/shape/.gitignore b/shape/.gitignore new file mode 100644 index 0000000..9e7fffa --- /dev/null +++ b/shape/.gitignore @@ -0,0 +1,5 @@ +# venv stuff +bin/ +lib/ +lib64 +pyvenv.cfg diff --git a/shape/README.md b/shape/README.md new file mode 100644 index 0000000..1da58be --- /dev/null +++ b/shape/README.md @@ -0,0 +1,4 @@ +# Shape + +A similar idea to [visualize](../visualize/), but converts text files to pngs +(with syntax highlighting support for various languages). diff --git a/shape/shape.py b/shape/shape.py new file mode 100644 index 0000000..3aaa6ba --- /dev/null +++ b/shape/shape.py @@ -0,0 +1,48 @@ +import argparse +import PIL.Image + +def convert_tabs(line, tabwidth): + result = [] + for char in line: + if char == "\t": + result.append(" " * tabwidth) + else: + result.append(char) + return "".join(result) + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("infile", + help="input source file") + parser.add_argument("outfile", + help="output image file (image format detected based on extension)") + parser.add_argument("--tabwidth", "-w", type=int, default=8, + help="the amount of spaces per tab") + parser.add_argument("--upscale", "-u", action="store_true", + help="increase the output image's size by 10") + args = parser.parse_args() + + with open(args.infile) as f: + text = f.read() + + lines = [convert_tabs(line, args.tabwidth) for line in text.splitlines()] + width = max(map(len, lines)) + height = len(lines) + + image = PIL.Image.new("RGB", (width, height), (255, 255, 255)) + + # Algorithm for drawing the "shape" of code, to be improved later + for y, line in enumerate(lines): + for x, char in enumerate(line): + if not char.isspace(): + image.putpixel((x, y), (0, 0, 0)) + + if args.upscale: + image = image.resize((width * 10, height * 10), + resample=PIL.Image.NEAREST) + + with open(args.outfile, "wb") as f: + image.save(f) + +if __name__ == "__main__": + main()