|
| 1 | +""" |
| 2 | +Sphinx plugin to run generate a gallery for notebooks |
| 3 | +""" |
| 4 | +import base64 |
| 5 | +import dataclasses |
| 6 | +import json |
| 7 | +import os |
| 8 | +import pathlib |
| 9 | +import random |
| 10 | +import shutil |
| 11 | +from textwrap import dedent |
| 12 | + |
| 13 | +import matplotlib.image |
| 14 | +import matplotlib.pyplot as plt |
| 15 | +import pandas as pd |
| 16 | +import yaml |
| 17 | + |
| 18 | +with open('lorem_ipsum.txt') as fid: |
| 19 | + descriptions = fid.read().split('\n\n') |
| 20 | + |
| 21 | + |
| 22 | +DOC_SRC = pathlib.Path(os.path.dirname(os.path.abspath(__file__))).parent |
| 23 | +default_img_loc = DOC_SRC / '_static/images/sphinx-logo.png' |
| 24 | +thumbnail_dir = DOC_SRC / '_static/thumbnails' |
| 25 | +thumbnail_dir.mkdir(parents=True, exist_ok=True) |
| 26 | + |
| 27 | + |
| 28 | +def create_thumbnail(infile, width=275, height=275, cx=0.5, cy=0.5, border=4): |
| 29 | + """Overwrites `infile` with a new file of the given size""" |
| 30 | + im = matplotlib.image.imread(infile) |
| 31 | + rows, cols = im.shape[:2] |
| 32 | + size = min(rows, cols) |
| 33 | + if size == cols: |
| 34 | + xslice = slice(0, size) |
| 35 | + ymin = min(max(0, int(cx * rows - size // 2)), rows - size) |
| 36 | + yslice = slice(ymin, ymin + size) |
| 37 | + else: |
| 38 | + yslice = slice(0, size) |
| 39 | + xmin = min(max(0, int(cx * cols - size // 2)), cols - size) |
| 40 | + xslice = slice(xmin, xmin + size) |
| 41 | + thumb = im[yslice, xslice] |
| 42 | + thumb[:border, :, :3] = thumb[-border:, :, :3] = 0 |
| 43 | + thumb[:, :border, :3] = thumb[:, -border:, :3] = 0 |
| 44 | + |
| 45 | + dpi = 100 |
| 46 | + fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi) |
| 47 | + |
| 48 | + ax = fig.add_axes([0, 0, 1, 1], aspect='auto', frameon=False, xticks=[], yticks=[]) |
| 49 | + ax.imshow(thumb, aspect='auto', resample=True, interpolation='bilinear') |
| 50 | + fig.savefig(infile, dpi=dpi) |
| 51 | + plt.close(fig) |
| 52 | + return fig |
| 53 | + |
| 54 | + |
| 55 | +@dataclasses.dataclass |
| 56 | +class NotebookInfo: |
| 57 | + filepath: pathlib.Path |
| 58 | + default_img_loc: pathlib.Path |
| 59 | + thumbnail_dir: pathlib.Path |
| 60 | + src_dir: pathlib.Path |
| 61 | + |
| 62 | + def __post_init__(self): |
| 63 | + self.thumbnail_dir.mkdir(parents=True, exist_ok=True) |
| 64 | + self.png_path = self.thumbnail_dir / f'{self.filepath.stem}.png' |
| 65 | + with open(self.filepath) as fid: |
| 66 | + self.json_source = json.load(fid) |
| 67 | + self.gen_preview() |
| 68 | + |
| 69 | + nb_id = f'{self.filepath.relative_to(self.src_dir).parent}/{self.filepath.stem}' |
| 70 | + self.info = { |
| 71 | + 'thumbnail': f'../{self.png_path.relative_to(self.src_dir).as_posix()}', |
| 72 | + 'notebook': f'../{self.filepath.relative_to(self.src_dir).as_posix()}', |
| 73 | + 'title': self.extract_title(), |
| 74 | + 'url': f'../{nb_id}.html', |
| 75 | + 'id': nb_id, |
| 76 | + 'description': random.choice(descriptions)[:200].strip(), |
| 77 | + } |
| 78 | + |
| 79 | + def gen_preview(self): |
| 80 | + preview = self.extract_preview_pic() |
| 81 | + if preview is not None: |
| 82 | + with open(self.png_path, 'wb') as buff: |
| 83 | + buff.write(preview) |
| 84 | + else: |
| 85 | + shutil.copy(self.default_img_loc, self.png_path) |
| 86 | + |
| 87 | + create_thumbnail(self.png_path) |
| 88 | + |
| 89 | + def extract_preview_pic(self): |
| 90 | + """Use the last image in the notebook as preview pic""" |
| 91 | + pic = None |
| 92 | + for cell in self.json_source['cells']: |
| 93 | + for output in cell.get('outputs', []): |
| 94 | + if 'image/png' in output.get('data', []): |
| 95 | + pic = output['data']['image/png'] |
| 96 | + if pic is not None: |
| 97 | + return base64.b64decode(pic) |
| 98 | + return None |
| 99 | + |
| 100 | + def extract_title(self): |
| 101 | + for cell in self.json_source['cells']: |
| 102 | + if cell['cell_type'] == 'markdown': |
| 103 | + rows = [row.strip() for row in cell['source'] if row.strip()] |
| 104 | + for row in rows: |
| 105 | + if row.startswith('# '): |
| 106 | + return row[2:].replace(':', '-') |
| 107 | + return self.filepath.stem.replace('_', ' ').replace(':', '-') |
| 108 | + |
| 109 | + |
| 110 | +def build_gallery(srcdir, gallery, contains_notebooks): |
| 111 | + src_dir = pathlib.Path(srcdir) |
| 112 | + os.chdir(srcdir) |
| 113 | + target_dir = src_dir / f'{gallery}_gallery' |
| 114 | + image_dir = target_dir / '_thumbnails' |
| 115 | + image_dir.mkdir(parents=True, exist_ok=True) |
| 116 | + |
| 117 | + if contains_notebooks: |
| 118 | + notebooks_path = src_dir / 'notebooks' |
| 119 | + notebooks = sorted( |
| 120 | + [notebook for notebook in notebooks_path.glob('**/*.ipynb') if 'checkpoint' not in notebook.name] |
| 121 | + ) |
| 122 | + entries = [ |
| 123 | + NotebookInfo(note, default_img_loc=default_img_loc, thumbnail_dir=image_dir, src_dir=src_dir).info |
| 124 | + for note in notebooks |
| 125 | + ] |
| 126 | + df = pd.DataFrame(entries).sort_values(by=['title']) |
| 127 | + entries = df.to_dict(orient='records') |
| 128 | + with open(target_dir / f'{gallery}_gallery.yaml', 'w') as fid: |
| 129 | + yaml.dump(entries, fid) |
| 130 | + |
| 131 | + panels_body = [] |
| 132 | + for entry in entries: |
| 133 | + x = f"""\ |
| 134 | + --- |
| 135 | + :img-top: {entry["thumbnail"]} |
| 136 | + +++ |
| 137 | + **{entry['title']}** |
| 138 | +
|
| 139 | + {entry['description'][:50]} ... |
| 140 | +
|
| 141 | + {{link-badge}}`{entry["url"]},"rendered-notebook",cls=badge-secondary text-white float-left p-2 mr-1` |
| 142 | + """ |
| 143 | + |
| 144 | + panels_body.append(x) |
| 145 | + |
| 146 | + panels_body = '\n'.join(panels_body) |
| 147 | + |
| 148 | + gallery_content = f'''# {gallery.capitalize()} Gallery |
| 149 | +````{{panels}} |
| 150 | +:container: full-width |
| 151 | +:column: text-left col-6 col-lg-4 |
| 152 | +:card: +my-2 |
| 153 | +:img-top-cls: w-75 m-auto p-2 |
| 154 | +:body: d-none |
| 155 | +
|
| 156 | +{dedent(panels_body)} |
| 157 | +```` |
| 158 | +''' |
| 159 | + with open(target_dir / 'index.md', 'w') as fid: |
| 160 | + fid.write(dedent(gallery_content)) |
| 161 | + |
| 162 | + |
| 163 | +def main(app): |
| 164 | + for gallery in [('notebooks', True)]: |
| 165 | + build_gallery(app.builder.srcdir, gallery[0], gallery[1]) |
| 166 | + |
| 167 | + |
| 168 | +def setup(app): |
| 169 | + app.connect('builder-inited', main) |
0 commit comments