From 07994f5e72052b0dd7110819a383ae955313f452 Mon Sep 17 00:00:00 2001 From: Victor Chahuneau Date: Tue, 16 Oct 2012 01:07:11 -0400 Subject: [python] Fix string problems + Documentation. - use bytes instead of char* - add some basic docstrings to functions/constructors --- python/src/_cdec.pyx | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) (limited to 'python/src/_cdec.pyx') diff --git a/python/src/_cdec.pyx b/python/src/_cdec.pyx index 6c6c8eee..71e083e4 100644 --- a/python/src/_cdec.pyx +++ b/python/src/_cdec.pyx @@ -3,7 +3,7 @@ from libcpp.vector cimport vector from utils cimport * cimport decoder -cdef char* as_str(data, char* error_msg='Cannot convert type %s to str'): +cdef bytes as_str(data, char* error_msg='Cannot convert type %s to str'): cdef bytes ret if isinstance(data, unicode): ret = data.encode('utf8') @@ -26,6 +26,7 @@ class InvalidConfig(Exception): pass class ParseFailed(Exception): pass def set_silent(yn): + """set_silent(bool): Configure the verbosity of cdec.""" SetSilent(yn) def _make_config(config): @@ -43,12 +44,10 @@ cdef class Decoder: cdef decoder.Decoder* dec cdef DenseVector weights - def __cinit__(self, config_str=None, **config): - """ Configuration can be given as a string: - Decoder('formalism = scfg') - or using keyword arguments: - Decoder(formalism='scfg') - """ + def __init__(self, config_str=None, **config): + """Decoder('formalism = scfg') -> initialize from configuration string + Decoder(formalism='scfg') -> initialize from named parameters + Create a decoder using a given configuration. Formalism is required.""" if config_str is None: formalism = config.get('formalism', None) if formalism not in ('scfg', 'fst', 'lextrans', 'pb', @@ -88,6 +87,7 @@ cdef class Decoder: return str(conf[0]['formalism'].as_str().c_str()) def read_weights(self, weights): + """decoder.read_weights(filename): Read decoder weights from a file.""" with open(weights) as fp: for line in fp: if line.strip().startswith('#'): continue @@ -95,6 +95,8 @@ cdef class Decoder: self.weights[fname.strip()] = float(value) def translate(self, sentence, grammar=None): + """decoder.translate(sentence, grammar=None) -> Hypergraph + Translate a sentence (string/Lattice) with a grammar (string/list of rules).""" cdef bytes input_str if isinstance(sentence, basestring): input_str = as_str(sentence.strip()) @@ -104,11 +106,11 @@ cdef class Decoder: raise TypeError('Cannot translate input type %s' % type(sentence)) if grammar: if isinstance(grammar, basestring): - self.dec.AddSupplementalGrammarFromString(string(as_str(grammar))) + self.dec.AddSupplementalGrammarFromString(as_str(grammar)) else: self.dec.AddSupplementalGrammar(TextGrammar(grammar).grammar[0]) cdef decoder.BasicObserver observer = decoder.BasicObserver() - self.dec.Decode(string(input_str), &observer) + self.dec.Decode(input_str, &observer) if observer.hypergraph == NULL: raise ParseFailed() cdef Hypergraph hg = Hypergraph() -- cgit v1.2.3