source: python/lib/gen_code.py @ 950a80c

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

lib/gen_code.py: comment out print

  • Property mode set to 100644
File size: 15.4 KB
Line 
1aubiodefvalue = {
2    # we have some clean up to do
3    'buf_size': 'Py_default_vector_length',
4    'win_s': 'Py_default_vector_length',
5    # and here too
6    'hop_size': 'Py_default_vector_length / 2',
7    'hop_s': 'Py_default_vector_length / 2',
8    # these should be alright
9    'samplerate': 'Py_aubio_default_samplerate',
10    # now for the non obvious ones
11    'n_filters': '40',
12    'n_coeffs': '13',
13    'nelems': '10',
14    'flow': '0.',
15    'fhig': '1.',
16    'ilow': '0.',
17    'ihig': '1.',
18    'thrs': '0.5',
19    'ratio': '0.5',
20    'method': '"default"',
21    'uri': '"none"',
22    }
23
24member_types = {
25        'name': 'type',
26        'char_t*': 'T_STRING',
27        'uint_t': 'T_INT',
28        'smpl_t': 'T_FLOAT',
29        }
30
31pyfromtype_fn = {
32        'smpl_t': 'PyFloat_FromDouble',
33        'uint_t': 'PyLong_FromLong', # was: 'PyInt_FromLong',
34        'fvec_t*': 'PyAubio_CFvecToArray',
35        'fmat_t*': 'PyAubio_CFmatToArray',
36        }
37
38pytoaubio_fn = {
39        'fvec_t*': 'PyAubio_ArrayToCFvec',
40        'cvec_t*': 'PyAubio_ArrayToCCvec',
41        #'fmat_t*': 'PyAubio_ArrayToCFmat',
42        }
43
44pyfromaubio_fn = {
45        'fvec_t*': 'PyAubio_CFvecToArray',
46        'cvec_t*': 'PyAubio_CCvecToArray',
47        'fmat_t*': 'PyAubio_CFmatToArray',
48        }
49
50newfromtype_fn = {
51        'fvec_t*': 'new_fvec',
52        'fmat_t*': 'new_fmat',
53        'cvec_t*': 'new_cvec',
54        }
55
56delfromtype_fn = {
57        'fvec_t*': 'del_fvec',
58        'fmat_t*': 'del_fmat',
59        'cvec_t*': 'del_cvec',
60        }
61
62param_init = {
63        'char_t*': 'NULL',
64        'uint_t': '0',
65        'sint_t': 0,
66        'smpl_t': 0.,
67        'lsmp_t': 0.,
68        }
69
70pyargparse_chars = {
71        'smpl_t': 'f',
72        'uint_t': 'I',
73        'sint_t': 'I',
74        'char_t*': 's',
75        'fmat_t*': 'O',
76        'fvec_t*': 'O',
77        'cvec_t*': 'O',
78        }
79
80objoutsize = {
81        'onset': '1',
82        'pitch': '1',
83        'wavetable': 'self->hop_size',
84        'sampler': 'self->hop_size',
85        'mfcc': 'self->n_coeffs',
86        'specdesc': '1',
87        'tempo': '2',
88        'filterbank': 'self->n_filters',
89        'tss': 'self->hop_size',
90        }
91
92def get_name(proto):
93    name = proto.replace(' *', '* ').split()[1].split('(')[0]
94    name = name.replace('*','')
95    if name == '': raise ValueError(proto + "gave empty name")
96    return name
97
98def get_return_type(proto):
99    import re
100    paramregex = re.compile('(\w+ ?\*?).*')
101    outputs = paramregex.findall(proto)
102    assert len(outputs) == 1
103    return outputs[0].replace(' ', '')
104
105def split_type(arg):
106    """ arg = 'foo *name'
107        return ['foo*', 'name'] """
108    l = arg.split()
109    type_arg = {} #'type': l[0], 'name': l[1]}
110    type_arg['type'] = " ".join(l[:-1])
111    type_arg['name'] = l[-1]
112    # fix up type / name
113    if type_arg['name'].startswith('*'):
114        # ['foo', '*name'] -> ['foo*', 'name']
115        type_arg['type'] += '*'
116        type_arg['name'] = type_arg['name'][1:]
117    if type_arg['type'].endswith(' *'):
118        # ['foo *', 'name'] -> ['foo*', 'name']
119        type_arg['type'] = type_arg['type'].replace(' *','*')
120    if type_arg['type'].startswith('const '):
121        # ['foo *', 'name'] -> ['foo*', 'name']
122        type_arg['type'] = type_arg['type'].replace('const ','')
123    return type_arg
124
125def get_params(proto):
126    """ get the list of parameters from a function prototype
127    example: proto = "int main (int argc, char ** argv)"
128    returns: ['int argc', 'char ** argv']
129    """
130    import re
131    paramregex = re.compile('.*\((.*)\);')
132    a = paramregex.findall(proto)[0].split(', ')
133    #a = [i.replace('const ', '') for i in a]
134    return a
135
136def get_input_params(proto):
137    a = get_params(proto)
138    return [i.replace('const ', '') for i in a if (i.startswith('const ') or i.startswith('uint_t ') or i.startswith('smpl_t '))]
139
140def get_output_params(proto):
141    a = get_params(proto)
142    return [i for i in a if not i.startswith('const ')][1:]
143
144def get_params_types_names(proto):
145    """ get the list of parameters from a function prototype
146    example: proto = "int main (int argc, char ** argv)"
147    returns: [['int', 'argc'], ['char **','argv']]
148    """
149    a = list(map(split_type, get_params(proto)))
150    #print proto, a
151    #import sys; sys.exit(1)
152    return a
153
154class MappedObject(object):
155
156    def __init__(self, prototypes):
157        self.prototypes = prototypes
158
159        self.shortname = prototypes['shortname']
160        self.longname = prototypes['longname']
161        self.new_proto = prototypes['new'][0]
162        self.del_proto = prototypes['del'][0]
163        self.do_proto = prototypes['do'][0]
164        self.input_params = get_params_types_names(self.new_proto)
165        self.input_params_list = "; ".join(get_input_params(self.new_proto))
166        self.outputs = get_params_types_names(self.do_proto)[2:]
167        self.do_inputs = [get_params_types_names(self.do_proto)[1]]
168        self.do_outputs = get_params_types_names(self.do_proto)[2:]
169        self.outputs_flat = get_output_params(self.do_proto)
170        self.output_results = "; ".join(self.outputs_flat)
171
172        #print ("input_params: ", map(split_type, get_input_params(self.do_proto)))
173        #print ("output_params", map(split_type, get_output_params(self.do_proto)))
174
175    def gen_code(self):
176        out = ""
177        out += self.gen_struct()
178        out += self.gen_doc()
179        out += self.gen_new()
180        out += self.gen_init()
181        out += self.gen_del()
182        out += self.gen_do()
183        out += self.gen_memberdef()
184        out += self.gen_set()
185        out += self.gen_get()
186        out += self.gen_methodef()
187        out += self.gen_typeobject()
188        return out
189
190    def gen_struct(self):
191        out = """
192// {shortname} structure
193typedef struct{{
194    PyObject_HEAD
195    // pointer to aubio object
196    {longname} *o;
197    // input parameters
198    {input_params_list};
199    // do input vectors
200    {do_inputs_list};
201    // output results
202    {output_results};
203}} Py_{shortname};
204"""
205        return out.format(do_inputs_list = "; ".join(get_input_params(self.do_proto)), **self.__dict__)
206
207    def gen_doc(self):
208        out = """
209// TODO: add documentation
210static char Py_{shortname}_doc[] = \"undefined\";
211"""
212        return out.format(**self.__dict__)
213
214    def gen_new(self):
215        out = """
216// new {shortname}
217static PyObject *
218Py_{shortname}_new (PyTypeObject * pytype, PyObject * args, PyObject * kwds)
219{{
220    Py_{shortname} *self;
221""".format(**self.__dict__)
222        params = self.input_params
223        for p in params:
224            out += """
225    {type} {name} = {defval};""".format(defval = param_init[p['type']], **p)
226        plist = ", ".join(["\"%s\"" % p['name'] for p in params])
227        out += """
228    static char *kwlist[] = {{ {plist}, NULL }};""".format(plist = plist)
229        argchars = "".join([pyargparse_chars[p['type']] for p in params])
230        arglist = ", ".join(["&%s" % p['name'] for p in params])
231        out += """
232    if (!PyArg_ParseTupleAndKeywords (args, kwds, "|{argchars}", kwlist,
233              {arglist})) {{
234        return NULL;
235    }}
236""".format(argchars = argchars, arglist = arglist)
237        out += """
238    self = (Py_{shortname} *) pytype->tp_alloc (pytype, 0);
239    if (self == NULL) {{
240        return NULL;
241    }}
242""".format(**self.__dict__)
243        params = self.input_params
244        for p in params:
245            out += self.check_valid(p)
246        out += """
247    return (PyObject *)self;
248}
249"""
250        return out
251
252    def check_valid(self, p):
253        if p['type'] == 'uint_t':
254            return self.check_valid_uint(p)
255        if p['type'] == 'char_t*':
256            return self.check_valid_char(p)
257        else:
258            print ("ERROR, no idea how to check %s for validity" % p['type'])
259
260    def check_valid_uint(self, p):
261        name = p['name']
262        return """
263    self->{name} = {defval};
264    if ((sint_t){name} > 0) {{
265        self->{name} = {name};
266    }} else if ((sint_t){name} < 0) {{
267        PyErr_SetString (PyExc_ValueError, "can not use negative value for {name}");
268        return NULL;
269    }}
270""".format(defval = aubiodefvalue[name], name = name)
271
272    def check_valid_char(self, p):
273        name = p['name']
274        return """
275    self->{name} = {defval};
276    if ({name} != NULL) {{
277        self->{name} = {name};
278    }}
279""".format(defval = aubiodefvalue[name], name = name)
280
281    def gen_init(self):
282        out = """
283// init {shortname}
284static int
285Py_{shortname}_init (Py_{shortname} * self, PyObject * args, PyObject * kwds)
286{{
287""".format(**self.__dict__)
288        new_name = get_name(self.new_proto)
289        new_params = ", ".join(["self->%s" % s['name'] for s in self.input_params])
290        out += """
291  self->o = {new_name}({new_params});
292""".format(new_name = new_name, new_params = new_params)
293        paramchars = "%s"
294        paramvals = "self->method"
295        out += """
296  // return -1 and set error string on failure
297  if (self->o == NULL) {{
298    //char_t errstr[30 + strlen(self->uri)];
299    //sprintf(errstr, "error creating {shortname} with params {paramchars}", {paramvals});
300    char_t errstr[60];
301    sprintf(errstr, "error creating {shortname} with given params");
302    PyErr_SetString (PyExc_Exception, errstr);
303    return -1;
304  }}
305""".format(paramchars = paramchars, paramvals = paramvals, **self.__dict__)
306        output_create = ""
307        for o in self.outputs:
308            output_create += """
309  self->{name} = {create_fn}({output_size});""".format(name = o['name'], create_fn = newfromtype_fn[o['type']], output_size = objoutsize[self.shortname])
310        out += """
311  // TODO get internal params after actual object creation?
312"""
313        for input_param in self.do_inputs:
314            out += """
315  self->{0} = ({1})malloc(sizeof({2}));""".format(input_param['name'], input_param['type'], input_param['type'][:-1])
316        out += """
317  // create outputs{output_create}
318""".format(output_create = output_create)
319        out += """
320  return 0;
321}
322"""
323        return out
324
325    def gen_memberdef(self):
326        out = """
327static PyMemberDef Py_{shortname}_members[] = {{
328""".format(**self.__dict__)
329        for p in get_params_types_names(self.new_proto):
330            tmp = "  {{\"{name}\", {ttype}, offsetof (Py_{shortname}, {name}), READONLY, \"TODO documentation\"}},\n"
331            pytype = member_types[p['type']]
332            out += tmp.format(name = p['name'], ttype = pytype, shortname = self.shortname)
333        out += """  {NULL}, // sentinel
334};
335"""
336        return out
337
338    def gen_del(self):
339        out = """
340// del {shortname}
341static void
342Py_{shortname}_del  (Py_{shortname} * self, PyObject * unused)
343{{""".format(**self.__dict__)
344        for input_param in self.do_inputs:
345            out += """
346    free(self->{0[name]});""".format(input_param)
347        for o in self.outputs:
348            name = o['name']
349            del_out = delfromtype_fn[o['type']]
350            out += """
351    {del_out}(self->{name});""".format(del_out = del_out, name = name)
352        del_fn = get_name(self.del_proto)
353        out += """
354    {del_fn}(self->o);
355    Py_TYPE(self)->tp_free((PyObject *) self);
356}}
357""".format(del_fn = del_fn)
358        return out
359
360    def gen_do(self):
361        output = self.outputs[0]
362        out = """
363// do {shortname}
364static PyObject*
365Py_{shortname}_do  (Py_{shortname} * self, PyObject * args)
366{{""".format(**self.__dict__)
367        input_params = self.do_inputs
368        output_params = self.do_outputs
369        #print input_params
370        #print output_params
371        for input_param in input_params:
372            out += """
373    PyObject *py_{0};""".format(input_param['name'], input_param['type'])
374        refs = ", ".join(["&py_%s" % p['name'] for p in input_params])
375        pyparamtypes = "".join([pyargparse_chars[p['type']] for p in input_params])
376        out += """
377    if (!PyArg_ParseTuple (args, "{pyparamtypes}", {refs})) {{
378        return NULL;
379    }}""".format(refs = refs, pyparamtypes = pyparamtypes, **self.__dict__)
380        for p in input_params:
381            out += """
382    if (!{pytoaubio}(py_{0[name]}, self->{0[name]})) {{
383        return NULL;
384    }}""".format(input_param, pytoaubio = pytoaubio_fn[input_param['type']])
385        do_fn = get_name(self.do_proto)
386        inputs = ", ".join(['self->'+p['name'] for p in input_params])
387        outputs = ", ".join(["self->%s" % p['name'] for p in self.do_outputs])
388        out += """
389
390    {do_fn}(self->o, {inputs}, {outputs});
391
392    return (PyObject *) {aubiotonumpy} ({outputs});
393}}
394""".format(
395        do_fn = do_fn,
396        aubiotonumpy = pyfromaubio_fn[output['type']], 
397        inputs = inputs, outputs = outputs,
398        )
399        return out
400
401    def gen_set(self):
402        out = """
403// {shortname} setters
404""".format(**self.__dict__)
405        for set_param in self.prototypes['set']:
406            params = get_params_types_names(set_param)[1]
407            paramtype = params['type']
408            method_name = get_name(set_param)
409            param = method_name.split('aubio_'+self.shortname+'_set_')[-1]
410            pyparamtype = pyargparse_chars[paramtype]
411            out += """
412static PyObject *
413Pyaubio_{shortname}_set_{param} (Py_{shortname} *self, PyObject *args)
414{{
415  uint_t err = 0;
416  {paramtype} {param};
417
418  if (!PyArg_ParseTuple (args, "{pyparamtype}", &{param})) {{
419    return NULL;
420  }}
421  err = aubio_{shortname}_set_{param} (self->o, {param});
422
423  if (err > 0) {{
424    PyErr_SetString (PyExc_ValueError, "error running aubio_{shortname}_set_{param}");
425    return NULL;
426  }}
427  Py_RETURN_NONE;
428}}
429""".format(param = param, paramtype = paramtype, pyparamtype = pyparamtype, **self.__dict__)
430        return out
431
432    def gen_get(self):
433        out = """
434// {shortname} getters
435""".format(**self.__dict__)
436        for method in self.prototypes['get']:
437            params = get_params_types_names(method)
438            method_name = get_name(method)
439            assert len(params) == 1, \
440                "get method has more than one parameter %s" % params
441            param = method_name.split('aubio_'+self.shortname+'_get_')[-1]
442            paramtype = get_return_type(method)
443            ptypeconv = pyfromtype_fn[paramtype]
444            out += """
445static PyObject *
446Pyaubio_{shortname}_get_{param} (Py_{shortname} *self, PyObject *unused)
447{{
448  {ptype} {param} = aubio_{shortname}_get_{param} (self->o);
449  return (PyObject *){ptypeconv} ({param});
450}}
451""".format(param = param, ptype = paramtype, ptypeconv = ptypeconv,
452        **self.__dict__)
453        return out
454
455    def gen_methodef(self):
456        out = """
457static PyMethodDef Py_{shortname}_methods[] = {{""".format(**self.__dict__)
458        for m in self.prototypes['set']:
459            name = get_name(m)
460            shortname = name.replace('aubio_%s_' % self.shortname, '')
461            out += """
462  {{"{shortname}", (PyCFunction) Py{name},
463    METH_VARARGS, ""}},""".format(name = name, shortname = shortname)
464        for m in self.prototypes['get']:
465            name = get_name(m)
466            shortname = name.replace('aubio_%s_' % self.shortname, '')
467            out += """
468  {{"{shortname}", (PyCFunction) Py{name},
469    METH_NOARGS, ""}},""".format(name = name, shortname = shortname)
470        out += """
471  {NULL} /* sentinel */
472};
473"""
474        return out
475
476    def gen_typeobject(self):
477        return """
478PyTypeObject Py_{shortname}Type = {{
479  //PyObject_HEAD_INIT (NULL)
480  //0,
481  PyVarObject_HEAD_INIT (NULL, 0)
482  "aubio.{shortname}",
483  sizeof (Py_{shortname}),
484  0,
485  (destructor) Py_{shortname}_del,
486  0,
487  0,
488  0,
489  0,
490  0,
491  0,
492  0,
493  0,
494  0,
495  (ternaryfunc)Py_{shortname}_do,
496  0,
497  0,
498  0,
499  0,
500  Py_TPFLAGS_DEFAULT,
501  Py_{shortname}_doc,
502  0,
503  0,
504  0,
505  0,
506  0,
507  0,
508  Py_{shortname}_methods,
509  Py_{shortname}_members,
510  0,
511  0,
512  0,
513  0,
514  0,
515  0,
516  (initproc) Py_{shortname}_init,
517  0,
518  Py_{shortname}_new,
519}};
520""".format(**self.__dict__)
Note: See TracBrowser for help on using the repository browser.