|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +
|
| 5 | +Convert sphinx gallery notebook from empty to image filled |
| 6 | +
|
| 7 | +Created on Fri Sep 1 16:43:45 2017 |
| 8 | +
|
| 9 | +@author: rflamary |
| 10 | +""" |
| 11 | + |
| 12 | +import sys |
| 13 | +import json |
| 14 | +import glob |
| 15 | +import hashlib |
| 16 | +import subprocess |
| 17 | + |
| 18 | +import os |
| 19 | + |
| 20 | +cache_file='cache_nbrun' |
| 21 | + |
| 22 | +path_doc='source/auto_examples/' |
| 23 | +path_nb='../../../notebooks/' |
| 24 | + |
| 25 | +def load_json(fname): |
| 26 | + try: |
| 27 | + f=open(fname) |
| 28 | + nb=json.load(f) |
| 29 | + f.close() |
| 30 | + except (OSError, IOError) : |
| 31 | + nb={} |
| 32 | + return nb |
| 33 | + |
| 34 | +def save_json(fname,nb): |
| 35 | + f=open(fname,'w') |
| 36 | + f.write(json.dumps(nb)) |
| 37 | + f.close() |
| 38 | + |
| 39 | + |
| 40 | +def md5(fname): |
| 41 | + hash_md5 = hashlib.md5() |
| 42 | + with open(fname, "rb") as f: |
| 43 | + for chunk in iter(lambda: f.read(4096), b""): |
| 44 | + hash_md5.update(chunk) |
| 45 | + return hash_md5.hexdigest() |
| 46 | + |
| 47 | +def to_update(fname,cache): |
| 48 | + if fname in cache: |
| 49 | + if md5(path_doc+fname)==cache[fname]: |
| 50 | + res=False |
| 51 | + else: |
| 52 | + res=True |
| 53 | + else: |
| 54 | + res=True |
| 55 | + |
| 56 | + return res |
| 57 | + |
| 58 | +def update(fname,cache): |
| 59 | + |
| 60 | + # jupyter nbconvert --to notebook --execute mynotebook.ipynb --output targte |
| 61 | + print(' '.join(['jupyter','nbconvert','--to','notebook','--execute',path_doc+fname,'--output',path_nb+fname])) |
| 62 | + subprocess.check_call(['jupyter','nbconvert','--to','notebook','--execute',path_doc+fname,'--output',path_nb+fname]) |
| 63 | + cache[fname]=md5(path_doc+fname) |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | +cache=load_json(cache_file) |
| 68 | + |
| 69 | +lst_file=glob.glob(path_doc+'*.ipynb') |
| 70 | + |
| 71 | +lst_file=[os.path.basename(name) for name in lst_file] |
| 72 | + |
| 73 | +for fname in lst_file: |
| 74 | + if to_update(fname,cache): |
| 75 | + print('Updating file: {}'.format(fname)) |
| 76 | + update(fname,cache) |
| 77 | + |
| 78 | + |
| 79 | + |
| 80 | + |
| 81 | +update(lst_file[0],cache) |
| 82 | + |
| 83 | + |
| 84 | +save_json(cache_file,cache) |
0 commit comments