Skip to content
This repository has been archived by the owner on Jun 28, 2021. It is now read-only.

Commit

Permalink
First implementation of linkgalleries directive
Browse files Browse the repository at this point in the history
  • Loading branch information
Chilipp committed Jul 18, 2017
1 parent a4e8f89 commit be3c4bb
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 10 deletions.
3 changes: 3 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
insert_bokeh='0.12.1',
urls='https://github.com/Chilipp/sphinx-nbexamples/blob/master/examples',
)
process_examples = not osp.exists(osp.join(osp.dirname(__file__), 'examples'))


if on_rtd:
Expand Down Expand Up @@ -401,6 +402,8 @@
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'sphinx': ('http://sphinx-doc.org/', None),
'sphinx_nbexamples': ('http://sphinx-nbexamples.readthedocs.io/en/dev/',
None),
}
if six.PY3:
intersphinx_mapping['python'] = ('https://docs.python.org/3.4/', None)
Expand Down
7 changes: 4 additions & 3 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
==============================================
Extending your autodoc API docs with a summary
==============================================
=============================================================
Create an examples gallery with sphinx from Jupyter Notebooks
=============================================================

.. start-badges
Expand Down Expand Up @@ -78,6 +78,7 @@ Content

installing
getting_started
linkgalleries
examples/index
api/sphinx_nbexamples

Expand Down
8 changes: 8 additions & 0 deletions docs/linkgalleries.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.. _linking-galleries:

Linking to other galleries
==========================

.. linkgalleries::

sphinx_nbexamples examples
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def readme():


setup(name='sphinx-nbexamples',
version='0.1.3',
version='0.2.0',
description=(
'Create an examples gallery with sphinx from Jupyter Notebooks'),
long_description=readme(),
Expand Down
66 changes: 60 additions & 6 deletions sphinx_nbexamples/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
from shutil import copyfile
import logging
import subprocess as spr
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives
from docutils.statemachine import ViewList
from docutils import nodes

if six.PY2:
from itertools import imap as map
Expand All @@ -41,7 +45,7 @@
from ordereddict import OrderedDict


__version__ = '0.1.3'
__version__ = '0.2.0'

__author__ = "Philipp Sommer"

Expand Down Expand Up @@ -327,7 +331,7 @@ def process_notebook(self, disable_warnings=True):
try:
ep.preprocess(nb, {'metadata': {'path': in_dir}})
except nbconvert.preprocessors.execute.CellExecutionError:
logging.getLogger(__name__).critical(
logger.critical(
'Error while processing %s!', self.infile, exc_info=True)
else:
logger.info('Done. Seconds needed: %i',
Expand Down Expand Up @@ -549,12 +553,11 @@ def scale_image(self, in_fname, out_fname, max_width, max_height):

def save_thumbnail(self, image_path):
"""Save the thumbnail image"""
base_image_name = os.path.splitext(os.path.basename(image_path))[0]
thumb_dir = os.path.join(os.path.dirname(image_path), 'thumb')
create_dirs(thumb_dir)

thumb_file = os.path.join(thumb_dir,
'example_glr_%s_thumb.png' % base_image_name)
'%s_thumb.png' % self.reference)
if os.path.exists(image_path):
self.scale_image(image_path, thumb_file, 400, 280)
self.thumb_file = thumb_file
Expand All @@ -578,8 +581,8 @@ def copy_thumbnail_figure(self):
if not isstring(self.nb.metadata.thumbnail_figure):
ret = self.nb.metadata.thumbnail_figure
else:
ret = osp.join(osp.dirname(self.outfile),
self.nb.metadata.thumbnail_figure)
ret = osp.join(osp.dirname(self.outfile), 'images',
osp.basename(self.nb.metadata.thumbnail_figure))
copyfile(osp.join(osp.dirname(self.infile),
self.nb.metadata.thumbnail_figure),
ret)
Expand Down Expand Up @@ -875,6 +878,55 @@ def get_url(self, nbfile):
return urls + nbfile


def align(argument):
"""Conversion function for the "align" option."""
return directives.choice(argument, ('left', 'center', 'right'))


class LinkGalleriesDirective(Directive):

has_content = True

option_spec = {'alt': directives.unchanged,
'height': directives.nonnegative_int,
'width': directives.nonnegative_int,
'scale': directives.nonnegative_int,
'align': align,
}

def create_image_nodes(self, link_url, header, thumb_url):
self.options['target'] = link_url
d = directives.images.Figure(
'image', [thumb_url], self.options, ViewList([header]),
self.lineno, self.content_offset, self.block_text, self.state,
self.state_machine)
return d.run()

def run(self):
self.env = self.state.document.settings.env
inventory = self.env.intersphinx_named_inventory
ret = []
for pkg_str in self.content:
pkg, directory = pkg_str.split()
try:
refs = inventory[pkg]['std:label']
except KeyError:
logger.warn('Could not load the inventory of %s!', pkg)
continue
base_url = self.env.config.intersphinx_mapping[pkg][0]
if not base_url.endswith('/'):
base_url += '/'
for key, val in refs.items():
if (key.startswith('gallery_' + directory) and
key.endswith('.ipynb')):
link_url = val[2]
header = val[3]
thumb_url = base_url + '_images/%s_thumb.png' % key
ret.extend(self.create_image_nodes(
link_url, header, thumb_url))
return ret


#: dictionary containing the configuration of the example gallery.
#:
#: Possible keys for the dictionary are the initialization keys of the
Expand Down Expand Up @@ -906,4 +958,6 @@ def setup(app):

app.add_stylesheet('example_gallery_styles.css')

app.add_directive('linkgalleries', LinkGalleriesDirective)

app.connect('builder-inited', Gallery.from_sphinx)

0 comments on commit be3c4bb

Please sign in to comment.