| 53 | return text |
| 54 | |
| 55 | class Encoder(object): |
| 56 | def __init__(self, args): |
| 57 | self.args = args |
| 58 | |
| 59 | def initializer(self): |
| 60 | # Use Encoder class as a container for global data |
| 61 | Encoder.tokenizer = build_tokenizer(self.args) |
| 62 | if self.args.split_sentences: |
| 63 | if not nltk_available: |
| 64 | print("NLTK is not available to split sentences.") |
| 65 | exit() |
| 66 | splitter = nltk.load("tokenizers/punkt/english.pickle") |
| 67 | if self.args.keep_newlines: |
| 68 | # this prevents punkt from eating newlines after sentences |
| 69 | Encoder.splitter = nltk.tokenize.punkt.PunktSentenceTokenizer( |
| 70 | train_text = splitter._params, |
| 71 | lang_vars = CustomLanguageVars()) |
| 72 | else: |
| 73 | Encoder.splitter = splitter |
| 74 | |
| 75 | else: |
| 76 | Encoder.splitter = IdentitySplitter() |
| 77 | |
| 78 | def encode(self, json_line): |
| 79 | data = json.loads(json_line) |
| 80 | ids = {} |
| 81 | for key in self.args.json_keys: |
| 82 | text = data[key] |
| 83 | doc_ids = [] |
| 84 | for sentence in Encoder.splitter.tokenize(text): |
| 85 | sentence_ids = Encoder.tokenizer.tokenize(sentence) |
| 86 | if len(sentence_ids) > 0: |
| 87 | doc_ids.append(sentence_ids) |
| 88 | if self.args.append_eod: |
| 89 | doc_ids[-1].append(Encoder.tokenizer.eod) |
| 90 | ids[key] = doc_ids |
| 91 | return ids, len(json_line) |
| 92 | |
| 93 | def get_args(): |
| 94 | parser = argparse.ArgumentParser() |