python/scripts/aubiocut: move usage string inside parse_args()
[aubio.git] / python / scripts / aubiocut
index f1a7b92..e348665 100755 (executable)
@@ -5,25 +5,24 @@
 """
 
 import sys
-#from aubio.task import *
-
-usage = "usage: %s [options] -i soundfile" % sys.argv[0]
 
 def parse_args():
     from optparse import OptionParser
+    usage = "usage: %s [options] -i soundfile" % sys.argv[0]
+    usage += "\n help: %s -h" % sys.argv[0]
     parser = OptionParser(usage=usage)
     parser.add_option("-i", "--input", action = "store", dest = "source_file",
             help="input sound file to analyse", metavar = "<source_file>")
-    parser.add_option("-m","--method",
+    parser.add_option("-O","--onset-method",
             action="store", dest="onset_method", default='default',
             metavar = "<onset_method>",
             help="onset detection method [default=default] \
                     complexdomain|hfc|phase|specdiff|energy|kl|mkl")
     # cutting methods
-    """
     parser.add_option("-b","--beat",
             action="store_true", dest="beat", default=False,
             help="use beat locations")
+    """
     parser.add_option("-S","--silencecut",
             action="store_true", dest="silencecut", default=False,
             help="use silence locations")
@@ -33,19 +32,19 @@ def parse_args():
             help="silence threshold [default=-70]")
             """
     # algorithm parameters
-    parser.add_option("--samplerate",
+    parser.add_option("-r", "--samplerate",
             metavar = "<freq>", type='int',
             action="store", dest="samplerate", default=0,
             help="samplerate at which the file should be represented")
     parser.add_option("-B","--bufsize",
             action="store", dest="bufsize", default=512,
-            metavar = "<size>",
+            metavar = "<size>", type='int',
             help="buffer size [default=512]")
     parser.add_option("-H","--hopsize",
-            metavar = "<size>",
+            metavar = "<size>", type='int',
             action="store", dest="hopsize", default=256,
             help="overlap size [default=256]")
-    parser.add_option("-t","--threshold",
+    parser.add_option("-t","--onset-threshold",
             metavar = "<value>", type="float",
             action="store", dest="threshold", default=0.3,
             help="onset peak picking threshold [default=0.3]")
@@ -53,6 +52,13 @@ def parse_args():
             action="store_true", dest="cut", default=False,
             help="cut input sound file at detected labels \
                     best used with option -L")
+
+    # minioi
+    parser.add_option("-M","--minioi",
+            metavar = "<value>", type='string',
+            action="store", dest="minioi", default="12ms",
+            help="minimum inter onset interval [default=12ms]")
+
     """
     parser.add_option("-D","--delay",
             action = "store", dest = "delay", type = "float",
@@ -63,10 +69,6 @@ def parse_args():
             metavar = "<value>",
             action="store", dest="dcthreshold", default=1.,
             help="onset peak picking DC component [default=1.]")
-    parser.add_option("-M","--mintol",
-            metavar = "<value>",
-            action="store", dest="mintol", default=0.048,
-            help="minimum inter onset interval [default=0.048]")
     parser.add_option("-L","--localmin",
             action="store_true", dest="localmin", default=False,
             help="use local minima after peak detection")
@@ -105,6 +107,23 @@ def parse_args():
             action="store_true", dest="spectro", default=False,
             help="add spectrogram to the plot")
     """
+    parser.add_option("-o","--output", type = str,
+            metavar = "<outputdir>",
+            action="store", dest="output_directory", default=None,
+            help="specify path where slices of the original file should be created")
+    parser.add_option("--cut-until-nsamples", type = int,
+            metavar = "<samples>",
+            action = "store", dest = "cut_until_nsamples", default = None,
+            help="how many extra samples should be added at the end of each slice")
+    parser.add_option("--cut-every-nslices", type = int,
+            metavar = "<samples>",
+            action = "store", dest = "cut_every_nslices", default = None,
+            help="how many slices should be groupped together at each cut")
+    parser.add_option("--cut-until-nslices", type = int,
+            metavar = "<slices>",
+            action = "store", dest = "cut_until_nslices", default = None,
+            help="how many extra slices should be added at the end of each slice")
+
     parser.add_option("-v","--verbose",
             action="store_true", dest="verbose", default=True,
             help="make lots of noise [default]")
@@ -113,8 +132,12 @@ def parse_args():
             help="be quiet")
     (options, args) = parser.parse_args()
     if not options.source_file:
