1# Generate a javascript snippet that links to a random gallery example 2 3import os 4import glob 5 6base_dir = os.path.abspath(os.path.dirname(__file__)) 7example_dir = os.path.join(base_dir, 'auto_examples') 8js_fn = os.path.join(base_dir, '_static/random.js') 9 10javascript = '''\ 11 12 function insert_gallery() { 13 var images = {{IMAGES}}; 14 var links = {{LINKS}}; 15 16 ix = Math.floor(Math.random() * images.length); 17 document.write( 18'{{GALLERY_DIV}}'.replace('IMG', images[ix]).replace('URL', links[ix]) 19 ); 20 21 console.log('{{GALLERY_DIV}}'.replace('IMG', images[ix]).replace('URL', links[ix])); 22 }; 23 24''' 25 26gallery_div = '''\ 27<div class="gallery_image"> 28 <a href="URL"><img src="IMG"/></a> 29</div>\ 30''' 31 32examples = glob.glob(os.path.join(example_dir, '**/plot_*.py'), recursive=True) 33 34images, links = [], [] 35image_url = 'https://scikit-image.org/docs/dev/_images/' 36link_url = 'https://scikit-image.org/docs/dev/auto_examples/' 37 38for example_path in examples: 39 example_path = os.path.relpath(example_path, example_dir) 40 41 example_temp, ext = os.path.splitext(example_path) 42 image_path, image_file = os.path.split(example_temp) 43 image_file = 'sphx_glr_' + image_file + '_001.png' 44 45 images.append(image_url + image_file) 46 links.append(link_url + example_temp + '.html') 47 48javascript = javascript.replace('{{IMAGES}}', str(images)) 49javascript = javascript.replace('{{LINKS}}', str(links)) 50javascript = javascript.replace('{{GALLERY_DIV}}', ''.join(gallery_div.split('\n'))) 51 52f = open(js_fn, 'w') 53f.write(javascript) 54f.close() 55