-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathformat_altair_html.py
218 lines (184 loc) · 6.39 KB
/
format_altair_html.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
"""Annotate ``altair`` chart with Twitter card and markdown summary.
You can either use function in module or run as command-line tool.
"""
import argparse
import textwrap
from bs4 import BeautifulSoup as bs
import markdown
def annotate_altair_chart(
chart_html, annotation_md, twitter_card, google_analytics_tag,
):
"""
This function annotates an altair chart with a twitter card and markdown
description.
Parameters
----------
chart_html: str
Path to an HTML file with embeded Vega spec.
annotation_md: str
Path to a text file with markdown description to appended to body.
twitter_card: dict
Site name, title, description and optionally image for Twitter card.
google_analytics_tag : str
Path to text with Google analytics tag.
Returns
-------
str:
A string of the HTML page formatted to be human readable.
"""
# Get the main page content
with open(chart_html, "r") as chart_file:
page = bs(chart_file, "html.parser")
# Get the annotation and convert it from markdown to HTML
with open(annotation_md, "r") as markdow_file:
annotation = bs(
markdown.markdown(
markdow_file.read(),
extensions=["mdx_math"],
),
"html.parser"
)
# Add the annotation to the bottom of the page
markdown_container = page.new_tag("div", attrs={"id": "markdown"})
page.body.append(markdown_container)
separator = page.new_tag("hr")
markdown_container.append(separator)
markdown_container.append(annotation)
# Make and add the twitter card
if not all(key in twitter_card.keys() for key in ["site", "title", "description"]):
raise ValueError(
"Missing required fields for twitter card: site, title, or description"
)
summary = page.new_tag("meta", attrs={"name": "twitter:card", "content": "summary"})
page.head.append(summary)
for name, content in twitter_card.items():
card_tag = page.new_tag(
"meta", attrs={"name": f"twitter:{name}", "content": content}
)
page.head.append(card_tag)
# Add some default styling with bootstrap
stylesheet = page.new_tag(
"link",
attrs={
"rel": "stylesheet",
"href": "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css", # noqa: E501
"integrity": "sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T", # noqa: E501
"crossorigin": "anonymous",
},
)
page.head.append(stylesheet)
# Add some custom styling and margins and overflow
page.head.style.append(
"#vis {margin-left: 2.5%; margin-left: 2.5%; width: 95vw; overflow-x: auto;}"
)
page.head.style.append(
"#markdown {margin-left: 2.5%; margin-right: 2.5%; margin-top: 10px; }"
)
# Fix the margins and font size for selectors within the vega vis
page.head.style.append(
"#vis input, #vis label, #vis span {font-size: 14px; margin: 0px 3px 1px 0px;}"
)
html_str = page.prettify()
# enable math to be added: https://stackoverflow.com/a/54373640
mathjax_script = textwrap.dedent(
r"""
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS_HTML-full">
</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
inlineMath: [["$", "$"], ["\\\\(", "\\\\)"]],
displayMath: [["$$", "$$"], ["\\[", "\\]"]],
processEscapes: true
},
config: ["MMLorHTML.js"],
jax: ["input/TeX", "output/HTML-CSS", "output/NativeMML"],
extensions: ["MathMenu.js", "MathZoom.js"]
});
</script>
"""
)
if html_str.count("</head>\n") == 1:
html_str = html_str.replace("</head>\n", "</head>\n" + mathjax_script)
else:
raise ValueError("failed to find exactly one tag end")
if google_analytics_tag:
with open(google_analytics_tag) as f:
tag = f.read()
if not tag.endswith("\n"):
tag = tag + "\n"
if html_str.count("</head>\n") == 1:
html_str = html_str.replace("</head>\n", "</head>\n" + tag)
else:
raise ValueError("failed to find exactly one tag end")
return html_str
if __name__ == "__main__":
# Command line interface
parser = argparse.ArgumentParser(
description="Format HTML file containing embeded Vega spec saved with Altair."
)
parser.add_argument(
"--chart",
type=str,
required=True,
help="Path to an HTML file containing a chart saved using Altair.",
)
parser.add_argument(
"--markdown",
type=str,
required=True,
help="Path to a markdown file with text to be included under the plot.",
)
parser.add_argument(
"--site",
type=str,
required=True,
help="URL for the Twitter card.",
)
parser.add_argument(
"--title",
type=str,
required=True,
help="Title of the Twitter card.",
)
parser.add_argument(
"--description",
type=str,
required=True,
help="Description in the Twitter card.",
)
parser.add_argument(
"--image",
type=str,
required=False,
help="Image for Twitter card.",
)
parser.add_argument(
"--google_analytics_tag",
type=str,
required=False,
help="Path to file containing Google analytics tag.",
)
parser.add_argument(
"--output",
type=str,
required=True,
help="Path to the HTML file to save the formatted chart.",
)
args = parser.parse_args()
# Place the site, title, and description into a dictionary
twitter_dictionary = {
"site": args.site,
"title": args.title,
"description": args.description,
}
if args.image:
twitter_dictionary["image"] = args.image
# Get the formated HTML as a string
annotated_chart = annotate_altair_chart(
args.chart, args.markdown, twitter_dictionary, args.google_analytics_tag,
)
# Write out to a file
with open(args.output, "w") as outfile:
outfile.write(annotated_chart)