source: python/lib/gen_external.py @ 150ec2d

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5
Last change on this file since 150ec2d was 150ec2d, checked in by Martin Hermant <martin.hermant@gmail.com>, 7 years ago

gen_external.py :

rename cpp_output to c_declarations
make pre processing parsing part of get_cpp_objects a distinct function get_c_declarations

  • Property mode set to 100644
File size: 8.8 KB
Line 
1import distutils.ccompiler
2import sys, os, subprocess, glob
3
4header = os.path.join('src', 'aubio.h')
5output_path = os.path.join('python', 'gen')
6
7source_header = """// this file is generated! do not modify
8#include "aubio-types.h"
9"""
10
11skip_objects = [
12  # already in ext/
13  'fft',
14  'pvoc',
15  'filter',
16  'filterbank',
17  # AUBIO_UNSTABLE
18  'hist',
19  'parameter',
20  'scale',
21  'beattracking',
22  'resampler',
23  'peakpicker',
24  'pitchfcomb',
25  'pitchmcomb',
26  'pitchschmitt',
27  'pitchspecacf',
28  'pitchyin',
29  'pitchyinfft',
30  'sink',
31  'sink_apple_audio',
32  'sink_sndfile',
33  'sink_wavwrite',
34  #'mfcc',
35  'source',
36  'source_apple_audio',
37  'source_sndfile',
38  'source_avcodec',
39  'source_wavread',
40  #'sampler',
41  'audio_unit',
42  'spectral_whitening',
43  ]
44
45def get_preprocessor():
46    # findout which compiler to use
47    from distutils.sysconfig import customize_compiler
48    compiler_name = distutils.ccompiler.get_default_compiler()
49    compiler = distutils.ccompiler.new_compiler(compiler=compiler_name)
50    try:
51        customize_compiler(compiler)
52    except AttributeError as e:
53        print("Warning: failed customizing compiler ({:s})".format(repr(e)))
54
55    if hasattr(compiler, 'initialize'):
56        try:
57            compiler.initialize()
58        except ValueError as e:
59            print("Warning: failed initializing compiler ({:s})".format(repr(e)))
60
61    cpp_cmd = None
62    if hasattr(compiler, 'preprocessor'): # for unixccompiler
63        cpp_cmd = compiler.preprocessor
64    elif hasattr(compiler, 'compiler'): # for ccompiler
65        cpp_cmd = compiler.compiler.split()
66        cpp_cmd += ['-E']
67    elif hasattr(compiler, 'cc'): # for msvccompiler
68        cpp_cmd = compiler.cc.split()
69        cpp_cmd += ['-E']
70
71    if not cpp_cmd:
72        print("Warning: could not guess preprocessor, using env's CC")
73        cpp_cmd = os.environ.get('CC', 'cc').split()
74        cpp_cmd += ['-E']
75    cpp_cmd += ['-x', 'c']  # force C language (emcc defaults to c++)
76    return cpp_cmd
77
78
79def get_c_declarations(header=header, usedouble=False):
80    ''' return a dense and preprocessed  string of all c declarations implied by aubio.h
81    '''
82    cpp_cmd = get_preprocessor()
83
84    macros = [('AUBIO_UNSTABLE', 1)]
85    if usedouble:
86        macros += [('HAVE_AUBIO_DOUBLE', 1)]
87
88    if not os.path.isfile(header):
89        raise Exception("could not find include file " + header)
90
91    includes = [os.path.dirname(header)]
92    cpp_cmd += distutils.ccompiler.gen_preprocess_options(macros, includes)
93    cpp_cmd += [header]
94
95    print("Running command: {:s}".format(" ".join(cpp_cmd)))
96    proc = subprocess.Popen(cpp_cmd,
97            stderr=subprocess.PIPE,
98            stdout=subprocess.PIPE)
99    assert proc, 'Proc was none'
100    cpp_output = proc.stdout.read()
101    err_output = proc.stderr.read()
102    if not cpp_output:
103        raise Exception("preprocessor output is empty:\n%s" % err_output)
104    elif err_output:
105        print ("Warning: preprocessor produced warnings:\n%s" % err_output)
106    if not isinstance(cpp_output, list):
107        cpp_output = [l.strip() for l in cpp_output.decode('utf8').split('\n')]
108
109    cpp_output = filter(lambda y: len(y) > 1, cpp_output)
110    cpp_output = list(filter(lambda y: not y.startswith('#'), cpp_output))
111
112    i = 1
113    while 1:
114        if i >= len(cpp_output):break
115        if ('{' in cpp_output[i - 1]) and (not '}' in cpp_output[i - 1]) or (not ';' in cpp_output[i - 1]):
116            cpp_output[i] = cpp_output[i-1] + ' ' + cpp_output[i]
117            cpp_output.pop(i-1)
118        elif ('}' in cpp_output[i]):
119            cpp_output[i] = cpp_output[i - 1] + ' ' + cpp_output[i]
120            cpp_output.pop(i - 1)
121        else:
122            i += 1
123
124    return cpp_output
125
126def get_cpp_objects_from_c_declarations(c_declarations):
127    typedefs = filter(lambda y: y.startswith ('typedef struct _aubio'), c_declarations)
128    cpp_objects = [a.split()[3][:-1] for a in typedefs]
129    return cpp_objects
130
131def analyze_c_declarations(cpp_objects, c_declarations):
132    lib = {}
133
134    for o in cpp_objects:
135        shortname = ''
136        if o[:6] == 'aubio_':
137            shortname = o[6:-2]  # without aubio_
138            longname = o[:-2]  # without _t
139        else: # support object not starting with aubio_ (fvec...)
140            shortname = o
141            longname = shortname
142       
143        if shortname in skip_objects:
144            continue
145        lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'get': [], 'set': [], 'other': []}
146        lib[shortname]['longname'] = o
147        lib[shortname]['shortname'] = shortname
148        valid_funcname_part = ['_'+longname,longname+'_']
149
150        for fn in c_declarations:
151            func_name = fn.split('(')[0].strip().split(' ')[1:]
152            if func_name:
153                func_name = func_name[-1]
154            else:
155                raise NameError('Warning : error while parsing : unexpected line %s' % fn)
156            if any(x in func_name for x in valid_funcname_part):
157                # print "found", shortname, "in", fn
158                if 'typedef struct ' in fn:
159                    lib[shortname]['struct'].append(fn)
160                elif '_do' in fn:
161                    lib[shortname]['do'].append(fn)
162                elif 'new_' in fn:
163                    lib[shortname]['new'].append(fn)
164                elif 'del_' in fn:
165                    lib[shortname]['del'].append(fn)
166                elif '_get_' in fn:
167                    lib[shortname]['get'].append(fn)
168                elif '_set_' in fn:
169                    lib[shortname]['set'].append(fn)
170                else:
171                    #print "no idea what to do about", fn
172                    lib[shortname]['other'].append(fn)
173    return lib
174
175def print_c_declarations_results(lib, c_declarations):
176    for fn in c_declarations:
177        found = 0
178        for o in lib:
179            for family in lib[o]:
180                if fn in lib[o][family]:
181                    found = 1
182        if found == 0:
183            print ("missing", fn)
184
185    for o in lib:
186        for family in lib[o]:
187            if type(lib[o][family]) == str:
188                print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
189            elif len(lib[o][family]) == 1:
190                print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family][0] ) )
191            else:
192                print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
193
194
195def generate_external(header=header, output_path=output_path, usedouble=False, overwrite=True):
196    if not os.path.isdir(output_path): os.mkdir(output_path)
197    elif not overwrite: return sorted(glob.glob(os.path.join(output_path, '*.c')))
198
199    c_declarations = get_c_declarations(header, usedouble=usedouble)
200    cpp_objects = get_cpp_objects_from_c_declarations(c_declarations)
201
202    lib = analyze_c_declarations(cpp_objects, c_declarations)
203    # print_c_declarations_results(lib, c_declarations)
204
205    sources_list = []
206    try:
207        from .gen_code import MappedObject
208    except (SystemError, ValueError):
209        from gen_code import MappedObject
210    for o in lib:
211        out = source_header
212        mapped = MappedObject(lib[o], usedouble = usedouble)
213        out += mapped.gen_code()
214        output_file = os.path.join(output_path, 'gen-%s.c' % o)
215        with open(output_file, 'w') as f:
216            f.write(out)
217            print ("wrote %s" % output_file )
218            sources_list.append(output_file)
219
220    out = source_header
221    out += "#include \"aubio-generated.h\""
222    check_types = "\n     ||  ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
223    out += """
224
225int generated_types_ready (void)
226{{
227  return ({pycheck_types});
228}}
229""".format(pycheck_types = check_types)
230
231    add_types = "".join(["""
232  Py_INCREF (&Py_{name}Type);
233  PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name = o) for o in lib])
234    out += """
235
236void add_generated_objects ( PyObject *m )
237{{
238{add_types}
239}}
240""".format(add_types = add_types)
241
242    output_file = os.path.join(output_path, 'aubio-generated.c')
243    with open(output_file, 'w') as f:
244        f.write(out)
245        print ("wrote %s" % output_file )
246        sources_list.append(output_file)
247
248    objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
249    out = """// generated list of objects created with gen_external.py
250
251#include <Python.h>
252"""
253    if usedouble:
254        out += """
255#ifndef HAVE_AUBIO_DOUBLE
256#define HAVE_AUBIO_DOUBLE 1
257#endif
258"""
259    out += """
260{objlist}
261int generated_objects ( void );
262void add_generated_objects( PyObject *m );
263""".format(objlist = objlist)
264
265    output_file = os.path.join(output_path, 'aubio-generated.h')
266    with open(output_file, 'w') as f:
267        f.write(out)
268        print ("wrote %s" % output_file )
269        # no need to add header to list of sources
270
271    return sorted(sources_list)
272
273if __name__ == '__main__':
274    if len(sys.argv) > 1: header = sys.argv[1]
275    if len(sys.argv) > 2: output_path = sys.argv[2]
276    generate_external(header, output_path)
Note: See TracBrowser for help on using the repository browser.