Fix concept-maps link
[rnaseq-cwl-training.git] / bin / extract_figures.py
1 #!/usr/bin/env python
2
3 from __future__ import print_function
4 import sys
5 import os
6 import glob
7 from optparse import OptionParser
8
9 from util import Reporter, read_markdown, IMAGE_FILE_SUFFIX
10
11 def main():
12     """Main driver."""
13
14     args = parse_args()
15     images = []
16     for filename in args.filenames:
17         images += get_images(args.parser, filename)
18     save(sys.stdout, images)
19
20
21 def parse_args():
22     """Parse command-line arguments."""
23
24     parser = OptionParser()
25     parser.add_option('-p', '--parser',
26                       default=None,
27                       dest='parser',
28                       help='path to Markdown parser')
29
30     args, extras = parser.parse_args()
31     require(args.parser is not None,
32             'Path to Markdown parser not provided')
33     require(extras,
34             'No filenames specified')
35
36     args.filenames = extras
37     return args
38
39
40 def get_filenames(source_dir):
41     """Get all filenames to be searched for images."""
42
43     return glob.glob(os.path.join(source_dir, '*.md'))
44
45
46 def get_images(parser, filename):
47     """Extract all images from file."""
48
49     content = read_markdown(parser, filename)
50     result = []
51     find_image_nodes(content['doc'], result)
52     find_image_links(content['doc'], result)
53     return result
54
55
56 def find_image_nodes(doc, result):
57     """Find all nested nodes representing images."""
58
59     if (doc['type'] == 'img') or \
60        ((doc['type'] == 'html_element') and (doc['value'] == 'img')):
61         alt = doc['attr'].get('alt', '')
62         result.append({'alt': alt, 'src': doc['attr']['src']})
63     else:
64         for child in doc.get('children', []):
65             find_image_nodes(child, result)
66
67
68 def find_image_links(doc, result):
69     """Find all links to files in the 'fig' directory."""
70
71     if ((doc['type'] == 'a') and ('attr' in doc) and ('href' in doc['attr'])) \
72        or \
73        ((doc['type'] == 'html_element') and (doc['value'] == 'a') and ('href' in doc['attr'])):
74         path = doc['attr']['href']
75         if os.path.splitext(path)[1].lower() in IMAGE_FILE_SUFFIX:
76             result.append({'alt':'', 'src': doc['attr']['href']})
77     else:
78         for child in doc.get('children', []):
79             find_image_links(child, result)
80
81
82 def save(stream, images):
83     """Save results as Markdown."""
84
85     text = '\n<hr/>\n'.join(['<p><img alt="{0}" src="{1}" /></p>'.format(img['alt'], img['src']) for img in images])
86     print(text, file=stream)
87
88
89 def require(condition, message):
90     """Fail if condition not met."""
91
92     if not condition:
93         print(message, file=sys.stderr)
94         sys.exit(1)
95
96
97 if __name__ == '__main__':
98     main()