source: python/lib/aubio/cmd.py @ 896c3a8

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5
Last change on this file since 896c3a8 was 896c3a8, checked in by Paul Brossier <piem@piem.org>, 7 years ago

python/lib/aubio/cmd.py: add quiet subcommand (closes #124)

  • Property mode set to 100644
File size: 17.9 KB
Line 
1#! /usr/bin/env python
2# -*- coding: utf-8 -*-
3
4"""aubio command line tool
5
6This file was written by Paul Brossier <piem@aubio.org> and is released under
7the GNU/GPL v3.
8
9Note: this script is mostly about parsing command line arguments. For more
10readable code examples, check out the `python/demos` folder."""
11
12import sys
13import argparse
14import aubio
15
16def aubio_parser():
17    epilog = 'use "%(prog)s <command> --help" for more info about each command'
18    parser = argparse.ArgumentParser(epilog=epilog)
19    parser.add_argument('-V', '--version', help="show version",
20            action="store_true", dest="show_version")
21
22    subparsers = parser.add_subparsers(title='commands', dest='command',
23            metavar="")
24
25    # onset subcommand
26    subparser = subparsers.add_parser('onset',
27            help='estimate time of onsets (beginning of sound event)',
28            formatter_class = argparse.ArgumentDefaultsHelpFormatter)
29    parser_add_input(subparser)
30    parser_add_buf_hop_size(subparser)
31    helpstr = "onset novelty function"
32    helpstr += " <default|energy|hfc|complex|phase|specdiff|kl|mkl|specflux>"
33    parser_add_method(subparser, helpstr=helpstr)
34    parser_add_threshold(subparser)
35    parser_add_silence(subparser)
36    parser_add_minioi(subparser)
37    parser_add_time_format(subparser)
38    parser_add_verbose_help(subparser)
39    subparser.set_defaults(process=process_onset)
40
41    # pitch subcommand
42    subparser = subparsers.add_parser('pitch',
43            help='estimate fundamental frequency (monophonic)')
44    parser_add_input(subparser)
45    parser_add_buf_hop_size(subparser, buf_size=2048)
46    helpstr = "pitch detection method <default|yinfft|yin|mcomb|fcomb|schmitt>"
47    parser_add_method(subparser, helpstr=helpstr)
48    parser_add_threshold(subparser)
49    parser_add_pitch_unit(subparser)
50    parser_add_silence(subparser)
51    parser_add_time_format(subparser)
52    parser_add_verbose_help(subparser)
53    subparser.set_defaults(process=process_pitch)
54
55    # beat subcommand
56    subparser = subparsers.add_parser('beat',
57            help='estimate location of beats')
58    parser_add_input(subparser)
59    parser_add_buf_hop_size(subparser, buf_size=1024, hop_size=512)
60    parser_add_time_format(subparser)
61    parser_add_verbose_help(subparser)
62    subparser.set_defaults(process=process_beat)
63
64    # tempo subcommand
65    subparser = subparsers.add_parser('tempo',
66            help='estimate overall tempo in bpm')
67    parser_add_input(subparser)
68    parser_add_buf_hop_size(subparser, buf_size=1024, hop_size=512)
69    parser_add_time_format(subparser)
70    parser_add_verbose_help(subparser)
71    subparser.set_defaults(process=process_tempo)
72
73    # notes subcommand
74    subparser = subparsers.add_parser('notes',
75            help='estimate midi-like notes (monophonic)')
76    parser_add_input(subparser)
77    parser_add_buf_hop_size(subparser)
78    parser_add_time_format(subparser)
79    parser_add_verbose_help(subparser)
80    subparser.set_defaults(process=process_notes)
81
82    # mfcc subcommand
83    subparser = subparsers.add_parser('mfcc',
84            help='extract Mel-Frequency Cepstrum Coefficients')
85    parser_add_input(subparser)
86    parser_add_buf_hop_size(subparser)
87    parser_add_time_format(subparser)
88    parser_add_verbose_help(subparser)
89    subparser.set_defaults(process=process_mfcc)
90
91    # melbands subcommand
92    subparser = subparsers.add_parser('melbands',
93            help='extract energies in Mel-frequency bands')
94    parser_add_input(subparser)
95    parser_add_buf_hop_size(subparser)
96    parser_add_time_format(subparser)
97    parser_add_verbose_help(subparser)
98    subparser.set_defaults(process=process_melbands)
99
100    # quiet subcommand
101    subparser = subparsers.add_parser('quiet',
102            help='')
103    parser_add_input(subparser)
104    parser_add_hop_size(subparser)
105    parser_add_silence(subparser)
106    parser_add_time_format(subparser)
107    parser_add_verbose_help(subparser)
108    subparser.set_defaults(process=process_quiet)
109
110    return parser
111
112def parser_add_input(parser):
113    parser.add_argument("source_uri", default=None, nargs='?',
114            help="input sound file to analyse", metavar = "<source_uri>")
115    parser.add_argument("-i", "--input", dest = "source_uri2",
116            help="input sound file to analyse", metavar = "<source_uri>")
117    parser.add_argument("-r", "--samplerate",
118            metavar = "<freq>", type=int,
119            action="store", dest="samplerate", default=0,
120            help="samplerate at which the file should be represented")
121
122def parser_add_verbose_help(parser):
123    parser.add_argument("-v","--verbose",
124            action="count", dest="verbose", default=1,
125            help="make lots of noise [default]")
126    parser.add_argument("-q","--quiet",
127            action="store_const", dest="verbose", const=0,
128            help="be quiet")
129
130def parser_add_buf_hop_size(parser, buf_size=512, hop_size=256):
131    parser_add_buf_size(parser, buf_size=buf_size)
132    parser_add_hop_size(parser, hop_size=hop_size)
133
134def parser_add_buf_size(parser, buf_size=512):
135    parser.add_argument("-B","--bufsize",
136            action="store", dest="buf_size", default=buf_size,
137            metavar = "<size>", type=int,
138            help="buffer size [default=%d]" % buf_size)
139
140def parser_add_hop_size(parser, hop_size=256):
141    parser.add_argument("-H","--hopsize",
142            metavar = "<size>", type=int,
143            action="store", dest="hop_size", default=hop_size,
144            help="overlap size [default=%d]" % hop_size)
145
146def parser_add_method(parser, method='default', helpstr='method'):
147    parser.add_argument("-m","--method",
148            metavar = "<method>", type=str,
149            action="store", dest="method", default=method,
150            help="%s [default=%s]" % (helpstr, method))
151
152def parser_add_threshold(parser, default=None):
153    parser.add_argument("-t","--threshold",
154            metavar = "<threshold>", type=float,
155            action="store", dest="threshold", default=default,
156            help="threshold [default=%s]" % default)
157
158def parser_add_silence(parser):
159    parser.add_argument("-s", "--silence",
160            metavar = "<value>", type=float,
161            action="store", dest="silence", default=-70,
162            help="silence threshold")
163
164def parser_add_minioi(parser):
165    parser.add_argument("-M", "--minioi",
166            metavar = "<value>", type=str,
167            action="store", dest="minioi", default="12ms",
168            help="minimum Inter-Onset Interval")
169
170def parser_add_pitch_unit(parser, default="Hz"):
171    help_str = "frequency unit, should be one of Hz, midi, bin, cent"
172    help_str += " [default=%s]" % default
173    parser.add_argument("-u", "--pitch-unit",
174            metavar = "<value>", type=str,
175            action="store", dest="pitch_unit", default=default,
176            help=help_str)
177
178def parser_add_time_format(parser):
179    helpstr = "select time values output format (samples, ms, seconds)"
180    helpstr += " [default=seconds]"
181    parser.add_argument("-T", "--time-format",
182             metavar='format',
183             dest="time_format",
184             default=None,
185             help=helpstr)
186
187# some utilities
188
189def samples2seconds(n_frames, samplerate):
190    return "%f\t" % (n_frames / float(samplerate))
191
192def samples2milliseconds(n_frames, samplerate):
193    return "%f\t" % (1000. * n_frames / float(samplerate))
194
195def samples2samples(n_frames, samplerate):
196    return "%d\t" % n_frames
197
198def timefunc(mode):
199    if mode is None or mode == 'seconds' or mode == 's':
200        return samples2seconds
201    elif mode == 'ms' or mode == 'milliseconds':
202        return samples2milliseconds
203    elif mode == 'samples':
204        return samples2samples
205    else:
206        raise ValueError("invalid time format '%s'" % mode)
207
208# definition of processing classes
209
210class default_process(object):
211    def __init__(self, args):
212        if 'time_format' in args:
213            self.time2string = timefunc(args.time_format)
214        if args.verbose > 2 and hasattr(self, 'options'):
215            name = type(self).__name__.split('_')[1]
216            optstr = ' '.join(['running', name, 'with options', repr(self.options), '\n'])
217            sys.stderr.write(optstr)
218    def flush(self, n_frames, samplerate):
219        # optionally called at the end of process
220        pass
221
222    def parse_options(self, args, valid_opts):
223        # get any valid options found in a dictionnary of arguments
224        options = {k :v for k,v in vars(args).items() if k in valid_opts}
225        self.options = options
226
227    def remap_pvoc_options(self, options):
228        # FIXME: we need to remap buf_size to win_s, hop_size to hop_s
229        # adjust python/ext/py-phasevoc.c to understand buf_size/hop_size
230        if 'buf_size' in options:
231            options['win_s'] = options['buf_size']
232            del options['buf_size']
233        if 'hop_size' in options:
234            options['hop_s'] = options['hop_size']
235            del options['hop_size']
236        self.options = options
237
238class process_onset(default_process):
239    valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
240    def __init__(self, args):
241        self.parse_options(args, self.valid_opts)
242        self.onset = aubio.onset(**self.options)
243        if args.threshold is not None:
244            self.onset.set_threshold(args.threshold)
245        if args.minioi:
246            if args.minioi.endswith('ms'):
247                self.onset.set_minioi_ms(float(args.minioi[:-2]))
248            elif args.minioi.endswith('s'):
249                self.onset.set_minioi_s(float(args.minioi[:-1]))
250            else:
251                self.onset.set_minioi(int(args.minioi))
252        if args.silence:
253            self.onset.set_silence(args.silence)
254        super(process_onset, self).__init__(args)
255    def __call__(self, block):
256        return self.onset(block)
257    def repr_res(self, res, frames_read, samplerate):
258        if res[0] != 0:
259            outstr = self.time2string(self.onset.get_last(), samplerate)
260            sys.stdout.write(outstr + '\n')
261
262class process_pitch(default_process):
263    valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
264    def __init__(self, args):
265        self.parse_options(args, self.valid_opts)
266        self.pitch = aubio.pitch(**self.options)
267        if args.pitch_unit is not None:
268            self.pitch.set_unit(args.pitch_unit)
269        if args.threshold is not None:
270            self.pitch.set_tolerance(args.threshold)
271        if args.silence is not None:
272            self.pitch.set_silence(args.silence)
273        super(process_pitch, self).__init__(args)
274    def __call__(self, block):
275        return self.pitch(block)
276    def repr_res(self, res, frames_read, samplerate):
277        fmt_out = self.time2string(frames_read, samplerate)
278        sys.stdout.write(fmt_out + "%.6f\n" % res[0])
279
280class process_beat(default_process):
281    valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
282    def __init__(self, args):
283        self.parse_options(args, self.valid_opts)
284        self.tempo = aubio.tempo(**self.options)
285        super(process_beat, self).__init__(args)
286    def __call__(self, block):
287        return self.tempo(block)
288    def repr_res(self, res, frames_read, samplerate):
289        if res[0] != 0:
290            outstr = self.time2string(self.tempo.get_last(), samplerate)
291            sys.stdout.write(outstr + '\n')
292
293class process_tempo(process_beat):
294    def __init__(self, args):
295        super(process_tempo, self).__init__(args)
296        self.beat_locations = []
297    def repr_res(self, res, frames_read, samplerate):
298        if res[0] != 0:
299            self.beat_locations.append(self.tempo.get_last_s())
300    def flush(self, frames_read, samplerate):
301        import numpy as np
302        if len(self.beat_locations) < 2:
303            outstr = "unknown bpm"
304        else:
305            bpms = 60./ np.diff(self.beat_locations)
306            median_bpm = np.mean(bpms)
307            if len(self.beat_locations) < 10:
308                outstr = "%.2f bpm (uncertain)" % median_bpm
309            else:
310                outstr = "%.2f bpm" % median_bpm
311        sys.stdout.write(outstr + '\n')
312
313class process_notes(default_process):
314    valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
315    def __init__(self, args):
316        self.parse_options(args, self.valid_opts)
317        self.notes = aubio.notes(**self.options)
318        super(process_notes, self).__init__(args)
319    def __call__(self, block):
320        return self.notes(block)
321    def repr_res(self, res, frames_read, samplerate):
322        if res[2] != 0: # note off
323            fmt_out = self.time2string(frames_read, samplerate)
324            sys.stdout.write(fmt_out + '\n')
325        if res[0] != 0: # note on
326            lastmidi = res[0]
327            fmt_out = "%f\t" % lastmidi
328            fmt_out += self.time2string(frames_read, samplerate)
329            sys.stdout.write(fmt_out) # + '\t')
330    def flush(self, frames_read, samplerate):
331        eof = self.time2string(frames_read, samplerate)
332        sys.stdout.write(eof + '\n')
333
334class process_mfcc(default_process):
335    def __init__(self, args):
336        valid_opts1 = ['hop_size', 'buf_size']
337        self.parse_options(args, valid_opts1)
338        self.remap_pvoc_options(self.options)
339        self.pv = aubio.pvoc(**self.options)
340
341        valid_opts2 = ['buf_size', 'n_filters', 'n_coeffs', 'samplerate']
342        self.parse_options(args, valid_opts2)
343        self.mfcc = aubio.mfcc(**self.options)
344
345        # remember all options
346        self.parse_options(args, list(set(valid_opts1 + valid_opts2)))
347
348        super(process_mfcc, self).__init__(args)
349
350    def __call__(self, block):
351        fftgrain = self.pv(block)
352        return self.mfcc(fftgrain)
353    def repr_res(self, res, frames_read, samplerate):
354        fmt_out = self.time2string(frames_read, samplerate)
355        fmt_out += ' '.join(["% 9.7f" % f for f in res.tolist()])
356        sys.stdout.write(fmt_out + '\n')
357
358class process_melbands(default_process):
359    def __init__(self, args):
360        self.args = args
361        valid_opts = ['hop_size', 'buf_size']
362        self.parse_options(args, valid_opts)
363        self.remap_pvoc_options(self.options)
364        self.pv = aubio.pvoc(**self.options)
365
366        valid_opts = ['buf_size', 'n_filters']
367        self.parse_options(args, valid_opts)
368        self.remap_pvoc_options(self.options)
369        self.filterbank = aubio.filterbank(**self.options)
370        self.filterbank.set_mel_coeffs_slaney(args.samplerate)
371
372        super(process_melbands, self).__init__(args)
373    def __call__(self, block):
374        fftgrain = self.pv(block)
375        return self.filterbank(fftgrain)
376    def repr_res(self, res, frames_read, samplerate):
377        fmt_out = self.time2string(frames_read, samplerate)
378        fmt_out += ' '.join(["% 9.7f" % f for f in res.tolist()])
379        sys.stdout.write(fmt_out + '\n')
380
381class process_quiet(default_process):
382    def __init__(self, args):
383        self.args = args
384        valid_opts = ['hop_size', 'silence']
385        self.parse_options(args, valid_opts)
386        self.issilence = None
387        self.wassilence = 1
388
389        if args.silence is not None:
390            self.silence = args.silence
391        super(process_quiet, self).__init__(args)
392
393    def __call__(self, block):
394        if aubio.silence_detection(block, self.silence) == 1:
395            if self.wassilence == 1:
396                self.issilence = 1
397            else:
398                self.issilence = 2
399            self.wassilence = 1
400        else:
401            if self.wassilence == 0:
402                self.issilence = 0
403            else:
404                self.issilence = -1
405            self.wassilence = 0
406
407    def repr_res(self, res, frames_read, samplerate):
408        fmt_out = None
409        if self.issilence == -1:
410            fmt_out = "NOISY: "
411        if self.issilence == 2:
412            fmt_out = "QUIET: "
413        if fmt_out is not None:
414            fmt_out += self.time2string(frames_read, samplerate)
415            sys.stdout.write(fmt_out + '\n')
416
417def main():
418    parser = aubio_parser()
419    args = parser.parse_args()
420    if 'show_version' in args and args.show_version:
421        sys.stdout.write('aubio version ' + aubio.version + '\n')
422        sys.exit(0)
423    elif 'verbose' in args and args.verbose > 3:
424        sys.stderr.write('aubio version ' + aubio.version + '\n')
425    if 'command' not in args or args.command is None:
426        # no command given, print help and return 1
427        parser.print_help()
428        sys.exit(1)
429    elif not args.source_uri and not args.source_uri2:
430        sys.stderr.write("Error: a source is required\n")
431        parser.print_help()
432        sys.exit(1)
433    elif args.source_uri2 is not None:
434        args.source_uri = args.source_uri2
435    try:
436        # open source_uri
437        with aubio.source(args.source_uri, hop_size=args.hop_size,
438                samplerate=args.samplerate) as a_source:
439            # always update args.samplerate to native samplerate, in case
440            # source was opened with args.samplerate=0
441            args.samplerate = a_source.samplerate
442            # create the processor for this subcommand
443            processor = args.process(args)
444            frames_read = 0
445            while True:
446                # read new block from source
447                block, read = a_source()
448                # execute processor on this block
449                res = processor(block)
450                # print results for this block
451                if args.verbose > 0:
452                    processor.repr_res(res, frames_read, a_source.samplerate)
453                # increment total number of frames read
454                frames_read += read
455                # exit loop at end of file
456                if read < a_source.hop_size: break
457            # flush the processor if needed
458            processor.flush(frames_read, a_source.samplerate)
459            if args.verbose > 1:
460                fmt_string = "read {:.2f}s"
461                fmt_string += " ({:d} samples in {:d} blocks of {:d})"
462                fmt_string += " from {:s} at {:d}Hz\n"
463                sys.stderr.write(fmt_string.format(
464                        frames_read/float(a_source.samplerate),
465                        frames_read,
466                        frames_read // a_source.hop_size + 1,
467                        a_source.hop_size,
468                        a_source.uri,
469                        a_source.samplerate))
470    except KeyboardInterrupt:
471        sys.exit(1)
Note: See TracBrowser for help on using the repository browser.