1# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""Keras text dataset generation utilities."""
16from __future__ import absolute_import
17from __future__ import division
18from __future__ import print_function
19
20import numpy as np
21
22from tensorflow.python.data.ops import dataset_ops
23from tensorflow.python.keras.preprocessing import dataset_utils
24from tensorflow.python.ops import io_ops
25from tensorflow.python.ops import string_ops
26from tensorflow.python.util.tf_export import keras_export
27
28
29@keras_export('keras.preprocessing.text_dataset_from_directory', v1=[])
30def text_dataset_from_directory(directory,
31                                labels='inferred',
32                                label_mode='int',
33                                class_names=None,
34                                batch_size=32,
35                                max_length=None,
36                                shuffle=True,
37                                seed=None,
38                                validation_split=None,
39                                subset=None,
40                                follow_links=False):
41  """Generates a `tf.data.Dataset` from text files in a directory.
42
43  If your directory structure is:
44
45  ```
46  main_directory/
47  ...class_a/
48  ......a_text_1.txt
49  ......a_text_2.txt
50  ...class_b/
51  ......b_text_1.txt
52  ......b_text_2.txt
53  ```
54
55  Then calling `text_dataset_from_directory(main_directory, labels='inferred')`
56  will return a `tf.data.Dataset` that yields batches of texts from
57  the subdirectories `class_a` and `class_b`, together with labels
58  0 and 1 (0 corresponding to `class_a` and 1 corresponding to `class_b`).
59
60  Only `.txt` files are supported at this time.
61
62  Args:
63    directory: Directory where the data is located.
64        If `labels` is "inferred", it should contain
65        subdirectories, each containing text files for a class.
66        Otherwise, the directory structure is ignored.
67    labels: Either "inferred"
68        (labels are generated from the directory structure),
69        None (no labels),
70        or a list/tuple of integer labels of the same size as the number of
71        text files found in the directory. Labels should be sorted according
72        to the alphanumeric order of the text file paths
73        (obtained via `os.walk(directory)` in Python).
74    label_mode:
75        - 'int': means that the labels are encoded as integers
76            (e.g. for `sparse_categorical_crossentropy` loss).
77        - 'categorical' means that the labels are
78            encoded as a categorical vector
79            (e.g. for `categorical_crossentropy` loss).
80        - 'binary' means that the labels (there can be only 2)
81            are encoded as `float32` scalars with values 0 or 1
82            (e.g. for `binary_crossentropy`).
83        - None (no labels).
84    class_names: Only valid if "labels" is "inferred". This is the explict
85        list of class names (must match names of subdirectories). Used
86        to control the order of the classes
87        (otherwise alphanumerical order is used).
88    batch_size: Size of the batches of data. Default: 32.
89    max_length: Maximum size of a text string. Texts longer than this will
90      be truncated to `max_length`.
91    shuffle: Whether to shuffle the data. Default: True.
92        If set to False, sorts the data in alphanumeric order.
93    seed: Optional random seed for shuffling and transformations.
94    validation_split: Optional float between 0 and 1,
95        fraction of data to reserve for validation.
96    subset: One of "training" or "validation".
97        Only used if `validation_split` is set.
98    follow_links: Whether to visits subdirectories pointed to by symlinks.
99        Defaults to False.
100
101  Returns:
102    A `tf.data.Dataset` object.
103      - If `label_mode` is None, it yields `string` tensors of shape
104        `(batch_size,)`, containing the contents of a batch of text files.
105      - Otherwise, it yields a tuple `(texts, labels)`, where `texts`
106        has shape `(batch_size,)` and `labels` follows the format described
107        below.
108
109  Rules regarding labels format:
110    - if `label_mode` is `int`, the labels are an `int32` tensor of shape
111      `(batch_size,)`.
112    - if `label_mode` is `binary`, the labels are a `float32` tensor of
113      1s and 0s of shape `(batch_size, 1)`.
114    - if `label_mode` is `categorial`, the labels are a `float32` tensor
115      of shape `(batch_size, num_classes)`, representing a one-hot
116      encoding of the class index.
117  """
118  if labels not in ('inferred', None):
119    if not isinstance(labels, (list, tuple)):
120      raise ValueError(
121          '`labels` argument should be a list/tuple of integer labels, of '
122          'the same size as the number of text files in the target '
123          'directory. If you wish to infer the labels from the subdirectory '
124          'names in the target directory, pass `labels="inferred"`. '
125          'If you wish to get a dataset that only contains text samples '
126          '(no labels), pass `labels=None`.')
127    if class_names:
128      raise ValueError('You can only pass `class_names` if the labels are '
129                       'inferred from the subdirectory names in the target '
130                       'directory (`labels="inferred"`).')
131  if label_mode not in {'int', 'categorical', 'binary', None}:
132    raise ValueError(
133        '`label_mode` argument must be one of "int", "categorical", "binary", '
134        'or None. Received: %s' % (label_mode,))
135  if labels is None or label_mode is None:
136    labels = None
137    label_mode = None
138  dataset_utils.check_validation_split_arg(
139      validation_split, subset, shuffle, seed)
140
141  if seed is None:
142    seed = np.random.randint(1e6)
143  file_paths, labels, class_names = dataset_utils.index_directory(
144      directory,
145      labels,
146      formats=('.txt',),
147      class_names=class_names,
148      shuffle=shuffle,
149      seed=seed,
150      follow_links=follow_links)
151
152  if label_mode == 'binary' and len(class_names) != 2:
153    raise ValueError(
154        'When passing `label_mode="binary", there must exactly 2 classes. '
155        'Found the following classes: %s' % (class_names,))
156
157  file_paths, labels = dataset_utils.get_training_or_validation_split(
158      file_paths, labels, validation_split, subset)
159  if not file_paths:
160    raise ValueError('No text files found.')
161
162  dataset = paths_and_labels_to_dataset(
163      file_paths=file_paths,
164      labels=labels,
165      label_mode=label_mode,
166      num_classes=len(class_names),
167      max_length=max_length)
168  if shuffle:
169    # Shuffle locally at each iteration
170    dataset = dataset.shuffle(buffer_size=batch_size * 8, seed=seed)
171  dataset = dataset.batch(batch_size)
172  # Users may need to reference `class_names`.
173  dataset.class_names = class_names
174  return dataset
175
176
177def paths_and_labels_to_dataset(file_paths,
178                                labels,
179                                label_mode,
180                                num_classes,
181                                max_length):
182  """Constructs a dataset of text strings and labels."""
183  path_ds = dataset_ops.Dataset.from_tensor_slices(file_paths)
184  string_ds = path_ds.map(
185      lambda x: path_to_string_content(x, max_length))
186  if label_mode:
187    label_ds = dataset_utils.labels_to_dataset(labels, label_mode, num_classes)
188    string_ds = dataset_ops.Dataset.zip((string_ds, label_ds))
189  return string_ds
190
191
192def path_to_string_content(path, max_length):
193  txt = io_ops.read_file(path)
194  if max_length is not None:
195    txt = string_ops.substr(txt, 0, max_length)
196  return txt
197