Exemple #1
0
    def _create_repeat_rule(self, merge_rule):
        merge_rule = merge_rule.prepare_for_merger()
        alts = [RuleRef(rule=merge_rule)
                ]  # +[RuleRef(rule=sm) for sm in selfmod]
        single_action = Alternative(alts)
        sequence = Repetition(single_action,
                              min=1,
                              max=self._max_repetitions,
                              name=CCRMerger2._SEQ)
        original = Alternative(alts, name=CCRMerger2._ORIGINAL)
        terminal = Alternative(alts, name=CCRMerger2._TERMINAL)

        class RepeatRule(CompoundRule):
            spec = "[<" + CCRMerger2._ORIGINAL + "> original] " + \
                   "[<" + CCRMerger2._SEQ + ">] " + \
                   "[terminal <" + CCRMerger2._TERMINAL + ">]"
            extras = [sequence, original, terminal]

            def _process_recognition(self, node, extras):
                _original = extras[
                    CCRMerger2.
                    _ORIGINAL] if CCRMerger2._ORIGINAL in extras else None
                _sequence = extras[
                    CCRMerger2._SEQ] if CCRMerger2._SEQ in extras else None
                _terminal = extras[
                    CCRMerger2.
                    _TERMINAL] if CCRMerger2._TERMINAL in extras else None
                if _original is not None: _original.execute()
                if _sequence is not None:
                    for action in _sequence:
                        action.execute()
                if _terminal is not None: _terminal.execute()

        return RepeatRule(name=self._get_new_rule_name())
Exemple #2
0
    def __init__(self, name=None, min=None, max=None, default=None,
                 content=None):
        if content:
            self._content = content
        elif not self._content:
            # Language-specific integer content has not been set yet, so
            #  we set it by retrieving the current speaker language content.
            self._set_content(language.IntegerContent)
        self._builders = self._content.builders

        self._min = min; self._max = max
        children = self._build_children(min, max)
        Alternative.__init__(self, children, name=name, default=default)
Exemple #3
0
 def _build_modified_paths(self, children, memo):
     # pylint: disable=unused-argument
     if len(children) == 0: return None
     if len(children) == 1: root = children[0]
     else: root = Alternative(children)
     return ModifiedPathsCollection(root, self._modifier_function,
                                    self._modifier_mode)
Exemple #4
0
    def _create_nested_rule(self, rule):
        alts = [RuleRef(rule=rule)]  #+[RuleRef(rule=sm) for sm in selfmod]
        single_action = Alternative(alts)
        bef = Repetition(single_action, min=1, max=8, name="before")
        aft = Repetition(single_action, min=1, max=8, name="after")
        seq1 = Repetition(single_action, min=1, max=6, name="sequence1")
        seq2 = Repetition(single_action, min=1, max=6, name="sequence2")
        sing1 = Alternative(alts, name="singleton1")
        sing2 = Alternative(alts, name="singleton2")

        if rule.nested.extras is None:
            rule.nested.extras = [bef, aft, seq1, seq2, sing1, sing2]
        else:
            rule.nested.extras.extend([bef, aft, seq1, seq2, sing1, sing2])

        nested = rule.nested()
        return nested
Exemple #5
0
    def __init__(self, name=None, zero=False):
        name = str(name)
        int_name = "_Number_int_" + name
        if zero:  int_min = 0
        else:     int_min = 1
        single = self._element_type(None, int_min, self._int_max)

        ser_name = "_Number_ser_" + name
        item = self._element_type(None, 0, 100)
        if zero:
            series = Repetition(item, 1, self._ser_len)
        else:
            first = self._element_type(None, 1, 100)
            repetition = Repetition(item, 0, self._ser_len - 1)
            series = Sequence([first, repetition])

        children = [single, series]
        Alternative.__init__(self, children, name=name)
Exemple #6
0
    def _build_element(self, min, max, memo):

        # Sanity check.
        if min >= max: return None

        # Calculate ranges of multipliers and remainders.
        first_multiplier = int(min / self._factor)
        last_multiplier = int((max - 1) / self._factor + 1)
        first_remainder = min % self._factor
        last_remainder = max % self._factor
        if last_remainder == 0:
            last_remainder = self._factor

        # Handle special case of only one possible multiplier value.
        if first_multiplier == last_multiplier - 1:
            return self._build_range(first_multiplier, last_multiplier,
                                     first_remainder, last_remainder, memo)

        children = []

        # Build partial range for first multiplier value, if necessary.
        if first_remainder > 0:
            c = self._build_range(first_multiplier, first_multiplier + 1,
                                  first_remainder, self._factor, memo)
            if c: children.append(c)
            first_multiplier += 1

        # Build partial range for last multiplier value, if necessary.
        if last_remainder > 0:
            c = self._build_range(last_multiplier - 1, last_multiplier, 0,
                                  last_remainder, memo)
            if c: children.append(c)
            last_multiplier -= 1

        # Build range for multiplier values which have the full
        #  range of remainder values.
        if first_multiplier < last_multiplier:
            c = self._build_range(first_multiplier, last_multiplier, 0,
                                  self._factor, memo)
            if c: children.append(c)

        # Build modified path elements, if necessary.
        if self._modifier_function is not None:
            c = self._build_modified_paths(children, memo)
            if c:
                # Don't use other children if in modifier mode REPLACE.
                mode = self._modifier_mode
                if mode == ModifiedPathsCollection.MODE_REPLACE:
                    del children[:]

                # Add the ModifiedPathsCollection element.
                children.append(c)

        # Wrap up result as is appropriate.
        if len(children) == 0: return None
        elif len(children) == 1: return children[0]
        else: return Alternative(children)
