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