3
3
import base64
4
4
import re
5
5
from nbconvert .exporters .html import HTMLExporter
6
+ from ipython_genutils .ipstruct import Struct
7
+ import os
6
8
7
9
try :
8
10
from urllib .request import urlopen # py3
@@ -31,8 +33,20 @@ def replfunc(self, match):
31
33
elif url .startswith ('data' ):
32
34
img = '<img src="' + url + '"'
33
35
return img
36
+ elif url .startswith ('attachment' ):
37
+ imgname = url .split (':' )[1 ]
38
+ available_formats = self .attachments [imgname ]
39
+ # get the image based on the configured image type priority
40
+ for imgformat in self .config .NbConvertBase .display_data_priority :
41
+ if imgformat in available_formats .keys ():
42
+ b64_data = self .attachments [imgname ][imgformat ]
43
+ img = '<img src="data:' + imgformat + \
44
+ ';base64,' + b64_data + '"'
45
+ return img
46
+ raise ValueError ('Could not find attachment for image "%s" in notebook' % imgname )
34
47
else :
35
- with open (url , 'rb' ) as f :
48
+ filename = os .path .join (self .path , url )
49
+ with open (filename , 'rb' ) as f :
36
50
data = f .read ()
37
51
38
52
self .log .info ("embedding url: %s, format: %s" % (url , imgformat ))
@@ -52,6 +66,11 @@ def from_notebook_node(self, nb, resources=None, **kw):
52
66
output , resources = super (
53
67
EmbedHTMLExporter , self ).from_notebook_node (nb , resources )
54
68
69
+ self .path = resources ['metadata' ]['path' ]
70
+ self .attachments = Struct ()
71
+ for cell in nb .cells :
72
+ if 'attachments' in cell .keys ():
73
+ self .attachments += cell ['attachments' ]
55
74
regex = re .compile ('<img\s+src="([^"]+)"' )
56
75
57
76
embedded_output = regex .sub (self .replfunc , output )
0 commit comments