Snakefile 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. try:
  118. with open(lyxfile) as f:
  119. lyx_text = f.read()
  120. for m in regex.finditer('\\\\(?:input|loadglsentries){(.*?[.]tex)}', lyx_text):
  121. yield m.group(1)
  122. except FileNotFoundError:
  123. pass
  124. def lyx_bib_deps(lyxfile):
  125. '''Return an iterator over all bib files referenced by a Lyx file.
  126. This will only return the names of existing files, so it will be
  127. unreliable in the case of an auto-generated bib file.
  128. '''
  129. try:
  130. with open(lyxfile) as f:
  131. lyx_text = f.read()
  132. bib_names = regex.search('bibfiles "(.*?)"', lyx_text).group(1).split(',')
  133. # Unfortunately LyX doesn't indicate which bib names refer to
  134. # files in the current directory and which don't. Currently that's
  135. # not a problem for me since all my refs are in bib files in the
  136. # current directory.
  137. for bn in bib_names:
  138. bib_path = bn + '.bib'
  139. yield bib_path
  140. except FileNotFoundError:
  141. pass
  142. def lyx_gfx_deps(lyxfile):
  143. '''Return an iterator over all graphics files included by a LyX file.'''
  144. try:
  145. with open(lyxfile) as f:
  146. lyx_text = f.read()
  147. for m in regex.finditer('\\\\begin_inset Graphics\\s+filename (.*?)$', lyx_text, regex.MULTILINE):
  148. yield m.group(1)
  149. except FileNotFoundError:
  150. pass
  151. def lyx_hrefs(lyxfile):
  152. '''Return an iterator over hrefs in a LyX file.'''
  153. try:
  154. pattern = '''
  155. (?xsm)
  156. ^ LatexCommand \\s+ href \\s* \\n
  157. (?: name \\b [^\\n]+ \\n )?
  158. target \\s+ "(.*?)" $
  159. '''
  160. with open(lyxfile) as f:
  161. return (urllib.parse.unquote(m.group(1)) for m in
  162. re.finditer(pattern, f.read()))
  163. except FileNotFoundError:
  164. pass
  165. def tex_gfx_extensions(tex_format = 'xetex'):
  166. '''Return the ordered list of graphics extensions.
  167. This yields the list of extensions that TeX will try for an
  168. \\includegraphics path.
  169. '''
  170. try:
  171. cmdout = check_output_decode(['texdef', '-t', tex_format, '-p', 'graphicx', 'Gin@extensions'])
  172. m = regex.search('^macro:->(.*?)$', cmdout, regex.MULTILINE)
  173. return m.group(1).split(',')
  174. except FileNotFoundError:
  175. return ()
  176. rsync_common_args = ['-rL', '--size-only', '--delete', '--exclude', '.DS_Store', '--delete-excluded',]
  177. rule build_all:
  178. input: 'thesis.pdf', 'thesis-final.pdf'
  179. # Note: Any rule that generates an input LyX file for this rule must
  180. # be marked as a checkpoint. See
  181. # https://snakemake.readthedocs.io/en/stable/snakefiles/rules.html#data-dependent-conditional-execution
  182. rule lyx_to_pdf:
  183. '''Produce PDF output for a LyX file.'''
  184. input: lyxfile = '{basename}.lyx',
  185. gfx_deps = lambda wildcards: lyx_gfx_deps(wildcards.basename + '.lyx'),
  186. bib_deps = lambda wildcards: lyx_bib_deps(wildcards.basename + '.lyx'),
  187. tex_deps = lambda wildcards: lyx_input_deps(wildcards.basename + '.lyx'),
  188. # This rule doesn't produce the PDFs in graphics/
  189. output: pdf='{basename,(?!graphics/).*}.pdf'
  190. run:
  191. if not LYX_PATH or LYX_PATH == '/bin/false':
  192. raise Exception('Path to LyX executable could not be found.')
  193. shell('''{LYX_PATH:q} -batch --verbose --export-to pdf4 {output.pdf:q} {input.lyxfile:q}''')
  194. if PDFINFO_PATH:
  195. shell('''{PDFINFO_PATH} {output.pdf:q}''')
  196. checkpoint lyx_add_final:
  197. '''Copy LyX file and add final option.'''
  198. input: lyxfile = '{basename}.lyx'
  199. # Ensure we can't get file-final-final-final-final.lyx
  200. output: lyxtemp = temp('{basename,(?!graphics/).*(?<!-final)}-final.lyx')
  201. run:
  202. with open(input.lyxfile, 'r') as infile, \
  203. open(output.lyxtemp, 'w') as outfile:
  204. lyx_text = infile.read()
  205. if not regex.search('\\\\options final', lyx_text):
  206. lyx_text = regex.sub('\\\\use_default_options true', '\\\\options final\n\\\\use_default_options true', lyx_text)
  207. outfile.write(lyx_text)
  208. # TODO: Remove all URLs from entries with a DOI
  209. rule process_bib:
  210. '''Preprocess bib file for LaTeX.
  211. For entries with a DOI, all URLs are stripped, since the DOI already
  212. provides a clickable link. For entries with no DOI, all but one URL is
  213. discarded, since LyX can't handle entries with multiple URLs. The
  214. shortest URL is kept.'''
  215. input: '{basename}.bib'
  216. output: '{basename,.*(?<!-PROCESSED)}-PROCESSED.bib'
  217. run:
  218. with open(input[0]) as infile:
  219. bib_db = bibtexparser.load(infile)
  220. entries = bib_db.entries
  221. for entry in entries:
  222. if 'doi' in entry:
  223. try:
  224. del entry['url']
  225. except KeyError:
  226. pass
  227. else:
  228. try:
  229. entry_urls = regex.split('\\s+', entry['url'])
  230. shortest_url = min(entry_urls, key=len)
  231. # Need to fix e.g. 'http://www.pubmedcentral.nih.gov/articlerender.fcgi?artid=55329{\\&}tool=pmcentrez{\\&}rendertype=abstract'
  232. shortest_url = re.sub('\\{\\\\(.)\\}', '\\1', shortest_url)
  233. entry['url'] = shortest_url
  234. except KeyError:
  235. pass
  236. new_db = BibDatabase()
  237. new_db.entries = entries
  238. with open(output[0], 'w') as outfile:
  239. bibtexparser.dump(new_db, outfile)
  240. rule pdf_extract_page:
  241. '''Extract a single page from a multi-page PDF.'''
  242. # Input is a PDF whose basename doesn't already have a page number
  243. input: pdf = 'graphics/{basename}.pdf'
  244. output: pdf = 'graphics/{basename}-PAGE{pagenum,[1-9][0-9]*}.pdf'
  245. run:
  246. # This could be done with a regex constraint on basename,
  247. # except that variable width lookbehind isn't supported.
  248. # Unfortunately, that makes this a runtime error instead of an
  249. # error during DAG construction.
  250. if regex.search('-PAGE[0-9]+$', wildcards.basename):
  251. raise ValueError("Can't extract page from extracted page PDF.")
  252. shell('pdfseparate -f {wildcards.pagenum:q} -l {wildcards.pagenum:q} {input:q} {output:q}')
  253. rule pdf_crop:
  254. '''Crop away empty margins from a PDF.'''
  255. input: pdf = 'graphics/{basename}.pdf'
  256. output: pdf = 'graphics/{basename,.*(?<!-CROP)}-CROP.pdf'
  257. shell: 'pdfcrop --resolution 300 {input:q} {output:q}'
  258. rule pdf_raster:
  259. '''Rasterize PDF to PNG at 600 PPI.'''
  260. input: pdf = 'graphics/{basename}.pdf'
  261. output: png = 'graphics/{basename}-RASTER.png'
  262. shell: 'pdftoppm -r 600 {input:q} | convert - {output:q}'
  263. rule png_crop:
  264. '''Crop away empty margins from a PNG.'''
  265. input: pdf = 'graphics/{basename}.png'
  266. output: pdf = 'graphics/{basename,.*(?<!-CROP)}-CROP.png'
  267. shell: 'convert {input:q} -trim {output:q}'
  268. rule svg_to_pdf:
  269. input: 'graphics/{filename}.svg'
  270. output: 'graphics/{filename}-SVG.pdf'
  271. shell: '''inkscape {input:q} --export-pdf={output:q} --export-dpi=300'''
  272. rule R_to_html:
  273. '''Render an R script as syntax-hilighted HTML.'''
  274. input: '{dirname}/{basename}.R'
  275. output: '{dirname}/{basename,[^/]+}.R.html'
  276. shell: 'pygmentize -f html -O full -l R -o {output:q} {input:q}'