source: python/lib/gen_external.py @ 6cbf34b

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

gen_external :

add function get_all_func_names_from_lib

analyze_c_declarations -> generate_lib_from_c_declarations

  • Property mode set to 100644
File size: 9.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    # clean pointer notations
125    tmp = []
126    for l in cpp_output:
127        tmp+=[ l.replace(' *','* ')]
128    cpp_output = tmp;
129
130
131    return cpp_output
132
133def get_cpp_objects_from_c_declarations(c_declarations):
134    typedefs = filter(lambda y: y.startswith ('typedef struct _aubio'), c_declarations)
135    cpp_objects = [a.split()[3][:-1] for a in typedefs]
136    return cpp_objects
137
138
139def get_all_func_names_from_lib(lib, depth=0):
140    ''' return flat string of all function used in lib
141    '''
142    res = []
143    indent = " " * depth
144    for k, v in lib.items():
145        if isinstance(v, dict):
146            res += get_all_func_names_from_lib(v, depth + 1)
147        elif isinstance(v, list):
148            for elem in v:
149                e = elem.split('(')
150                if len(e) < 2:
151                    continue  # not a function
152                fname_part = e[0].strip().split(' ')
153                fname = fname_part[-1]
154                if fname:
155                    res += [fname]
156                else:
157                    raise NameError('gen_lib : weird function: ' + str(e))
158
159    return res
160
161
162def generate_lib_from_c_declarations(cpp_objects, c_declarations):
163    ''' returns a lib from given cpp_object names
164
165    a lib is a dict grouping functions by family (onset,pitch...)
166        each eement is itself a dict of functions grouped by puposes as :
167        struct, new, del, do, get, set and other
168    '''
169    lib = {}
170
171    for o in cpp_objects:
172        shortname = ''
173        if o[:6] == 'aubio_':
174            shortname = o[6:-2]  # without aubio_
175            longname = o[:-2]  # without _t
176        else: # support object not starting with aubio_ (fvec...)
177            shortname = o
178            longname = shortname
179       
180        if shortname in skip_objects:
181            continue
182        lib[shortname] = {'struct': [], 'new': [], 'del': [], 'do': [], 'get': [], 'set': [], 'other': []}
183        lib[shortname]['longname'] = longname
184        lib[shortname]['shortname'] = shortname
185
186        for fn in c_declarations:
187            func_name = fn.split('(')[0].strip().split(' ')[1:]
188            if func_name:
189                func_name = func_name[-1]
190            else:
191                raise NameError('Warning : error while parsing : unexpected line %s' % fn)
192            if func_name.startswith(longname + '_') or func_name.endswith(longname):
193                # print "found", shortname, "in", fn
194                if 'typedef struct ' in fn:
195                    lib[shortname]['struct'].append(fn)
196                elif '_do' in fn:
197                    lib[shortname]['do'].append(fn)
198                elif 'new_' in fn:
199                    lib[shortname]['new'].append(fn)
200                elif 'del_' in fn:
201                    lib[shortname]['del'].append(fn)
202                elif '_get_' in fn:
203                    lib[shortname]['get'].append(fn)
204                elif '_set_' in fn:
205                    lib[shortname]['set'].append(fn)
206                else:
207                    #print "no idea what to do about", fn
208                    lib[shortname]['other'].append(fn)
209    return lib
210
211def print_c_declarations_results(lib, c_declarations):
212    for fn in c_declarations:
213        found = 0
214        for o in lib:
215            for family in lib[o]:
216                if fn in lib[o][family]:
217                    found = 1
218        if found == 0:
219            print ("missing", fn)
220
221    for o in lib:
222        for family in lib[o]:
223            if type(lib[o][family]) == str:
224                print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
225            elif len(lib[o][family]) == 1:
226                print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family][0] ) )
227            else:
228                print ( "{:15s} {:10s} {:s}".format(o, family, lib[o][family] ) )
229
230
231def generate_external(header=header, output_path=output_path, usedouble=False, overwrite=True):
232    if not os.path.isdir(output_path): os.mkdir(output_path)
233    elif not overwrite: return sorted(glob.glob(os.path.join(output_path, '*.c')))
234
235    c_declarations = get_c_declarations(header, usedouble=usedouble)
236    cpp_objects = get_cpp_objects_from_c_declarations(c_declarations)
237
238    lib = generate_lib_from_c_declarations(cpp_objects, c_declarations)
239    # print_c_declarations_results(lib, c_declarations)
240
241    sources_list = []
242    try:
243        from .gen_code import MappedObject
244    except (SystemError, ValueError):
245        from gen_code import MappedObject
246    for o in lib:
247        out = source_header
248        mapped = MappedObject(lib[o], usedouble = usedouble)
249        out += mapped.gen_code()
250        output_file = os.path.join(output_path, 'gen-%s.c' % o)
251        with open(output_file, 'w') as f:
252            f.write(out)
253            print ("wrote %s" % output_file )
254            sources_list.append(output_file)
255
256    out = source_header
257    out += "#include \"aubio-generated.h\""
258    check_types = "\n     ||  ".join(["PyType_Ready(&Py_%sType) < 0" % o for o in lib])
259    out += """
260
261int generated_types_ready (void)
262{{
263  return ({pycheck_types});
264}}
265""".format(pycheck_types = check_types)
266
267    add_types = "".join(["""
268  Py_INCREF (&Py_{name}Type);
269  PyModule_AddObject(m, "{name}", (PyObject *) & Py_{name}Type);""".format(name = o) for o in lib])
270    out += """
271
272void add_generated_objects ( PyObject *m )
273{{
274{add_types}
275}}
276""".format(add_types = add_types)
277
278    output_file = os.path.join(output_path, 'aubio-generated.c')
279    with open(output_file, 'w') as f:
280        f.write(out)
281        print ("wrote %s" % output_file )
282        sources_list.append(output_file)
283
284    objlist = "".join(["extern PyTypeObject Py_%sType;\n" % p for p in lib])
285    out = """// generated list of objects created with gen_external.py
286
287#include <Python.h>
288"""
289    if usedouble:
290        out += """
291#ifndef HAVE_AUBIO_DOUBLE
292#define HAVE_AUBIO_DOUBLE 1
293#endif
294"""
295    out += """
296{objlist}
297int generated_objects ( void );
298void add_generated_objects( PyObject *m );
299""".format(objlist = objlist)
300
301    output_file = os.path.join(output_path, 'aubio-generated.h')
302    with open(output_file, 'w') as f:
303        f.write(out)
304        print ("wrote %s" % output_file )
305        # no need to add header to list of sources
306
307    return sorted(sources_list)
308
309if __name__ == '__main__':
310    if len(sys.argv) > 1: header = sys.argv[1]
311    if len(sys.argv) > 2: output_path = sys.argv[2]
312    generate_external(header, output_path)
Note: See TracBrowser for help on using the repository browser.