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