Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding Utility to Detokenize as list of Strings to Tokenizer Base Class #124

Merged
merged 13 commits into from
May 3, 2022
38 changes: 38 additions & 0 deletions keras_nlp/tokenizers/tokenizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

from typing import List

import tensorflow as tf
from tensorflow import keras


Expand Down Expand Up @@ -129,3 +130,40 @@ def call(self, *args, mode="tokenize", training=None, **kwargs):
raise ValueError(
f"Unsupported tokenizer mode. Received: mode={mode}"
)

def recursive_utf8_decoder(self, inputs, *args, **kwargs):
aflah02 marked this conversation as resolved.
Show resolved Hide resolved
aflah02 marked this conversation as resolved.
Show resolved Hide resolved
"""Recursively decodes to list of strings with 'utf-8' encoding."""
if str(type(inputs)) == "<class 'bytes'>":
aflah02 marked this conversation as resolved.
Show resolved Hide resolved
inputs = inputs.decode("utf-8")
aflah02 marked this conversation as resolved.
Show resolved Hide resolved
return inputs
if str(type(inputs[0])) == "<class 'bytes'>":
for i in range(len(inputs)):
inputs[i] = inputs[i].decode("utf-8")
return inputs
else:
for i in range(len(inputs)):
aflah02 marked this conversation as resolved.
Show resolved Hide resolved
inputs[i] = self.recursive_utf8_decoder(
inputs[i], *args, **kwargs
)

def detokenize_to_strings(self, inputs, *args, **kwargs):
"""Transform detokenized inputs to strings.
aflah02 marked this conversation as resolved.
Show resolved Hide resolved
Args:
aflah02 marked this conversation as resolved.
Show resolved Hide resolved
inputs: Input tensor, or dict/list/tuple of input tensors.
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
"""
detokenized_input = self.detokenize(inputs)
scalar = detokenized_input.shape.rank == 0
if isinstance(detokenized_input, tf.RaggedTensor):
detokenized_input = detokenized_input.to_list()
elif isinstance(detokenized_input, tf.Tensor):
if scalar:
detokenized_input = detokenized_input.numpy()
return detokenized_input.decode("utf-8")
else:
detokenized_input = detokenized_input.numpy().tolist()
detokenized_input = list(
aflah02 marked this conversation as resolved.
Show resolved Hide resolved
map(self.recursive_utf8_decoder, detokenized_input)
)
return detokenized_input