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