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