Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • python/lib/aubio/cmd.py

    r930bfec rdc74f69  
    1212import sys
    1313import argparse
     14import warnings
    1415import aubio
    1516
     
    102103    subparser.add_input()
    103104    subparser.add_buf_hop_size()
     105    subparser.add_silence()
     106    subparser.add_release_drop()
    104107    subparser.add_time_format()
    105108    subparser.add_verbose_help()
     
    138141
    139142def parser_add_subcommand_cut(subparsers):
    140     # quiet subcommand
     143    # cut subcommand
    141144    subparser = subparsers.add_parser('cut',
    142145            help='slice at timestamps')
     
    167170
    168171    def add_verbose_help(self):
    169         self.add_argument("-v","--verbose",
     172        self.add_argument("-v", "--verbose",
    170173                action="count", dest="verbose", default=1,
    171174                help="make lots of noise [default]")
    172         self.add_argument("-q","--quiet",
     175        self.add_argument("-q", "--quiet",
    173176                action="store_const", dest="verbose", const=0,
    174177                help="be quiet")
     
    179182
    180183    def add_buf_size(self, buf_size=512):
    181         self.add_argument("-B","--bufsize",
     184        self.add_argument("-B", "--bufsize",
    182185                action="store", dest="buf_size", default=buf_size,
    183186                metavar = "<size>", type=int,
     
    185188
    186189    def add_hop_size(self, hop_size=256):
    187         self.add_argument("-H","--hopsize",
     190        self.add_argument("-H", "--hopsize",
    188191                metavar = "<size>", type=int,
    189192                action="store", dest="hop_size", default=hop_size,
     
    191194
    192195    def add_method(self, method='default', helpstr='method'):
    193         self.add_argument("-m","--method",
     196        self.add_argument("-m", "--method",
    194197                metavar = "<method>", type=str,
    195198                action="store", dest="method", default=method,
     
    197200
    198201    def add_threshold(self, default=None):
    199         self.add_argument("-t","--threshold",
     202        self.add_argument("-t", "--threshold",
    200203                metavar = "<threshold>", type=float,
    201204                action="store", dest="threshold", default=default,
     
    207210                action="store", dest="silence", default=-70,
    208211                help="silence threshold")
     212
     213    def add_release_drop(self):
     214        self.add_argument("-d", "--release-drop",
     215                metavar = "<value>", type=float,
     216                action="store", dest="release_drop", default=10,
     217                help="release drop threshold")
    209218
    210219    def add_minioi(self, default="12ms"):
     
    232241
    233242    def add_slicer_options(self):
    234         self.add_argument("-o","--output", type = str,
     243        self.add_argument("-o", "--output", type = str,
    235244                metavar = "<outputdir>",
    236245                action="store", dest="output_directory", default=None,
    237                 help="specify path where slices of the original file should be created")
     246                help="specify path where slices of the original file should"
     247                " be created")
    238248        self.add_argument("--cut-until-nsamples", type = int,
    239249                metavar = "<samples>",
    240250                action = "store", dest = "cut_until_nsamples", default = None,
    241                 help="how many extra samples should be added at the end of each slice")
     251                help="how many extra samples should be added at the end of"
     252                " each slice")
    242253        self.add_argument("--cut-every-nslices", type = int,
    243254                metavar = "<samples>",
     
    247258                metavar = "<slices>",
    248259                action = "store", dest = "cut_until_nslices", default = None,
    249                 help="how many extra slices should be added at the end of each slice")
     260                help="how many extra slices should be added at the end of"
     261                " each slice")
     262        self.add_argument("--create-first",
     263                action = "store_true", dest = "create_first", default = False,
     264                help="always include first slice")
    250265
    251266# some utilities
     
    278293        if args.verbose > 2 and hasattr(self, 'options'):
    279294            name = type(self).__name__.split('_')[1]
    280             optstr = ' '.join(['running', name, 'with options', repr(self.options), '\n'])
     295            optstr = ' '.join(['running', name, 'with options',
     296                repr(self.options), '\n'])
    281297            sys.stderr.write(optstr)
    282298    def flush(self, frames_read, samplerate):
     
    286302    def parse_options(self, args, valid_opts):
    287303        # get any valid options found in a dictionnary of arguments
    288         options = {k :v for k,v in vars(args).items() if k in valid_opts}
     304        options = {k: v for k, v in vars(args).items() if k in valid_opts}
    289305        self.options = options
    290306
     
    367383            outstr = "unknown bpm"
    368384        else:
    369             bpms = 60./ np.diff(self.beat_locations)
     385            bpms = 60. / np.diff(self.beat_locations)
    370386            median_bpm = np.mean(bpms)
    371387            if len(self.beat_locations) < 10:
     
    380396        self.parse_options(args, self.valid_opts)
    381397        self.notes = aubio.notes(**self.options)
     398        if args.silence is not None:
     399            self.notes.set_silence(args.silence)
     400        if args.release_drop is not None:
     401            self.notes.set_release_drop(args.release_drop)
    382402        super(process_notes, self).__init__(args)
    383403    def __call__(self, block):
    384404        return self.notes(block)
    385405    def repr_res(self, res, frames_read, samplerate):
    386         if res[2] != 0: # note off
     406        if res[2] != 0:  # note off
    387407            fmt_out = self.time2string(frames_read, samplerate)
    388408            sys.stdout.write(fmt_out + '\n')
    389         if res[0] != 0: # note on
     409        if res[0] != 0:  # note on
    390410            lastmidi = res[0]
    391411            fmt_out = "%f\t" % lastmidi
    392412            fmt_out += self.time2string(frames_read, samplerate)
    393             sys.stdout.write(fmt_out) # + '\t')
     413            sys.stdout.write(fmt_out)  # + '\t')
    394414    def flush(self, frames_read, samplerate):
    395415        eof = self.time2string(frames_read, samplerate)
     
    458478            if self.wassilence != 1:
    459479                self.wassilence = 1
    460                 return 2 # newly found silence
    461             return 1 # silence again
     480                return 2   # newly found silence
     481            return 1       # silence again
    462482        else:
    463483            if self.wassilence != 0:
    464484                self.wassilence = 0
    465                 return -1 # newly found noise
    466             return 0 # noise again
     485                return -1  # newly found noise
     486            return 0       # noise again
    467487
    468488    def repr_res(self, res, frames_read, samplerate):
     
    484504    def __call__(self, block):
    485505        ret = super(process_cut, self).__call__(block)
    486         if ret: self.slices.append(self.onset.get_last())
     506        if ret:
     507            self.slices.append(self.onset.get_last())
    487508        return ret
    488509
    489510    def flush(self, frames_read, samplerate):
    490         from aubio.cut import _cut_slice
    491511        _cut_slice(self.options, self.slices)
    492         duration = float (frames_read) / float(samplerate)
    493         base_info = '%(source_file)s' % {'source_file': self.options.source_uri}
     512        duration = float(frames_read) / float(samplerate)
     513        base_info = '%(source_file)s' % \
     514                    {'source_file': self.options.source_uri}
    494515        base_info += ' (total %(duration).2fs at %(samplerate)dHz)\n' % \
    495                 {'duration': duration, 'samplerate': samplerate}
     516                     {'duration': duration, 'samplerate': samplerate}
    496517        info = "created %d slices from " % len(self.slices)
    497518        info += base_info
    498519        sys.stderr.write(info)
    499520
     521def _cut_slice(options, timestamps):
     522    # cutting pass
     523    nstamps = len(timestamps)
     524    if nstamps > 0:
     525        # generate output files
     526        timestamps_end = None
     527        if options.cut_every_nslices:
     528            timestamps = timestamps[::options.cut_every_nslices]
     529            nstamps = len(timestamps)
     530        if options.cut_until_nslices and options.cut_until_nsamples:
     531            msg = "using cut_until_nslices, but cut_until_nsamples is set"
     532            warnings.warn(msg)
     533        if options.cut_until_nsamples:
     534            lag = options.cut_until_nsamples
     535            timestamps_end = [t + lag for t in timestamps[1:]]
     536            timestamps_end += [1e120]
     537        if options.cut_until_nslices:
     538            slice_lag = options.cut_until_nslices
     539            timestamps_end = [t for t in timestamps[1 + slice_lag:]]
     540            timestamps_end += [1e120] * (options.cut_until_nslices + 1)
     541        aubio.slice_source_at_stamps(options.source_uri,
     542                timestamps, timestamps_end = timestamps_end,
     543                output_dir = options.output_directory,
     544                samplerate = options.samplerate,
     545                create_first = options.create_first)
     546
    500547def main():
    501548    parser = aubio_parser()
    502     args = parser.parse_args()
     549    if sys.version_info[0] != 3:
     550        # on py2, create a dummy ArgumentParser to workaround the
     551        # optional subcommand issue. See https://bugs.python.org/issue9253
     552        # This ensures that:
     553        #  - version string is shown when only '-V' is passed
     554        #  - help is printed if  '-V' is passed with any other argument
     555        #  - any other argument get forwarded to the real parser
     556        parser_root = argparse.ArgumentParser(add_help=False)
     557        parser_root.add_argument('-V', '--version', help="show version",
     558                action="store_true", dest="show_version")
     559        args, extras = parser_root.parse_known_args()
     560        if not args.show_version:  # no -V, forward to parser
     561            args = parser.parse_args(extras, namespace=args)
     562        elif len(extras) != 0:     # -V with other arguments, print help
     563            parser.print_help()
     564            sys.exit(1)
     565    else:  # in py3, we can simply use parser directly
     566        args = parser.parse_args()
    503567    if 'show_version' in args and args.show_version:
    504568        sys.stdout.write('aubio version ' + aubio.version + '\n')
     
    506570    elif 'verbose' in args and args.verbose > 3:
    507571        sys.stderr.write('aubio version ' + aubio.version + '\n')
    508     if 'command' not in args or args.command is None or args.command in ['help']:
     572    if 'command' not in args or args.command is None \
     573            or args.command in ['help']:
    509574        # no command given, print help and return 1
    510575        parser.print_help()
     
    540605                frames_read += read
    541606                # exit loop at end of file
    542                 if read < a_source.hop_size: break
     607                if read < a_source.hop_size:
     608                    break
    543609            # flush the processor if needed
    544610            processor.flush(frames_read, a_source.samplerate)
     
    548614                fmt_string += " from {:s} at {:d}Hz\n"
    549615                sys.stderr.write(fmt_string.format(
    550                         frames_read/float(a_source.samplerate),
     616                        frames_read / float(a_source.samplerate),
    551617                        frames_read,
    552618                        frames_read // a_source.hop_size + 1,
Note: See TracChangeset for help on using the changeset viewer.