Skip to content

string_replace

StringReplaceLayer ¤

StringReplaceLayer(
    string_match_constant=None,
    string_replace_constant=None,
    regex=False,
    name=None,
    input_dtype=None,
    output_dtype=None,
    **kwargs
)

Bases: BaseLayer

StringReplaceLayer layer for TensorFlow.

Initialises the StringReplaceLayer layer.

WARNING: While it works, the use of tensors in matching/replacement is not recommended due to the complexity of the regex matching which requires use of a map_fn. This will be comparatively VERY slow and may not be suitable for inference use-cases. If you know where in the string the match is, you will be much better off slicing the string and checking for equality.

Parameters:

Name Type Description Default
string_match_constant Optional[str]

The string to match against and replace. Defaults to None.

None
string_replace_constant Optional[str]

The string to replace the matched string with. Defaults to None.

None
regex bool

Whether to treat the string match as a regular expression. Defaults to False. In the case regex is enabled, the string_match_constant or second input tensor elements are treated as a regex pattern. Please be aware that while testing has tried to catch corner cases, this is not guaranteed to be bug-free due to slight differences in the regex implementations between Spark and TensorFlow.

False
name Optional[str]

The name of the layer. Defaults to None.

None
input_dtype Optional[str]

The dtype to cast the input to. Defaults to None.

None
output_dtype Optional[str]

The dtype to cast the output to. Defaults to None.

None
Source code in src/kamae/tensorflow/layers/string_replace.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def __init__(
    self,
    string_match_constant: Optional[str] = None,
    string_replace_constant: Optional[str] = None,
    regex: bool = False,
    name: Optional[str] = None,
    input_dtype: Optional[str] = None,
    output_dtype: Optional[str] = None,
    **kwargs: Any,
) -> None:
    """
    Initialises the StringReplaceLayer layer.

    WARNING: While it works, the use of tensors in matching/replacement
    is not recommended due to the complexity of the regex matching which requires
    use of a map_fn. This will be comparatively VERY slow and may not be suitable
    for inference use-cases.
    If you know where in the string the match is, you will be much
    better off slicing the string and checking for equality.

    :param string_match_constant: The string to match against and replace.
        Defaults to `None`.
    :param string_replace_constant: The string to replace the matched string with.
        Defaults to `None`.
    :param regex: Whether to treat the string match as a regular expression.
        Defaults to `False`. In the case regex is enabled, the string_match_constant
        or second input tensor elements are treated as a regex pattern. Please be
        aware that while testing has tried to catch corner cases, this is not
        guaranteed to be bug-free due to slight differences in the regex
        implementations between Spark and TensorFlow.
    :param name: The name of the layer. Defaults to `None`.
    :param input_dtype: The dtype to cast the input to. Defaults to `None`.
    :param output_dtype: The dtype to cast the output to. Defaults to `None`.
    """
    super().__init__(
        name=name, input_dtype=input_dtype, output_dtype=output_dtype, **kwargs
    )
    self.string_match_constant = string_match_constant
    self.string_replace_constant = string_replace_constant
    self.regex = regex

compatible_dtypes property ¤

compatible_dtypes

Returns the compatible dtypes of the layer.

Returns:

Type Description
Optional[List[DType]]

The compatible dtypes of the layer.

_call ¤

_call(inputs, **kwargs)

Checks for the existence of a substring/pattern within a tensor and replaces if there is a match.

KNOWN ISSUE: when replacing with a string that contains a backslash, the backslash must be double escaped (\) in order to be added properly. This is consistent in both spark and tensorflow components.

WARNING: While it works, the use of tensors in matching/replacement is not recommended due to the complexity of the regex matching which requires use of a map_fn. This will be comparatively VERY slow and may not be suitable for inference use-cases. If you know where in the string the match is, you will be much better off slicing the string and checking for equality.

Decorated with @allow_single_or_multiple_tensor_input to ensure that the input is either a single tensor or an iterable of tensors. Returns this result as a list of tensors for easier use here.

Parameters:

Name Type Description Default
inputs Union[Tensor, Iterable[Tensor]]

A string tensor or iterable of up to three string tensors. In the case multiple tensors are passed, require that the order of inputs is [string input, {string match tensor}, {string replace tensor}].

required

Returns:

Type Description
Tensor

A string tensor of regex replaced strings.

