summaryrefslogtreecommitdiff
path: root/tools/tflitefile_tool/select_operator.py
blob: c5d311d59723fe38f99d93e06ea0dc806ef898f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
#!/usr/bin/python

# Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys
import numpy

sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tflite'))
sys.path.append(
    os.path.join(
        os.path.dirname(os.path.abspath(__file__)), '../../externals/flatbuffers/python'))

import flatbuffers
import tflite.Model
import tflite.SubGraph
import tflite.BuiltinOptions
import argparse


# Assume we use only main model in model file
# Get selected operators from file, and return operator index list
def GetOperatorList(oplist_file):
    lines = oplist_file.readlines()
    opcode_list = []

    for line in lines:
        words = line.split()
        for word in words:
            if word.isdigit():
                opcode_list.append(int(word))
            else:
                opcode_range = word.split('-')
                if ((len(opcode_range) == 2) and opcode_range[0].isdigit()
                        and opcode_range[1].isdigit()):
                    start = int(opcode_range[0])
                    end = int(opcode_range[1])
                    for num in range(start, end + 1):
                        opcode_list.append(int(num))
                else:
                    print("Error: Cannot get operator list")
                    print(
                        "Please pass operators as operator index or range list split by space and/or line"
                    )
                    exit(1)

    if len(opcode_list) == 0:
        print("No selected operator")
        exit(1)

    return opcode_list


def GenerateOperatorCodes(new_builder, sample_model, used_operators_dic):
    operator_code_num = sample_model.OperatorCodesLength()
    new_operator_code_list = []
    new_operator_code_string_list = {}

    if operator_code_num == 0:
        return 0

    # Create operator_code string
    for operator_code_idx in range(operator_code_num):
        if operator_code_idx in used_operators_dic:
            operator_code = sample_model.OperatorCodes(operator_code_idx)
            operator_code_string = operator_code.CustomCode()
            if operator_code_string and (operator_code_string != "") and (
                    not operator_code_string in new_operator_code_string_list):
                new_operator_code_string_list[
                    operator_code_string] = new_builder.CreateString(operator_code_string)

    # Create tables of operator_code
    for operator_code_idx in range(operator_code_num):
        if operator_code_idx in used_operators_dic:
            operator_code = sample_model.OperatorCodes(operator_code_idx)

            # Create operator_code table
            tflite.OperatorCode.OperatorCodeStart(new_builder)
            tflite.OperatorCode.OperatorCodeAddBuiltinCode(new_builder,
                                                           operator_code.BuiltinCode())

            new_operator_code_string = operator_code.CustomCode()
            if new_operator_code_string in new_operator_code_string_list:
                tflite.OperatorCode.OperatorCodeAddCustomCode(
                    new_builder, new_operator_code_string_list[new_operator_code_string])
            new_operator_code = tflite.OperatorCode.OperatorCodeEnd(new_builder)
            new_operator_code_list.append(new_operator_code)

    # Create operator_code vector
    new_operator_code_num = len(new_operator_code_list)
    tflite.Model.ModelStartOperatorCodesVector(new_builder, new_operator_code_num)
    for operator_code_idx in reversed(range(new_operator_code_num)):
        new_builder.PrependUOffsetTRelative(new_operator_code_list[operator_code_idx])

    return new_builder.EndVector(new_operator_code_num)


def GenerateQuantization(new_builder, selected_quantization):
    # Create min vector
    min_num = selected_quantization.MinLength()
    if min_num != 0:
        tflite.QuantizationParameters.QuantizationParametersStartMinVector(
            new_builder, min_num)
        for min_idx in reversed(range(min_num)):
            new_builder.PrependFloat32(selected_quantization.Min(min_idx))
        new_min = new_builder.EndVector(min_num)

    # Create max vector
    max_num = selected_quantization.MaxLength()
    if max_num != 0:
        tflite.QuantizationParameters.QuantizationParametersStartMaxVector(
            new_builder, max_num)
        for max_idx in reversed(range(max_num)):
            new_builder.PrependFloat32(selected_quantization.Max(max_idx))
        new_max = new_builder.EndVector(max_num)

    # Create scale vector
    scale_num = selected_quantization.ScaleLength()
    if scale_num != 0:
        tflite.QuantizationParameters.QuantizationParametersStartScaleVector(
            new_builder, scale_num)
        for scale_idx in reversed(range(scale_num)):
            new_builder.PrependFloat32(selected_quantization.Scale(scale_idx))
        new_scale = new_builder.EndVector(scale_num)

    # Create zero_point vector
    zeropoint_num = selected_quantization.ZeroPointLength()
    if zeropoint_num != 0:
        tflite.QuantizationParameters.QuantizationParametersStartScaleVector(
            new_builder, zeropoint_num)
        for zeropoint_idx in reversed(range(zeropoint_num)):
            new_builder.PrependFloat32(selected_quantization.ZeroPoint(zeropoint_idx))
        new_zeropoint = new_builder.EndVector(zeropoint_num)

    # Create quantization
    tflite.QuantizationParameters.QuantizationParametersStart(new_builder)
    if min_num != 0:
        tflite.QuantizationParameters.QuantizationParametersAddMin(new_builder, new_min)
    if max_num != 0:
        tflite.QuantizationParameters.QuantizationParametersAddMax(new_builder, new_max)
    if scale_num != 0:
        tflite.QuantizationParameters.QuantizationParametersAddScale(
            new_builder, new_scale)
    if zeropoint_num != 0:
        tflite.QuantizationParameters.QuantizationParametersAddZeroPoint(
            new_builder, new_zeropoint)

    return tflite.QuantizationParameters.QuantizationParametersEnd(new_builder)


def GenerateTensor(new_builder, selected_tensor, used_buffers_dic):

    # Create shape vector for tensor
    shape_num = selected_tensor.ShapeLength()
    tflite.Tensor.TensorStartShapeVector(new_builder, shape_num)
    if shape_num != 0:
        for shape_idx in reversed(range(shape_num)):
            new_builder.PrependInt32(selected_tensor.Shape(shape_idx))
    new_shape = new_builder.EndVector(shape_num)

    # Create tensor_type
    tensor_type = selected_tensor.Type()

    # Create input vector for tensor
    buffer_idx = selected_tensor.Buffer()
    new_buffer_idx = used_buffers_dic[buffer_idx]

    # Create name string
    name_string = selected_tensor.Name()
    if name_string != "":
        new_name = new_builder.CreateString(name_string)

    # Create quantization
    quantization = selected_tensor.Quantization()
    if quantization != 0:
        new_quantization = GenerateQuantization(new_builder, quantization)

    # Create tensor
    tflite.Tensor.TensorStart(new_builder)
    tflite.Tensor.TensorAddShape(new_builder, new_shape)
    tflite.Tensor.TensorAddType(new_builder, tensor_type)
    tflite.Tensor.TensorAddBuffer(new_builder, new_buffer_idx)
    if name_string != "":
        tflite.Tensor.TensorAddName(new_builder, new_name)
    if quantization != 0:
        tflite.Tensor.TensorAddQuantization(new_builder, new_quantization)

    return tflite.Tensor.TensorEnd(new_builder)


def GenerateTensors(new_builder, selected_subgraph, used_tensors_dic, used_buffers_dic):
    tensor_num = selected_subgraph.TensorsLength()
    new_tensor_list = []

    if tensor_num == 0:
        return 0

    for tensor_idx in range(tensor_num):
        if tensor_idx in used_tensors_dic:
            selected_tensor = selected_subgraph.Tensors(tensor_idx)
            new_tensor = GenerateTensor(new_builder, selected_tensor, used_buffers_dic)
            new_tensor_list.append(new_tensor)

    new_tensor_num = len(new_tensor_list)
    if new_tensor_num == 0:
        return 0

    tflite.SubGraph.SubGraphStartTensorsVector(new_builder, new_tensor_num)
    for new_tensor in reversed(new_tensor_list):
        new_builder.PrependUOffsetTRelative(new_tensor)

    return new_builder.EndVector(new_tensor_num)


def GenerateBuiltinOption(new_builder, selected_builtin_option, builtin_option_type):

    # Conv2D option
    import tflite.Conv2DOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().Conv2DOptions:

        conv2d_options = tflite.Conv2DOptions.Conv2DOptions()
        conv2d_options.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.Conv2DOptions.Conv2DOptionsStart(new_builder)
        tflite.Conv2DOptions.Conv2DOptionsAddPadding(new_builder,
                                                     conv2d_options.Padding())
        tflite.Conv2DOptions.Conv2DOptionsAddStrideW(new_builder,
                                                     conv2d_options.StrideW())
        tflite.Conv2DOptions.Conv2DOptionsAddStrideH(new_builder,
                                                     conv2d_options.StrideH())
        tflite.Conv2DOptions.Conv2DOptionsAddFusedActivationFunction(
            new_builder, conv2d_options.FusedActivationFunction())
        return tflite.Conv2DOptions.Conv2DOptionsEnd(new_builder)

    # DepthwiseConv2D option
    import tflite.DepthwiseConv2DOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions(
    ).DepthwiseConv2DOptions:

        depthconv2d_option = tflite.DepthwiseConv2DOptions.DepthwiseConv2DOptions()
        depthconv2d_option.Init(selected_builtin_option.Bytes,
                                selected_builtin_option.Pos)

        tflite.DepthwiseConv2DOptions.DepthwiseConv2DOptionsStart(new_builder)
        tflite.DepthwiseConv2DOptions.DepthwiseConv2DOptionsAddPadding(
            new_builder, depthconv2d_option.Padding())
        tflite.DepthwiseConv2DOptions.DepthwiseConv2DOptionsAddStrideW(
            new_builder, depthconv2d_option.StrideW())
        tflite.DepthwiseConv2DOptions.DepthwiseConv2DOptionsAddStrideH(
            new_builder, depthconv2d_option.StrideH())
        tflite.DepthwiseConv2DOptions.DepthwiseConv2DOptionsAddDepthMultiplier(
            new_builder, depthconv2d_option.DepthMultiplier())
        tflite.DepthwiseConv2DOptions.DepthwiseConv2DOptionsAddFusedActivationFunction(
            new_builder, depthconv2d_option.FusedActivationFunction())
        tflite.DepthwiseConv2DOptions.DepthwiseConv2DOptionsAddDilationWFactor(
            new_builder, depthconv2d_option.DilationWFactor())
        tflite.DepthwiseConv2DOptions.DepthwiseConv2DOptionsAddDilationHFactor(
            new_builder, depthconv2d_option.DilationHFactor())
        return tflite.DepthwiseConv2DOptions.DepthwiseConv2DOptionsEnd(new_builder)

    # ConcatEmbeddingsOptions: not supported
    # LSHProjectionOptions: not supported

    # Pool2DPOption
    import tflite.Pool2DOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().Pool2DOptions:

        pool2d_option = tflite.Pool2DOptions.Pool2DOptions()
        pool2d_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.Pool2DOptions.Pool2DOptionsStart(new_builder)
        tflite.Pool2DOptions.Pool2DOptionsAddPadding(new_builder, pool2d_option.Padding())
        tflite.Pool2DOptions.Pool2DOptionsAddStrideW(new_builder, pool2d_option.StrideW())
        tflite.Pool2DOptions.Pool2DOptionsAddStrideH(new_builder, pool2d_option.StrideH())
        tflite.Pool2DOptions.Pool2DOptionsAddFilterWidth(new_builder,
                                                         pool2d_option.FilterWidth())
        tflite.Pool2DOptions.Pool2DOptionsAddFilterHeight(new_builder,
                                                          pool2d_option.FilterHeight())
        tflite.Pool2DOptions.Pool2DOptionsAddFusedActivationFunction(
            new_builder, pool2d_option.FusedActivationFunction())
        return tflite.Pool2DOptions.Pool2DOptionsEnd(new_builder)

    # SVDFOptions: not supported

    # RNNOptions
    import tflite.RNNOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().RNNOptions:

        rnn_option = tflite.RNNOptions.RNNOptions()
        rnn_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.RNNOptions.RNNOptionsStart(new_builder)
        tflite.RNNOptions.RNNOptionsAddFusedActivationFunction(
            new_builder, rnn_option.FusedActivationFunction())
        return tflite.RNNOptions.RNNOptionsEnd(new_builder)

    # FullyConnectedOptions
    import tflite.FullyConnectedOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions(
    ).FullyConnectedOptions:

        fc_option = tflite.FullyConnectedOptions.FullyConnectedOptions()
        fc_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.FullyConnectedOptions.FullyConnectedOptionsStart(new_builder)
        tflite.FullyConnectedOptions.FullyConnectedOptionsAddFusedActivationFunction(
            new_builder, fc_option.FusedActivationFunction())
        return tflite.FullyConnectedOptions.FullyConnectedOptionsEnd(new_builder)

    # SoftmaxOptions
    import tflite.SoftmaxOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().SoftmaxOptions:

        softmax_option = tflite.SoftmaxOptions.SoftmaxOptions()
        softmax_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.SoftmaxOptions.SoftmaxOptionsStart(new_builder)
        tflite.SoftmaxOptions.SoftmaxOptionsAddBeta(new_builder, softmax_option.Beta())
        return tflite.SoftmaxOptions.SoftmaxOptionsEnd(new_builder)

    # ConcatenationOptions
    import tflite.ConcatenationOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().ConcatenationOptions:

        concat_option = tflite.ConcatenationOptions.ConcatenationOptions()
        concat_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.ConcatenationOptions.ConcatenationOptionsStart(new_builder)
        tflite.ConcatenationOptions.ConcatenationOptionsAddAxis(
            new_builder, concat_option.Axis())
        tflite.ConcatenationOptions.ConcatenationOptionsAddFusedActivationFunction(
            new_builder, concat_option.FusedActivationFunction())
        return tflite.ConcatenationOptions.ConcatenationOptionsEnd(new_builder)

    # AddOptions
    import tflite.AddOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().AddOptions:

        add_option = tflite.AddOptions.AddOptions()
        add_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.AddOptions.AddOptionsStart(new_builder)
        tflite.AddOptions.AddOptionsAddFusedActivationFunction(
            new_builder, add_option.FusedActivationFunction())
        return tflite.AddOptions.AddOptionsEnd(new_builder)

    # L2NormOptions
    import tflite.L2NormOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().L2NormOptions:

        l2norm_option = tflite.L2NormOptions.L2NormOptions()
        l2norm_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.L2NormOptions.L2NormOptionsStart(new_builder)
        tflite.L2NormOptions.L2NormOptionsAddFusedActivationFunction(
            new_builder, l2norm_option.FusedActivationFunction())
        return tflite.L2NormOptions.L2NormOptionsEnd(new_builder)

    # LocalResponseNormalizationOptions
    import tflite.LocalResponseNormalizationOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions(
    ).LocalResponseNormalizationOptions:

        lrn_option = tflite.LocalResponseNormalizationOptions.LocalResponseNormalizationOptions(
        )
        lrn_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.LocalResponseNormalizationOptions.LocalResponseNormalizationOptionsStart(
            new_builder)
        tflite.LocalResponseNormalizationOptions.LocalResponseNormalizationOptionsAddRadius(
            new_builder, lrn_option.Radius())
        tflite.LocalResponseNormalizationOptions.LocalResponseNormalizationOptionsAddBias(
            new_builder, lrn_option.Bias())
        tflite.LocalResponseNormalizationOptions.LocalResponseNormalizationOptionsAddAlpha(
            new_builder, lrn_option.Alpha())
        tflite.LocalResponseNormalizationOptions.LocalResponseNormalizationOptionsAddBeta(
            new_builder, lrn_option.Beta())
        return tflite.LocalResponseNormalizationOptions.LocalResponseNormalizationOptionsEnd(
            new_builder)

    # LSTMOptions: not supported

    # ResizeBilinearOptions
    import tflite.ResizeBilinearOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions(
    ).ResizeBilinearOptions:

        resize_bilinear_option = tflite.ResizeBilinearOptions.ResizeBilinearOptions()
        resize_bilinear_option.Init(selected_builtin_option.Bytes,
                                    selected_builtin_option.Pos)

        tflite.ResizeBilinearOptions.ResizeBilinearOptionsStart(new_builder)
        tflite.ResizeBilinearOptions.ResizeBilinearOptionsAddAlignCorners(
            new_builder, resize_bilinear_option.AlignCorners())
        return tflite.ResizeBilinearOptions.ResizeBilinearOptionsEnd(new_builder)

    # CallOptions: not supported

    # ReshapeOptions
    import tflite.ReshapeOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().ReshapeOptions:

        reshape_option = tflite.ReshapeOptions.ReshapeOptions()
        reshape_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        shape_num = reshape_option.NewShapeLength()
        if shape_num != 0:
            tflite.ReshapeOptions.ReshapeOptionsStartNewShapeVector(
                new_builder, shape_num)
            for new_shape_idx in reversed(range(shape_num)):
                new_shape_val = reshape_option.NewShape(new_shape_idx)
                new_builder.PrependInt32(new_shape_val)
            new_shape = new_builder.EndVector(shape_num)

        tflite.ReshapeOptions.ReshapeOptionsStart(new_builder)
        if shape_num != 0:
            tflite.ReshapeOptions.ReshapeOptionsAddNewShape(new_builder, new_shape)
        return tflite.ReshapeOptions.ReshapeOptionsEnd(new_builder)

    # SkipGramOptions: not supported

    # SpaceToDepthOptions
    import tflite.SpaceToDepthOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().SpaceToDepthOptions:

        space_to_depth_option = tflite.SpaceToDepthOptions.SpaceToDepthOptions()
        space_to_depth_option.Init(selected_builtin_option.Bytes,
                                   selected_builtin_option.Pos)

        tflite.SpaceToDepthOptions.SpaceToDepthOptionsStart(new_builder)
        tflite.SpaceToDepthOptions.SpaceToDepthOptionsAddBlockSize(
            new_builder, space_to_depth_option.BlockSize())
        return tflite.SpaceToDepthOptions.SpaceToDepthOptionsEnd(new_builder)

    # EmbeddingLookupSparseOptions: not supported

    # MulOptions
    import tflite.MulOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().MulOptions:

        mul_option = tflite.MulOptions.MulOptions()
        mul_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.MulOptions.MulOptionsStart(new_builder)
        tflite.MulOptions.MulOptionsAddFusedActivationFunction(
            new_builder, mul_option.FusedActivationFunction())
        return tflite.MulOptions.MulOptionsEnd(new_builder)

    # PadOptions
    import tflite.PadOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().PadOptions:

        pad_option = tflite.PadOptions.PadOptions()
        pad_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.PadOptions.PadOptionsStart(new_builder)
        return tflite.PadOptions.PadOptionsEnd(new_builder)

    # GatherOptions
    import tflite.GatherOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().GatherOptions:

        gather_option = tflite.GatherOptions.GatherOptions()
        gather_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.GatherOptions.GatherOptionsStart(new_builder)
        tflite.GatherOptions.GatherOptionsAddAxis(new_builder, gather_option.Axis())
        return tflite.GatherOptions.GatherOptionsEnd(new_builder)

    # BatchToSpaceNDOptions
    import tflite.BatchToSpaceNDOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions(
    ).BatchToSpaceNDOptions:

        btsnd_option = tflite.BatchToSpaceNDOptions.BatchToSpaceNDOptions()
        btsnd_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.BatchToSpaceNDOptions.BatchToSpaceNDOptionsStart(new_builder)
        return tflite.BatchToSpaceNDOptions.BatchToSpaceNDOptionsEnd(new_builder)

    # SpaceToBatchNDOptions
    import tflite.SpaceToBatchNDOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions(
    ).SpaceToBatchNDOptions:

        stbnd_option = tflite.SpaceToBatchNDOptions.SpaceToBatchNDOptions()
        stbnd_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.SpaceToBatchNDOptions.SpaceToBatchNDOptionsStart(new_builder)
        return tflite.SpaceToBatchNDOptions.SpaceToBatchNDOptionsEnd(new_builder)

    # TransposeOptions:
    import tflite.TransposeOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().TransposeOptions:

        transpose_option = tflite.TransposeOptions.TransposeOptions()
        transpose_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.TransposeOptions.TransposeOptionsStart(new_builder)
        return tflite.TransposeOptions.TransposeOptionsEnd(new_builder)

    # ReducerOptions
    import tflite.ReducerOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().ReducerOptions:

        reducer_option = tflite.ReducerOptions.ReducerOptions()
        reducer_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.ReducerOptions.ReducerOptionsStart(new_builder)
        tflite.ReducerOptions.ReducerOptionsAddKeepDims(new_builder,
                                                        reducer_option.KeepDims())
        return tflite.ReducerOptions.ReducerOptionsEnd(new_builder)

    # SubOptions
    import tflite.SubOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().SubOptions:

        sub_option = tflite.SubOptions.SubOptions()
        sub_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.SubOptions.SubOptionsStart(new_builder)
        tflite.SubOptions.SubOptionsAddFusedActivationFunction(
            new_builder, sub_option.FusedActivationFunction())
        return tflite.SubOptions.SubOptionsEnd(new_builder)

    # DivOptions
    import tflite.DivOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().DivOptions:

        div_option = tflite.DivOptions.DivOptions()
        div_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.DivOptions.DivOptionsStart(new_builder)
        tflite.DivOptions.DivOptionsAddFusedActivationFunction(
            new_builder, div_option.FusedActivationFunction())
        return tflite.DivOptions.DivOptionsEnd(new_builder)

    # SqueezeOptions
    import tflite.SqueezeOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().SqueezeOptions:

        squeeze_option = tflite.SqueezeOptions.SqueezeOptions()
        squeeze_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        squeeze_dims_num = squeeze_option.SqueezeDimsLength()
        if squeeze_dims_num != 0:
            tflite.SqueezeOptions.SqueezeOptionsStartSqueezeDimsVector(
                new_builder, squeeze_dims_num)
            for squeeze_dims_idx in reversed(range(squeeze_dims_num)):
                squeeze_dims_val = squeeze_option.SqueezeDims(squeeze_dims_idx)
                new_builder.PrependInt32(squeeze_dims_val)
            new_squeeze_dims = new_builder.EndVector(squeeze_dims_num)

        tflite.SqueezeOptions.SqueezeOptionsStart(new_builder)
        if squeeze_dims_num != 0:
            tflite.SqueezeOptions.SqueezeOptionsAddSqueezeDims(new_builder,
                                                               new_squeeze_dims)
        return tflite.SqueezeOptions.SqueezeOptionsEnd(new_builder)

    # SequenceRNNOptions: not supported

    # StridedSliceOptions
    import tflite.StridedSliceOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().StridedSliceOptions:

        stride_slice_option = tflite.StridedSliceOptions.StridedSliceOptions()
        stride_slice_option.Init(selected_builtin_option.Bytes,
                                 selected_builtin_option.Pos)

        tflite.StridedSliceOptions.StridedSliceOptionsStart(new_builder)
        tflite.StridedSliceOptions.StridedSliceOptionsAddBeginMask(
            new_builder, stride_slice_option.BeginMask())
        tflite.StridedSliceOptions.StridedSliceOptionsAddEndMask(
            new_builder, stride_slice_option.EndMask())
        tflite.StridedSliceOptions.StridedSliceOptionsAddEllipsisMask(
            new_builder, stride_slice_option.EllipsisMask())
        tflite.StridedSliceOptions.StridedSliceOptionsAddNewAxisMask(
            new_builder, stride_slice_option.NewAxisMask())
        tflite.StridedSliceOptions.StridedSliceOptionsAddShrinkAxisMask(
            new_builder, stride_slice_option.ShrinkAxisMask())

        return tflite.StridedSliceOptions.StridedSliceOptionsEnd(new_builder)

    # ExpOptions
    import tflite.ExpOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().ExpOptions:

        exp_option = tflite.ExpOptions.ExpOptions()
        exp_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.ExpOptions.ExpOptionsStart(new_builder)
        return tflite.ExpOptions.ExpOptionsEnd(new_builder)

    # TopKV2Options
    import tflite.TopKV2Options
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().TopKV2Options:

        topkv2_option = tflite.TopKV2Options.TopKV2Options()
        topkv2_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.TopKV2Options.TopKV2OptionsStart(new_builder)
        return tflite.TopKV2Options.TopKV2OptionsEnd(new_builder)

    # SplitOptions
    import tflite.SplitOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().SplitOptions:

        split_option = tflite.SplitOptions.SplitOptions()
        split_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.SplitOptions.SplitOptionsStart(new_builder)
        tflite.SplitOptions.SplitOptionsAddNumSplits(new_builder,
                                                     split_option.NumSplits())
        return tflite.SplitOptions.SplitOptionsEnd(new_builder)

    # LogSoftmaxOptions: not supported

    # CastOptions: not supported
    import tflite.CastOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().CastOptions:

        cast_option = tflite.CastOptions.CastOptions()
        cast_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.CastOptions.CastOptionsStart(new_builder)
        return tflite.CastOptions.CastOptionsEnd(new_builder)

    # DequantizeOptions:
    import tflite.DequantizeOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().DequantizeOptions:

        dequantize_option = tflite.DequantizeOptions.DequantizeOptions()
        dequantize_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.EqualOptions.DequantizeOptionsStart(new_builder)
        return tflite.DequantizeOptions.DequantizeOptionsEnd(new_builder)

    # MaximumMinimumOptions: not supported

    # ArgMaxOptions
    import tflite.ArgMaxOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().ArgMaxOptions:

        arg_max_option = tflite.ArgMaxOptions.ArgMaxOptions()
        arg_max_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.ArgMaxOptions.ArgMaxOptionsStart(new_builder)
        tflite.ArgMaxOptions.ArgMaxOptionsAddOutputType(new_builder,
                                                        arg_max_option.OutputType())
        return tflite.ArgMaxOptions.ArgMaxOptionsEnd(new_builder)

    # LessOptions: not supported

    # NegOptions
    import tflite.NegOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().NegOptions:

        neg_option = tflite.NegOptions.NegOptions()
        neg_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.NegOptions.NegOptionsStart(new_builder)
        return tflite.NegOptions.NegOptionsEnd(new_builder)

    # EqualOptions
    import tflite.EqualOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().EqualOptions:

        equal_option = tflite.EqualOptions.EqualOptions()
        equal_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.EqualOptions.EqualOptionsStart(new_builder)
        return tflite.EqualOptions.EqualOptionsEnd(new_builder)

    # PadV2Options: not supported
    # GreaterOptions: not supported
    # GreaterEqualOptions: not supported
    # LessEqualOptions: not supported
    # SelectOptions: not supported
    # SliceOptions: not supported

    # TransposeConvOptions
    import tflite.TransposeConvOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().TransposeConvOptions:

        transposeconv_option = tflite.TransposeConvOptions.TransposeConvOptions()
        transposeconv_option.Init(selected_builtin_option.Bytes,
                                  selected_builtin_option.Pos)

        tflite.TransposeConvOptions.TransposeConvOptionsStart(new_builder)
        tflite.TransposeConvOptions.TransposeConvOptionsAddPadding(
            new_builder, transposeconv_option.Padding())
        tflite.TransposeConvOptions.TransposeConvOptionsAddStrideW(
            new_builder, transposeconv_option.StrideW())
        tflite.TransposeConvOptions.TransposeConvOptionsAddStrideH(
            new_builder, transposeconv_option.StrideH())
        return tflite.TransposeConvOptions.TransposeConvOptionsEnd(new_builder)

    # SparseToDenseOptions: not supported
    # TileOptions: not supported
    # ExpandDimsOptions: not supported

    # NotEqualOptions:
    import tflite.NotEqualOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().NotEqualOptions:

        notequal_option = tflite.NotEqualOptions.NotEqualOptions()
        notequal_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.NotEqualOptions.NotEqualOptionsStart(new_builder)
        return tflite.NotEqualOptions.NotEqualOptionsEnd(new_builder)

    # ShapeOptions: not supported
    # PowOptions: not supported
    # ArgMinOptions: not supported
    # FakeQuantOptions: not supported

    # PackOptions:
    import tflite.PackOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().PackOptions:

        pack_option = tflite.PackOptions.PackOptions()
        pack_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.PackOptions.PackOptionsStart(new_builder)
        tflite.PackOptions.PackOptionsAddValuesCount(new_builder,
                                                     pack_option.ValuesCount())
        tflite.PackOptions.PackOptionsAddAxis(new_builder, pack_option.Axis())
        return tflite.PackOptions.PackOptionsEnd(new_builder)

    # LogicalOrOptions:
    import tflite.LogicalOrOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().LogicalOrOptions:

        logical_or_option = tflite.LogicalAndOptions.LogicalOrOptions()
        logical_or_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.LogicalOrOptions.LogicalOrOptionsStart(new_builder)
        return tflite.LogicalOrOptions.LogicalOrOptionsEnd(new_builder)

    # OneHotOptions: not supported

    # LogicalNotOptions
    import tflite.LogicalNotOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().LogicalNotOptions:

        equal_option = tflite.LogicalNotOptions.LogicalNotOptions()
        equal_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.LogicalNotOptions.LogicalNotOptionsStart(new_builder)
        return tflite.LogicalNotOptions.LogicalNotOptionsEnd(new_builder)

    # UnpackOptions:
    import tflite.UnpackOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().UnpackOptions:

        unpack_option = tflite.unpackOptions.unpackOptions()
        unpack_option.Init(selected_builtin_option.Bytes, selected_builtin_option.Pos)

        tflite.unpackOptions.UnpackOptionsStart(new_builder)
        tflite.unpackOptions.UnpackOptionsAddNum(new_builder, unpack_option.Num())
        tflite.PackOptions.UnpackOptionsAddAxis(new_builder, unpack_option.Axis())
        return tflite.UnpackOptions.UnpackOptionsEnd(new_builder)

    # FloorDivOptions: not supported
    # SquareOptions: not supported
    # ZerosLikeOptions: not supported
    # FillOptions: not supported

    # LogicalAndOptions
    import tflite.LogicalAndOptions
    if builtin_option_type == tflite.BuiltinOptions.BuiltinOptions().LogicalAndOptions:

        logical_and_option = tflite.LogicalAndOptions.LogicalAndOptions()
        logical_and_option.Init(selected_builtin_option.Bytes,
                                selected_builtin_option.Pos)

        tflite.LogicalAndOptions.LogicalAndOptionsStart(new_builder)
        return tflite.LogicalAndOptions.LogicalAndOptionsEnd(new_builder)

    # Cannot handle builtin option type yet
    print("Cannot handle this option yet")
    exit(1)


def GenerateOperator(new_builder, selected_operator, used_tensors_dic,
                     used_operators_dic):

    # define opcode_index
    opcode_index = selected_operator.OpcodeIndex()
    new_opcode_index = used_operators_dic[opcode_index]

    # create input vector
    input_num = selected_operator.InputsLength()
    if input_num != 0:
        new_input_list = []
        tflite.Operator.OperatorStartInputsVector(new_builder, input_num)
        for input_idx in reversed(range(input_num)):
            input_tensor_idx = selected_operator.Inputs(input_idx)
            new_input_tensor_idx = used_tensors_dic[input_tensor_idx]
            new_builder.PrependInt32(new_input_tensor_idx)
            new_input_list.append(new_input_tensor_idx)
        new_input = new_builder.EndVector(input_num)

    # create output_vector
    output_num = selected_operator.OutputsLength()
    if output_num != 0:
        tflite.Operator.OperatorStartOutputsVector(new_builder, output_num)
        for output_idx in reversed(range(output_num)):
            output_tensor_idx = selected_operator.Outputs(output_idx)
            new_output_tensor_idx = used_tensors_dic[output_tensor_idx]
            new_builder.PrependInt32(new_output_tensor_idx)
        new_output = new_builder.EndVector(output_num)

    # Create builtin_option
    builtin_option_type = selected_operator.BuiltinOptionsType()
    if builtin_option_type != 0:
        selected_builtin_option = selected_operator.BuiltinOptions()
        new_builtin_option = GenerateBuiltinOption(new_builder, selected_builtin_option,
                                                   builtin_option_type)

    # Create custum option vector
    custom_option_num = selected_operator.CustomOptionsLength()
    if custom_option_num != 0:
        tflite.Operator.OperatorStartCustomOptionsVector(new_builder, custom_option_num)
        for custom_option_idx in reversed(range(custom_option_num)):
            new_builder.PrependUint8(selected_operator.CustomOptions(custom_option_idx))
        new_custom_option = new_builder.EndVector(custom_option_num)

    # Create custum option type
    custom_option_type = selected_operator.CustomOptionsFormat()

    # Create operator
    tflite.Operator.OperatorStart(new_builder)
    tflite.Operator.OperatorAddOpcodeIndex(new_builder, new_opcode_index)
    if input_num != 0:
        tflite.Operator.OperatorAddInputs(new_builder, new_input)
    if output_num != 0:
        tflite.Operator.OperatorAddOutputs(new_builder, new_output)
    tflite.Operator.OperatorAddBuiltinOptionsType(new_builder, builtin_option_type)
    if builtin_option_type != 0:
        tflite.Operator.OperatorAddBuiltinOptions(new_builder, new_builtin_option)
    if custom_option_num != 0:
        tflite.Operator.OperatorAddCustomOptions(new_builder, new_custom_option)
    tflite.Operator.OperatorAddCustomOptionsFormat(new_builder, custom_option_type)
    return tflite.Operator.OperatorEnd(new_builder)


def GenerateOperators(new_builder, selected_subgraph, opcode_list, used_tensors_dic,
                      used_operators_dic):
    operator_num = selected_subgraph.OperatorsLength()
    new_operator_list = []

    if operator_num == 0:
        return 0

    for operator_idx in range(operator_num):
        if operator_idx in opcode_list:
            selected_operator = selected_subgraph.Operators(operator_idx)
            new_operator = GenerateOperator(new_builder, selected_operator,
                                            used_tensors_dic, used_operators_dic)
            new_operator_list.append(new_operator)

    new_operator_num = len(new_operator_list)
    if new_operator_num == 0:
        return 0

    tflite.SubGraph.SubGraphStartOperatorsVector(new_builder, new_operator_num)
    for new_operator in reversed(new_operator_list):
        new_builder.PrependUOffsetTRelative(new_operator)

    return new_builder.EndVector(new_operator_num)


def GenerateSubgraph(new_builder, selected_subgraph, opcode_list, new_input_tensor,
                     new_output_tensor, used_tensors_dic, used_buffers_dic,
                     used_operators_dic):

    # Tensors
    tensors = GenerateTensors(new_builder, selected_subgraph, used_tensors_dic,
                              used_buffers_dic)

    # Create input vector for subgraph table
    new_input_tensor_num = len(new_input_tensor)
    if new_input_tensor_num != 0:
        tflite.SubGraph.SubGraphStartInputsVector(new_builder, new_input_tensor_num)
        for input_tensor_idx in reversed(new_input_tensor):
            new_input_tensor_idx = used_tensors_dic[input_tensor_idx]
            new_builder.PrependInt32(new_input_tensor_idx)
        new_inputs = new_builder.EndVector(new_input_tensor_num)

    # Create output vector for subgraph table
    new_output_tensor_num = len(new_output_tensor)
    if new_output_tensor_num != 0:
        tflite.SubGraph.SubGraphStartInputsVector(new_builder, new_output_tensor_num)
        for output_tensor_idx in reversed(new_output_tensor):
            new_output_tensor_idx = used_tensors_dic[output_tensor_idx]
            new_builder.PrependInt32(new_output_tensor_idx)
        new_outputs = new_builder.EndVector(new_output_tensor_num)

    # Operators
    operators = GenerateOperators(new_builder, selected_subgraph, opcode_list,
                                  used_tensors_dic, used_operators_dic)

    # Name
    subgraph_name = selected_subgraph.Name()
    have_name = False
    if subgraph_name and subgraph_name != "":
        have_name = True
        new_subgraph_name = new_builder.CreateString(subgraph_name)

    tflite.SubGraph.SubGraphStart(new_builder)
    tflite.SubGraph.SubGraphAddTensors(new_builder, tensors)
    if new_input_tensor_num != 0:
        tflite.SubGraph.SubGraphAddInputs(new_builder, new_inputs)
    if new_output_tensor_num != 0:
        tflite.SubGraph.SubGraphAddOutputs(new_builder, new_outputs)
    tflite.SubGraph.SubGraphAddOperators(new_builder, operators)
    if have_name:
        tflite.SubGraph.SubGraphAddName(new_builder, new_subgraph_name)

    return tflite.SubGraph.SubGraphEnd(new_builder)


def GenerateSubgraphs(new_builder, sample_model, opcode_list, new_input_tensor,
                      new_output_tensor, used_tensors_dic, used_buffers_dic,
                      used_operators_dic):
    new_subgraph_list = []

    # We think only main graph
    selected_subgraph = sample_model.Subgraphs(0)
    new_subgraph = GenerateSubgraph(new_builder, selected_subgraph, opcode_list,
                                    new_input_tensor, new_output_tensor, used_tensors_dic,
                                    used_buffers_dic, used_operators_dic)
    new_subgraph_list.append(new_subgraph)

    new_subgraph_num = 1
    tflite.Model.ModelStartSubgraphsVector(new_builder, new_subgraph_num)
    for subgraph_idx in reversed(range(new_subgraph_num)):
        new_builder.PrependUOffsetTRelative(new_subgraph_list[subgraph_idx])

    return new_builder.EndVector(new_subgraph_num)


def GenerateBuffers(new_builder, sample_model, used_buffers_dic):
    buffer_num = sample_model.BuffersLength()
    new_buffer_data_list = {}
    new_buffer_list = []

    if buffer_num == 0:
        return 0

    # Create data vector for buffer table
    for buffer_idx in range(buffer_num):
        buffer = sample_model.Buffers(buffer_idx)
        buffer_length = buffer.DataLength()

        if (buffer_length != 0) and (buffer_idx in used_buffers_dic):
            tflite.Buffer.BufferStartDataVector(new_builder, buffer_length)
            for buffer_data_idx in reversed(range(buffer_length)):
                new_builder.PrependUint8(buffer.Data(buffer_data_idx))
            new_buffer = new_builder.EndVector(buffer_length)
            new_buffer_data_list[buffer_idx] = new_buffer

    # Create tables of buffer
    for buffer_idx in range(buffer_num):
        buffer = sample_model.Buffers(buffer_idx)

        if buffer_idx in used_buffers_dic:
            # Create buffer table
            tflite.Buffer.BufferStart(new_builder)
            if buffer.DataLength() != 0:
                tflite.Buffer.BufferAddData(new_builder, new_buffer_data_list[buffer_idx])
            new_buffer = tflite.Buffer.BufferEnd(new_builder)
            new_buffer_list.append(new_buffer)

    # Create buffer vector
    new_buffer_num = len(new_buffer_list)
    if new_buffer_num == 0:
        return 0

    tflite.Model.ModelStartBuffersVector(new_builder, new_buffer_num)
    for new_buffer_idx in reversed(range(new_buffer_num)):
        new_builder.PrependUOffsetTRelative(new_buffer_list[new_buffer_idx])

    return new_builder.EndVector(new_buffer_num)


def GenerateModel(new_builder, sample_model, opcode_list, new_input_tensors,
                  new_output_tensors, used_tensors_dic, used_buffers_dic,
                  used_operators_dic):
    # uint
    version = sample_model.Version()

    # pointer of operator code 'table' vector
    operator_codes = GenerateOperatorCodes(new_builder, sample_model, used_operators_dic)

    # subgraphs
    subgraphs = GenerateSubgraphs(new_builder, sample_model, opcode_list,
                                  new_input_tensors, new_output_tensors, used_tensors_dic,
                                  used_buffers_dic, used_operators_dic)

    # description
    description_string = new_builder.CreateString(sample_model.Description())

    # buffers
    buffers = GenerateBuffers(new_builder, sample_model, used_buffers_dic)

    # Generate model
    tflite.Model.ModelStart(new_builder)
    tflite.Model.ModelAddVersion(new_builder, version)
    tflite.Model.ModelAddOperatorCodes(new_builder, operator_codes)
    tflite.Model.ModelAddSubgraphs(new_builder, subgraphs)
    tflite.Model.ModelAddDescription(new_builder, description_string)
    tflite.Model.ModelAddBuffers(new_builder, buffers)

    return tflite.Model.ModelEnd(new_builder)


def Finish(new_builder, new_model):
    # Cusrom implementation: identifier
    # Python API don't support identifier input yet
    # Reference: Finish(self, rootTable)) in builder.py, Finish(uoffset_t root, const char *file_identifier, bool size_prefix) in flatbuffers.h
    new_builder.Prep(new_builder.minalign,
                     flatbuffers.number_types.UOffsetTFlags.bytewidth)

    new_builder.PrependByte(0x33)
    new_builder.PrependByte(0x4c)
    new_builder.PrependByte(0x46)
    new_builder.PrependByte(0x54)

    new_builder.PrependUOffsetTRelative(new_model)
    new_builder.finished = True
    return new_builder.Head()


def main(args):
    input_model_file = args.input_model
    oplist_file = args.opcode_list
    output_model_file = args.output_model

    # Parse operator list file
    opcode_list = GetOperatorList(oplist_file)

    # Get sample model and subgraph
    # We use only 1st subgraph
    sample_buf = input_model_file.read()
    sample_buf = bytearray(sample_buf)
    sample_model = tflite.Model.Model.GetRootAsModel(sample_buf, 0)
    sample_subgraph = sample_model.Subgraphs(0)

    # Collect used tensor & used operator
    used_tensors = []
    used_operators = []

    for opcode_idx in opcode_list:
        opcode = sample_subgraph.Operators(opcode_idx)
        for input_idx in range(opcode.InputsLength()):
            input_tensor_idx = opcode.Inputs(input_idx)
            if not input_tensor_idx in used_tensors:
                # default: same as input sample
                used_tensors.append(input_tensor_idx)

        for output_idx in range(opcode.OutputsLength()):
            output_tensor_idx = opcode.Outputs(output_idx)
            if not output_tensor_idx in used_tensors:
                # default: same as input sample
                used_tensors.append(output_tensor_idx)

        opcode_idx = opcode.OpcodeIndex()
        if not opcode_idx in used_operators:
            used_operators.append(opcode_idx)

    used_tensors.sort()
    used_operators.sort()

    # Collect used buffer
    # buffer[0] should be blank. So it should start from 1
    used_buffers = [0]

    for used_tensor in used_tensors:
        # key and value is same in prepare phase
        buf_idx = (sample_subgraph.Tensors(used_tensor)).Buffer()
        used_buffers.append(buf_idx)
    used_buffers.sort()

    # Assign new index for operator
    used_operators_dic = {}

    for new_operator_idx in range(len(used_operators)):
        sample_operator_idx = used_operators[new_operator_idx]
        used_operators_dic[sample_operator_idx] = new_operator_idx

    # Assign new index for tensor
    used_tensors_dic = {}

    for new_tensor_idx in range(len(used_tensors)):
        sample_tensor_idx = used_tensors[new_tensor_idx]
        used_tensors_dic[sample_tensor_idx] = new_tensor_idx

    # Assign new index for buffer
    used_buffers_dic = {}

    for new_buffer_idx in range(len(used_buffers)):
        sample_buffer_idx = used_buffers[new_buffer_idx]
        used_buffers_dic[sample_buffer_idx] = new_buffer_idx

    # Find input & output tensor in new model
    new_input_tensors = used_tensors[:]
    new_output_tensors = used_tensors[:]

    for opcode_idx in opcode_list:
        opcode = sample_subgraph.Operators(opcode_idx)
        for input_idx in range(opcode.InputsLength()):
            input_tensor_idx = opcode.Inputs(input_idx)
            if input_tensor_idx in new_output_tensors:
                new_output_tensors.remove(input_tensor_idx)
            if input_tensor_idx in new_input_tensors:
                matched_buffer_idx = sample_subgraph.Tensors(input_tensor_idx).Buffer()
                matched_buffer = sample_model.Buffers(matched_buffer_idx)
                if matched_buffer.DataLength() != 0:
                    new_input_tensors.remove(input_tensor_idx)

        for output_idx in range(opcode.OutputsLength()):
            output_tensor_idx = opcode.Outputs(output_idx)
            if output_tensor_idx in new_input_tensors:
                new_input_tensors.remove(output_tensor_idx)
            if output_tensor_idx in new_output_tensors:
                matched_buffer_idx = sample_subgraph.Tensors(output_tensor_idx).Buffer()
                matched_buffer = sample_model.Buffers(matched_buffer_idx)
                if matched_buffer.DataLength() != 0:
                    new_output_tensors.remove(input_tensor_idx)

    new_input_tensors_newidx = []
    new_output_tensors_newidx = []

    for input_tensor_idx in new_input_tensors:
        new_input_tensors_newidx.append(used_tensors_dic[input_tensor_idx])
    for output_tensor_idx in new_output_tensors:
        new_output_tensors_newidx.append(used_tensors_dic[output_tensor_idx])

    print("Input tensor(s): " + str(new_input_tensors_newidx))
    print("Output tensor(s): " + str(new_output_tensors_newidx))

    # Create new model file
    new_builder = flatbuffers.Builder(1024)

    new_model = GenerateModel(new_builder, sample_model, opcode_list, new_input_tensors,
                              new_output_tensors, used_tensors_dic, used_buffers_dic,
                              used_operators_dic)

    Finish(new_builder, new_model)
    new_buf = new_builder.Output()

    output_model_file.write(new_buf)


if __name__ == '__main__':
    # Define argument and read
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument(
        "input_model",
        type=argparse.FileType('rb'),
        help="input tflite model file to read")
    arg_parser.add_argument(
        "opcode_list",
        type=argparse.FileType('r'),
        help="text file including selected operator list")
    arg_parser.add_argument(
        "output_model", type=argparse.FileType('wb'), help="output tflite model file")
    args = arg_parser.parse_args()

    # Call main function
    main(args)