source: python/lib/aubio/cut.py @ 965adee

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

python/lib/aubio/cut.py: upgrade to argparse

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