Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redesign gallery based on sphinx-design library #219

Merged
merged 11 commits into from
Jun 30, 2022
119 changes: 59 additions & 60 deletions nbsite/gallery/gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import requests
import sphinx.util

from PIL import Image, ImageOps

try:
import bs4
except:
Expand All @@ -22,7 +24,7 @@
function gallery_toggle(input) {{
backends = {backends};
for (i in backends) {{
entries = $('.'+backends[i]+'_example');
entries = $('.'+backends[i]+'-example');
if (backends[i] == input) {{
entries.show();
}} else {{
Expand Down Expand Up @@ -52,19 +54,12 @@
$(document).ready(function () {{
backends = {backends};
for (var i=0; i<backends.length; i++){{
$('.'+backends[i]+'_example').hide();
$('.'+backends[i]+'-example').hide();
}}
}});
</script>
"""

CLEAR_DIV = """
.. raw:: html

<div style='clear:both'></div>

"""

THUMBNAIL_URL = 'https://assets.holoviews.org/thumbnails'

PREFIX = """
Expand Down Expand Up @@ -117,19 +112,16 @@
"""

THUMBNAIL_TEMPLATE = """
.. raw:: html

<div class="sphx-glr-thumbcontainer {backend}example" tooltip="{label}">

.. figure:: /{thumbnail}

:ref:`{label} <{prefix}gallery_{ref_name}>`

.. raw:: html

</div>

.. grid-item-card:: {label}
:link: {section}/{fname}
:link-type: doc
:class-card: {backend_prefix}example
:shadow: md

.. image:: /{thumbnail}
:alt: {label}
"""

IFRAME_TEMPLATE = """

.. raw:: html
Expand Down Expand Up @@ -157,19 +149,6 @@
</div>
"""

INLINE_GALLERY_STYLE = """

.. raw:: html

<style>
.sphx-glr-section {
display: inline-block;
vertical-align: top;
padding-right: 20px;
}
</style>

"""

DEFAULT_GALLERY_CONF = {
'backends': None,
Expand Down Expand Up @@ -281,10 +260,8 @@ def generate_file_rst(app, src_dir, dest_dir, page, section, backend,
continue

with open(rst_path, 'w') as rst_file:
prefix = '_'.join([p for p in (section, backend, 'gallery') if p])
rst_file.write('.. _%s_%s:\n\n' % (prefix, name))
rst_file.write(title+'\n')
rst_file.write('_'*len(title)+'\n\n')
rst_file.write('='*len(title)+'\n\n')

deployed_file = get_deployed_url(deployment_urls, basename)
if nblink in ['top', 'both']:
Expand Down Expand Up @@ -326,26 +303,44 @@ def add_nblink(rst_file, host, deployed_file, download_as,
path='/'.join(components), basename=basename, ftype=ftype))


def _thumbnail_div(path_components, section, backend, fname, extension, normalize=True, title=None):
def _normalize_label(string):
return ' '.join([s[0].upper()+s[1:] for s in string.split('_')])


def _thumbnail_div(thumb_path, section, backend, fname, normalize=True, title=None):
"""Generates RST to place a thumbnail in a gallery"""
if title is not None:
label = title
elif normalize:
label = fname.replace('_', ' ').title()
label = _normalize_label(fname)
else:
label = fname
thumb = os.path.join(*path_components+['thumbnails', '%s.%s' % (fname, extension)])

# Inside rst files forward slash defines paths
thumb = thumb.replace(os.sep, "/")
prefix = '_'.join([pre for pre in (section, backend) if pre])
backend = backend+'_' if backend else ''
if prefix:
prefix += '_'
thumb_path = thumb_path.replace(os.sep, "/")

if backend:
section = f'{section}/{backend}'

return THUMBNAIL_TEMPLATE.format(
backend=backend, prefix=prefix, thumbnail=thumb, ref_name=fname,
label=label)
backend_prefix=backend+'-', section=section, thumbnail=thumb_path,
label=label, fname=fname
)


def resize_pad(im_pth, desired_size=500):
im = Image.open(im_pth)
old_size = im.size # old_size[0] is in (width, height) format

ratio = float(desired_size)/max(old_size)
new_size = tuple([int(x*ratio) for x in old_size])
w = (desired_size-new_size[0])//2
h = (desired_size-new_size[1])//2

im = im.resize(new_size, Image.ANTIALIAS)
new_im = Image.new("RGBA", (desired_size, desired_size), color=(0, 0, 0, 0))
new_im.paste(im, (w, h))
new_im.save(im_pth)


def generate_gallery(app, page):
Expand Down Expand Up @@ -404,9 +399,6 @@ def generate_gallery(app, page):
label=backend.capitalize()))
gallery_rst += BUTTON_GROUP_TEMPLATE.format(buttons=''.join(buttons), backends=backends)

if inline:
gallery_rst += INLINE_GALLERY_STYLE

for section in sections:
if isinstance(section, dict):
section_backends = section.get('backends', backends)
Expand Down Expand Up @@ -437,9 +429,9 @@ def generate_gallery(app, page):
gallery_rst += f'\n\n{heading}\n{underline}\n\n'

if section:
gallery_rst += f'\n\n.. toctree::\n :glob:\n :hidden:\n\n {heading}\n {section}/*\n\n'
gallery_rst += f'.. toctree::\n :glob:\n :hidden:\n\n {heading}\n {section}/*\n\n'
else:
gallery_rst += f'\n\n.. toctree::\n :glob:\n :hidden:\n\n {heading}\n *\n\n'
gallery_rst += f'.. toctree::\n :glob:\n :hidden:\n\n {heading}\n *\n\n'

if labels:
gallery_rst += '\n\n.. raw:: html\n\n'
Expand All @@ -458,6 +450,8 @@ def generate_gallery(app, page):
if description:
gallery_rst += description + '\n\n'

gallery_rst += '.. grid:: 2 2 4 5\n :gutter: 3\n :margin: 0\n'

thumb_extension = 'png'
for backend in (section_backends or ('',)):
path_components = [page]
Expand Down Expand Up @@ -559,30 +553,35 @@ def generate_gallery(app, page):
if extension == 'py':
continue
thumb_prefix = '_'.join([pre for pre in (section, backend) if pre])
backend_str = backend+'_' if backend else ''
if thumb_prefix:
thumb_prefix += '_'
if basename in titles:
label = titles[basename]
elif normalize:
label = basename.replace('_', ' ').title()
label = _normalize_label(basename)
else:
label = basename
if backend:
section_path = f'{section}/{backend}'
else:
section_path = section
this_entry = THUMBNAIL_TEMPLATE.format(
backend=backend_str, prefix=thumb_prefix, thumbnail=logo_path,
ref_name=basename, label=label)
backend_prefix=backend+'-', section=section_path, thumbnail=logo_path,
fname=basename, label=label
)
else:
logger.info('%s %s thumbnail' % (verb, basename))
thumb_path = os.path.join(*path_components+['thumbnails', '%s.%s' % (basename, thumb_extension)])
if thumb_extension not in ('svg', 'gif'):
resize_pad(os.path.join(doc_dir, thumb_path))
this_entry = _thumbnail_div(
path_components, section, backend, basename,
thumb_extension, normalize, titles.get(basename)
thumb_path, section, backend, basename,
normalize, titles.get(basename)
)

gallery_rst += this_entry
generate_file_rst(app, path, dest_dir, page, section,
backend, thumb_extension, skip, deployment_urls)
# clear at the end of the section
gallery_rst += CLEAR_DIV

if backends or section_backends:
gallery_rst += HIDE_JS.format(backends=repr(backends[1:]))
Expand Down
1 change: 1 addition & 0 deletions nbsite/shared_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ def remove_mystnb_static(app):

extensions = [
'myst_nb',
'sphinx_design',
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
Expand Down
3 changes: 2 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,12 @@ def get_setup_version(root, reponame):
'nbconvert <6.0',
'jupyter_client <6.2',
'myst-nb <0.14',
'sphinx-design',
'notebook',
'sphinx',
'beautifulsoup4',
'jinja2 <3.1',
'pillow',
'pydata-sphinx-theme <0.9.0',
philippjfr marked this conversation as resolved.
Show resolved Hide resolved
philippjfr marked this conversation as resolved.
Show resolved Hide resolved
'myst-parser',
],
Expand All @@ -86,7 +88,6 @@ def get_setup_version(root, reponame):
'sphinx_holoviz_theme',
'holoviews',
'bokeh',
'pillow',
'matplotlib',
'xarray',
'pandas',
Expand Down