Beispiel #1
0
 def __init__(self, factor, spec, multiplier, remainder, name=None):
     self._factor = factor
     self._mul = multiplier
     self._rem = remainder
     Compound.__init__(self,
                       spec,
                       extras=[multiplier, remainder],
                       name=name)
Beispiel #2
0
 def build_element(self, min, max):
     elements = [(spec, value) for spec, value in self._mapping.iteritems()
                 if min <= value < max]
     if len(elements) > 1:
         children = [
             Compound(spec=spec, value=value) for spec, value in elements
         ]
         return Alternative(children)
     elif len(elements) == 1:
         return Compound(spec=elements[0][0], value=elements[0][1])
     else:
         return None
Beispiel #3
0
    def test_dictation_non_ascii(self):
        """ Test handling of non-ASCII characters in dictation. """
        def value_func(node, extras):
            return extras["text"]

        element = Compound("test <text>",
                           extras=[Dictation(name="text")],
                           value_func=value_func)
        tester = ElementTester(element)
        words = [u"test", u"touché"]
        engine = get_engine()
        uppercase_dictation_required = engine.name in ['sphinx', 'text']
        if uppercase_dictation_required:
            words[1] = words[1].upper()
        dictation = tester.recognize(words)

        # Verify recognition returned dictation result.
        if not isinstance(dictation, DictationContainerBase):
            encoding = locale.getpreferredencoding()
            message = (u"Expected recognition result to be a dictation"
                       u" container, but received %r" % (repr(dictation), ))
            self.fail(message.encode(encoding))

        # Verifying dictation converts/encode successfully.
        string = "touché"
        if isinstance(string, binary_type):
            encoding = locale.getpreferredencoding()
            string = string.decode("windows-1252").encode(encoding)
        self.assertEqual(str(dictation), string)
        self.assertEqual(text_type(dictation), u"touché")
        self.assertTrue(isinstance(repr(dictation), string_types))
Beispiel #4
0
    def _build_element(self):
        def value_func(node, extras):
            return str(extras["text"])

        return Compound("test <text>",
                        extras=[Dictation(name="text").apply(self.f)],
                        value_func=value_func)
Beispiel #5
0
    def _build_element(self):
        def value_func(node, extras):
            return str(extras["text"])

        return Compound(
            "test <text>",
            extras=[Dictation(name="text").upper().replace(" ", "/")],
            value_func=value_func)
Beispiel #6
0
class Year(Alternative):

    alts = [
        IntegerRef("year", 2000, 2100),
        Compound(
            spec="<century> <year>",
            extras=[Integer("century", 20, 21),
                    IntegerRef("year", 10, 100)],
            value_func=lambda n, e: e["century"] * 100 + e["year"]),
        Compound(
            spec="<century> <year>",
            extras=[Integer("century", 19, 20),
                    IntegerRef("year", 1, 100)],
            value_func=lambda n, e: e["century"] * 100 + e["year"]),
    ]

    def __init__(self, name):
        Alternative.__init__(self, name=name, children=self.alts)
Beispiel #7
0
    def __init__(self,
                 name=None,
                 mapping=None,
                 extras=None,
                 defaults=None,
                 exported=None,
                 context=None):
        # pylint: disable=too-many-branches

        if name is None: name = self.__class__.__name__
        if mapping is None: mapping = self.mapping
        if extras is None: extras = self.extras
        if defaults is None: defaults = self.defaults
        if context is None: context = self.context

        # Complex handling of exported, because of clashing use of the
        #  exported name at the class level: property & class-value.
        if exported is not None:
            pass
        elif (hasattr(self.__class__, "exported")
              and not isinstance(self.__class__.exported, property)):
            exported = self.__class__.exported
        else:
            exported = self._default_exported

        # Type checking of initialization values.
        assert isinstance(name, string_types)
        assert isinstance(mapping, dict)
        for key, value in mapping.items():
            assert isinstance(key, string_types)
        assert isinstance(extras, (list, tuple))
        for item in extras:
            assert isinstance(item, ElementBase)
        assert exported in (True, False)

        self._name = name
        self._mapping = mapping
        self._extras = {element.name: element for element in extras}
        self._defaults = defaults

        children = []
        for spec, value in self._mapping.items():
            c = Compound(spec, elements=self._extras, value=value)
            children.append(c)

        if children: element = Alternative(children)
        else: element = None
        Rule.__init__(self,
                      self._name,
                      element,
                      exported=exported,
                      context=context)
