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