-        print "no file name given\n", usage
-        sys.exit(1)
+        import os.path
+        if len(args) == 1:
+            options.source_file = args[0]
+        else:
+            print ("no file name given\n" + usage)
+            sys.exit(1)
     return options, args
 
 if __name__ == '__main__':
@@ -125,39 +148,64 @@ if __name__ == '__main__':
     samplerate = options.samplerate
     source_file = options.source_file
 
-    from aubio import onset, source, sink
+    from aubio import onset, tempo, source, sink
 
     s = source(source_file, samplerate, hopsize)
     if samplerate == 0: samplerate = s.get_samplerate()
 
-    o = onset(options.onset_method, bufsize, hopsize)
+    if options.beat:
+        o = tempo(options.onset_method, bufsize, hopsize)
+    else:
+        o = onset(options.onset_method, bufsize, hopsize)
+        if options.minioi:
+            if options.minioi.endswith('ms'):
+                o.set_minioi_ms(int(options.minioi[:-2]))
+            elif options.minioi.endswith('s'):
+                o.set_minioi_s(int(options.minioi[:-1]))
+            else:
+                o.set_minioi(int(options.minioi))
     o.set_threshold(options.threshold)
 
-    slice_number = 0
-    #if options.cut:
-    this_slice = sink('/tmp/t-%02d.wav' % slice_number, samplerate)
-
     timestamps = []
-    block_read = 0
+    total_frames = 0
+    # analyze pass
     while True:
         samples, read = s()
-        #ring_buffer = hstack([ring_buffer, samples])
-        is_onset = o(samples)
-        if is_onset:
-            this_onset = (block_read - 4. + is_onset[0]) * hopsize 
-            if options.verbose:
-                print "%.4f" % ( this_onset / samplerate )
-            timestamps.append (this_onset)
-            del this_slice
-            slice_number += 1
-            this_slice = sink('/tmp/t-%02d.wav' % slice_number, samplerate)
-        this_slice(samples, read)
-        block_read += 1
+        if o(samples):
+            timestamps.append (o.get_last())
+            if options.verbose: print ("%.4f" % o.get_last_s())
+        total_frames += read
         if read < hopsize: break
-
+    del s
     # print some info
-    duration = float ( block_read * hopsize + read ) / samplerate
     nstamps = len(timestamps)
+    duration = float (total_frames) / float(samplerate)
     info = 'found %(nstamps)d timestamps in %(source_file)s' % locals()
-    info += ' (read %(duration).2fs at %(samplerate)dHz)\n' % locals()
+    info += ' (total %(duration).2fs at %(samplerate)dHz)\n' % locals()
     sys.stderr.write(info)
+
+    # cutting pass
+    if options.cut and nstamps > 0:
+        # generate output files
+        from aubio.slicing import slice_source_at_stamps
+        timestamps_end = None
+        if options.cut_every_nslices:
+            timestamps = timestamps[::options.cut_every_nslices]
+            nstamps = len(timestamps)
+        if options.cut_until_nslices and options.cut_until_nsamples:
+            print ("warning: using cut_until_nslices, but cut_until_nsamples is set")
+        if options.cut_until_nsamples:
+            timestamps_end = [t + options.cut_until_nsamples for t in timestamps[1:]]
+            timestamps_end += [ 1e120 ]
+        if options.cut_until_nslices:
+            timestamps_end = [t for t in timestamps[1 + options.cut_until_nslices:]]
+            timestamps_end += [ 1e120 ] * (options.cut_until_nslices + 1)
+        slice_source_at_stamps(source_file, timestamps, timestamps_end = timestamps_end,
+                output_dir = options.output_directory,
+                samplerate = samplerate)
+
+        # print some info
+        duration = float (total_frames) / float(samplerate)
+        info = 'created %(nstamps)d slices from %(source_file)s' % locals()
+        info += ' (total %(duration).2fs at %(samplerate)dHz)\n' % locals()
+        sys.stderr.write(info)