-
Notifications
You must be signed in to change notification settings - Fork 187
/
custom_directives.py
399 lines (324 loc) · 13.5 KB
/
custom_directives.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
# BSD 3-Clause License
# Copyright (c) 2017, Pytorch contributors
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import unicode_literals
from docutils.parsers.rst import Directive, directives
from docutils.statemachine import StringList
from docutils import nodes
import re
import os
import sphinx_gallery
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
GALLERY_TEMPLATE = """
.. raw:: html
<div class="sphx-glr-thumbcontainer" data-category="{tags}" tooltip="{tooltip}">
.. only:: html
.. figure:: {thumbnail}
{description}
.. raw:: html
</div>
"""
class CustomGalleryItemDirective(Directive):
"""Create a sphinx gallery style thumbnail.
tooltip and figure are self explanatory. Description could be a link to
a document like in below example.
Example usage:
.. customgalleryitem::
:tooltip: I am writing this tutorial to focus specifically on NLP for people who have never written code in any deep learning framework
:figure: /_static/img/thumbnails/babel.jpg
:description: :doc:`/beginner/deep_learning_nlp_tutorial`
If figure is specified, a thumbnail will be made out of it and stored in
_static/thumbs. Therefore, consider _static/thumbs as a 'built' directory.
"""
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = True
option_spec = {'tooltip': directives.unchanged,
'figure': directives.unchanged,
'description': directives.unchanged,
'tags': directives.unchanged}
has_content = False
add_index = False
def run(self):
try:
if 'tooltip' in self.options:
tooltip = self.options['tooltip'][:195]
else:
raise ValueError('tooltip not found')
tags = ""
if 'tags' in self.options:
tags = self.options['tags']
if 'figure' in self.options:
env = self.state.document.settings.env
rel_figname, figname = env.relfn2path(self.options['figure'])
thumbnail = os.path.join(
'_static/thumbs/', os.path.basename(figname))
try:
os.makedirs('_static/thumbs')
except FileExistsError:
pass
sphinx_gallery.gen_rst.scale_image(
figname, thumbnail, 400, 280)
else:
thumbnail = '_static/thumbs/code.png'
if 'description' in self.options:
description = self.options['description']
else:
raise ValueError('description not doc found')
except FileNotFoundError as e:
print(e)
return []
except ValueError as e:
print(e)
raise
return []
thumbnail_rst = GALLERY_TEMPLATE.format(tooltip=tooltip,
thumbnail=thumbnail,
description=description,
tags=tags)
thumbnail = StringList(thumbnail_rst.split('\n'))
thumb = nodes.paragraph()
self.state.nested_parse(thumbnail, self.content_offset, thumb)
return [thumb]
YOUTUBE_TEMPLATE = """
.. raw:: html
<a href="https://youtube.com/watch?v={id}" target="_blank">
<div class="card">
<img class="card-img-top img-fluid" src="https://img.youtube.com/vi/{id}/hqdefault.jpg"/>
<div class="card-body">
<h4 class="card-title">{title}</h4>
<p class="card-text grey-text">{author}</p>
<p class="card-text">
{description}
</p>
</div>
<div class="white-text watch">
<hr>
<h5>Watch <i class="fas fa-angle-double-right"></i></h5>
</div>
</div>
</a>
"""
class YoutubeItemDirective(Directive):
"""Create a sphinx gallery style thumbnail.
"""
required_arguments = 1
optional_arguments = 2
option_spec = {
'title': directives.unchanged,
'author': directives.unchanged}
final_argument_whitespace = False
has_content = True
add_index = False
def run(self):
ytid = self.arguments[0]
description = [i if i != "" else "<br><br>" for i in self.content]
thumbnail_rst = YOUTUBE_TEMPLATE.format(id=ytid,
title=self.options["title"],
author=self.options["author"],
description=" ".join(description))
thumbnail = StringList(thumbnail_rst.split('\n'))
thumb = nodes.paragraph()
self.state.nested_parse(thumbnail, self.content_offset, thumb)
return [thumb]
COMMUNITY_CARD_TEMPLATE = """
.. raw:: html
<div class="col-lg-6 mb-4">
<div class="card plugin-card" id={id}>
<div class="card-header {color} lighten-4">
<h4 class="card-header__text">{title}</h4>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-8 d-flex flex-column">
<div>
<h6>{author}</h6>
<p class="font-small"><i class="far fa-clock pr-1"></i>{date}</p>
</div>
<p class="plugin-card__description">
{description}
</p>
<div class="mt-auto plugin-card__read-more-wrapper">
<a class="plugin-card__read-more text-primary d-none" data-toggle="modal" data-target="#{id}-modal">Read More</a>
</div>
</div>
<div class="col-lg-4 d-flex">
<div class="plugin-card__buttons">
{paper_footer}
{blog_footer}
{code_footer}
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="{id}-modal" tabindex="-1" role="dialog" aria-labelledby="{id}-modal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title mt-0">{title}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{description}
</div>
<div class="modal-footer">
{paper_footer}
{blog_footer}
{code_footer}
</div>
</div>
</div>
</div>
"""
PAPER_FOOTER = """<a href="{paper}" class="btn btn-info plugin-card__paper-btn">
<i class="fas fa-book"></i> Paper
</a>
"""
BLOG_FOOTER = """<a href="{blog}" class="btn btn-info plugin-card__blog-btn">
<i class="fas fa-newspaper"></i> Blog
</a>
"""
CODE_FOOTER = """<a href="{code}" class="btn btn-default plugin-card__code-btn">
<i class="fas fa-code-branch"></i></i> Code
</a>
"""
class CommunityCardDirective(Directive):
"""Create a community card."""
required_arguments = 0
optional_arguments = 2
option_spec = {
'title': directives.unchanged,
'author': directives.unchanged,
'paper': directives.unchanged,
'blog': directives.unchanged,
'code': directives.unchanged,
'date': directives.unchanged,
'color': directives.unchanged,
}
final_argument_whitespace = False
has_content = True
add_index = False
def run(self):
description = [i if i != "" else "<br><br>" for i in self.content]
color = self.options.get("color", "heavy-rain-gradient")
code_footer = ""
paper_footer = ""
blog_footer = ""
paper_url = self.options.get("paper", None)
if paper_url is not None:
paper_footer = PAPER_FOOTER.format(paper=paper_url)
code_url = self.options.get("code", None)
if code_url is not None:
code_footer = CODE_FOOTER.format(code=code_url)
blog_url = self.options.get("blog", None)
if blog_url is not None:
blog_footer = BLOG_FOOTER.format(blog=blog_url)
def remove_accents(raw_text):
"""Removes common accent characters."""
raw_text = re.sub(u"[àáâãäå]", 'a', raw_text)
raw_text = re.sub(u"[èéêë]", 'e', raw_text)
raw_text = re.sub(u"[ìíîï]", 'i', raw_text)
raw_text = re.sub(u"[òóôõö]", 'o', raw_text)
raw_text = re.sub(u"[ùúûü]", 'u', raw_text)
raw_text = re.sub(u"[ýÿ]", 'y', raw_text)
raw_text = re.sub(u"[ß]", 'ss', raw_text)
raw_text = re.sub(u"[ñ]", 'n', raw_text)
return raw_text
card_rst = COMMUNITY_CARD_TEMPLATE.format(
title=self.options["title"],
author=self.options["author"],
description=" ".join(description),
date=self.options["date"],
paper_footer=paper_footer,
code_footer=code_footer,
blog_footer=blog_footer,
color=color,
id=remove_accents(self.options["author"].split(
" ")[-1].lower()) + self.options["date"].split("/")[-1] + self.options["title"].split(" ")[0].lower(),
)
thumbnail = StringList(card_rst.split('\n'))
thumb = nodes.paragraph()
self.state.nested_parse(thumbnail, self.content_offset, thumb)
return [thumb]
RELATED = """
.. raw:: html
<script type="text/javascript">
var related_tutorials = [{urls}];
var related_tutorials_titles = {linkText};
</script>
"""
class RelatedDirective(Directive):
"""Add related demos to the sidebar.
"""
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
has_content = True
add_index = False
def run(self):
urls = [f"\"{u.split(' ')[0]}.html\"" for u in list(self.content)]
linkText = [' '.join(u.split(' ')[1:]) for u in list(self.content)]
urls = ", ".join(urls)
html = RELATED.format(urls=urls, linkText=linkText)
str_list = StringList(html.split('\n'))
related_variables = nodes.paragraph()
self.state.nested_parse(
str_list, self.content_offset, related_variables)
return [related_variables]
class Bio(Directive):
""" Embed author bio in posts (ReST format).
Based on the pelican_youtube plugin:
https://github.com/kura/pelican_youtube
Usage:
.. bio:: Author name goes here
:photo: ../_static/avatar.webp
Write the author bio content here. It must be preceded by a blank line.
"""
def boolean(argument):
"""Conversion function for yes/no True/False."""
value = directives.choice(argument, ("yes", "True", "no", "False"))
return value in ("yes", "True")
required_arguments = 1
optional_arguments = 8
option_spec = {
"photo": str,
}
final_argument_whitespace = False
has_content = True
def run(self):
authorStringArray = self.arguments
author = ' '.join([str(item) for item in authorStringArray])
photo = self.options.get("photo", None)
bio = self.content[0].strip()
bio_block = '<div class="bio" > <div class="photo" ><img class="photo__img" src="{}" alt="{}" ></div><div class="bio-text"><h4 class="bio-text__author-name">{}</h4><p class="bio-text__author-description">{}</p></div></div>'.format(
photo, author, author, bio)
return [
nodes.raw("", bio_block, format="html"),
]