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