setup.py: move cut and cmd inside aubio module, use entry_points to generate scripts
[aubio.git] / python / lib / aubio / cut.py
1 #! /usr/bin/env python
2
3 """ this file was written by Paul Brossier
4   it is released under the GNU/GPL license.
5 """
6
7 import sys
8
9 def parse_args():
10     from optparse import OptionParser
11     usage = "usage: %s [options] -i soundfile" % sys.argv[0]
12     usage += "\n help: %s -h" % sys.argv[0]
13     parser = OptionParser(usage=usage)
14     parser.add_option("-i", "--input", action = "store", dest = "source_file",
15             help="input sound file to analyse", metavar = "<source_file>")
16     parser.add_option("-O","--onset-method",
17             action="store", dest="onset_method", default='default',
18             metavar = "<onset_method>",
19             help="onset detection method [default=default] \
20                     complexdomain|hfc|phase|specdiff|energy|kl|mkl")
21     # cutting methods
22     parser.add_option("-b","--beat",
23             action="store_true", dest="beat", default=False,
24             help="use beat locations")
25     """
26     parser.add_option("-S","--silencecut",
27             action="store_true", dest="silencecut", default=False,
28             help="use silence locations")
29     parser.add_option("-s","--silence",
30             metavar = "<value>",
31             action="store", dest="silence", default=-70,
32             help="silence threshold [default=-70]")
33             """
34     # algorithm parameters
35     parser.add_option("-r", "--samplerate",
36             metavar = "<freq>", type='int',
37             action="store", dest="samplerate", default=0,
38             help="samplerate at which the file should be represented")
39     parser.add_option("-B","--bufsize",
40             action="store", dest="bufsize", default=512,
41             metavar = "<size>", type='int',
42             help="buffer size [default=512]")
43     parser.add_option("-H","--hopsize",
44             metavar = "<size>", type='int',
45             action="store", dest="hopsize", default=256,
46             help="overlap size [default=256]")
47     parser.add_option("-t","--onset-threshold",
48             metavar = "<value>", type="float",
49             action="store", dest="threshold", default=0.3,
50             help="onset peak picking threshold [default=0.3]")
51     parser.add_option("-c","--cut",
52             action="store_true", dest="cut", default=False,
53             help="cut input sound file at detected labels \
54                     best used with option -L")
55
56     # minioi
57     parser.add_option("-M","--minioi",
58             metavar = "<value>", type='string',
59             action="store", dest="minioi", default="12ms",
60             help="minimum inter onset interval [default=12ms]")
61
62     """
63     parser.add_option("-D","--delay",
64             action = "store", dest = "delay", type = "float",
65             metavar = "<seconds>", default=0,
66             help="number of seconds to take back [default=system]\
67                     default system delay is 3*hopsize/samplerate")
68     parser.add_option("-C","--dcthreshold",
69             metavar = "<value>",
70             action="store", dest="dcthreshold", default=1.,
71             help="onset peak picking DC component [default=1.]")
72     parser.add_option("-L","--localmin",
73             action="store_true", dest="localmin", default=False,
74             help="use local minima after peak detection")
75     parser.add_option("-d","--derivate",
76             action="store_true", dest="derivate", default=False,
77             help="derivate onset detection function")
78     parser.add_option("-z","--zerocross",
79             metavar = "<value>",
80             action="store", dest="zerothres", default=0.008,
81             help="zero-crossing threshold for slicing [default=0.00008]")
82             """
83     # plotting functions
84     """
85     parser.add_option("-p","--plot",
86             action="store_true", dest="plot", default=False,
87             help="draw plot")
88     parser.add_option("-x","--xsize",
89             metavar = "<size>",
90             action="store", dest="xsize", default=1.,
91             type='float', help="define xsize for plot")
92     parser.add_option("-y","--ysize",
93             metavar = "<size>",
94             action="store", dest="ysize", default=1.,
95             type='float', help="define ysize for plot")
96     parser.add_option("-f","--function",
97             action="store_true", dest="func", default=False,
98             help="print detection function")
99     parser.add_option("-n","--no-onsets",
100             action="store_true", dest="nplot", default=False,
101             help="do not plot detected onsets")
102     parser.add_option("-O","--outplot",
103             metavar = "<output_image>",
104             action="store", dest="outplot", default=None,
105             help="save plot to output.{ps,png}")
106     parser.add_option("-F","--spectrogram",
107             action="store_true", dest="spectro", default=False,
108             help="add spectrogram to the plot")
109     """
110     parser.add_option("-o","--output", type = str,
111             metavar = "<outputdir>",
112             action="store", dest="output_directory", default=None,
113             help="specify path where slices of the original file should be created")
114     parser.add_option("--cut-until-nsamples", type = int,
115             metavar = "<samples>",
116             action = "store", dest = "cut_until_nsamples", default = None,
117             help="how many extra samples should be added at the end of each slice")
118     parser.add_option("--cut-every-nslices", type = int,
119             metavar = "<samples>",
120             action = "store", dest = "cut_every_nslices", default = None,
121             help="how many slices should be groupped together at each cut")
122     parser.add_option("--cut-until-nslices", type = int,
123             metavar = "<slices>",
124             action = "store", dest = "cut_until_nslices", default = None,
125             help="how many extra slices should be added at the end of each slice")
126
127     parser.add_option("-v","--verbose",
128             action="store_true", dest="verbose", default=True,
129             help="make lots of noise [default]")
130     parser.add_option("-q","--quiet",
131             action="store_false", dest="verbose", default=True,
132             help="be quiet")
133     (options, args) = parser.parse_args()
134     if not options.source_file:
135         import os.path
136         if len(args) == 1:
137             options.source_file = args[0]
138         else:
139             print ("no file name given\n" + usage)
140             sys.exit(1)
141     return options, args
142
143 def main():
144     options, args = parse_args()
145
146     hopsize = options.hopsize
147     bufsize = options.bufsize
148     samplerate = options.samplerate
149     source_file = options.source_file
150
151     from aubio import onset, tempo, source, sink
152
153     s = source(source_file, samplerate, hopsize)
154     if samplerate == 0: samplerate = s.get_samplerate()
155
156     if options.beat:
157         o = tempo(options.onset_method, bufsize, hopsize)
158     else:
159         o = onset(options.onset_method, bufsize, hopsize)
160         if options.minioi:
161             if options.minioi.endswith('ms'):
162                 o.set_minioi_ms(int(options.minioi[:-2]))
163             elif options.minioi.endswith('s'):
164                 o.set_minioi_s(int(options.minioi[:-1]))
165             else:
166                 o.set_minioi(int(options.minioi))
167     o.set_threshold(options.threshold)
168
169     timestamps = []
170     total_frames = 0
171     # analyze pass
172     while True:
173         samples, read = s()
174         if o(samples):
175             timestamps.append (o.get_last())
176             if options.verbose: print ("%.4f" % o.get_last_s())
177         total_frames += read
178         if read < hopsize: break
179     del s
180     # print some info
181     nstamps = len(timestamps)
182     duration = float (total_frames) / float(samplerate)
183     info = 'found %(nstamps)d timestamps in %(source_file)s' % locals()
184     info += ' (total %(duration).2fs at %(samplerate)dHz)\n' % locals()
185     sys.stderr.write(info)
186
187     # cutting pass
188     if options.cut and nstamps > 0:
189         # generate output files
190         from aubio.slicing import slice_source_at_stamps
191         timestamps_end = None
192         if options.cut_every_nslices:
193             timestamps = timestamps[::options.cut_every_nslices]
194             nstamps = len(timestamps)
195         if options.cut_until_nslices and options.cut_until_nsamples:
196             print ("warning: using cut_until_nslices, but cut_until_nsamples is set")
197         if options.cut_until_nsamples:
198             timestamps_end = [t + options.cut_until_nsamples for t in timestamps[1:]]
199             timestamps_end += [ 1e120 ]
200         if options.cut_until_nslices:
201             timestamps_end = [t for t in timestamps[1 + options.cut_until_nslices:]]
202             timestamps_end += [ 1e120 ] * (options.cut_until_nslices + 1)
203         slice_source_at_stamps(source_file, timestamps, timestamps_end = timestamps_end,
204                 output_dir = options.output_directory,
205                 samplerate = samplerate)
206
207         # print some info
208         duration = float (total_frames) / float(samplerate)
209         info = 'created %(nstamps)d slices from %(source_file)s' % locals()
210         info += ' (total %(duration).2fs at %(samplerate)dHz)\n' % locals()
211         sys.stderr.write(info)