Exemple #7
0
    def __init__(self, name=None, zero=False, default=None):
        name = str(name)
        int_name = "_Number_int_" + name
        if zero: int_min = 0
        else: int_min = 1
        single = Integer(None, int_min, self._int_max)

        ser_name = "_Number_ser_" + name
        item = Integer(None, 0, 100)
        if zero:
            series = Repetition(item, 1, self._ser_len)
        else:
            first = Integer(None, 1, 100)
            repetition = Repetition(item, 0, self._ser_len - 1)
            series = Sequence([first, repetition])

        children = [single, series]
        Alternative.__init__(self, children, name=name, default=default)
Exemple #8
0
    def _create_repeat_rule(self, rule):
        ORIGINAL, SEQ, TERMINAL = "original", "caster_base_sequence", "terminal"
        alts = [RuleRef(rule=rule)]  #+[RuleRef(rule=sm) for sm in selfmod]
        single_action = Alternative(alts)
        max = SETTINGS["max_ccr_repetitions"]
        sequence = Repetition(single_action, min=1, max=max, name=SEQ)
        original = Alternative(alts, name=ORIGINAL)
        terminal = Alternative(alts, name=TERMINAL)

        class RepeatRule(CompoundRule):
            spec = "[<" + ORIGINAL + "> original] [<" + SEQ + ">] [terminal <" + TERMINAL + ">]"
            extras = [sequence, original, terminal]

            def _process_recognition(self, node, extras):
                original = extras[ORIGINAL] if ORIGINAL in extras else None
                sequence = extras[SEQ] if SEQ in extras else None
                terminal = extras[TERMINAL] if TERMINAL in extras else None
                if original is not None: original.execute()
                if sequence is not None:
                    for action in sequence:
                        action.execute()
                if terminal is not None: terminal.execute()

        rules = []
        rules.append(RepeatRule(name="Repeater" + MergeRule.get_merge_name()))

        if rule.nested is not None:
            bef = Repetition(single_action, min=1, max=8, name="before")
            aft = Repetition(single_action, min=1, max=8, name="after")
            seq1 = Repetition(single_action, min=1, max=6, name="sequence1")
            seq2 = Repetition(single_action, min=1, max=6, name="sequence2")
            sing1 = Alternative(alts, name="singleton1")
            sing2 = Alternative(alts, name="singleton2")

            if rule.nested.extras is None:
                rule.nested.extras = [bef, aft, seq1, seq2, sing1, sing2]
            else:
                rule.nested.extras.extend([bef, aft, seq1, seq2, sing1, sing2])
            nested = rule.nested()
            rules.append(nested)

        return rules
Exemple #9
0
 def _create_repeat_rule(self, rule):
     ORIGINAL, SEQ, TERMINAL = "original", "caster_base_sequence", "terminal"
     alts = [RuleRef(rule=rule)]#+[RuleRef(rule=sm) for sm in selfmod]
     single_action = Alternative(alts)
     max = settings.SETTINGS["miscellaneous"]["max_ccr_repetitions"]
     sequence = Repetition(single_action, min=1, max=max, name=SEQ)
     original = Alternative(alts, name=ORIGINAL)
     terminal = Alternative(alts, name=TERMINAL)
     class RepeatRule(CompoundRule):
         spec = "[<"+ORIGINAL+"> original] [<" + SEQ + ">] [terminal <"+TERMINAL+">]"
         extras = [ sequence, original, terminal ] 
         def _process_recognition(self, node, extras):
             original = extras[ORIGINAL] if ORIGINAL in extras else None
             sequence = extras[SEQ] if SEQ in extras else None
             terminal = extras[TERMINAL] if TERMINAL in extras else None
             if original is not None: original.execute()
             if sequence is not None:
                 for action in sequence:
                     action.execute()
             if terminal is not None: terminal.execute()
     return RepeatRule(name="Repeater"+MergeRule.get_merge_name())
Exemple #10
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
Exemple #11
0
    def _build_range_set(self, set, min, max):
        # Iterate through the set allowing each item to build an element.
        children = [c.build_element(min, max) for c in set]
        children = [c for c in children if c]

        # Wrap up results appropriately.
        if not children:
            return None
        if len(children) == 1:
            return children[0]
        else:
            return Alternative(children)
