Snakefile 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. # -*- coding: utf-8; -*-
  2. import locale
  3. import os.path
  4. import regex
  5. import urllib.parse
  6. import os.path
  7. import bibtexparser
  8. from collections.abc import Iterable, Mapping
  9. from distutils.spawn import find_executable
  10. from fnmatch import fnmatch
  11. from subprocess import check_output, check_call
  12. from tempfile import NamedTemporaryFile
  13. from bibtexparser.bibdatabase import BibDatabase
  14. try:
  15. from os import scandir, walk
  16. except ImportError:
  17. from scandir import scandir, walk
  18. def unnest(*args):
  19. '''Un-nest list- and tuple-like elements in arguments.
  20. "List-like" means anything with a len() and whose elments can be
  21. accessed with numeric indexing, except for string-like elements. It
  22. must also be an instance of the collections.Iterable abstract class.
  23. Dict-like elements and iterators/generators are not affected.
  24. This function always returns a list, even if it is passed a single
  25. scalar argument.
  26. '''
  27. result = []
  28. for arg in args:
  29. if isinstance(arg, str):
  30. # String
  31. result.append(arg)
  32. elif isinstance(arg, Mapping):
  33. # Dict-like
  34. result.append(arg)
  35. elif isinstance(arg, Iterable):
  36. try:
  37. # Duck-typing test for list-ness (a stricter condition
  38. # than just "iterable")
  39. for i in range(len(arg)):
  40. result.append(arg[i])
  41. except TypeError:
  42. # Iterable but not list-like
  43. result.append(arg)
  44. else:
  45. # Not iterable
  46. result.append(arg)
  47. return result
  48. def check_output_decode(*args, encoding=locale.getpreferredencoding(), **kwargs):
  49. '''Shortcut for check.output + str.decode'''
  50. return check_output(*args, **kwargs).decode(encoding)
  51. def find_mac_app(name):
  52. try:
  53. result = \
  54. check_output_decode(
  55. ['mdfind',
  56. 'kMDItemDisplayName=={name}.app&&kMDItemKind==Application'.format(name=name)]).split('\n')[0] or \
  57. check_output_decode(
  58. ['mdfind',
  59. 'kMDItemDisplayName=={name}&&kMDItemKind==Application'.format(name=name)]).split('\n')[0]
  60. if result:
  61. return result
  62. else:
  63. raise Exception("Not found")
  64. except Exception:
  65. return None
  66. def find_lyx():
  67. lyx_finders = [
  68. lambda: find_executable('lyx'),
  69. lambda: os.path.join(find_mac_app('LyX'), 'Contents/MacOS/lyx'),
  70. lambda: '/Applications/Lyx.app/Contents/MacOS/lyx',
  71. ]
  72. for finder in lyx_finders:
  73. try:
  74. lyxpath = finder()
  75. if not lyxpath:
  76. continue
  77. elif not os.access(lyxpath, os.X_OK):
  78. continue
  79. else:
  80. return lyxpath
  81. except Exception:
  82. pass
  83. else:
  84. # Fallback which will just trigger an error when run
  85. return '/bin/false'
  86. LYX_PATH = find_lyx()
  87. PDFINFO_PATH = find_executable('pdfinfo')
  88. def glob_recursive(pattern, top='.', include_hidden=False, *args, **kwargs):
  89. '''Combination of glob.glob and os.walk.
  90. Reutrns the relative path to every file or directory matching the
  91. pattern anywhere in the specified directory hierarchy. Defaults to the
  92. current working directory. Any additional arguments are passed to
  93. os.walk.'''
  94. for (path, dirs, files) in walk(top, *args, **kwargs):
  95. for f in dirs + files:
  96. if include_hidden or f.startswith('.'):
  97. continue
  98. if fnmatch(f, pattern):
  99. yield os.path.normpath(os.path.join(path, f))
  100. def rsync_list_files(*paths, extra_rsync_args=(), include_dirs=False):
  101. '''Iterate over the files in path that rsync would copy.
  102. By default, only files are listed, not directories, since doit doesn't
  103. like dependencies on directories because it can't hash them.
  104. This uses "rsync --list-only" to make rsync directly indicate which
  105. files it would copy, so any exclusion/inclusion rules are taken into
  106. account.
  107. '''
  108. rsync_list_cmd = [ 'rsync', '-r', '--list-only' ] + unnest(extra_rsync_args) + unnest(paths) + [ '.' ]
  109. rsync_out = check_output_decode(rsync_list_cmd).splitlines()
  110. for line in rsync_out:
  111. s = regex.search('^(-|d)(?:\S+\s+){4}(.*)', line)
  112. if s is not None:
  113. if include_dirs or s.group(1) == '-':
  114. yield s.group(2)
  115. def lyx_input_deps(lyxfile):
  116. '''Return an iterator over all tex files included by a Lyx file.'''
  117. with open(lyxfile) as f:
  118. lyx_text = f.read()
  119. for m in regex.finditer('\\\\(?:input|loadglsentries){(.*?[.]tex)}', lyx_text):
  120. yield m.group(1)
  121. def lyx_bib_deps(lyxfile):
  122. '''Return an iterator over all bib files referenced by a Lyx file.
  123. This will only return the names of existing files, so it will be
  124. unreliable in the case of an auto-generated bib file.
  125. '''
  126. with open(lyxfile) as f:
  127. lyx_text = f.read()
  128. bib_names = regex.search('bibfiles "(.*?)"', lyx_text).group(1).split(',')
  129. # Unfortunately LyX doesn't indicate which bib names refer to
  130. # files in the current directory and which don't. Currently that's
  131. # not a problem for me since all my refs are in bib files in the
  132. # current directory.
  133. for bn in bib_names:
  134. bib_path = bn + '.bib'
  135. yield bib_path
  136. def lyx_gfx_deps(lyxfile):
  137. '''Return an iterator over all graphics files included by a LyX file.'''
  138. with open(lyxfile) as f:
  139. lyx_text = f.read()
  140. for m in regex.finditer('\\\\begin_inset Graphics\\s+filename (.*?)$', lyx_text, regex.MULTILINE):
  141. yield m.group(1)
  142. def lyx_hrefs(lyxfile):
  143. '''Return an iterator over hrefs in a LyX file.'''
  144. pattern = '''
  145. (?xsm)
  146. ^ LatexCommand \\s+ href \\s* \\n
  147. (?: name \\b [^\\n]+ \\n )?
  148. target \\s+ "(.*?)" $
  149. '''
  150. with open(lyxfile) as f:
  151. return (urllib.parse.unquote(m.group(1)) for m in
  152. re.finditer(pattern, f.read()))
  153. def tex_gfx_extensions(tex_format = 'xetex'):
  154. '''Return the ordered list of graphics extensions.
  155. This yields the list of extensions that TeX will try for an
  156. \\includegraphics path.
  157. '''
  158. cmdout = check_output_decode(['texdef', '-t', tex_format, '-p', 'graphicx', 'Gin@extensions'])
  159. m = regex.search('^macro:->(.*?)$', cmdout, regex.MULTILINE)
  160. return m.group(1).split(',')
  161. rsync_common_args = ['-rL', '--size-only', '--delete', '--exclude', '.DS_Store', '--delete-excluded',]
  162. rule build_all:
  163. input: 'thesis.pdf', 'thesis-final.pdf'
  164. # Currently assumes the lyx file always exists, because it is required
  165. # to get the gfx and bib dependencies
  166. rule lyx_to_pdf:
  167. '''Produce PDF output for a LyX file.'''
  168. input: lyxfile = '{basename}.lyx',
  169. gfx_deps = lambda wildcards: lyx_gfx_deps(wildcards.basename + '.lyx'),
  170. bib_deps = lambda wildcards: lyx_bib_deps(wildcards.basename + '.lyx'),
  171. tex_deps = lambda wildcards: lyx_input_deps(wildcards.basename + '.lyx'),
  172. # Need to exclude pdfs in graphics/
  173. output: pdf='{basename,(?!graphics/).*(?<!-final)}.pdf'
  174. run:
  175. if not LYX_PATH or LYX_PATH == '/bin/false':
  176. raise Exception('PAth to LyX executable could not be found.')
  177. shell('''{LYX_PATH:q} -batch --verbose --export-to pdf4 {output.pdf:q} {input.lyxfile:q}''')
  178. if PDFINFO_PATH:
  179. shell('''{PDFINFO_PATH} {output.pdf:q}''')
  180. rule lyx_to_pdf_final:
  181. '''Produce PDF output for a LyX file with the final option enabled.'''
  182. input: lyxfile = '{basename}.lyx',
  183. gfx_deps = lambda wildcards: lyx_gfx_deps(wildcards.basename + '.lyx'),
  184. bib_deps = lambda wildcards: lyx_bib_deps(wildcards.basename + '.lyx'),
  185. tex_deps = lambda wildcards: lyx_input_deps(wildcards.basename + '.lyx'),
  186. # Need to exclude pdfs in graphics/
  187. output: pdf='{basename,(?!graphics/).*}-final.pdf',
  188. lyxtemp='{basename,(?!graphics/).*}-final.lyx',
  189. run:
  190. if not LYX_PATH or LYX_PATH == '/bin/false':
  191. raise Exception('PAth to LyX executable could not be found.')
  192. with open(input.lyxfile, 'r') as infile, \
  193. open(output.lyxtemp, 'w') as outfile:
  194. lyx_text = infile.read()
  195. if not regex.search('\\\\options final', lyx_text):
  196. lyx_text = regex.sub('\\\\use_default_options true', '\\\\options final\n\\\\use_default_options true', lyx_text)
  197. outfile.write(lyx_text)
  198. shell('''{LYX_PATH:q} -batch --verbose --export-to pdf4 {output.pdf:q} {output.lyxtemp:q}''')
  199. if PDFINFO_PATH:
  200. shell('''{PDFINFO_PATH} {output.pdf:q}''')
  201. # TODO: Remove all URLs from entries with a DOI
  202. rule process_bib:
  203. '''Preprocess bib file for LaTeX.
  204. For entries with a DOI, all URLs are stripped, since the DOI already
  205. provides a clickable link. For entries with no DOI, all but one URL is
  206. discarded, since LyX can't handle entries with multiple URLs. The
  207. shortest URL is kept.'''
  208. input: '{basename}.bib'
  209. output: '{basename,.*(?<!-PROCESSED)}-PROCESSED.bib'
  210. run:
  211. with open(input[0]) as infile:
  212. bib_db = bibtexparser.load(infile)
  213. entries = bib_db.entries
  214. for entry in entries:
  215. if 'doi' in entry:
  216. try:
  217. del entry['url']
  218. except KeyError:
  219. pass
  220. else:
  221. try:
  222. entry_urls = regex.split('\\s+', entry['url'])
  223. shortest_url = min(entry_urls, key=len)
  224. entry['url'] = shortest_url
  225. except KeyError:
  226. pass
  227. new_db = BibDatabase()
  228. new_db.entries = entries
  229. with open(output[0], 'w') as outfile:
  230. bibtexparser.dump(new_db, outfile)
  231. rule pdf_extract_page:
  232. '''Extract a single page from a multi-page PDF.'''
  233. # Input is a PDF whose basename doesn't already have a page number
  234. input: pdf = 'graphics/{basename}.pdf'
  235. output: pdf = 'graphics/{basename}-PAGE{pagenum,[1-9][0-9]*}.pdf'
  236. run:
  237. # This could be done with a regex constraint on basename,
  238. # except that variable width lookbehind isn't supported.
  239. # Unfortunately, that makes this a runtime error instead of an
  240. # error during DAG construction.
  241. if regex.search('-PAGE[0-9]+$', wildcards.basename):
  242. raise ValueError("Can't extract page from extracted page PDF.")
  243. shell('pdfseparate -f {wildcards.pagenum:q} -l {wildcards.pagenum:q} {input:q} {output:q}')
  244. rule pdf_crop:
  245. '''Crop away empty margins from a PDF.'''
  246. input: pdf = 'graphics/{basename}.pdf'
  247. output: pdf = 'graphics/{basename,.*(?<!-CROP)}-CROP.pdf'
  248. shell: 'pdfcrop --resolution 300 {input:q} {output:q}'
  249. rule pdf_raster:
  250. '''Rasterize PDF to PNG at 600 PPI.'''
  251. input: pdf = 'graphics/{basename}.pdf'
  252. output: png = 'graphics/{basename}-RASTER.png'
  253. shell: 'pdftoppm -r 600 {input:q} | convert - {output:q}'
  254. rule png_crop:
  255. '''Crop away empty margins from a PNG.'''
  256. input: pdf = 'graphics/{basename}.png'
  257. output: pdf = 'graphics/{basename,.*(?<!-CROP)}-CROP.png'
  258. shell: 'convert {input:q} -trim {output:q}'
  259. rule svg_to_pdf:
  260. input: 'graphics/{filename}.svg'
  261. output: 'graphics/{filename}-SVG.pdf'
  262. shell: '''inkscape {input:q} --export-pdf={output:q} --export-dpi=300'''
  263. rule R_to_html:
  264. '''Render an R script as syntax-hilighted HTML.'''
  265. input: '{dirname}/{basename}.R'
  266. output: '{dirname}/{basename,[^/]+}.R.html'
  267. shell: 'pygmentize -f html -O full -l R -o {output:q} {input:q}'