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