Show More
@@ -1,343 +1,488 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 | import base64 | |||
|
8 | import struct | |||
|
9 | from io import BytesIO | |||
|
10 | import wave | |||
|
11 | import mimetypes | |||
|
12 | ||||
|
13 | import numpy as np | |||
|
14 | from IPython.core.display import DisplayObject | |||
|
15 | ||||
|
16 | ||||
|
17 | class Audio(DisplayObject): | |||
|
18 | """Create an audio object. | |||
|
19 | ||||
|
20 | When this object is returned by an input cell or passed to the | |||
|
21 | display function, it will result in Audio controls being displayed | |||
|
22 | in the frontend (only works in the notebook). | |||
|
23 | ||||
|
24 | Parameters | |||
|
25 | ---------- | |||
|
26 | data : numpy array, unicode, str or bytes | |||
|
27 | Can be a | |||
|
28 | * Numpy array containing the desired waveform, | |||
|
29 | * String containingvthe filename | |||
|
30 | * Bytestring containing raw PCM data or | |||
|
31 | * URL pointing to a file on the web. | |||
|
32 | ||||
|
33 | If the array option is used the waveform will be normalized. | |||
|
34 | ||||
|
35 | If a filename or url is used the format support will be browser | |||
|
36 | dependent. | |||
|
37 | url : unicode | |||
|
38 | A URL to download the data from. | |||
|
39 | filename : unicode | |||
|
40 | Path to a local file to load the data from. | |||
|
41 | embed : boolean | |||
|
42 | Should the image data be embedded using a data URI (True) or be | |||
|
43 | loaded using an <img> tag. Set this to True if you want the image | |||
|
44 | to be viewable later with no internet connection in the notebook. | |||
|
45 | ||||
|
46 | Default is `True`, unless the keyword argument `url` is set, then | |||
|
47 | default value is `False`. | |||
|
48 | rate : integer | |||
|
49 | The sampling rate of the raw data. | |||
|
50 | Only required when data parameter is being used as an array | |||
|
51 | autoplay : bool | |||
|
52 | Set to True if the audio should immediately start playing. | |||
|
53 | Default is `False`. | |||
|
54 | ||||
|
55 | Examples | |||
|
56 | -------- | |||
|
57 | ||||
|
58 | # Generate a sound | |||
|
59 | import numpy as np | |||
|
60 | framerate = 44100 | |||
|
61 | t = np.linspace(0,5,framerate*5) | |||
|
62 | data = np.sin(2*np.pi*440*np.sin(10*t**2)) | |||
|
63 | Audio(data,rate=framerate) | |||
|
64 | ||||
|
65 | Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") | |||
|
66 | Audio(url="http://media.bradsucks.net/albums/ooi-128/01_-_Brad_Sucks_-_Dropping_out_of_School.mp3") | |||
|
67 | Audio(url="http://www.w3schools.com/html/horse.ogg", embed=True) | |||
|
68 | ||||
|
69 | Audio('/path/to/sound.wav') | |||
|
70 | Audio(filename='/path/to/sound.ogg') | |||
|
71 | ||||
|
72 | Audio(b'RAW_WAV_DATA..) | |||
|
73 | Audio(data=b'RAW_WAV_DATA..) | |||
7 |
|
|
74 | ||
|
75 | """ | |||
|
76 | ||||
|
77 | def __init__(self, data=None, filename=None, url=None, embed=None, rate=None, autoplay=False): | |||
|
78 | if filename is None and url is None and data is None: | |||
|
79 | raise ValueError("No image data found. Expecting filename, url, or data.") | |||
|
80 | if embed is False and url is None: | |||
|
81 | raise ValueError("No url found. Expecting url when embed=False") | |||
|
82 | ||||
|
83 | if url is not None and embed is not True: | |||
|
84 | self.embed = False | |||
|
85 | else: | |||
|
86 | self.embed = True | |||
|
87 | self.autoplay = autoplay | |||
|
88 | super(Audio, self).__init__(data=data, url=url, filename=filename) | |||
|
89 | ||||
|
90 | if self.data is not None and not isinstance(self.data, bytes): | |||
|
91 | self.data = self._make_wav(data,rate) | |||
|
92 | ||||
|
93 | def reload(self): | |||
|
94 | """Reload the raw data from file or URL.""" | |||
|
95 | if self.embed: | |||
|
96 | super(Audio, self).reload() | |||
|
97 | ||||
|
98 | if self.filename is not None: | |||
|
99 | self.mimetype = mimetypes.guess_type(self.filename)[0] | |||
|
100 | elif self.url is not None: | |||
|
101 | self.mimetype = mimetypes.guess_type(self.url)[0] | |||
|
102 | else: | |||
|
103 | self.mimetype = "audio/wav" | |||
|
104 | ||||
|
105 | ||||
|
106 | def _make_wav(self,data,rate): | |||
|
107 | """ Transform a numpy array to a PCM bytestring """ | |||
|
108 | data = np.array(data) | |||
|
109 | scaled = np.int16(data/np.max(np.abs(data)) * 32767) | |||
|
110 | fp = BytesIO() | |||
|
111 | waveobj = wave.open(fp,mode='wb') | |||
|
112 | waveobj.setnchannels(1) | |||
|
113 | waveobj.setframerate(rate) | |||
|
114 | waveobj.setsampwidth(2) | |||
|
115 | waveobj.setcomptype('NONE','NONE') | |||
|
116 | waveobj.writeframes(b''.join([struct.pack('<h',x) for x in scaled])) | |||
|
117 | val = fp.getvalue() | |||
|
118 | waveobj.close() | |||
|
119 | return val | |||
|
120 | ||||
|
121 | def _data_and_metadata(self): | |||
|
122 | """shortcut for returning metadata with url information, if defined""" | |||
|
123 | md = {} | |||
|
124 | if self.url: | |||
|
125 | md['url'] = self.url | |||
|
126 | if md: | |||
|
127 | return self.data, md | |||
|
128 | else: | |||
|
129 | return self.data | |||
|
130 | ||||
|
131 | def _repr_html_(self): | |||
|
132 | src = """ | |||
|
133 | <audio controls="controls" {autoplay}> | |||
|
134 | <source src="{src}" type="{type}" /> | |||
|
135 | Your browser does not support the audio element. | |||
|
136 | </audio> | |||
|
137 | """ | |||
|
138 | return src.format(src=self.src_attr(),type=self.mimetype, autoplay=self.autoplay_attr()) | |||
|
139 | ||||
|
140 | def src_attr(self): | |||
|
141 | if self.embed and (self.data is not None): | |||
|
142 | return """data:{type};base64,{base64}""".format(type=self.mimetype, base64=base64.encodestring(self.data)) | |||
|
143 | elif self.url is not None: | |||
|
144 | return self.url | |||
|
145 | else: | |||
|
146 | return "" | |||
|
147 | ||||
|
148 | def autoplay_attr(self): | |||
|
149 | if(self.autoplay): | |||
|
150 | return 'autoplay="autoplay"' | |||
|
151 | else: | |||
|
152 | return '' | |||
8 |
|
153 | |||
9 | class IFrame(object): |
|
154 | class IFrame(object): | |
10 | """ |
|
155 | """ | |
11 | Generic class to embed an iframe in an IPython notebook |
|
156 | Generic class to embed an iframe in an IPython notebook | |
12 | """ |
|
157 | """ | |
13 |
|
158 | |||
14 | iframe = """ |
|
159 | iframe = """ | |
15 | <iframe |
|
160 | <iframe | |
16 | width="{width}" |
|
161 | width="{width}" | |
17 | height={height}" |
|
162 | height={height}" | |
18 | src="{src}{params}" |
|
163 | src="{src}{params}" | |
19 | frameborder="0" |
|
164 | frameborder="0" | |
20 | allowfullscreen |
|
165 | allowfullscreen | |
21 | ></iframe> |
|
166 | ></iframe> | |
22 | """ |
|
167 | """ | |
23 |
|
168 | |||
24 | def __init__(self, src, width, height, **kwargs): |
|
169 | def __init__(self, src, width, height, **kwargs): | |
25 | self.src = src |
|
170 | self.src = src | |
26 | self.width = width |
|
171 | self.width = width | |
27 | self.height = height |
|
172 | self.height = height | |
28 | self.params = kwargs |
|
173 | self.params = kwargs | |
29 |
|
174 | |||
30 | def _repr_html_(self): |
|
175 | def _repr_html_(self): | |
31 | """return the embed iframe""" |
|
176 | """return the embed iframe""" | |
32 | if self.params: |
|
177 | if self.params: | |
33 | from urllib import urlencode |
|
178 | from urllib import urlencode | |
34 | params = "?" + urlencode(self.params) |
|
179 | params = "?" + urlencode(self.params) | |
35 | else: |
|
180 | else: | |
36 | params = "" |
|
181 | params = "" | |
37 | return self.iframe.format(src=self.src, |
|
182 | return self.iframe.format(src=self.src, | |
38 | width=self.width, |
|
183 | width=self.width, | |
39 | height=self.height, |
|
184 | height=self.height, | |
40 | params=params) |
|
185 | params=params) | |
41 |
|
186 | |||
42 | class YouTubeVideo(IFrame): |
|
187 | class YouTubeVideo(IFrame): | |
43 | """Class for embedding a YouTube Video in an IPython session, based on its video id. |
|
188 | """Class for embedding a YouTube Video in an IPython session, based on its video id. | |
44 |
|
189 | |||
45 | e.g. to embed the video on this page: |
|
190 | e.g. to embed the video on this page: | |
46 |
|
191 | |||
47 | http://www.youtube.com/watch?v=foo |
|
192 | http://www.youtube.com/watch?v=foo | |
48 |
|
193 | |||
49 | you would do: |
|
194 | you would do: | |
50 |
|
195 | |||
51 | vid = YouTubeVideo("foo") |
|
196 | vid = YouTubeVideo("foo") | |
52 | display(vid) |
|
197 | display(vid) | |
53 |
|
198 | |||
54 | To start from 30 seconds: |
|
199 | To start from 30 seconds: | |
55 |
|
200 | |||
56 | vid = YouTubeVideo("abc", start=30) |
|
201 | vid = YouTubeVideo("abc", start=30) | |
57 | display(vid) |
|
202 | display(vid) | |
58 |
|
203 | |||
59 | To calculate seconds from time as hours, minutes, seconds use: |
|
204 | To calculate seconds from time as hours, minutes, seconds use: | |
60 | start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds()) |
|
205 | start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds()) | |
61 |
|
206 | |||
62 | Other parameters can be provided as documented at |
|
207 | Other parameters can be provided as documented at | |
63 | https://developers.google.com/youtube/player_parameters#parameter-subheader |
|
208 | https://developers.google.com/youtube/player_parameters#parameter-subheader | |
64 | """ |
|
209 | """ | |
65 |
|
210 | |||
66 | def __init__(self, id, width=400, height=300, **kwargs): |
|
211 | def __init__(self, id, width=400, height=300, **kwargs): | |
67 | src = "http://www.youtube.com/embed/{0}".format(id) |
|
212 | src = "http://www.youtube.com/embed/{0}".format(id) | |
68 | super(YouTubeVideo, self).__init__(src, width, height, **kwargs) |
|
213 | super(YouTubeVideo, self).__init__(src, width, height, **kwargs) | |
69 |
|
214 | |||
70 | class VimeoVideo(IFrame): |
|
215 | class VimeoVideo(IFrame): | |
71 | """ |
|
216 | """ | |
72 | Class for embedding a Vimeo video in an IPython session, based on its video id. |
|
217 | Class for embedding a Vimeo video in an IPython session, based on its video id. | |
73 | """ |
|
218 | """ | |
74 |
|
219 | |||
75 | def __init__(self, id, width=400, height=300, **kwargs): |
|
220 | def __init__(self, id, width=400, height=300, **kwargs): | |
76 | src="http://player.vimeo.com/video/{0}".format(id) |
|
221 | src="http://player.vimeo.com/video/{0}".format(id) | |
77 | super(VimeoVideo, self).__init__(src, width, height, **kwargs) |
|
222 | super(VimeoVideo, self).__init__(src, width, height, **kwargs) | |
78 |
|
223 | |||
79 | class ScribdDocument(IFrame): |
|
224 | class ScribdDocument(IFrame): | |
80 | """ |
|
225 | """ | |
81 | Class for embedding a Scribd document in an IPython session |
|
226 | Class for embedding a Scribd document in an IPython session | |
82 |
|
227 | |||
83 | Use the start_page params to specify a starting point in the document |
|
228 | 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 |
|
229 | Use the view_mode params to specify display type one off scroll | slideshow | book | |
85 |
|
230 | |||
86 | e.g to Display Wes' foundational paper about PANDAS in book mode from page 3 |
|
231 | e.g to Display Wes' foundational paper about PANDAS in book mode from page 3 | |
87 |
|
232 | |||
88 | ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book") |
|
233 | ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book") | |
89 | """ |
|
234 | """ | |
90 |
|
235 | |||
91 | def __init__(self, id, width=400, height=300, **kwargs): |
|
236 | def __init__(self, id, width=400, height=300, **kwargs): | |
92 | src="http://www.scribd.com/embeds/{0}/content".format(id) |
|
237 | src="http://www.scribd.com/embeds/{0}/content".format(id) | |
93 | super(ScribdDocument, self).__init__(src, width, height, **kwargs) |
|
238 | super(ScribdDocument, self).__init__(src, width, height, **kwargs) | |
94 |
|
239 | |||
95 | class FileLink(object): |
|
240 | class FileLink(object): | |
96 | """Class for embedding a local file link in an IPython session, based on path |
|
241 | """Class for embedding a local file link in an IPython session, based on path | |
97 |
|
242 | |||
98 | e.g. to embed a link that was generated in the IPython notebook as my/data.txt |
|
243 | e.g. to embed a link that was generated in the IPython notebook as my/data.txt | |
99 |
|
244 | |||
100 | you would do:: |
|
245 | you would do:: | |
101 |
|
246 | |||
102 | local_file = FileLink("my/data.txt") |
|
247 | local_file = FileLink("my/data.txt") | |
103 | display(local_file) |
|
248 | display(local_file) | |
104 |
|
249 | |||
105 | or in the HTML notebook, just:: |
|
250 | or in the HTML notebook, just:: | |
106 |
|
251 | |||
107 | FileLink("my/data.txt") |
|
252 | FileLink("my/data.txt") | |
108 | """ |
|
253 | """ | |
109 |
|
254 | |||
110 | html_link_str = "<a href='%s' target='_blank'>%s</a>" |
|
255 | html_link_str = "<a href='%s' target='_blank'>%s</a>" | |
111 |
|
256 | |||
112 | def __init__(self, |
|
257 | def __init__(self, | |
113 | path, |
|
258 | path, | |
114 | url_prefix='files/', |
|
259 | url_prefix='files/', | |
115 | result_html_prefix='', |
|
260 | result_html_prefix='', | |
116 | result_html_suffix='<br>'): |
|
261 | result_html_suffix='<br>'): | |
117 | """ |
|
262 | """ | |
118 | Parameters |
|
263 | Parameters | |
119 | ---------- |
|
264 | ---------- | |
120 | path : str |
|
265 | path : str | |
121 | path to the file or directory that should be formatted |
|
266 | path to the file or directory that should be formatted | |
122 | directory_prefix : str |
|
267 | directory_prefix : str | |
123 | prefix to be prepended to all files to form a working link [default: |
|
268 | prefix to be prepended to all files to form a working link [default: | |
124 | 'files'] |
|
269 | 'files'] | |
125 | result_html_prefix : str |
|
270 | result_html_prefix : str | |
126 | text to append to beginning to link [default: none] |
|
271 | text to append to beginning to link [default: none] | |
127 | result_html_suffix : str |
|
272 | result_html_suffix : str | |
128 | text to append at the end of link [default: '<br>'] |
|
273 | text to append at the end of link [default: '<br>'] | |
129 | """ |
|
274 | """ | |
130 | if isdir(path): |
|
275 | if isdir(path): | |
131 | raise ValueError,\ |
|
276 | raise ValueError,\ | |
132 | ("Cannot display a directory using FileLink. " |
|
277 | ("Cannot display a directory using FileLink. " | |
133 | "Use FileLinks to display '%s'." % path) |
|
278 | "Use FileLinks to display '%s'." % path) | |
134 | self.path = path |
|
279 | self.path = path | |
135 | self.url_prefix = url_prefix |
|
280 | self.url_prefix = url_prefix | |
136 | self.result_html_prefix = result_html_prefix |
|
281 | self.result_html_prefix = result_html_prefix | |
137 | self.result_html_suffix = result_html_suffix |
|
282 | self.result_html_suffix = result_html_suffix | |
138 |
|
283 | |||
139 | def _format_path(self): |
|
284 | def _format_path(self): | |
140 | fp = ''.join([self.url_prefix,self.path]) |
|
285 | fp = ''.join([self.url_prefix,self.path]) | |
141 | return ''.join([self.result_html_prefix, |
|
286 | return ''.join([self.result_html_prefix, | |
142 | self.html_link_str % (fp, self.path), |
|
287 | self.html_link_str % (fp, self.path), | |
143 | self.result_html_suffix]) |
|
288 | self.result_html_suffix]) | |
144 |
|
289 | |||
145 | def _repr_html_(self): |
|
290 | def _repr_html_(self): | |
146 | """return html link to file |
|
291 | """return html link to file | |
147 | """ |
|
292 | """ | |
148 | if not exists(self.path): |
|
293 | if not exists(self.path): | |
149 | return ("Path (<tt>%s</tt>) doesn't exist. " |
|
294 | return ("Path (<tt>%s</tt>) doesn't exist. " | |
150 | "It may still be in the process of " |
|
295 | "It may still be in the process of " | |
151 | "being generated, or you may have the " |
|
296 | "being generated, or you may have the " | |
152 | "incorrect path." % self.path) |
|
297 | "incorrect path." % self.path) | |
153 |
|
298 | |||
154 | return self._format_path() |
|
299 | return self._format_path() | |
155 |
|
300 | |||
156 | def __repr__(self): |
|
301 | def __repr__(self): | |
157 | """return absolute path to file |
|
302 | """return absolute path to file | |
158 | """ |
|
303 | """ | |
159 | return abspath(self.path) |
|
304 | return abspath(self.path) | |
160 |
|
305 | |||
161 | class FileLinks(FileLink): |
|
306 | class FileLinks(FileLink): | |
162 | """Class for embedding local file links in an IPython session, based on path |
|
307 | """Class for embedding local file links in an IPython session, based on path | |
163 |
|
308 | |||
164 | e.g. to embed links to files that were generated in the IPython notebook under my/data |
|
309 | e.g. to embed links to files that were generated in the IPython notebook under my/data | |
165 |
|
310 | |||
166 | you would do: |
|
311 | you would do: | |
167 |
|
312 | |||
168 | local_files = FileLinks("my/data") |
|
313 | local_files = FileLinks("my/data") | |
169 | display(local_files) |
|
314 | display(local_files) | |
170 |
|
315 | |||
171 | or in the HTML notebook, just |
|
316 | or in the HTML notebook, just | |
172 |
|
317 | |||
173 | FileLinks("my/data") |
|
318 | FileLinks("my/data") | |
174 |
|
319 | |||
175 | """ |
|
320 | """ | |
176 | def __init__(self, |
|
321 | def __init__(self, | |
177 | path, |
|
322 | path, | |
178 | url_prefix='files/', |
|
323 | url_prefix='files/', | |
179 | included_suffixes=None, |
|
324 | included_suffixes=None, | |
180 | result_html_prefix='', |
|
325 | result_html_prefix='', | |
181 | result_html_suffix='<br>', |
|
326 | result_html_suffix='<br>', | |
182 | notebook_display_formatter=None, |
|
327 | notebook_display_formatter=None, | |
183 | terminal_display_formatter=None): |
|
328 | terminal_display_formatter=None): | |
184 | """ |
|
329 | """ | |
185 | included_suffixes : list of filename suffixes to include when |
|
330 | included_suffixes : list of filename suffixes to include when | |
186 | formatting output [default: include all files] |
|
331 | formatting output [default: include all files] | |
187 |
|
332 | |||
188 | See the FileLink (baseclass of LocalDirectory) docstring for |
|
333 | See the FileLink (baseclass of LocalDirectory) docstring for | |
189 | information on additional parameters. |
|
334 | information on additional parameters. | |
190 |
|
335 | |||
191 | notebook_display_formatter : func used to format links for display |
|
336 | notebook_display_formatter : func used to format links for display | |
192 | in the notebook. See discussion of formatter function below. |
|
337 | in the notebook. See discussion of formatter function below. | |
193 |
|
338 | |||
194 | terminal_display_formatter : func used to format links for display |
|
339 | terminal_display_formatter : func used to format links for display | |
195 | in the terminal. See discussion of formatter function below. |
|
340 | in the terminal. See discussion of formatter function below. | |
196 |
|
341 | |||
197 |
|
342 | |||
198 | Passing custom formatter functions |
|
343 | Passing custom formatter functions | |
199 | ---------------------------------- |
|
344 | ---------------------------------- | |
200 | Formatter functions must be of the form: |
|
345 | Formatter functions must be of the form: | |
201 | f(dirname, fnames, included_suffixes) |
|
346 | f(dirname, fnames, included_suffixes) | |
202 | dirname : the name of a directory (a string), |
|
347 | dirname : the name of a directory (a string), | |
203 | fnames : a list of the files in that directory |
|
348 | fnames : a list of the files in that directory | |
204 | included_suffixes : a list of the file suffixes that should be |
|
349 | included_suffixes : a list of the file suffixes that should be | |
205 | included in the output (passing None means |
|
350 | included in the output (passing None means | |
206 | to include all suffixes in the output in |
|
351 | to include all suffixes in the output in | |
207 | the built-in formatters) |
|
352 | the built-in formatters) | |
208 |
|
353 | |||
209 | returns a list of lines that should will be print in the |
|
354 | returns a list of lines that should will be print in the | |
210 | notebook (if passing notebook_display_formatter) or the terminal |
|
355 | notebook (if passing notebook_display_formatter) or the terminal | |
211 | (if passing terminal_display_formatter). This function is iterated |
|
356 | (if passing terminal_display_formatter). This function is iterated | |
212 | over for each directory in self.path. Default formatters are in |
|
357 | over for each directory in self.path. Default formatters are in | |
213 | place, can be passed here to support alternative formatting. |
|
358 | place, can be passed here to support alternative formatting. | |
214 |
|
359 | |||
215 | """ |
|
360 | """ | |
216 | if isfile(path): |
|
361 | if isfile(path): | |
217 | raise ValueError,\ |
|
362 | raise ValueError,\ | |
218 | ("Cannot display a file using FileLinks. " |
|
363 | ("Cannot display a file using FileLinks. " | |
219 | "Use FileLink to display '%s'." % path) |
|
364 | "Use FileLink to display '%s'." % path) | |
220 | self.included_suffixes = included_suffixes |
|
365 | self.included_suffixes = included_suffixes | |
221 | # remove trailing slashs for more consistent output formatting |
|
366 | # remove trailing slashs for more consistent output formatting | |
222 | path = path.rstrip('/') |
|
367 | path = path.rstrip('/') | |
223 |
|
368 | |||
224 | self.path = path |
|
369 | self.path = path | |
225 | self.url_prefix = url_prefix |
|
370 | self.url_prefix = url_prefix | |
226 | self.result_html_prefix = result_html_prefix |
|
371 | self.result_html_prefix = result_html_prefix | |
227 | self.result_html_suffix = result_html_suffix |
|
372 | self.result_html_suffix = result_html_suffix | |
228 |
|
373 | |||
229 | self.notebook_display_formatter = \ |
|
374 | self.notebook_display_formatter = \ | |
230 | notebook_display_formatter or self._get_notebook_display_formatter() |
|
375 | notebook_display_formatter or self._get_notebook_display_formatter() | |
231 | self.terminal_display_formatter = \ |
|
376 | self.terminal_display_formatter = \ | |
232 | terminal_display_formatter or self._get_terminal_display_formatter() |
|
377 | terminal_display_formatter or self._get_terminal_display_formatter() | |
233 |
|
378 | |||
234 | def _get_display_formatter(self, |
|
379 | def _get_display_formatter(self, | |
235 | dirname_output_format, |
|
380 | dirname_output_format, | |
236 | fname_output_format, |
|
381 | fname_output_format, | |
237 | fp_format, |
|
382 | fp_format, | |
238 | fp_cleaner=None): |
|
383 | fp_cleaner=None): | |
239 | """ generate built-in formatter function |
|
384 | """ generate built-in formatter function | |
240 |
|
385 | |||
241 | this is used to define both the notebook and terminal built-in |
|
386 | this is used to define both the notebook and terminal built-in | |
242 | formatters as they only differ by some wrapper text for each entry |
|
387 | formatters as they only differ by some wrapper text for each entry | |
243 |
|
388 | |||
244 | dirname_output_format: string to use for formatting directory |
|
389 | dirname_output_format: string to use for formatting directory | |
245 | names, dirname will be substituted for a single "%s" which |
|
390 | names, dirname will be substituted for a single "%s" which | |
246 | must appear in this string |
|
391 | must appear in this string | |
247 | fname_output_format: string to use for formatting file names, |
|
392 | fname_output_format: string to use for formatting file names, | |
248 | if a single "%s" appears in the string, fname will be substituted |
|
393 | if a single "%s" appears in the string, fname will be substituted | |
249 | if two "%s" appear in the string, the path to fname will be |
|
394 | if two "%s" appear in the string, the path to fname will be | |
250 | substituted for the first and fname will be substituted for the |
|
395 | substituted for the first and fname will be substituted for the | |
251 | second |
|
396 | second | |
252 | fp_format: string to use for formatting filepaths, must contain |
|
397 | fp_format: string to use for formatting filepaths, must contain | |
253 | exactly two "%s" and the dirname will be subsituted for the first |
|
398 | exactly two "%s" and the dirname will be subsituted for the first | |
254 | and fname will be substituted for the second |
|
399 | and fname will be substituted for the second | |
255 | """ |
|
400 | """ | |
256 | def f(dirname, fnames, included_suffixes=None): |
|
401 | def f(dirname, fnames, included_suffixes=None): | |
257 | result = [] |
|
402 | result = [] | |
258 | # begin by figuring out which filenames, if any, |
|
403 | # begin by figuring out which filenames, if any, | |
259 | # are going to be displayed |
|
404 | # are going to be displayed | |
260 | display_fnames = [] |
|
405 | display_fnames = [] | |
261 | for fname in fnames: |
|
406 | for fname in fnames: | |
262 | if (isfile(join(dirname,fname)) and |
|
407 | if (isfile(join(dirname,fname)) and | |
263 | (included_suffixes == None or |
|
408 | (included_suffixes == None or | |
264 | splitext(fname)[1] in included_suffixes)): |
|
409 | splitext(fname)[1] in included_suffixes)): | |
265 | display_fnames.append(fname) |
|
410 | display_fnames.append(fname) | |
266 |
|
411 | |||
267 | if len(display_fnames) == 0: |
|
412 | if len(display_fnames) == 0: | |
268 | # if there are no filenames to display, don't print anything |
|
413 | # if there are no filenames to display, don't print anything | |
269 | # (not even the directory name) |
|
414 | # (not even the directory name) | |
270 | pass |
|
415 | pass | |
271 | else: |
|
416 | else: | |
272 | # otherwise print the formatted directory name followed by |
|
417 | # otherwise print the formatted directory name followed by | |
273 | # the formatted filenames |
|
418 | # the formatted filenames | |
274 | dirname_output_line = dirname_output_format % dirname |
|
419 | dirname_output_line = dirname_output_format % dirname | |
275 | result.append(dirname_output_line) |
|
420 | result.append(dirname_output_line) | |
276 | for fname in display_fnames: |
|
421 | for fname in display_fnames: | |
277 | fp = fp_format % (dirname,fname) |
|
422 | fp = fp_format % (dirname,fname) | |
278 | if fp_cleaner is not None: |
|
423 | if fp_cleaner is not None: | |
279 | fp = fp_cleaner(fp) |
|
424 | fp = fp_cleaner(fp) | |
280 | try: |
|
425 | try: | |
281 | # output can include both a filepath and a filename... |
|
426 | # output can include both a filepath and a filename... | |
282 | fname_output_line = fname_output_format % (fp, fname) |
|
427 | fname_output_line = fname_output_format % (fp, fname) | |
283 | except TypeError: |
|
428 | except TypeError: | |
284 | # ... or just a single filepath |
|
429 | # ... or just a single filepath | |
285 | fname_output_line = fname_output_format % fname |
|
430 | fname_output_line = fname_output_format % fname | |
286 | result.append(fname_output_line) |
|
431 | result.append(fname_output_line) | |
287 | return result |
|
432 | return result | |
288 | return f |
|
433 | return f | |
289 |
|
434 | |||
290 | def _get_notebook_display_formatter(self, |
|
435 | def _get_notebook_display_formatter(self, | |
291 | spacer=" "): |
|
436 | spacer=" "): | |
292 | """ generate function to use for notebook formatting |
|
437 | """ generate function to use for notebook formatting | |
293 | """ |
|
438 | """ | |
294 | dirname_output_format = \ |
|
439 | dirname_output_format = \ | |
295 | self.result_html_prefix + "%s/" + self.result_html_suffix |
|
440 | self.result_html_prefix + "%s/" + self.result_html_suffix | |
296 | fname_output_format = \ |
|
441 | fname_output_format = \ | |
297 | self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix |
|
442 | self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix | |
298 | fp_format = self.url_prefix + '%s/%s' |
|
443 | fp_format = self.url_prefix + '%s/%s' | |
299 | if sep == "\\": |
|
444 | if sep == "\\": | |
300 | # Working on a platform where the path separator is "\", so |
|
445 | # Working on a platform where the path separator is "\", so | |
301 | # must convert these to "/" for generating a URI |
|
446 | # must convert these to "/" for generating a URI | |
302 | def fp_cleaner(fp): |
|
447 | def fp_cleaner(fp): | |
303 | # Replace all occurences of backslash ("\") with a forward |
|
448 | # Replace all occurences of backslash ("\") with a forward | |
304 | # slash ("/") - this is necessary on windows when a path is |
|
449 | # slash ("/") - this is necessary on windows when a path is | |
305 | # provided as input, but we must link to a URI |
|
450 | # provided as input, but we must link to a URI | |
306 | return fp.replace('\\','/') |
|
451 | return fp.replace('\\','/') | |
307 | else: |
|
452 | else: | |
308 | fp_cleaner = None |
|
453 | fp_cleaner = None | |
309 |
|
454 | |||
310 | return self._get_display_formatter(dirname_output_format, |
|
455 | return self._get_display_formatter(dirname_output_format, | |
311 | fname_output_format, |
|
456 | fname_output_format, | |
312 | fp_format, |
|
457 | fp_format, | |
313 | fp_cleaner) |
|
458 | fp_cleaner) | |
314 |
|
459 | |||
315 | def _get_terminal_display_formatter(self, |
|
460 | def _get_terminal_display_formatter(self, | |
316 | spacer=" "): |
|
461 | spacer=" "): | |
317 | """ generate function to use for terminal formatting |
|
462 | """ generate function to use for terminal formatting | |
318 | """ |
|
463 | """ | |
319 | dirname_output_format = "%s/" |
|
464 | dirname_output_format = "%s/" | |
320 | fname_output_format = spacer + "%s" |
|
465 | fname_output_format = spacer + "%s" | |
321 | fp_format = '%s/%s' |
|
466 | fp_format = '%s/%s' | |
322 |
|
467 | |||
323 | return self._get_display_formatter(dirname_output_format, |
|
468 | return self._get_display_formatter(dirname_output_format, | |
324 | fname_output_format, |
|
469 | fname_output_format, | |
325 | fp_format) |
|
470 | fp_format) | |
326 |
|
471 | |||
327 | def _format_path(self): |
|
472 | def _format_path(self): | |
328 | result_lines = [] |
|
473 | result_lines = [] | |
329 | walked_dir = list(walk(self.path)) |
|
474 | walked_dir = list(walk(self.path)) | |
330 | walked_dir.sort() |
|
475 | walked_dir.sort() | |
331 | for dirname, subdirs, fnames in walked_dir: |
|
476 | for dirname, subdirs, fnames in walked_dir: | |
332 | result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes) |
|
477 | result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes) | |
333 | return '\n'.join(result_lines) |
|
478 | return '\n'.join(result_lines) | |
334 |
|
479 | |||
335 | def __repr__(self): |
|
480 | def __repr__(self): | |
336 | """return newline-separated absolute paths |
|
481 | """return newline-separated absolute paths | |
337 | """ |
|
482 | """ | |
338 | result_lines = [] |
|
483 | result_lines = [] | |
339 | walked_dir = list(walk(self.path)) |
|
484 | walked_dir = list(walk(self.path)) | |
340 | walked_dir.sort() |
|
485 | walked_dir.sort() | |
341 | for dirname, subdirs, fnames in walked_dir: |
|
486 | for dirname, subdirs, fnames in walked_dir: | |
342 | result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes) |
|
487 | result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes) | |
343 | return '\n'.join(result_lines) |
|
488 | return '\n'.join(result_lines) |
General Comments 0
You need to be logged in to leave comments.
Login now