source: python/lib/gen_code.py @ c6388f4

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

python/{ext,lib}: prepare for double precision

  • Property mode set to 100644
File size: 15.5 KB
RevLine 
[ccb9fb5]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',
[c6388f4]28        'smpl_t': 'AUBIO_NPY_SMPL',
[ccb9fb5]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',
[a7f398d]41        #'fmat_t*': 'PyAubio_ArrayToCFmat',
[ccb9fb5]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',
[a7f398d]77        'cvec_t*': 'O',
[ccb9fb5]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',
[de63017]87        'tempo': '1',
[ccb9fb5]88        'filterbank': 'self->n_filters',
[a7f398d]89        'tss': 'self->hop_size',
[ccb9fb5]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()
[a7f398d]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 ','')
[ccb9fb5]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
[a7f398d]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:]
[ccb9fb5]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    """
[a7f398d]149    a = list(map(split_type, get_params(proto)))
150    #print proto, a
151    #import sys; sys.exit(1)
152    return a
[ccb9fb5]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)
[a7f398d]165        self.input_params_list = "; ".join(get_input_params(self.new_proto))
[ccb9fb5]166        self.outputs = get_params_types_names(self.do_proto)[2:]
[a7f398d]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
[950a80c]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)))
[ccb9fb5]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};
[a7f398d]199    // do input vectors
200    {do_inputs_list};
[ccb9fb5]201    // output results
202    {output_results};
203}} Py_{shortname};
204"""
[569b363]205        # fmat_t* / fvec_t* / cvec_t* inputs -> full fvec_t /.. struct in Py_{shortname}
206        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')
207        return out.format(do_inputs_list = do_inputs_list, **self.__dict__)
[ccb9fb5]208
209    def gen_doc(self):
210        out = """
211// TODO: add documentation
212static char Py_{shortname}_doc[] = \"undefined\";
[a7f398d]213"""
[ccb9fb5]214        return out.format(**self.__dict__)
215
216    def gen_new(self):
217        out = """
218// new {shortname}
219static PyObject *
220Py_{shortname}_new (PyTypeObject * pytype, PyObject * args, PyObject * kwds)
221{{
222    Py_{shortname} *self;
223""".format(**self.__dict__)
224        params = self.input_params
225        for p in params:
226            out += """
227    {type} {name} = {defval};""".format(defval = param_init[p['type']], **p)
228        plist = ", ".join(["\"%s\"" % p['name'] for p in params])
229        out += """
230    static char *kwlist[] = {{ {plist}, NULL }};""".format(plist = plist)
231        argchars = "".join([pyargparse_chars[p['type']] for p in params])
232        arglist = ", ".join(["&%s" % p['name'] for p in params])
233        out += """
234    if (!PyArg_ParseTupleAndKeywords (args, kwds, "|{argchars}", kwlist,
235              {arglist})) {{
236        return NULL;
237    }}
238""".format(argchars = argchars, arglist = arglist)
239        out += """
240    self = (Py_{shortname} *) pytype->tp_alloc (pytype, 0);
241    if (self == NULL) {{
242        return NULL;
243    }}
244""".format(**self.__dict__)
245        params = self.input_params
246        for p in params:
[a7f398d]247            out += self.check_valid(p)
[ccb9fb5]248        out += """
249    return (PyObject *)self;
250}
251"""
252        return out
253
254    def check_valid(self, p):
255        if p['type'] == 'uint_t':
256            return self.check_valid_uint(p)
257        if p['type'] == 'char_t*':
258            return self.check_valid_char(p)
259        else:
260            print ("ERROR, no idea how to check %s for validity" % p['type'])
261
262    def check_valid_uint(self, p):
263        name = p['name']
264        return """
265    self->{name} = {defval};
266    if ((sint_t){name} > 0) {{
267        self->{name} = {name};
268    }} else if ((sint_t){name} < 0) {{
269        PyErr_SetString (PyExc_ValueError, "can not use negative value for {name}");
270        return NULL;
271    }}
272""".format(defval = aubiodefvalue[name], name = name)
273
274    def check_valid_char(self, p):
275        name = p['name']
276        return """
277    self->{name} = {defval};
278    if ({name} != NULL) {{
279        self->{name} = {name};
280    }}
281""".format(defval = aubiodefvalue[name], name = name)
282
283    def gen_init(self):
284        out = """
285// init {shortname}
286static int
287Py_{shortname}_init (Py_{shortname} * self, PyObject * args, PyObject * kwds)
288{{
289""".format(**self.__dict__)
290        new_name = get_name(self.new_proto)
291        new_params = ", ".join(["self->%s" % s['name'] for s in self.input_params])
292        out += """
293  self->o = {new_name}({new_params});
294""".format(new_name = new_name, new_params = new_params)
295        paramchars = "%s"
296        paramvals = "self->method"
297        out += """
298  // return -1 and set error string on failure
299  if (self->o == NULL) {{
300    //char_t errstr[30 + strlen(self->uri)];
301    //sprintf(errstr, "error creating {shortname} with params {paramchars}", {paramvals});
302    char_t errstr[60];
303    sprintf(errstr, "error creating {shortname} with given params");
304    PyErr_SetString (PyExc_Exception, errstr);
305    return -1;
306  }}
307""".format(paramchars = paramchars, paramvals = paramvals, **self.__dict__)
308        output_create = ""
309        for o in self.outputs:
310            output_create += """
311  self->{name} = {create_fn}({output_size});""".format(name = o['name'], create_fn = newfromtype_fn[o['type']], output_size = objoutsize[self.shortname])
312        out += """
313  // TODO get internal params after actual object creation?
314"""
315        out += """
316  // create outputs{output_create}
317""".format(output_create = output_create)
318        out += """
319  return 0;
320}
321"""
322        return out
323
324    def gen_memberdef(self):
325        out = """
326static PyMemberDef Py_{shortname}_members[] = {{
327""".format(**self.__dict__)
328        for p in get_params_types_names(self.new_proto):
329            tmp = "  {{\"{name}\", {ttype}, offsetof (Py_{shortname}, {name}), READONLY, \"TODO documentation\"}},\n"
330            pytype = member_types[p['type']]
331            out += tmp.format(name = p['name'], ttype = pytype, shortname = self.shortname)
332        out += """  {NULL}, // sentinel
333};
334"""
335        return out
336
337    def gen_del(self):
338        out = """
339// del {shortname}
340static void
341Py_{shortname}_del  (Py_{shortname} * self, PyObject * unused)
342{{""".format(**self.__dict__)
[a7f398d]343        for input_param in self.do_inputs:
[569b363]344            if input_param['type'] == 'fmat_t *':
345                out += """
346    free(self->{0[name]}.data);""".format(input_param)
[ccb9fb5]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)
[a7f398d]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})) {{
[ccb9fb5]378        return NULL;
[a7f398d]379    }}""".format(refs = refs, pyparamtypes = pyparamtypes, **self.__dict__)
380        for p in input_params:
381            out += """
[569b363]382    if (!{pytoaubio}(py_{0[name]}, &(self->{0[name]}))) {{
[ccb9fb5]383        return NULL;
[a7f398d]384    }}""".format(input_param, pytoaubio = pytoaubio_fn[input_param['type']])
385        do_fn = get_name(self.do_proto)
[569b363]386        inputs = ", ".join(['&(self->'+p['name']+')' for p in input_params])
[a7f398d]387        outputs = ", ".join(["self->%s" % p['name'] for p in self.do_outputs])
388        out += """
[ccb9fb5]389
[a7f398d]390    {do_fn}(self->o, {inputs}, {outputs});
[ccb9fb5]391
392    return (PyObject *) {aubiotonumpy} ({outputs});
393}}
[a7f398d]394""".format(
395        do_fn = do_fn,
396        aubiotonumpy = pyfromaubio_fn[output['type']], 
397        inputs = inputs, outputs = outputs,
398        )
399        return out
[ccb9fb5]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.