- Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathrender.py
More file actions
Latest commit
192 lines (159 loc) · 6.52 KB
/
Copy pathrender.py
File metadata and controls
192 lines (159 loc) · 6.52 KB
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
#!/usr/local/bin/python
# encoding=utf8
importsys
importjson
fromjinja2importEnvironment, FileSystemLoader
fromcollectionsimportdefaultdict
importre
importmarkdown
importlogging
importsubprocess
importbase64
importhashlib
importio
fromPILimportImage
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
md=markdown.Markdown(extensions=['meta', 'footnotes'])
packages= {
"pandas": "Pandas",
"matplotlib": "Matplotlib",
"seaborn": "Seaborn",
"seaborn-objects": "seaborn.objects",
"plotnine": "plotnine",
"lets-plot": "lets-plot",
"plotly": "plotly",
"hvplot": "hvPlot (Bokeh)",
"altair": "Altair",
"ggplot": "ggplot2 (R)",
}
names= {
"bar-counts": "Bar Chart",
"simple-histogram": "Histogram",
"box-plot": "Box Plot",
"scatter-plot": "Scatter Plot",
"timeseries": "Time Series",
"scatter-plot-with-colors": "Scatter Plot with Faceted with Color",
"scatter-plot-with-size": "Scatter Plot with Points Sized by Continuous Value",
"scatter-plot-with-facet": "Scatter Plot Faceted on One Variable",
"scatter-plot-with-facets": "Scatter Plot Faceted on Two Variables",
"scatter-with-regression": "Scatter Plot and Regression Line with 95% Confidence Interval Layered",
"stacked-smooth-line-and-scatter": "Smoothed Line Plot and Scatter Plot Layered",
"stacked-bar-chart": "Stacked Bar Chart",
"dodged-bar-chart": "Dodged Bar Chart",
"stacked-kde": "Stacked KDE Plot",
"heatmap": "Heatmap",
}
withopen("INTRO.md", "r") asf:
intro=f.read()
WEBP_QUALITY=85
defimage_from_cell(cell):
"""Save the cell's PNG output as WebP and return its path and pixel size.
The filename stays the MD5 of the base64 PNG, so a plot that hasn't changed
keeps its URL. The pixel size lets the template declare width/height, which
reserves layout space for the lazily loaded images.
"""
try:
forcincell['outputs']:
if'data'incand'image/png'inc['data']:
base64_img=c['data']['image/png'].replace("\n", "").strip()
filename=hashlib.md5()
filename.update(base64_img.encode('ascii'))
web_path="/img/plots/{}.webp".format(filename.hexdigest())
full_path="web"+web_path
image=Image.open(io.BytesIO(base64.b64decode(base64_img)))
ifimage.modenotin ("RGB", "RGBA"):
image=image.convert("RGBA")
image.save(full_path, "WEBP", quality=WEBP_QUALITY, method=6)
return {"path": web_path, "width": image.width, "height": image.height}
exceptKeyErrorase:
logging.error("Can't find image in cell: %s", cell['source'])
raisee
raiseException("Can't find an image in cell %s", cell['source'])
defsource_from_cell(cell):
source="".join(cell['source']).strip()
source=source.replace(";", "")
source=re.sub(r"\bImage\(.*\)", "", source) # remove bokeh render
if"%%R"insource:
source='\n'.join(source.split('\n')[1:])
if"%%altair"insource:
source='\n'.join(source.split('\n')[1:])
else:
source=source.replace('"', "'")
ifsource.startswith('"""') orsource.startswith("'''"):
m=re.match("(?:[\"']{3,})((?:.|\n)*)(?:[\"']{3,})((?:.|\n)*)", source, re.MULTILINE)
returnm.groups()
return"", source
deftags_from_cell(cell, type='ex'):
tags=set(cell['metadata'].get('tags') or {})
iftypeintags:
return {t.split(":")[0]: t.split(":")[1] fortintagsif":"int}
defdata_from_cell(cell):
classes="table table-sm table-striped table-responsive table-bordered"
try:
forcincell['outputs']:
if'data'incand'text/html'inc['data']:
table=' '.join(c['data']['text/html'])
table=table.replace('border="1" class="dataframe"', 'class="{}"'.format(classes))
table=table.replace('<thead>', '<thead class="thead-inverse">')
returntable
exceptKeyErrorase:
logging.error("Can't find data in cell: %s", cell['source'])
raisee
raiseException("Can't find an dataset in cell %s", cell['source'])
defreorder_meta(meta):
deforder_plots(plots):
ifplots:
returnsorted(plots, key=lambdak: list(packages.keys()).index(k['package-slug']))
else:
returnplots
meta= {(name, slug): order_plots(meta[slug]) forslug, nameinnames.items()}
returnmeta
defextract_data(path):
withopen(path, 'r') asf:
nb=json.load(f)
cells=nb['cells']
full_data= {}
tags= {i: tags_from_cell(c, type='data') fori, cinenumerate(cells)}
forcell_num, tagsintags.items():
iftagsisNone:
continue
data=data_from_cell(cells[cell_num])
full_data[tags['name']] =data
returnfull_data
defextract_cells(path):
withopen(path, 'r') asf:
nb=json.load(f)
cells=nb['cells']
tags= {i: tags_from_cell(c) fori, cinenumerate(cells)}
meta=defaultdict(list)
forcell_num, tagsintags.items():
iftagsisNone:
continue
comment, source=source_from_cell(cells[cell_num])
image=image_from_cell(cells[cell_num])
meta[tags['name']].append({
"cell_num": cell_num,
"package": packages.get(tags["package"], tags["package"]),
"package-slug": tags['package'],
"image": image["path"],
"image-width": image["width"],
"image-height": image["height"],
"content": source,
"comment": md.convert(comment) orNone,
})
meta=reorder_meta(meta)
returnmeta
defget_git_revision_short_hash():
returnsubprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode("utf8")
if__name__=='__main__':
plots=extract_cells(sys.argv[1])
data=extract_data(sys.argv[1])
env=Environment(loader=FileSystemLoader('templates'), extensions=['jinja2_highlight.HighlightExtension'])
template=env.get_template('t_index.html')
output_from_parsed_template=template.render(intro=md.convert(intro),
plots=plots,
git=get_git_revision_short_hash(),
data=data)
# to save the results
withopen("web/index.html", "w") asfh:
fh.write(output_from_parsed_template)