source: python/lib/aubio/cmd.py @ 357f81e

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

[cmd] add --silence and --release-drop to notes subcommand

  • Property mode set to 100644
File size: 22.0 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            parser_class= AubioArgumentParser,
24            metavar="")
25
26    parser_add_subcommand_help(subparsers)
27
28    parser_add_subcommand_onset(subparsers)
29    parser_add_subcommand_pitch(subparsers)
30    parser_add_subcommand_beat(subparsers)
31    parser_add_subcommand_tempo(subparsers)
32    parser_add_subcommand_notes(subparsers)
33    parser_add_subcommand_mfcc(subparsers)
34    parser_add_subcommand_melbands(subparsers)
35    parser_add_subcommand_quiet(subparsers)
36    parser_add_subcommand_cut(subparsers)
37
38    return parser
39
40def parser_add_subcommand_help(subparsers):
41    # global help subcommand
42    subparsers.add_parser('help',
43            help='show help message',
44            formatter_class = argparse.ArgumentDefaultsHelpFormatter)
45
46def parser_add_subcommand_onset(subparsers):
47    # onset subcommand
48    subparser = subparsers.add_parser('onset',
49            help='estimate time of onsets (beginning of sound event)',
50            formatter_class = argparse.ArgumentDefaultsHelpFormatter)
51    subparser.add_input()
52    subparser.add_buf_hop_size()
53    helpstr = "onset novelty function"
54    helpstr += " <default|energy|hfc|complex|phase|specdiff|kl|mkl|specflux>"
55    subparser.add_method(helpstr=helpstr)
56    subparser.add_threshold()
57    subparser.add_silence()
58    subparser.add_minioi()
59    subparser.add_time_format()
60    subparser.add_verbose_help()
61    subparser.set_defaults(process=process_onset)
62
63def parser_add_subcommand_pitch(subparsers):
64    # pitch subcommand
65    subparser = subparsers.add_parser('pitch',
66            help='estimate fundamental frequency (monophonic)')
67    subparser.add_input()
68    subparser.add_buf_hop_size(buf_size=2048)
69    helpstr = "pitch detection method <default|yinfft|yin|mcomb|fcomb|schmitt>"
70    subparser.add_method(helpstr=helpstr)
71    subparser.add_threshold()
72    subparser.add_pitch_unit()
73    subparser.add_silence()
74    subparser.add_time_format()
75    subparser.add_verbose_help()
76    subparser.set_defaults(process=process_pitch)
77
78def parser_add_subcommand_beat(subparsers):
79    # beat subcommand
80    subparser = subparsers.add_parser('beat',
81            help='estimate location of beats')
82    subparser.add_input()
83    subparser.add_buf_hop_size(buf_size=1024, hop_size=512)
84    subparser.add_time_format()
85    subparser.add_verbose_help()
86    subparser.set_defaults(process=process_beat)
87
88def parser_add_subcommand_tempo(subparsers):
89    # tempo subcommand
90    subparser = subparsers.add_parser('tempo',
91            help='estimate overall tempo in bpm')
92    subparser.add_input()
93    subparser.add_buf_hop_size(buf_size=1024, hop_size=512)
94    subparser.add_time_format()
95    subparser.add_verbose_help()
96    subparser.set_defaults(process=process_tempo)
97
98def parser_add_subcommand_notes(subparsers):
99    # notes subcommand
100    subparser = subparsers.add_parser('notes',
101            help='estimate midi-like notes (monophonic)')
102    subparser.add_input()
103    subparser.add_buf_hop_size()
104    subparser.add_silence()
105    subparser.add_release_drop()
106    subparser.add_time_format()
107    subparser.add_verbose_help()
108    subparser.set_defaults(process=process_notes)
109
110def parser_add_subcommand_mfcc(subparsers):
111    # mfcc subcommand
112    subparser = subparsers.add_parser('mfcc',
113            help='extract Mel-Frequency Cepstrum Coefficients')
114    subparser.add_input()
115    subparser.add_buf_hop_size()
116    subparser.add_time_format()
117    subparser.add_verbose_help()
118    subparser.set_defaults(process=process_mfcc)
119
120def parser_add_subcommand_melbands(subparsers):
121    # melbands subcommand
122    subparser = subparsers.add_parser('melbands',
123            help='extract energies in Mel-frequency bands')
124    subparser.add_input()
125    subparser.add_buf_hop_size()
126    subparser.add_time_format()
127    subparser.add_verbose_help()
128    subparser.set_defaults(process=process_melbands)
129
130def parser_add_subcommand_quiet(subparsers):
131    # quiet subcommand
132    subparser = subparsers.add_parser('quiet',
133            help='extract timestamps of quiet and loud regions')
134    subparser.add_input()
135    subparser.add_hop_size()
136    subparser.add_silence()
137    subparser.add_time_format()
138    subparser.add_verbose_help()
139    subparser.set_defaults(process=process_quiet)
140
141def parser_add_subcommand_cut(subparsers):
142    # cut subcommand
143    subparser = subparsers.add_parser('cut',
144            help='slice at timestamps')
145    subparser.add_input()
146    helpstr = "onset novelty function"
147    helpstr += " <default|energy|hfc|complex|phase|specdiff|kl|mkl|specflux>"
148    subparser.add_method(helpstr=helpstr)
149    subparser.add_buf_hop_size()
150    subparser.add_silence()
151    subparser.add_threshold(default=0.3)
152    subparser.add_minioi()
153    subparser.add_slicer_options()
154    subparser.add_time_format()
155    subparser.add_verbose_help()
156    subparser.set_defaults(process=process_cut)
157
158class AubioArgumentParser(argparse.ArgumentParser):
159
160    def add_input(self):
161        self.add_argument("source_uri", default=None, nargs='?',
162                help="input sound file to analyse", metavar = "<source_uri>")
163        self.add_argument("-i", "--input", dest = "source_uri2",
164                help="input sound file to analyse", metavar = "<source_uri>")
165        self.add_argument("-r", "--samplerate",
166                metavar = "<freq>", type=int,
167                action="store", dest="samplerate", default=0,
168                help="samplerate at which the file should be represented")
169
170    def add_verbose_help(self):
171        self.add_argument("-v","--verbose",
172                action="count", dest="verbose", default=1,
173                help="make lots of noise [default]")
174        self.add_argument("-q","--quiet",
175                action="store_const", dest="verbose", const=0,
176                help="be quiet")
177
178    def add_buf_hop_size(self, buf_size=512, hop_size=256):
179        self.add_buf_size(buf_size=buf_size)
180        self.add_hop_size(hop_size=hop_size)
181
182    def add_buf_size(self, buf_size=512):
183        self.add_argument("-B","--bufsize",
184                action="store", dest="buf_size", default=buf_size,
185                metavar = "<size>", type=int,
186                help="buffer size [default=%d]" % buf_size)
187
188    def add_hop_size(self, hop_size=256):
189        self.add_argument("-H","--hopsize",
190                metavar = "<size>", type=int,
191                action="store", dest="hop_size", default=hop_size,
192                help="overlap size [default=%d]" % hop_size)
193
194    def add_method(self, method='default', helpstr='method'):
195        self.add_argument("-m","--method",
196                metavar = "<method>", type=str,
197                action="store", dest="method", default=method,
198                help="%s [default=%s]" % (helpstr, method))
199
200    def add_threshold(self, default=None):
201        self.add_argument("-t","--threshold",
202                metavar = "<threshold>", type=float,
203                action="store", dest="threshold", default=default,
204                help="threshold [default=%s]" % default)
205
206    def add_silence(self):
207        self.add_argument("-s", "--silence",
208                metavar = "<value>", type=float,
209                action="store", dest="silence", default=-70,
210                help="silence threshold")
211
212    def add_release_drop(self):
213        self.add_argument("-d", "--release-drop",
214                metavar = "<value>", type=float,
215                action="store", dest="release_drop", default=10,
216                help="release drop threshold")
217
218    def add_minioi(self, default="12ms"):
219        self.add_argument("-M", "--minioi",
220                metavar = "<value>", type=str,
221                action="store", dest="minioi", default=default,
222                help="minimum Inter-Onset Interval [default=%s]" % default)
223
224    def add_pitch_unit(self, default="Hz"):
225        help_str = "frequency unit, should be one of Hz, midi, bin, cent"
226        help_str += " [default=%s]" % default
227        self.add_argument("-u", "--pitch-unit",
228                metavar = "<value>", type=str,
229                action="store", dest="pitch_unit", default=default,
230                help=help_str)
231
232    def add_time_format(self):
233        helpstr = "select time values output format (samples, ms, seconds)"
234        helpstr += " [default=seconds]"
235        self.add_argument("-T", "--time-format",
236                 metavar='format',
237                 dest="time_format",
238                 default=None,
239                 help=helpstr)
240
241    def add_slicer_options(self):
242        self.add_argument("-o","--output", type = str,
243                metavar = "<outputdir>",
244                action="store", dest="output_directory", default=None,
245                help="specify path where slices of the original file should be created")
246        self.add_argument("--cut-until-nsamples", type = int,
247                metavar = "<samples>",
248                action = "store", dest = "cut_until_nsamples", default = None,
249                help="how many extra samples should be added at the end of each slice")
250        self.add_argument("--cut-every-nslices", type = int,
251                metavar = "<samples>",
252                action = "store", dest = "cut_every_nslices", default = None,
253                help="how many slices should be groupped together at each cut")
254        self.add_argument("--cut-until-nslices", type = int,
255                metavar = "<slices>",
256                action = "store", dest = "cut_until_nslices", default = None,
257                help="how many extra slices should be added at the end of each slice")
258
259# some utilities
260
261def samples2seconds(n_frames, samplerate):
262    return "%f\t" % (n_frames / float(samplerate))
263
264def samples2milliseconds(n_frames, samplerate):
265    return "%f\t" % (1000. * n_frames / float(samplerate))
266
267def samples2samples(n_frames, _samplerate):
268    return "%d\t" % n_frames
269
270def timefunc(mode):
271    if mode is None or mode == 'seconds' or mode == 's':
272        return samples2seconds
273    elif mode == 'ms' or mode == 'milliseconds':
274        return samples2milliseconds
275    elif mode == 'samples':
276        return samples2samples
277    else:
278        raise ValueError("invalid time format '%s'" % mode)
279
280# definition of processing classes
281
282class default_process(object):
283    def __init__(self, args):
284        if 'time_format' in args:
285            self.time2string = timefunc(args.time_format)
286        if args.verbose > 2 and hasattr(self, 'options'):
287            name = type(self).__name__.split('_')[1]
288            optstr = ' '.join(['running', name, 'with options', repr(self.options), '\n'])
289            sys.stderr.write(optstr)
290    def flush(self, frames_read, samplerate):
291        # optionally called at the end of process
292        pass
293
294    def parse_options(self, args, valid_opts):
295        # get any valid options found in a dictionnary of arguments
296        options = {k :v for k,v in vars(args).items() if k in valid_opts}
297        self.options = options
298
299    def remap_pvoc_options(self, options):
300        # FIXME: we need to remap buf_size to win_s, hop_size to hop_s
301        # adjust python/ext/py-phasevoc.c to understand buf_size/hop_size
302        if 'buf_size' in options:
303            options['win_s'] = options['buf_size']
304            del options['buf_size']
305        if 'hop_size' in options:
306            options['hop_s'] = options['hop_size']
307            del options['hop_size']
308        self.options = options
309
310class process_onset(default_process):
311    valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
312    def __init__(self, args):
313        self.parse_options(args, self.valid_opts)
314        self.onset = aubio.onset(**self.options)
315        if args.threshold is not None:
316            self.onset.set_threshold(args.threshold)
317        if args.minioi:
318            if args.minioi.endswith('ms'):
319                self.onset.set_minioi_ms(float(args.minioi[:-2]))
320            elif args.minioi.endswith('s'):
321                self.onset.set_minioi_s(float(args.minioi[:-1]))
322            else:
323                self.onset.set_minioi(int(args.minioi))
324        if args.silence:
325            self.onset.set_silence(args.silence)
326        super(process_onset, self).__init__(args)
327    def __call__(self, block):
328        return self.onset(block)
329    def repr_res(self, res, _frames_read, samplerate):
330        if res[0] != 0:
331            outstr = self.time2string(self.onset.get_last(), samplerate)
332            sys.stdout.write(outstr + '\n')
333
334class process_pitch(default_process):
335    valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
336    def __init__(self, args):
337        self.parse_options(args, self.valid_opts)
338        self.pitch = aubio.pitch(**self.options)
339        if args.pitch_unit is not None:
340            self.pitch.set_unit(args.pitch_unit)
341        if args.threshold is not None:
342            self.pitch.set_tolerance(args.threshold)
343        if args.silence is not None:
344            self.pitch.set_silence(args.silence)
345        super(process_pitch, self).__init__(args)
346    def __call__(self, block):
347        return self.pitch(block)
348    def repr_res(self, res, frames_read, samplerate):
349        fmt_out = self.time2string(frames_read, samplerate)
350        sys.stdout.write(fmt_out + "%.6f\n" % res[0])
351
352class process_beat(default_process):
353    valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
354    def __init__(self, args):
355        self.parse_options(args, self.valid_opts)
356        self.tempo = aubio.tempo(**self.options)
357        super(process_beat, self).__init__(args)
358    def __call__(self, block):
359        return self.tempo(block)
360    def repr_res(self, res, _frames_read, samplerate):
361        if res[0] != 0:
362            outstr = self.time2string(self.tempo.get_last(), samplerate)
363            sys.stdout.write(outstr + '\n')
364
365class process_tempo(process_beat):
366    def __init__(self, args):
367        super(process_tempo, self).__init__(args)
368        self.beat_locations = []
369    def repr_res(self, res, _frames_read, samplerate):
370        if res[0] != 0:
371            self.beat_locations.append(self.tempo.get_last_s())
372    def flush(self, frames_read, samplerate):
373        import numpy as np
374        if len(self.beat_locations) < 2:
375            outstr = "unknown bpm"
376        else:
377            bpms = 60./ np.diff(self.beat_locations)
378            median_bpm = np.mean(bpms)
379            if len(self.beat_locations) < 10:
380                outstr = "%.2f bpm (uncertain)" % median_bpm
381            else:
382                outstr = "%.2f bpm" % median_bpm
383        sys.stdout.write(outstr + '\n')
384
385class process_notes(default_process):
386    valid_opts = ['method', 'hop_size', 'buf_size', 'samplerate']
387    def __init__(self, args):
388        self.parse_options(args, self.valid_opts)
389        self.notes = aubio.notes(**self.options)
390        if args.silence is not None:
391            self.notes.set_silence(args.silence)
392        if args.release_drop is not None:
393            self.notes.set_release_drop(args.release_drop)
394        super(process_notes, self).__init__(args)
395    def __call__(self, block):
396        return self.notes(block)
397    def repr_res(self, res, frames_read, samplerate):
398        if res[2] != 0: # note off
399            fmt_out = self.time2string(frames_read, samplerate)
400            sys.stdout.write(fmt_out + '\n')
401        if res[0] != 0: # note on
402            lastmidi = res[0]
403            fmt_out = "%f\t" % lastmidi
404            fmt_out += self.time2string(frames_read, samplerate)
405            sys.stdout.write(fmt_out) # + '\t')
406    def flush(self, frames_read, samplerate):
407        eof = self.time2string(frames_read, samplerate)
408        sys.stdout.write(eof + '\n')
409
410class process_mfcc(default_process):
411    def __init__(self, args):
412        valid_opts1 = ['hop_size', 'buf_size']
413        self.parse_options(args, valid_opts1)
414        self.remap_pvoc_options(self.options)
415        self.pv = aubio.pvoc(**self.options)
416
417        valid_opts2 = ['buf_size', 'n_filters', 'n_coeffs', 'samplerate']
418        self.parse_options(args, valid_opts2)
419        self.mfcc = aubio.mfcc(**self.options)
420
421        # remember all options
422        self.parse_options(args, list(set(valid_opts1 + valid_opts2)))
423
424        super(process_mfcc, self).__init__(args)
425
426    def __call__(self, block):
427        fftgrain = self.pv(block)
428        return self.mfcc(fftgrain)
429    def repr_res(self, res, frames_read, samplerate):
430        fmt_out = self.time2string(frames_read, samplerate)
431        fmt_out += ' '.join(["% 9.7f" % f for f in res.tolist()])
432        sys.stdout.write(fmt_out + '\n')
433
434class process_melbands(default_process):
435    def __init__(self, args):
436        self.args = args
437        valid_opts = ['hop_size', 'buf_size']
438        self.parse_options(args, valid_opts)
439        self.remap_pvoc_options(self.options)
440        self.pv = aubio.pvoc(**self.options)
441
442        valid_opts = ['buf_size', 'n_filters']
443        self.parse_options(args, valid_opts)
444        self.remap_pvoc_options(self.options)
445        self.filterbank = aubio.filterbank(**self.options)
446        self.filterbank.set_mel_coeffs_slaney(args.samplerate)
447
448        super(process_melbands, self).__init__(args)
449    def __call__(self, block):
450        fftgrain = self.pv(block)
451        return self.filterbank(fftgrain)
452    def repr_res(self, res, frames_read, samplerate):
453        fmt_out = self.time2string(frames_read, samplerate)
454        fmt_out += ' '.join(["% 9.7f" % f for f in res.tolist()])
455        sys.stdout.write(fmt_out + '\n')
456
457class process_quiet(default_process):
458    def __init__(self, args):
459        self.args = args
460        valid_opts = ['hop_size', 'silence']
461        self.parse_options(args, valid_opts)
462        self.wassilence = 1
463
464        if args.silence is not None:
465            self.silence = args.silence
466        super(process_quiet, self).__init__(args)
467
468    def __call__(self, block):
469        if aubio.silence_detection(block, self.silence) == 1:
470            if self.wassilence != 1:
471                self.wassilence = 1
472                return 2 # newly found silence
473            return 1 # silence again
474        else:
475            if self.wassilence != 0:
476                self.wassilence = 0
477                return -1 # newly found noise
478            return 0 # noise again
479
480    def repr_res(self, res, frames_read, samplerate):
481        fmt_out = None
482        if res == -1:
483            fmt_out = "NOISY: "
484        if res == 2:
485            fmt_out = "QUIET: "
486        if fmt_out is not None:
487            fmt_out += self.time2string(frames_read, samplerate)
488            sys.stdout.write(fmt_out + '\n')
489
490class process_cut(process_onset):
491    def __init__(self, args):
492        super(process_cut, self).__init__(args)
493        self.slices = []
494        self.options = args
495
496    def __call__(self, block):
497        ret = super(process_cut, self).__call__(block)
498        if ret: self.slices.append(self.onset.get_last())
499        return ret
500
501    def flush(self, frames_read, samplerate):
502        from aubio.cut import _cut_slice
503        _cut_slice(self.options, self.slices)
504        duration = float (frames_read) / float(samplerate)
505        base_info = '%(source_file)s' % {'source_file': self.options.source_uri}
506        base_info += ' (total %(duration).2fs at %(samplerate)dHz)\n' % \
507                {'duration': duration, 'samplerate': samplerate}
508        info = "created %d slices from " % len(self.slices)
509        info += base_info
510        sys.stderr.write(info)
511
512def main():
513    parser = aubio_parser()
514    args = parser.parse_args()
515    if 'show_version' in args and args.show_version:
516        sys.stdout.write('aubio version ' + aubio.version + '\n')
517        sys.exit(0)
518    elif 'verbose' in args and args.verbose > 3:
519        sys.stderr.write('aubio version ' + aubio.version + '\n')
520    if 'command' not in args or args.command is None or args.command in ['help']:
521        # no command given, print help and return 1
522        parser.print_help()
523        if args.command and args.command in ['help']:
524            sys.exit(0)
525        else:
526            sys.exit(1)
527    elif not args.source_uri and not args.source_uri2:
528        sys.stderr.write("Error: a source is required\n")
529        parser.print_help()
530        sys.exit(1)
531    elif args.source_uri2 is not None:
532        args.source_uri = args.source_uri2
533    try:
534        # open source_uri
535        with aubio.source(args.source_uri, hop_size=args.hop_size,
536                samplerate=args.samplerate) as a_source:
537            # always update args.samplerate to native samplerate, in case
538            # source was opened with args.samplerate=0
539            args.samplerate = a_source.samplerate
540            # create the processor for this subcommand
541            processor = args.process(args)
542            frames_read = 0
543            while True:
544                # read new block from source
545                block, read = a_source()
546                # execute processor on this block
547                res = processor(block)
548                # print results for this block
549                if args.verbose > 0:
550                    processor.repr_res(res, frames_read, a_source.samplerate)
551                # increment total number of frames read
552                frames_read += read
553                # exit loop at end of file
554                if read < a_source.hop_size: break
555            # flush the processor if needed
556            processor.flush(frames_read, a_source.samplerate)
557            if args.verbose > 1:
558                fmt_string = "read {:.2f}s"
559                fmt_string += " ({:d} samples in {:d} blocks of {:d})"
560                fmt_string += " from {:s} at {:d}Hz\n"
561                sys.stderr.write(fmt_string.format(
562                        frames_read/float(a_source.samplerate),
563                        frames_read,
564                        frames_read // a_source.hop_size + 1,
565                        a_source.hop_size,
566                        a_source.uri,
567                        a_source.samplerate))
568    except KeyboardInterrupt:
569        sys.exit(1)
Note: See TracBrowser for help on using the repository browser.