Exemple #12
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)
Exemple #13
0
    def __init__(self, element, modifier_function, modifier_mode, name=None):

        if not 0 < modifier_mode <= 2:
            raise ValueError("Invalid modifier mode: %d" % modifier_mode)

        # Generate element tree recognition paths and use them to create
        #  elements.
        children = []
        specs = set()
        for path in self._generate_paths(element):
            # Get a flat list of each word in this path.
            all_words = []
            for words in path:
                all_words.extend(words)

            # Get a spec using the modifier function.
            text = " ".join(all_words)
            spec = modifier_function(text)

            # Handle the result based on the specified modifier mode.
            if modifier_mode is self.MODE_AUGMENT:
                if not spec or text == spec:
                    continue
            elif modifier_mode is self.MODE_REPLACE:
                if not spec:
                    continue

            # Always skip duplicate specs.
            if spec in specs:
                continue

            # Initialize a new ModifiedPath element, passing the original
            #  element and words for decode-time calculation of the integer
            #  value.
            specs.add(spec)
            children.append(ModifiedPath(spec, all_words, element))

        # Initialize super class.
        Alternative.__init__(self, children=children, name=name)
Exemple #14
0
    def _create_repeat_rule(self, rule):
        SEQ = "caster_base_sequence"
        alts = [RuleRef(rule=rule)]
        single_action = Alternative(alts)
        max = CCRMerger.MAX_REPETITIONS

        class RepeatRule(CompoundRule):
            spec = "<%s>" % SEQ
            extras = [Repetition(single_action, min=1, max=max, name=SEQ)]

            def _process_recognition(self, node, extras):
                for action in extras[SEQ]:
                    action.execute()

        return RepeatRule(name="Repeater" + MergeRule.get_merge_name())
Exemple #15
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)
Exemple #16
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
Exemple #17
0
    def build_element(self, min, max):

        # Sanity check.
        if min >= max: return None

        # Calculate ranges of multipliers and remainders.
        first_multiplier = min / self._factor
        last_multiplier = (max - 1) / self._factor + 1
        first_remainder = min % self._factor
        last_remainder = max % self._factor
        if last_remainder == 0:
            last_remainder = self._factor

        # Handle special case of only one possible multiplier value.
        if first_multiplier == last_multiplier - 1:
            return self._build_range(first_multiplier, last_multiplier,
                                     first_remainder, last_remainder)

        children = []

        # Build partial range for first multiplier value, if necessary.
        if first_remainder > 0:
            c = self._build_range(first_multiplier, first_multiplier + 1,
                                  first_remainder, self._factor)
            if c: children.append(c)
            first_multiplier += 1

        # Build partial range for last multiplier value, if necessary.
        if last_remainder > 0:
            c = self._build_range(last_multiplier - 1, last_multiplier, 0,
                                  last_remainder)
            if c: children.append(c)
            last_multiplier -= 1

        # Build range for multiplier values which have the full
        #  range of remainder values.
        if first_multiplier < last_multiplier:
            c = self._build_range(first_multiplier, last_multiplier, 0,
                                  self._factor)
            if c: children.append(c)

        # Wrap up result as is appropriate.
        if len(children) == 0: return None
        elif len(children) == 1: return children[0]
        else: return Alternative(children)
Exemple #18
0
    def value(self, node):
        value = Alternative.value(self, node)

        if isinstance(value, list):
            items = []
            for item in value:
                if isinstance(item, list):
                    items.extend(item)
                else:
                    items.append(item)
            value = 0
            for item in items:
                if item < 10: factor = 10
                else: factor = 100
                value *= factor
                value += item

        return value
Exemple #19
0
    def value(self, node):
        value = Alternative.value(self, node)

        if isinstance(value, list):
            items = []
            for item in value:
                if isinstance(item, list):
                    items.extend(item)
                else:
                    items.append(item)
            value = 0
            for item in items:
                if item < 10:  factor = 10
                else:          factor = 100
                value *= factor
                value += item

        return value
Exemple #20
0
    def _build_range_set(self, set, min, max, memo):
        # Iterate through the set allowing each item to build an element.
        children = [c.build_element(min, max, memo) for c in set]
        children = [c for c in children if c]

        # Build modified path elements, if necessary.
        if self._modifier_function is not None:
            c = self._build_modified_paths(children, memo)
            if c:
                # Don't use other children if in modifier mode REPLACE.
                mode = self._modifier_mode
                if mode == ModifiedPathsCollection.MODE_REPLACE:
                    del children[:]

                # Add the ModifiedPathsCollection element.
                children.append(c)

        # Wrap up results appropriately.
        if not children:
            return None
        if len(children) == 1:
            return children[0]
        else:
            return Alternative(children)
Exemple #21
0
 def __init__(self, name):
     Alternative.__init__(self, name=name, children=self.alts)
Exemple #22
0
 def __init__(self, name=None, min=None, max=None):
     self._min = min; self._max = max
     children = self._build_children(min, max)
     Alternative.__init__(self, children, name=name)
Exemple #23
0
 def __init__(self, name=None, min=None, max=None):
     self._min = min
     self._max = max
     children = self._build_children(min, max)
     Alternative.__init__(self, children, name=name)