1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ANDROID_PACKAGES_MODULES_NEURALNETWORKS_RUNTIME_FLATBUFFER_MODEL_BUILDER_H
18 #define ANDROID_PACKAGES_MODULES_NEURALNETWORKS_RUNTIME_FLATBUFFER_MODEL_BUILDER_H
19 
20 #include <tensorflow/lite/schema/schema_generated.h>
21 
22 #include <utility>
23 #include <vector>
24 
25 #include "FlatbufferModelBuilderUtils.h"
26 #include "ModelBuilder.h"
27 #include "NeuralNetworks.h"
28 
29 namespace android {
30 namespace nn {
31 
32 class FlatbufferModelBuilder : public ModelBuilder {
33    public:
34     // Return generated TFLite Model if successful
35     Result<const tflite::Model*> createTfliteModel();
36 
37    private:
38     void verifyModel(const tflite::Model* model);
39 
40     // Clears mBufferVector and initializes the first Buffer to be an empty Buffer
41     // for Tensors that do not have a buffer.
42     void initializeBufferVector();
43     // Clears mOpCodeIndexForOperationType and initializes elements to be -1
44     void initializeOpCodeIndexForOperationType();
45 
46     // Helper functions to convert Subgraphs
47     Result<SubGraphFlatbuffer> createSubGraphFlatbuffer(const Model::Subgraph& subgraph);
48     Result<std::vector<SubGraphFlatbuffer>> createSubGraphs();
49 
50     // Generates metadata for each Buffer
51     // Must be called after mBufferVector is filled.
52     std::vector<MetadataFlatbuffer> createMetadataVector();
53 
54     flatbuffers::FlatBufferBuilder mBuilder;
55     Model mModel;
56 
57     std::vector<OperatorCodeFlatbuffer> mOpCodesVector;
58     std::vector<int> mOpCodeIndexForOperationType;
59     std::vector<BufferFlatbuffer> mBufferVector;
60 };
61 
62 }  // namespace nn
63 }  // namespace android
64 
65 #endif  // ANDROID_PACKAGES_MODULES_NEURALNETWORKS_RUNTIME_FLATBUFFER_MODEL_BUILDER_H
66