|
| 1 | +# Copyright 2021 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 | +# Lint as: python3 |
| 16 | +"""Video classification input and model functions for serving/inference.""" |
| 17 | +from typing import Mapping, Dict, Text |
| 18 | + |
| 19 | +import tensorflow as tf |
| 20 | + |
| 21 | +from official.vision.beta.dataloaders import video_input |
| 22 | +from official.vision.beta.serving import export_base |
| 23 | +from official.vision.beta.tasks import video_classification |
| 24 | + |
| 25 | +MEAN_RGB = (0.485 * 255, 0.456 * 255, 0.406 * 255) |
| 26 | +STDDEV_RGB = (0.229 * 255, 0.224 * 255, 0.225 * 255) |
| 27 | + |
| 28 | + |
| 29 | +class VideoClassificationModule(export_base.ExportModule): |
| 30 | + """Video classification Module.""" |
| 31 | + |
| 32 | + def _build_model(self): |
| 33 | + input_params = self.params.task.train_data |
| 34 | + self._num_frames = input_params.feature_shape[0] |
| 35 | + self._stride = input_params.temporal_stride |
| 36 | + self._min_resize = input_params.min_image_size |
| 37 | + self._crop_size = input_params.feature_shape[1] |
| 38 | + |
| 39 | + self._output_audio = input_params.output_audio |
| 40 | + task = video_classification.VideoClassificationTask(self.params.task) |
| 41 | + return task.build_model() |
| 42 | + |
| 43 | + def _decode_tf_example(self, encoded_inputs: tf.Tensor): |
| 44 | + sequence_description = { |
| 45 | + # Each image is a string encoding JPEG. |
| 46 | + video_input.IMAGE_KEY: |
| 47 | + tf.io.FixedLenSequenceFeature((), tf.string), |
| 48 | + } |
| 49 | + if self._output_audio: |
| 50 | + sequence_description[self._params.task.validation_data.audio_feature] = ( |
| 51 | + tf.io.VarLenFeature(dtype=tf.float32)) |
| 52 | + _, decoded_tensors = tf.io.parse_single_sequence_example( |
| 53 | + encoded_inputs, {}, sequence_description) |
| 54 | + for key, value in decoded_tensors.items(): |
| 55 | + if isinstance(value, tf.SparseTensor): |
| 56 | + decoded_tensors[key] = tf.sparse.to_dense(value) |
| 57 | + return decoded_tensors |
| 58 | + |
| 59 | + def _preprocess_image(self, image): |
| 60 | + image = video_input.process_image( |
| 61 | + image=image, |
| 62 | + is_training=False, |
| 63 | + num_frames=self._num_frames, |
| 64 | + stride=self._stride, |
| 65 | + num_test_clips=1, |
| 66 | + min_resize=self._min_resize, |
| 67 | + crop_size=self._crop_size, |
| 68 | + num_crops=1) |
| 69 | + image = tf.cast(image, tf.float32) # Use config. |
| 70 | + features = {'image': image} |
| 71 | + return features |
| 72 | + |
| 73 | + def _preprocess_audio(self, audio): |
| 74 | + features = {} |
| 75 | + audio = tf.cast(audio, dtype=tf.float32) # Use config. |
| 76 | + audio = video_input.preprocess_ops_3d.sample_sequence( |
| 77 | + audio, 20, random=False, stride=1) |
| 78 | + audio = tf.ensure_shape( |
| 79 | + audio, self._params.task.validation_data.audio_feature_shape) |
| 80 | + features['audio'] = audio |
| 81 | + return features |
| 82 | + |
| 83 | + @tf.function |
| 84 | + def inference_from_tf_example( |
| 85 | + self, encoded_inputs: tf.Tensor) -> Mapping[str, tf.Tensor]: |
| 86 | + with tf.device('cpu:0'): |
| 87 | + if self._output_audio: |
| 88 | + inputs = tf.map_fn( |
| 89 | + self._decode_tf_example, (encoded_inputs), |
| 90 | + fn_output_signature={ |
| 91 | + video_input.IMAGE_KEY: tf.string, |
| 92 | + self._params.task.validation_data.audio_feature: tf.float32 |
| 93 | + }) |
| 94 | + return self.serve(inputs['image'], inputs['audio']) |
| 95 | + else: |
| 96 | + inputs = tf.map_fn( |
| 97 | + self._decode_tf_example, (encoded_inputs), |
| 98 | + fn_output_signature={ |
| 99 | + video_input.IMAGE_KEY: tf.string, |
| 100 | + }) |
| 101 | + return self.serve(inputs[video_input.IMAGE_KEY], tf.zeros([1, 1])) |
| 102 | + |
| 103 | + @tf.function |
| 104 | + def inference_from_image_tensors( |
| 105 | + self, input_frames: tf.Tensor) -> Mapping[str, tf.Tensor]: |
| 106 | + return self.serve(input_frames, tf.zeros([1, 1])) |
| 107 | + |
| 108 | + @tf.function |
| 109 | + def inference_from_image_audio_tensors( |
| 110 | + self, input_frames: tf.Tensor, |
| 111 | + input_audio: tf.Tensor) -> Mapping[str, tf.Tensor]: |
| 112 | + return self.serve(input_frames, input_audio) |
| 113 | + |
| 114 | + @tf.function |
| 115 | + def inference_from_image_bytes(self, inputs: tf.Tensor): |
| 116 | + raise NotImplementedError( |
| 117 | + 'Video classification do not support image bytes input.') |
| 118 | + |
| 119 | + def serve(self, input_frames: tf.Tensor, input_audio: tf.Tensor): |
| 120 | + """Cast image to float and run inference. |
| 121 | +
|
| 122 | + Args: |
| 123 | + input_frames: uint8 Tensor of shape [batch_size, None, None, 3] |
| 124 | + input_audio: float32 |
| 125 | +
|
| 126 | + Returns: |
| 127 | + Tensor holding classification output logits. |
| 128 | + """ |
| 129 | + with tf.device('cpu:0'): |
| 130 | + inputs = tf.map_fn( |
| 131 | + self._preprocess_image, (input_frames), |
| 132 | + fn_output_signature={ |
| 133 | + 'image': tf.float32, |
| 134 | + }) |
| 135 | + if self._output_audio: |
| 136 | + inputs.update( |
| 137 | + tf.map_fn( |
| 138 | + self._preprocess_audio, (input_audio), |
| 139 | + fn_output_signature={'audio': tf.float32})) |
| 140 | + logits = self.inference_step(inputs) |
| 141 | + if self.params.task.train_data.is_multilabel: |
| 142 | + probs = tf.math.sigmoid(logits) |
| 143 | + else: |
| 144 | + probs = tf.nn.softmax(logits) |
| 145 | + return {'logits': logits, 'probs': probs} |
| 146 | + |
| 147 | + def get_inference_signatures(self, function_keys: Dict[Text, Text]): |
| 148 | + """Gets defined function signatures. |
| 149 | +
|
| 150 | + Args: |
| 151 | + function_keys: A dictionary with keys as the function to create signature |
| 152 | + for and values as the signature keys when returns. |
| 153 | +
|
| 154 | + Returns: |
| 155 | + A dictionary with key as signature key and value as concrete functions |
| 156 | + that can be used for tf.saved_model.save. |
| 157 | + """ |
| 158 | + signatures = {} |
| 159 | + for key, def_name in function_keys.items(): |
| 160 | + if key == 'image_tensor': |
| 161 | + input_signature = tf.TensorSpec( |
| 162 | + shape=[self._batch_size] + self._input_image_size + [3], |
| 163 | + dtype=tf.uint8, |
| 164 | + name='INPUT_FRAMES') |
| 165 | + signatures[ |
| 166 | + def_name] = self.inference_from_image_tensors.get_concrete_function( |
| 167 | + input_signature) |
| 168 | + elif key == 'frames_audio': |
| 169 | + input_signature = [ |
| 170 | + tf.TensorSpec( |
| 171 | + shape=[self._batch_size] + self._input_image_size + [3], |
| 172 | + dtype=tf.uint8, |
| 173 | + name='INPUT_FRAMES'), |
| 174 | + tf.TensorSpec( |
| 175 | + shape=[self._batch_size] + |
| 176 | + self.params.task.train_data.audio_feature_shape, |
| 177 | + dtype=tf.float32, |
| 178 | + name='INPUT_AUDIO') |
| 179 | + ] |
| 180 | + signatures[ |
| 181 | + def_name] = self.inference_from_image_audio_tensors.get_concrete_function( |
| 182 | + input_signature) |
| 183 | + elif key == 'serve_examples' or key == 'tf_example': |
| 184 | + input_signature = tf.TensorSpec( |
| 185 | + shape=[self._batch_size], dtype=tf.string) |
| 186 | + signatures[ |
| 187 | + def_name] = self.inference_from_tf_example.get_concrete_function( |
| 188 | + input_signature) |
| 189 | + else: |
| 190 | + raise ValueError('Unrecognized `input_type`') |
| 191 | + return signatures |
0 commit comments