1
Fork 0
This repository has been archived on 2023-03-26. You can view files and clone it, but cannot push or open issues or pull requests.
tex-template-builder/build.py

69 lines
2 KiB
Python
Raw Normal View History

2018-03-26 09:42:38 +01:00
#!/usr/bin/env python3
import argparse
import pathlib
import os
import subprocess
2018-03-28 19:47:06 +01:00
import re
import tempfile
2018-03-26 09:42:38 +01:00
CWD = pathlib.Path(os.getcwd())
BASE_DIR = pathlib.Path(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_FILE = BASE_DIR / 'main.tex'
OUTPUT_FILE = CWD / 'output.pdf'
2018-03-28 19:47:06 +01:00
WORDCOUNT_TEMPLATE = BASE_DIR / 'wordcount.yaml'
2018-03-26 09:42:38 +01:00
2018-03-28 20:17:10 +01:00
def build(input_file, additional_args=None):
2018-03-26 09:42:38 +01:00
build_args = ['pandoc', str(input_file)]
2018-03-28 19:47:06 +01:00
if additional_args is not None:
build_args.extend(additional_args)
2018-03-26 09:42:38 +01:00
build_args.extend([
'--template',
str(TEMPLATE_FILE),
'-o',
str(OUTPUT_FILE)
])
return subprocess.run(build_args, cwd=str(BASE_DIR), check=True)
2018-03-28 20:17:10 +01:00
def get_word_count():
2018-03-28 19:47:06 +01:00
words = subprocess.check_output([
'pdftotext', str(OUTPUT_FILE), '-'
], cwd=str(BASE_DIR))
return len(re.findall(r'\w+', words.decode()))
2018-03-28 20:17:10 +01:00
def write_wordcount():
2018-03-28 19:47:06 +01:00
_, out_file_path = tempfile.mkstemp(suffix='.yaml')
wordcount = get_word_count()
with open(out_file_path, 'w') as out_file:
with WORDCOUNT_TEMPLATE.open() as template:
out_file.write(template.read().format(wordcount=wordcount))
return pathlib.Path(out_file_path)
def parse_args():
2018-03-26 09:42:38 +01:00
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", help="Set verbosity level (repeat argument)", action="count", default=0)
parser.add_argument("input", help="Input File", action='store', type=pathlib.Path,)
parser.add_help = True
2018-03-28 19:47:06 +01:00
return parser.parse_args()
2018-03-26 09:42:38 +01:00
if __name__ == '__main__':
args = parse_args()
input_file = args.input.resolve()
operating_dir = input_file.parents[0]
context_file = operating_dir.joinpath('context.yaml')
2018-03-26 09:42:38 +01:00
if not input_file.is_file():
raise ValueError("Failed to find {}".format(input_file))
additional_args = []
if context_file.exists():
additional_args.append(str(context_file))
build(input_file, additional_args)
additional_args.append(write_wordcount())
2018-03-28 21:31:48 +01:00
build(input_file, additional_args)