custom_directives.py 6.52 KB
Newer Older
moto's avatar
moto committed
1
import hashlib
moto's avatar
moto committed
2
import os
moto's avatar
moto committed
3
4
5
6
7
8
from pathlib import Path
from typing import List
from urllib.parse import quote, urlencode

import requests
from docutils import nodes
moto's avatar
moto committed
9
from docutils.parsers.rst import Directive, directives
moto's avatar
moto committed
10
from docutils.parsers.rst.directives.images import Image
moto's avatar
moto committed
11
from docutils.statemachine import StringList
moto's avatar
moto committed
12
from sphinx.util.docutils import SphinxDirective
moto's avatar
moto committed
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


_THIS_DIR = Path(__file__).parent

# Color palette from PyTorch Developer Day 2021 Presentation Template
YELLOW = "F9DB78"
GREEN = "70AD47"
BLUE = "00B0F0"
PINK = "FF71DA"
ORANGE = "FF8300"
TEAL = "00E5D1"
GRAY = "7F7F7F"


def _get_cache_path(key, ext):
    filename = f"{hashlib.sha256(key).hexdigest()}{ext}"
    cache_dir = _THIS_DIR / "gen_images"
    cache_dir.mkdir(parents=True, exist_ok=True)
    return cache_dir / filename


def _download(url, path):
    response = requests.get(url)
    response.raise_for_status()
    with open(path, "wb") as file:
        file.write(response.content)


def _fetch_image(url):
    path = _get_cache_path(url.encode("utf-8"), ext=".svg")
    if not path.exists():
        _download(url, path)
moto's avatar
moto committed
45
    return os.sep + str(path.relative_to(_THIS_DIR))
moto's avatar
moto committed
46
47


moto's avatar
moto committed
48
49
50
51
52
53
54
55
56
def _get_relpath(target, base):
    target = os.sep + target
    base = os.sep + base
    target_path, filename = os.path.split(target)
    rel_path = os.path.relpath(target_path, os.path.dirname(base))
    return os.path.normpath(os.path.join(rel_path, filename))


class BaseShield(Image, SphinxDirective):
moto's avatar
moto committed
57
58
59
60
61
62
63
64
    def run(self, params, alt, section) -> List[nodes.Node]:
        url = f"https://img.shields.io/static/v1?{urlencode(params, quote_via=quote)}"
        path = _fetch_image(url)
        self.arguments = [path]
        self.options["alt"] = alt
        if "class" not in self.options:
            self.options["class"] = []
        self.options["class"].append("shield-badge")
moto's avatar
moto committed
65
66
        target = _get_relpath("supported_features.html", self.env.docname)
        self.options["target"] = f"{target}#{section}"
moto's avatar
moto committed
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
        return super().run()


def _parse_devices(arg: str):
    devices = sorted(arg.strip().split())

    valid_values = {"CPU", "CUDA"}
    if any(val not in valid_values for val in devices):
        raise ValueError(
            f"One or more device values are not valid. The valid values are {valid_values}. Given value: '{arg}'"
        )
    return ", ".join(sorted(devices))


def _parse_properties(arg: str):
    properties = sorted(arg.strip().split())

    valid_values = {"Autograd", "TorchScript"}
    if any(val not in valid_values for val in properties):
        raise ValueError(
            "One or more property values are not valid. "
            f"The valid values are {valid_values}. "
            f"Given value: '{arg}'"
        )
    return ", ".join(sorted(properties))


class SupportedDevices(BaseShield):
    """List the supported devices"""

    required_arguments = 1
    final_argument_whitespace = True

    def run(self) -> List[nodes.Node]:
        devices = _parse_devices(self.arguments[0])
        alt = f"This feature supports the following devices: {devices}"
        params = {
            "label": "Devices",
            "message": devices,
            "labelColor": GRAY,
            "color": BLUE,
            "style": "flat-square",
        }
        return super().run(params, alt, "devices")


class SupportedProperties(BaseShield):
    """List the supported properties"""

    required_arguments = 1
    final_argument_whitespace = True

    def run(self) -> List[nodes.Node]:
        properties = _parse_properties(self.arguments[0])
        alt = f"This API supports the following properties: {properties}"
        params = {
            "label": "Properties",
            "message": properties,
            "labelColor": GRAY,
            "color": GREEN,
            "style": "flat-square",
        }
        return super().run(params, alt, "properties")
moto's avatar
moto committed
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


_CARDLIST_START = """
.. raw:: html

   <div id="tutorial-cards-container">
     <nav class="navbar navbar-expand-lg navbar-light tutorials-nav col-12">
       <div class="tutorial-tags-container">
         <div id="dropdown-filter-tags">
           <div class="tutorial-filter-menu">
             <div class="tutorial-filter filter-btn all-tag-selected" data-tag="all">All</div>
           </div>
         </div>
       </div>
     </nav>

     <hr class="tutorials-hr">

     <div class="row">
       <div id="tutorial-cards">
         <div class="list">
"""

_CARD_TEMPLATE = """
.. raw:: html

   <div class="col-md-12 tutorials-card-container" data-tags={tags}>
     <div class="card tutorials-card">
       <a href="{link}">
         <div class="card-body">
           <div class="card-title-container">
             <h4>{header}</h4>
           </div>
           <p>Topics: <span class="tags">{tags}</span></p>
           <p class="card-summary">{card_description}</p>
           <div class="tutorials-image">{image}</div>
         </div>
       </a>
     </div>
   </div>
"""

_CARDLIST_END = """
.. raw:: html

         </div>
         <div class="pagination d-flex justify-content-center"></div>
       </div>
     </div>
   </div>
"""


class CustomCardStart(Directive):
    def run(self):
        para = nodes.paragraph()
        self.state.nested_parse(StringList(_CARDLIST_START.split("\n")), self.content_offset, para)
        return [para]


class CustomCardItem(Directive):
    option_spec = {
        "header": directives.unchanged,
        "image": directives.unchanged,
        "link": directives.unchanged,
        "card_description": directives.unchanged,
        "tags": directives.unchanged,
    }

    def run(self):
        for key in ["header", "card_description", "link"]:
            if key not in self.options:
                raise ValueError(f"Key: `{key}` is missing")

        header = self.options["header"]
        link = self.options["link"]
        card_description = self.options["card_description"]
        tags = self.options.get("tags", "")

        if "image" in self.options:
            image = "<img src='" + self.options["image"] + "'>"
        else:
            image = "_static/img/thumbnails/default.png"

        card_rst = _CARD_TEMPLATE.format(
            header=header, image=image, link=link, card_description=card_description, tags=tags
        )
        card_list = StringList(card_rst.split("\n"))
        card = nodes.paragraph()
        self.state.nested_parse(card_list, self.content_offset, card)
        return [card]


class CustomCardEnd(Directive):
    def run(self):
        para = nodes.paragraph()
        self.state.nested_parse(StringList(_CARDLIST_END.split("\n")), self.content_offset, para)
        return [para]