##// END OF EJS Templates
IFrame + ScribdDocument
Eugene Van den Bulke -
Show More
@@ -1,332 +1,354 b''
1 """Various display related classes.
1 """Various display related classes.
2
2
3 Authors : MinRK, gregcaporaso, dannystaple
3 Authors : MinRK, gregcaporaso, dannystaple
4 """
4 """
5 from os.path import exists, isfile, splitext, abspath, join, isdir
5 from os.path import exists, isfile, splitext, abspath, join, isdir
6 from os import walk, sep
6 from os import walk, sep
7
7
8
8
9 class VideoIFrame(object):
9 class IFrame(object):
10 """
10 """
11 Generic class to embed videos in a iframe
11 Generic class to embed an iframe in an IPython notebook
12 """
12 """
13
13
14 def __init__(self, id, width=400, height=300, **kwargs):
14 def __init__(self, id, width=400, height=300, **kwargs):
15 self.id = id
15 self.id = id
16 self.width = width
16 self.width = width
17 self.height = height
17 self.height = height
18 self.params = kwargs
18 self.params = kwargs
19
19
20 def _repr_html_(self):
20 def _repr_html_(self):
21 """return the embed iframe for this video id"""
21 """return the embed iframe for this video id"""
22 if self.params:
22 if self.params:
23 from urllib import urlencode
23 from urllib import urlencode
24 params = "?" + urlencode(self.params)
24 params = "?" + urlencode(self.params)
25 else:
25 else:
26 params = ""
26 params = ""
27 return self.iframe.format(width=self.width,
27 return self.iframe.format(width=self.width,
28 height=self.height,
28 height=self.height,
29 id=self.id,
29 id=self.id,
30 params=params)
30 params=params)
31
31
32 class YouTubeVideo(VideoIFrame):
32 class YouTubeVideo(IFrame):
33 """Class for embedding a YouTube Video in an IPython session, based on its video id.
33 """Class for embedding a YouTube Video in an IPython session, based on its video id.
34
34
35 e.g. to embed the video on this page:
35 e.g. to embed the video on this page:
36
36
37 http://www.youtube.com/watch?v=foo
37 http://www.youtube.com/watch?v=foo
38
38
39 you would do:
39 you would do:
40
40
41 vid = YouTubeVideo("foo")
41 vid = YouTubeVideo("foo")
42 display(vid)
42 display(vid)
43
43
44 To start from 30 seconds:
44 To start from 30 seconds:
45
45
46 vid = YouTubeVideo("abc", start=30)
46 vid = YouTubeVideo("abc", start=30)
47 display(vid)
47 display(vid)
48
48
49 To calculate seconds from time as hours, minutes, seconds use:
49 To calculate seconds from time as hours, minutes, seconds use:
50 start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())
50 start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())
51
51
52 Other parameters can be provided as documented at
52 Other parameters can be provided as documented at
53 https://developers.google.com/youtube/player_parameters#parameter-subheader
53 https://developers.google.com/youtube/player_parameters#parameter-subheader
54 """
54 """
55
55
56 iframe = """
56 iframe = """
57 <iframe
57 <iframe
58 width="{width}"
58 width="{width}"
59 height={height}"
59 height={height}"
60 src="http://www.youtube.com/embed/{id}{params}"
60 src="http://www.youtube.com/embed/{id}{params}"
61 frameborder="0"
61 frameborder="0"
62 allowfullscreen
62 allowfullscreen
63 ></iframe>
63 ></iframe>
64 """
64 """
65
65
66 class VimeoVideo(VideoIFrame):
66 class VimeoVideo(VideoIFrame):
67 """
67 """
68 Class for embedding a Vimeo video in an IPython session, based on its video id.
68 Class for embedding a Vimeo video in an IPython session, based on its video id.
69 """
69 """
70
70
71 iframe = """
71 iframe = """
72 <iframe
72 <iframe
73 width = "{width}"
73 width = "{width}"
74 height = "{height}"
74 height = "{height}"
75 src="http://player.vimeo.com/video/{id}{params}"
75 src="http://player.vimeo.com/video/{id}{params}"
76 frameborder="0"
76 frameborder="0"
77 webkitAllowFullScreen
77 webkitAllowFullScreen
78 mozallowfullscreen
78 mozallowfullscreen
79 allowFullScreen
79 allowFullScreen
80 ></iframe>
80 ></iframe>
81 """
81 """
82
82
83 class ScribdDocument(IFrame):
84 """
85 Class for embedding a Scribd document in an IPython session
86
87 Use the start_page params to specify a starting point in the document
88 Use the view_mode params to specify display type one off scroll | slideshow | book
89
90 e.g to Display Wes' foundational paper about PANDAS in book mode from page 3
91
92 ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book")
93 """
94
95 iframe = """
96 <iframe
97 width = "{width}"
98 height = "{height}"
99 src="http://www.scribd.com/embeds/{id}/content{params}"
100 data-auto-height="false"
101 scrolling="no"
102 frameborder="0">
103 </iframe>
104 """
83
105
84 class FileLink(object):
106 class FileLink(object):
85 """Class for embedding a local file link in an IPython session, based on path
107 """Class for embedding a local file link in an IPython session, based on path
86
108
87 e.g. to embed a link that was generated in the IPython notebook as my/data.txt
109 e.g. to embed a link that was generated in the IPython notebook as my/data.txt
88
110
89 you would do::
111 you would do::
90
112
91 local_file = FileLink("my/data.txt")
113 local_file = FileLink("my/data.txt")
92 display(local_file)
114 display(local_file)
93
115
94 or in the HTML notebook, just::
116 or in the HTML notebook, just::
95
117
96 FileLink("my/data.txt")
118 FileLink("my/data.txt")
97 """
119 """
98
120
99 html_link_str = "<a href='%s' target='_blank'>%s</a>"
121 html_link_str = "<a href='%s' target='_blank'>%s</a>"
100
122
101 def __init__(self,
123 def __init__(self,
102 path,
124 path,
103 url_prefix='files/',
125 url_prefix='files/',
104 result_html_prefix='',
126 result_html_prefix='',
105 result_html_suffix='<br>'):
127 result_html_suffix='<br>'):
106 """
128 """
107 Parameters
129 Parameters
108 ----------
130 ----------
109 path : str
131 path : str
110 path to the file or directory that should be formatted
132 path to the file or directory that should be formatted
111 directory_prefix : str
133 directory_prefix : str
112 prefix to be prepended to all files to form a working link [default:
134 prefix to be prepended to all files to form a working link [default:
113 'files']
135 'files']
114 result_html_prefix : str
136 result_html_prefix : str
115 text to append to beginning to link [default: none]
137 text to append to beginning to link [default: none]
116 result_html_suffix : str
138 result_html_suffix : str
117 text to append at the end of link [default: '<br>']
139 text to append at the end of link [default: '<br>']
118 """
140 """
119 if isdir(path):
141 if isdir(path):
120 raise ValueError,\
142 raise ValueError,\
121 ("Cannot display a directory using FileLink. "
143 ("Cannot display a directory using FileLink. "
122 "Use FileLinks to display '%s'." % path)
144 "Use FileLinks to display '%s'." % path)
123 self.path = path
145 self.path = path
124 self.url_prefix = url_prefix
146 self.url_prefix = url_prefix
125 self.result_html_prefix = result_html_prefix
147 self.result_html_prefix = result_html_prefix
126 self.result_html_suffix = result_html_suffix
148 self.result_html_suffix = result_html_suffix
127
149
128 def _format_path(self):
150 def _format_path(self):
129 fp = ''.join([self.url_prefix,self.path])
151 fp = ''.join([self.url_prefix,self.path])
130 return ''.join([self.result_html_prefix,
152 return ''.join([self.result_html_prefix,
131 self.html_link_str % (fp, self.path),
153 self.html_link_str % (fp, self.path),
132 self.result_html_suffix])
154 self.result_html_suffix])
133
155
134 def _repr_html_(self):
156 def _repr_html_(self):
135 """return html link to file
157 """return html link to file
136 """
158 """
137 if not exists(self.path):
159 if not exists(self.path):
138 return ("Path (<tt>%s</tt>) doesn't exist. "
160 return ("Path (<tt>%s</tt>) doesn't exist. "
139 "It may still be in the process of "
161 "It may still be in the process of "
140 "being generated, or you may have the "
162 "being generated, or you may have the "
141 "incorrect path." % self.path)
163 "incorrect path." % self.path)
142
164
143 return self._format_path()
165 return self._format_path()
144
166
145 def __repr__(self):
167 def __repr__(self):
146 """return absolute path to file
168 """return absolute path to file
147 """
169 """
148 return abspath(self.path)
170 return abspath(self.path)
149
171
150 class FileLinks(FileLink):
172 class FileLinks(FileLink):
151 """Class for embedding local file links in an IPython session, based on path
173 """Class for embedding local file links in an IPython session, based on path
152
174
153 e.g. to embed links to files that were generated in the IPython notebook under my/data
175 e.g. to embed links to files that were generated in the IPython notebook under my/data
154
176
155 you would do:
177 you would do:
156
178
157 local_files = FileLinks("my/data")
179 local_files = FileLinks("my/data")
158 display(local_files)
180 display(local_files)
159
181
160 or in the HTML notebook, just
182 or in the HTML notebook, just
161
183
162 FileLinks("my/data")
184 FileLinks("my/data")
163
185
164 """
186 """
165 def __init__(self,
187 def __init__(self,
166 path,
188 path,
167 url_prefix='files/',
189 url_prefix='files/',
168 included_suffixes=None,
190 included_suffixes=None,
169 result_html_prefix='',
191 result_html_prefix='',
170 result_html_suffix='<br>',
192 result_html_suffix='<br>',
171 notebook_display_formatter=None,
193 notebook_display_formatter=None,
172 terminal_display_formatter=None):
194 terminal_display_formatter=None):
173 """
195 """
174 included_suffixes : list of filename suffixes to include when
196 included_suffixes : list of filename suffixes to include when
175 formatting output [default: include all files]
197 formatting output [default: include all files]
176
198
177 See the FileLink (baseclass of LocalDirectory) docstring for
199 See the FileLink (baseclass of LocalDirectory) docstring for
178 information on additional parameters.
200 information on additional parameters.
179
201
180 notebook_display_formatter : func used to format links for display
202 notebook_display_formatter : func used to format links for display
181 in the notebook. See discussion of formatter function below.
203 in the notebook. See discussion of formatter function below.
182
204
183 terminal_display_formatter : func used to format links for display
205 terminal_display_formatter : func used to format links for display
184 in the terminal. See discussion of formatter function below.
206 in the terminal. See discussion of formatter function below.
185
207
186
208
187 Passing custom formatter functions
209 Passing custom formatter functions
188 ----------------------------------
210 ----------------------------------
189 Formatter functions must be of the form:
211 Formatter functions must be of the form:
190 f(dirname, fnames, included_suffixes)
212 f(dirname, fnames, included_suffixes)
191 dirname : the name of a directory (a string),
213 dirname : the name of a directory (a string),
192 fnames : a list of the files in that directory
214 fnames : a list of the files in that directory
193 included_suffixes : a list of the file suffixes that should be
215 included_suffixes : a list of the file suffixes that should be
194 included in the output (passing None means
216 included in the output (passing None means
195 to include all suffixes in the output in
217 to include all suffixes in the output in
196 the built-in formatters)
218 the built-in formatters)
197
219
198 returns a list of lines that should will be print in the
220 returns a list of lines that should will be print in the
199 notebook (if passing notebook_display_formatter) or the terminal
221 notebook (if passing notebook_display_formatter) or the terminal
200 (if passing terminal_display_formatter). This function is iterated
222 (if passing terminal_display_formatter). This function is iterated
201 over for each directory in self.path. Default formatters are in
223 over for each directory in self.path. Default formatters are in
202 place, can be passed here to support alternative formatting.
224 place, can be passed here to support alternative formatting.
203
225
204 """
226 """
205 if isfile(path):
227 if isfile(path):
206 raise ValueError,\
228 raise ValueError,\
207 ("Cannot display a file using FileLinks. "
229 ("Cannot display a file using FileLinks. "
208 "Use FileLink to display '%s'." % path)
230 "Use FileLink to display '%s'." % path)
209 self.included_suffixes = included_suffixes
231 self.included_suffixes = included_suffixes
210 # remove trailing slashs for more consistent output formatting
232 # remove trailing slashs for more consistent output formatting
211 path = path.rstrip('/')
233 path = path.rstrip('/')
212
234
213 self.path = path
235 self.path = path
214 self.url_prefix = url_prefix
236 self.url_prefix = url_prefix
215 self.result_html_prefix = result_html_prefix
237 self.result_html_prefix = result_html_prefix
216 self.result_html_suffix = result_html_suffix
238 self.result_html_suffix = result_html_suffix
217
239
218 self.notebook_display_formatter = \
240 self.notebook_display_formatter = \
219 notebook_display_formatter or self._get_notebook_display_formatter()
241 notebook_display_formatter or self._get_notebook_display_formatter()
220 self.terminal_display_formatter = \
242 self.terminal_display_formatter = \
221 terminal_display_formatter or self._get_terminal_display_formatter()
243 terminal_display_formatter or self._get_terminal_display_formatter()
222
244
223 def _get_display_formatter(self,
245 def _get_display_formatter(self,
224 dirname_output_format,
246 dirname_output_format,
225 fname_output_format,
247 fname_output_format,
226 fp_format,
248 fp_format,
227 fp_cleaner=None):
249 fp_cleaner=None):
228 """ generate built-in formatter function
250 """ generate built-in formatter function
229
251
230 this is used to define both the notebook and terminal built-in
252 this is used to define both the notebook and terminal built-in
231 formatters as they only differ by some wrapper text for each entry
253 formatters as they only differ by some wrapper text for each entry
232
254
233 dirname_output_format: string to use for formatting directory
255 dirname_output_format: string to use for formatting directory
234 names, dirname will be substituted for a single "%s" which
256 names, dirname will be substituted for a single "%s" which
235 must appear in this string
257 must appear in this string
236 fname_output_format: string to use for formatting file names,
258 fname_output_format: string to use for formatting file names,
237 if a single "%s" appears in the string, fname will be substituted
259 if a single "%s" appears in the string, fname will be substituted
238 if two "%s" appear in the string, the path to fname will be
260 if two "%s" appear in the string, the path to fname will be
239 substituted for the first and fname will be substituted for the
261 substituted for the first and fname will be substituted for the
240 second
262 second
241 fp_format: string to use for formatting filepaths, must contain
263 fp_format: string to use for formatting filepaths, must contain
242 exactly two "%s" and the dirname will be subsituted for the first
264 exactly two "%s" and the dirname will be subsituted for the first
243 and fname will be substituted for the second
265 and fname will be substituted for the second
244 """
266 """
245 def f(dirname, fnames, included_suffixes=None):
267 def f(dirname, fnames, included_suffixes=None):
246 result = []
268 result = []
247 # begin by figuring out which filenames, if any,
269 # begin by figuring out which filenames, if any,
248 # are going to be displayed
270 # are going to be displayed
249 display_fnames = []
271 display_fnames = []
250 for fname in fnames:
272 for fname in fnames:
251 if (isfile(join(dirname,fname)) and
273 if (isfile(join(dirname,fname)) and
252 (included_suffixes == None or
274 (included_suffixes == None or
253 splitext(fname)[1] in included_suffixes)):
275 splitext(fname)[1] in included_suffixes)):
254 display_fnames.append(fname)
276 display_fnames.append(fname)
255
277
256 if len(display_fnames) == 0:
278 if len(display_fnames) == 0:
257 # if there are no filenames to display, don't print anything
279 # if there are no filenames to display, don't print anything
258 # (not even the directory name)
280 # (not even the directory name)
259 pass
281 pass
260 else:
282 else:
261 # otherwise print the formatted directory name followed by
283 # otherwise print the formatted directory name followed by
262 # the formatted filenames
284 # the formatted filenames
263 dirname_output_line = dirname_output_format % dirname
285 dirname_output_line = dirname_output_format % dirname
264 result.append(dirname_output_line)
286 result.append(dirname_output_line)
265 for fname in display_fnames:
287 for fname in display_fnames:
266 fp = fp_format % (dirname,fname)
288 fp = fp_format % (dirname,fname)
267 if fp_cleaner is not None:
289 if fp_cleaner is not None:
268 fp = fp_cleaner(fp)
290 fp = fp_cleaner(fp)
269 try:
291 try:
270 # output can include both a filepath and a filename...
292 # output can include both a filepath and a filename...
271 fname_output_line = fname_output_format % (fp, fname)
293 fname_output_line = fname_output_format % (fp, fname)
272 except TypeError:
294 except TypeError:
273 # ... or just a single filepath
295 # ... or just a single filepath
274 fname_output_line = fname_output_format % fname
296 fname_output_line = fname_output_format % fname
275 result.append(fname_output_line)
297 result.append(fname_output_line)
276 return result
298 return result
277 return f
299 return f
278
300
279 def _get_notebook_display_formatter(self,
301 def _get_notebook_display_formatter(self,
280 spacer="&nbsp;&nbsp;"):
302 spacer="&nbsp;&nbsp;"):
281 """ generate function to use for notebook formatting
303 """ generate function to use for notebook formatting
282 """
304 """
283 dirname_output_format = \
305 dirname_output_format = \
284 self.result_html_prefix + "%s/" + self.result_html_suffix
306 self.result_html_prefix + "%s/" + self.result_html_suffix
285 fname_output_format = \
307 fname_output_format = \
286 self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
308 self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
287 fp_format = self.url_prefix + '%s/%s'
309 fp_format = self.url_prefix + '%s/%s'
288 if sep == "\\":
310 if sep == "\\":
289 # Working on a platform where the path separator is "\", so
311 # Working on a platform where the path separator is "\", so
290 # must convert these to "/" for generating a URI
312 # must convert these to "/" for generating a URI
291 def fp_cleaner(fp):
313 def fp_cleaner(fp):
292 # Replace all occurences of backslash ("\") with a forward
314 # Replace all occurences of backslash ("\") with a forward
293 # slash ("/") - this is necessary on windows when a path is
315 # slash ("/") - this is necessary on windows when a path is
294 # provided as input, but we must link to a URI
316 # provided as input, but we must link to a URI
295 return fp.replace('\\','/')
317 return fp.replace('\\','/')
296 else:
318 else:
297 fp_cleaner = None
319 fp_cleaner = None
298
320
299 return self._get_display_formatter(dirname_output_format,
321 return self._get_display_formatter(dirname_output_format,
300 fname_output_format,
322 fname_output_format,
301 fp_format,
323 fp_format,
302 fp_cleaner)
324 fp_cleaner)
303
325
304 def _get_terminal_display_formatter(self,
326 def _get_terminal_display_formatter(self,
305 spacer=" "):
327 spacer=" "):
306 """ generate function to use for terminal formatting
328 """ generate function to use for terminal formatting
307 """
329 """
308 dirname_output_format = "%s/"
330 dirname_output_format = "%s/"
309 fname_output_format = spacer + "%s"
331 fname_output_format = spacer + "%s"
310 fp_format = '%s/%s'
332 fp_format = '%s/%s'
311
333
312 return self._get_display_formatter(dirname_output_format,
334 return self._get_display_formatter(dirname_output_format,
313 fname_output_format,
335 fname_output_format,
314 fp_format)
336 fp_format)
315
337
316 def _format_path(self):
338 def _format_path(self):
317 result_lines = []
339 result_lines = []
318 walked_dir = list(walk(self.path))
340 walked_dir = list(walk(self.path))
319 walked_dir.sort()
341 walked_dir.sort()
320 for dirname, subdirs, fnames in walked_dir:
342 for dirname, subdirs, fnames in walked_dir:
321 result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes)
343 result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes)
322 return '\n'.join(result_lines)
344 return '\n'.join(result_lines)
323
345
324 def __repr__(self):
346 def __repr__(self):
325 """return newline-separated absolute paths
347 """return newline-separated absolute paths
326 """
348 """
327 result_lines = []
349 result_lines = []
328 walked_dir = list(walk(self.path))
350 walked_dir = list(walk(self.path))
329 walked_dir.sort()
351 walked_dir.sort()
330 for dirname, subdirs, fnames in walked_dir:
352 for dirname, subdirs, fnames in walked_dir:
331 result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes)
353 result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes)
332 return '\n'.join(result_lines)
354 return '\n'.join(result_lines)
General Comments 0
You need to be logged in to leave comments. Login now