Source code in src/kamae/tensorflow/layers/string_replace.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
@allow_single_or_multiple_tensor_input
def _call(self, inputs: Union[Tensor, Iterable[Tensor]], **kwargs: Any) -> Tensor:
    """
    Checks for the existence of a substring/pattern within a tensor and replaces
    if there is a match.

    KNOWN ISSUE: when replacing with a string that contains a backslash,
    the backslash must be double escaped (\\\\) in order to be added properly.
    This is consistent in both spark and tensorflow components.

    WARNING: While it works, the use of tensors in matching/replacement
    is not recommended due to the complexity of the regex matching which requires
    use of a map_fn. This will be comparatively VERY slow and may not be suitable
    for inference use-cases.
    If you know where in the string the match is, you will be much
    better off slicing the string and checking for equality.

    Decorated with `@allow_single_or_multiple_tensor_input` to ensure that the input
    is either a single tensor or an iterable of tensors. Returns this result as a
    list of tensors for easier use here.

    :param inputs: A string tensor or iterable of up to three string
        tensors.
        In the case multiple tensors are passed, require that the order of inputs is
         [string input, {string match tensor}, {string replace tensor}].
    :returns: A string tensor of regex replaced strings.
    """

    match_all_pattern = r"([\w]\\+\_+\!+\?+)*"

    # Case both match and replacement are constant
    if (
        self.string_replace_constant is not None
        and self.string_match_constant is not None
    ):
        if len(inputs) == 1:
            # Need the tensor for shapes to be consistent
            input_tensor = inputs[0]

            match_substring = self.string_match_constant

            if not self.regex:
                match_substring = self._escape_special_characters(match_substring)

            # Calls regex replace function on the input tensor, matching
            # with match constant and replacing with replace constant
            replaced_tensor = tf.strings.regex_replace(
                input_tensor,
                tf.constant(
                    match_all_pattern + match_substring + match_all_pattern
                    if match_substring != ""
                    else "^$"
                ),
                tf.constant(self.string_replace_constant),
            )

        else:
            raise ValueError(
                """When string_match_constant and string_replace_constant are
                defined, expected a single tensor as input."""
            )
    else:
        # Preserve input shape
        input_shape = tf.shape(inputs[0])
        # Generate a tensor that can be used by map_fn
        # First we define 3 tensors, the input string, the match string and the
        # replace string
        string_tensor = inputs[0]
        match_substring = (
            tf.constant(self.string_match_constant, shape=string_tensor.shape)
            if self.string_match_constant is not None
            else inputs[1]
        )
        replace_substring = (
            tf.constant(self.string_replace_constant, shape=string_tensor.shape)
            if self.string_replace_constant is not None
            else inputs[1 + (len(inputs) == 3)]
        )

        # Stack the input, match and replace elements into a single tensor
        # then flatten for use in map_fn
        mappable_tensor = tf.stack(
            [string_tensor, match_substring, replace_substring], axis=-1
        )
        mappable_tensor = tf.reshape(mappable_tensor, [-1, 3])

        def _tensor_replace(x: List[Tensor]) -> Tensor:
            match_substring = x[1]
            if not self.regex:
                match_substring = self._escape_special_characters(x[1])
            return tf.strings.regex_replace(
                input=x[0],
                pattern=match_all_pattern + match_substring + match_all_pattern
                if match_substring != ""
                else "^$",
                rewrite=x[2],
            )

        # TODO: tf.vectorized_map may be slightly faster with larger batches
        #  but this requires some refactoring
        replaced_tensor = tf.map_fn(
            _tensor_replace,
            elems=mappable_tensor,
            dtype=tf.string,
        )

        # Reshape to the preserved input shape
        replaced_tensor = tf.reshape(replaced_tensor, input_shape)

    return replaced_tensor

_escape_special_characters ¤

_escape_special_characters(string_to_escape)

Escapes special characters in a string so they are not parsed as regex.

Parameters:

Name Type Description Default
string_to_escape Union[str, Tensor]

The string or string tensor to escape special characters in.

required

Returns:

Type Description
Union[str, Tensor]

The escaped string or string tensor.

Source code in src/kamae/tensorflow/layers/string_replace.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
def _escape_special_characters(
    self, string_to_escape: Union[str, Tensor]
) -> Union[str, Tensor]:
    """
    Escapes special characters in a string so they are not parsed as regex.
    :param string_to_escape: The string or string tensor to escape special characters in.
    :returns: The escaped string or string tensor.
    """

    for char in [
        ".",
        "^",
        "$",
        "*",
        "+",
        "?",
        "{",
        "}",
        "[",
        "]",
        "(",
        ")",
        "|",
    ]:
        if isinstance(string_to_escape, str):
            string_to_escape = string_to_escape.replace(char, "\\\\" + char)
        else:
            string_to_escape = tf.strings.regex_replace(
                string_to_escape, "\\" + char, "\\\\" + char
            )
    return string_to_escape

get_config ¤

get_config()

Gets the configuration of the StringReplace layer. Used for saving and loading the layer from disk.

Specifically, regex, string_match_constant and string_replace_constant are added to the config.

Returns:

Type Description
Dict[str, Any]

Dictionary configuration of the layer.

Source code in src/kamae/tensorflow/layers/string_replace.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def get_config(self) -> Dict[str, Any]:
    """
    Gets the configuration of the StringReplace layer.
    Used for saving and loading the layer from disk.

    Specifically, `regex`, `string_match_constant` and `string_replace_constant`
    are added to the config.

    :returns: Dictionary configuration of the layer.
    """
    config = super().get_config()
    config.update(
        {
            "regex": self.regex,
            "string_match_constant": self.string_match_constant,
            "string_replace_constant": self.string_replace_constant,
        }
    )
    return config