source: python/lib/gen_code.py @ 9492313a

feature/constantq
Last change on this file since 9492313a was 9492313a, checked in by Paul Brossier <piem@piem.org>, 5 years ago

[py] use a string for cqt/bins_per_octave

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