1 // Copyright 2005-2020 Google LLC
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 // See www.openfst.org for extensive documentation on this weighted
16 // finite-state transducer library.
17 //
18 // Composes two FSTs.
19 
20 #include <cstring>
21 #include <memory>
22 #include <string>
23 
24 #include <fst/flags.h>
25 #include <fst/log.h>
26 #include <fst/script/compose.h>
27 #include <fst/script/getters.h>
28 
29 DECLARE_string(compose_filter);
30 DECLARE_bool(connect);
31 
fstcompose_main(int argc,char ** argv)32 int fstcompose_main(int argc, char **argv) {
33   namespace s = fst::script;
34   using fst::ComposeFilter;
35   using fst::ComposeOptions;
36   using fst::script::FstClass;
37   using fst::script::VectorFstClass;
38 
39   std::string usage = "Composes two FSTs.\n\n  Usage: ";
40   usage += argv[0];
41   usage += " in1.fst in2.fst [out.fst]\n";
42 
43   std::set_new_handler(FailedNewHandler);
44   SET_FLAGS(usage.c_str(), &argc, &argv, true);
45   if (argc < 3 || argc > 4) {
46     ShowUsage();
47     return 1;
48   }
49 
50   const std::string in1_name = strcmp(argv[1], "-") != 0 ? argv[1] : "";
51   const std::string in2_name =
52       (argc > 2 && (strcmp(argv[2], "-") != 0)) ? argv[2] : "";
53   const std::string out_name =
54       (argc > 3 && (strcmp(argv[3], "-") != 0)) ? argv[3] : "";
55 
56   if (in1_name.empty() && in2_name.empty()) {
57     LOG(ERROR) << argv[0] << ": Can't take both inputs from standard input";
58     return 1;
59   }
60 
61   std::unique_ptr<FstClass> ifst1(FstClass::Read(in1_name));
62   if (!ifst1) return 1;
63 
64   std::unique_ptr<FstClass> ifst2(FstClass::Read(in2_name));
65   if (!ifst2) return 1;
66 
67   if (ifst1->ArcType() != ifst2->ArcType()) {
68     LOG(ERROR) << argv[0] << ": Input FSTs must have the same arc type";
69     return 1;
70   }
71 
72   VectorFstClass ofst(ifst1->ArcType());
73 
74   ComposeFilter compose_filter;
75   if (!s::GetComposeFilter(FST_FLAGS_compose_filter,
76                            &compose_filter)) {
77     LOG(ERROR) << argv[0] << ": Unknown or unsupported compose filter type: "
78                << FST_FLAGS_compose_filter;
79     return 1;
80   }
81 
82   const ComposeOptions opts(FST_FLAGS_connect, compose_filter);
83 
84   s::Compose(*ifst1, *ifst2, &ofst, opts);
85 
86   return !ofst.Write(out_name);
87 }
88