Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/main/custom_directives.py
Views: 710
from docutils.parsers.rst import Directive, directives1from docutils.statemachine import StringList2from docutils import nodes3import re4import os5import sphinx_gallery67try:8FileNotFoundError9except NameError:10FileNotFoundError = IOError111213class IncludeDirective(Directive):14"""Include source file without docstring at the top of file.1516Implementation just replaces the first docstring found in file17with '' once.1819Example usage:2021.. includenodoc:: /beginner/examples_tensor/two_layer_net_tensor.py2223"""2425# defines the parameter the directive expects26# directives.unchanged means you get the raw value from RST27required_arguments = 128optional_arguments = 029final_argument_whitespace = True30has_content = False31add_index = False3233docstring_pattern = r'"""(?P<docstring>(?:.|[\r\n])*?)"""\n'34docstring_regex = re.compile(docstring_pattern)3536def run(self):37document = self.state.document38env = document.settings.env39rel_filename, filename = env.relfn2path(self.arguments[0])4041try:42text = open(filename).read()43text_no_docstring = self.docstring_regex.sub('', text, count=1)4445code_block = nodes.literal_block(text=text_no_docstring)46return [code_block]47except FileNotFoundError as e:48print(e)49return []505152class GalleryItemDirective(Directive):53"""54Create a sphinx gallery thumbnail for insertion anywhere in docs.5556Optionally, you can specify the custom figure and intro/tooltip for the57thumbnail.5859Example usage:6061.. galleryitem:: intermediate/char_rnn_generation_tutorial.py62:figure: _static/img/char_rnn_generation.png63:intro: Put your custom intro here.6465If figure is specified, a thumbnail will be made out of it and stored in66_static/thumbs. Therefore, consider _static/thumbs as a 'built' directory.67"""6869required_arguments = 170optional_arguments = 071final_argument_whitespace = True72option_spec = {'figure': directives.unchanged,73'intro': directives.unchanged}74has_content = False75add_index = False7677def run(self):78args = self.arguments79fname = args[-1]8081env = self.state.document.settings.env82fname, abs_fname = env.relfn2path(fname)83basename = os.path.basename(fname)84dirname = os.path.dirname(fname)8586try:87if 'intro' in self.options:88intro = self.options['intro'][:195] + '...'89else:90_, blocks = sphinx_gallery.gen_rst.split_code_and_text_blocks(abs_fname)91intro, _ = sphinx_gallery.gen_rst.extract_intro_and_title(abs_fname, blocks[0][1])9293thumbnail_rst = ''94#sphinx_gallery.backreferences._thumbnail_div(95# dirname, basename, intro)9697if 'figure' in self.options:98rel_figname, figname = env.relfn2path(self.options['figure'])99save_figname = os.path.join('_static/thumbs/',100os.path.basename(figname))101102try:103os.makedirs('_static/thumbs')104except OSError:105pass106107sphinx_gallery.gen_rst.scale_image(figname, save_figname,108400, 280)109# replace figure in rst with simple regex110thumbnail_rst = re.sub(r'..\sfigure::\s.*\.png',111'.. figure:: /{}'.format(save_figname),112thumbnail_rst)113114thumbnail = StringList(thumbnail_rst.split('\n'))115thumb = nodes.paragraph()116self.state.nested_parse(thumbnail, self.content_offset, thumb)117118return [thumb]119except FileNotFoundError as e:120print(e)121return []122123124GALLERY_TEMPLATE = """125.. raw:: html126127<div class="sphx-glr-thumbcontainer" tooltip="{tooltip}">128129.. only:: html130131.. figure:: {thumbnail}132133{description}134135.. raw:: html136137</div>138"""139140141class CustomGalleryItemDirective(Directive):142"""Create a sphinx gallery style thumbnail.143144tooltip and figure are self explanatory. Description could be a link to145a document like in below example.146147Example usage:148149.. customgalleryitem::150:tooltip: I am writing this tutorial to focus specifically on NLP for people who have never written code in any deep learning framework151:figure: /_static/img/thumbnails/babel.jpg152:description: :doc:`/beginner/deep_learning_nlp_tutorial`153154If figure is specified, a thumbnail will be made out of it and stored in155_static/thumbs. Therefore, consider _static/thumbs as a 'built' directory.156"""157158required_arguments = 0159optional_arguments = 0160final_argument_whitespace = True161option_spec = {'tooltip': directives.unchanged,162'figure': directives.unchanged,163'description': directives.unchanged}164165has_content = False166add_index = False167168def run(self):169try:170if 'tooltip' in self.options:171tooltip = self.options['tooltip'][:195] + '...'172else:173raise ValueError('tooltip not found')174175if 'figure' in self.options:176env = self.state.document.settings.env177rel_figname, figname = env.relfn2path(self.options['figure'])178thumbnail = os.path.join('_static/thumbs/', os.path.basename(figname))179180try:181os.makedirs('_static/thumbs')182except FileExistsError:183pass184185sphinx_gallery.gen_rst.scale_image(figname, thumbnail, 400, 280)186else:187thumbnail = '_static/img/thumbnails/default.png'188189if 'description' in self.options:190description = self.options['description']191else:192raise ValueError('description not doc found')193194except FileNotFoundError as e:195print(e)196return []197except ValueError as e:198print(e)199raise200return []201202thumbnail_rst = GALLERY_TEMPLATE.format(tooltip=tooltip,203thumbnail=thumbnail,204description=description)205thumbnail = StringList(thumbnail_rst.split('\n'))206thumb = nodes.paragraph()207self.state.nested_parse(thumbnail, self.content_offset, thumb)208return [thumb]209210211class CustomCardItemDirective(Directive):212option_spec = {'header': directives.unchanged,213'image': directives.unchanged,214'link': directives.unchanged,215'card_description': directives.unchanged,216'tags': directives.unchanged}217218def run(self):219try:220if 'header' in self.options:221header = self.options['header']222else:223raise ValueError('header not doc found')224225if 'image' in self.options:226image = "<img src='" + self.options['image'] + "'>"227else:228image = '_static/img/thumbnails/default.png'229230if 'link' in self.options:231link = self.options['link']232else:233link = ''234235if 'card_description' in self.options:236card_description = self.options['card_description']237else:238card_description = ''239240if 'tags' in self.options:241tags = self.options['tags']242else:243tags = ''244245except FileNotFoundError as e:246print(e)247return []248except ValueError as e:249print(e)250raise251return []252253card_rst = CARD_TEMPLATE.format(header=header,254image=image,255link=link,256card_description=card_description,257tags=tags)258card_list = StringList(card_rst.split('\n'))259card = nodes.paragraph()260self.state.nested_parse(card_list, self.content_offset, card)261return [card]262263264CARD_TEMPLATE = """265.. raw:: html266267<div class="col-md-12 tutorials-card-container" data-tags={tags}>268269<div class="card tutorials-card">270271<a href="{link}">272273<div class="card-body">274275<div class="card-title-container">276<h4>{header}</h4>277</div>278279<p class="card-summary">{card_description}</p>280281<p class="tags">{tags}</p>282283<div class="tutorials-image">{image}</div>284285</div>286287</a>288289</div>290291</div>292"""293294class CustomCalloutItemDirective(Directive):295option_spec = {'header': directives.unchanged,296'description': directives.unchanged,297'button_link': directives.unchanged,298'button_text': directives.unchanged}299300def run(self):301try:302if 'description' in self.options:303description = self.options['description']304else:305description = ''306307if 'header' in self.options:308header = self.options['header']309else:310raise ValueError('header not doc found')311312if 'button_link' in self.options:313button_link = self.options['button_link']314else:315button_link = ''316317if 'button_text' in self.options:318button_text = self.options['button_text']319else:320button_text = ''321322except FileNotFoundError as e:323print(e)324return []325except ValueError as e:326print(e)327raise328return []329330callout_rst = CALLOUT_TEMPLATE.format(description=description,331header=header,332button_link=button_link,333button_text=button_text)334callout_list = StringList(callout_rst.split('\n'))335callout = nodes.paragraph()336self.state.nested_parse(callout_list, self.content_offset, callout)337return [callout]338339CALLOUT_TEMPLATE = """340.. raw:: html341342<div class="col-md-6">343<div class="text-container">344<h3>{header}</h3>345<p class="body-paragraph">{description}</p>346<a class="btn with-right-arrow callout-button" href="{button_link}">{button_text}</a>347</div>348</div>349"""350351352