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
2018-03-28 20:17:10 +01:00

67 lines
1.9 KiB
Python
Executable file

#!/usr/bin/env python3
import argparse
import pathlib
import os
import subprocess
import re
import tempfile
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'
CONTEXT_FILE = CWD / 'context.yaml'
WORDCOUNT_TEMPLATE = BASE_DIR / 'wordcount.yaml'
def build(input_file, additional_args=None):
build_args = ['pandoc', str(input_file)]
if CONTEXT_FILE.exists():
build_args.append(str(CONTEXT_FILE))
if additional_args is not None:
build_args.extend(additional_args)
build_args.extend([
'--template',
str(TEMPLATE_FILE),
'-o',
str(OUTPUT_FILE)
])
return subprocess.run(build_args, cwd=str(BASE_DIR), check=True)
def get_word_count():
words = subprocess.check_output([
'pdftotext', str(OUTPUT_FILE), '-'
], cwd=str(BASE_DIR))
return len(re.findall(r'\w+', words.decode()))
def write_wordcount():
_, 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():
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
return parser.parse_args()
if __name__ == '__main__':
args = parse_args()
input_file = args.input.resolve()
if not input_file.is_file():
raise ValueError("Failed to find {}".format(input_file))
build(input_file)
wordcount_metadata_file = write_wordcount()
build(input_file, [str(wordcount_metadata_file)])