Beispiel #8
0
    def __init__(self, name=None, min=1, max=12, as_int=False):
        self._as_int = as_int
        if self._as_int: self._base = len(self._digits) - 1

        pairs = []
        for value, word in enumerate(self._digits):
            if isinstance(word, str):
                pairs.append((word, value))
            elif isinstance(word, (tuple, list)):
                pairs.extend([(w, value) for w in word])
            else:
                raise ValueError("Invalid type in digit list: %r" % word)

        alternatives = [Compound(w, value=v, name=self._digit_name)
                        for w, v in pairs]
        child = Alternative(alternatives)
        Repetition.__init__(self, child, min, max, name=name)
Beispiel #9
0
 def _build_element(self, min, max, memo):
     mapping_memo = {}
     children = []
     for spec, value in self._mapping.items():
         if min <= value < max:
             if spec in mapping_memo:
                 children.append(mapping_memo[spec])
             else:
                 element = Compound(spec=spec, value=value)
                 children.append(element)
                 mapping_memo[spec] = element
     if len(children) > 1:
         return Alternative(children)
     elif len(children) == 1:
         return children[0]
     else:
         return None
Beispiel #10
0
    def __init__(self,
                 name=None,
                 spec=None,
                 extras=None,
                 defaults=None,
                 exported=None,
                 context=None):
        if name is None: name = self._name or self.__class__.__name__
        if spec is None: spec = self.spec
        if extras is None: extras = self.extras
        if defaults is None: defaults = self.defaults
        if context is None: context = self.context

        # Complex handling of exported, because of clashing use of the
        #  exported name at the class level: property & class-value.
        if exported is not None:
            pass
        elif (hasattr(self.__class__, "exported")
              and not isinstance(self.__class__.exported, property)):
            exported = self.__class__.exported
        else:
            exported = self._default_exported

        assert isinstance(name, string_types)
        assert isinstance(spec, string_types)
        assert isinstance(extras, (list, tuple))
        for item in extras:
            assert isinstance(item, ElementBase)
        assert exported in (True, False)

        self._name = name
        self._spec = spec
        self.spec = spec
        self._extras = dict((element.name, element) for element in extras)
        self._defaults = dict(defaults)

        child = Compound(spec, extras=self._extras)
        Rule.__init__(self, name, child, exported=exported, context=context)
Beispiel #11
0
    def test_dictation_non_ascii(self):
        """ Test handling of non-ASCII characters in dictation. """
        def value_func(node, extras):
            return extras["text"]

        element = Compound("test <text>",
                           extras=[Dictation(name="text")],
                           value_func=value_func)
        tester = ElementTester(element)

        words = [u"test", u"TOUCHÉ"]
        dictation = tester.recognize(words)

        # Verify recognition returned dictation result.
        if not isinstance(dictation, DictationContainerBase):
            message = (u"Expected recognition result to be a dictation"
                       u" container, but received %r" %
                       (repr(dictation).decode("utf-8"), ))
            self.fail(message.encode("utf-8"))

        # Verifying dictation converts/encode successfully.
        self.assertEqual(str(dictation), "touché")
        self.assertEqual(text_type(dictation), u"touché")
        self.assertTrue(isinstance(repr(dictation), string_types))
Beispiel #12
0
 def __init__(self, name):
     Compound.__init__(self, name=name, spec=self.spec, extras=self.extras)
Beispiel #13
0
 def __init__(self, factor, spec, multiplier, remainder, name=None):
     self._factor = factor
     self._mul = multiplier
     self._rem = remainder
     Compound.__init__(self, spec, extras=[multiplier, remainder], name=name)
Beispiel #14
0
 def __init__(self, spec, element, name=None):
     self._element = element
     Compound.__init__(self, spec, extras=[element], name=name)
Beispiel #15
0
 def __init__(self, spec, element, name=None):
     self._element = element
     Compound.__init__(self, spec, extras=[element], name=name)
Beispiel #16
0
 def __init__(self, spec, words, orig_root_element, name=None):
     self._words = words
     self._orig_root_element = orig_root_element
     Compound.__init__(self, spec, name=name)