Skip to content

Instantly share code, notes, and snippets.

@romyilano
Last active June 23, 2024 23:54
Show Gist options
  • Save romyilano/33cdae9100b424bf9a0638eb7f182be8 to your computer and use it in GitHub Desktop.
Save romyilano/33cdae9100b424bf9a0638eb7f182be8 to your computer and use it in GitHub Desktop.
general epub script for book printing
import os
import re
import subprocess
import argparse
# Set up argument parsing
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--format", action='append', choices=['tex', 'pdf', 'epub'], type=str.lower, required=True)
parser.add_argument("--skip-image-generation", help="skip image generation", action="store_true")
args = parser.parse_args()
latexEngine = "xelatex"
outputPath = "."
srcDirectory = "src" # Assuming your markdown files are in the 'src' directory
# Create output directory if it doesn't exist
if not os.path.exists(outputPath):
os.makedirs(outputPath)
chapters = []
def injectShaderBlocks(folder, text):
rta = ""
lines = text.split('\n')
for line in lines:
if '<div class="codeAndCanvas"' in line:
shaderTextureResults = re.findall(r'<div class="codeAndCanvas" data=".*" data-imgs="(.*)"></div>', line.rstrip())
shaderFile = re.sub(r'<div class="codeAndCanvas" data="(.*?)"(>| .+>)</div>', r'\1', line.rstrip())
shaderName, shaderExt = os.path.splitext(shaderFile)
shaderPath = os.path.join(folder, shaderFile)
shaderTexturePaths = [os.path.join(folder, f) for f in shaderTextureResults[0].split(",")] if shaderTextureResults else []
shaderString = open(shaderPath, 'r').read()
rta += '```glsl\n' + shaderString.rstrip('\n') + '\n```\n'
shaderImage = os.path.join(folder, "tmp-" + shaderName + ".png")
shaderCommand = "glslViewer {} {} --headless -e wait,0.5 -E screenshot,{}".format(shaderPath, " ".join(shaderTexturePaths), shaderImage)
print(shaderCommand)
if not args.skip_image_generation:
subprocess.call(shaderCommand, shell=True)
rta += "![](" + shaderImage + ")\n"
elif '.gif' in line:
gifPath = re.sub(r'\!\[.*\]\((.*\.gif)\)', r'\1', line.rstrip())
gifName, gifExt = os.path.splitext(gifPath)
pngImage = gifName + ".png"
convertCommand = "convert {} {}".format(gifPath, pngImage)
print(convertCommand)
if not args.skip_image_generation:
subprocess.call(convertCommand, shell=True)
rta += re.sub(r'\!\[(.*)\]\((.*)\.gif\)', r'![\1](\2-0.png)', line) + '\n'
else:
rta += line + '\n'
return rta
# Collect chapters from the src directory
for filename in sorted(os.listdir(srcDirectory)):
if filename.endswith(".md"):
chapterPath = os.path.join(srcDirectory, filename)
with open(chapterPath, "r") as originalChapter:
fileString = originalChapter.read()
# Correct path for images
imgPattern = r'(\!\[.*?\]\()(.*)'
subPattern = r'\1' + srcDirectory + r'/\2'
modifiedChapterString = re.sub(imgPattern, subPattern, fileString)
modifiedChapterString = injectShaderBlocks(srcDirectory, modifiedChapterString)
modifiedChapterPath = os.path.join(srcDirectory, 'tmp-' + filename)
with open(modifiedChapterPath, "w") as modifiedChapter:
modifiedChapter.write(modifiedChapterString)
chapters.append(modifiedChapterPath)
# Set up the appropriate options for the pandoc command
generalOptions = ["-N", "--toc", "--standalone", "--preserve-tabs", "-V documentclass=scrbook", "-V papersize=a4", "-V links-as-note"]
latexOptions = ["--pdf-engine=" + latexEngine]
for outputFormat in args.format:
bookPath = os.path.join(outputPath, "book.{0}".format(outputFormat))
formatOutputOptions = []
if outputFormat == 'epub':
formatOutputOptions = ["--epub-metadata=epub/metadata.xml", "--epub-cover-image=epub/cover.png"]
outputOptions = ["--output={0}".format(bookPath)] + formatOutputOptions
pandocCommand = ["pandoc"] + chapters + outputOptions + generalOptions + latexOptions
# Print out the chapters being built and the flags being used
print("Generating {0} from:".format(bookPath))
for chapter in chapters:
print("\t{0}".format(chapter))
print("Using the following flags:")
for flag in outputOptions + generalOptions + latexOptions:
print("\t{0}".format(flag))
returnCode = subprocess.call(pandocCommand)
if returnCode == 0:
print("Successfully built {0}".format(bookPath))
else:
print("Error in building {0}".format(bookPath))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment