Imported Upstream version 1.8.0
[platform/core/ml/nnfw.git] / compiler / circlechef / tools / file / Driver.cpp
1 /*
2  * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
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 #include "circlechef/ModelChef.h"
18
19 #include <google/protobuf/io/coded_stream.h>
20 #include <google/protobuf/io/zero_copy_stream_impl.h>
21 #include <google/protobuf/text_format.h>
22
23 #include <arser/arser.h>
24
25 #include <fstream>
26 #include <iostream>
27
28 int entry(int argc, char **argv)
29 {
30   arser::Arser arser;
31   arser.add_argument("recipe")
32       .type(arser::DataType::STR)
33       .help("Source recipe file path to convert");
34   arser.add_argument("circle").type(arser::DataType::STR).help("Target circle file path");
35
36   try
37   {
38     arser.parse(argc, argv);
39   }
40   catch (const std::runtime_error &err)
41   {
42     std::cout << err.what() << std::endl;
43     std::cout << arser;
44     return 255;
45   }
46
47   int32_t model_version = 1;
48
49   ::circlechef::ModelRecipe model_recipe;
50
51   std::string recipe_path = arser.get<std::string>("recipe");
52   // Load model recipe from a file
53   {
54     std::ifstream is{recipe_path};
55     google::protobuf::io::IstreamInputStream iis{&is};
56     if (!google::protobuf::TextFormat::Parse(&iis, &model_recipe))
57     {
58       std::cerr << "ERROR: Failed to parse recipe '" << recipe_path << "'" << std::endl;
59       return 255;
60     }
61
62     if (model_recipe.has_version())
63     {
64       model_version = model_recipe.version();
65     }
66   }
67
68   if (model_version > 1)
69   {
70     std::cerr << "ERROR: Unsupported recipe version: " << model_version << ", '" << recipe_path
71               << "'" << std::endl;
72     return 255;
73   }
74
75   auto generated_model = circlechef::cook(model_recipe);
76
77   std::string circle_path = arser.get<std::string>("circle");
78   // Dump generated model into a file
79   {
80     std::ofstream os{circle_path, std::ios::binary};
81     os.write(generated_model.base(), generated_model.size());
82   }
83
84   return 0;
85 }