Home | History | Annotate | Download | only in pdt
      1 // pdtreplace.cc
      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 // Copyright 2005-2010 Google, Inc.
     16 // Author: riley (at) google.com (Michael Riley)
     17 //
     18 // Converts an RTN represented by FSTs and non-terminal labels into a PDT .
     19 
     20 #include <utility>
     21 using std::pair; using std::make_pair;
     22 #include <vector>
     23 using std::vector;
     24 #include <fst/extensions/pdt/pdtscript.h>
     25 #include <fst/vector-fst.h>
     26 #include <fst/util.h>
     27 
     28 DEFINE_string(pdt_parentheses, "", "PDT parenthesis label pairs.");
     29 
     30 int main(int argc, char **argv) {
     31   namespace s = fst::script;
     32 
     33   string usage = "Converts an RTN represented by FSTs";
     34   usage += " and non-terminal labels into PDT";
     35   usage += " Usage: ";
     36   usage += argv[0];
     37   usage += " root.fst rootlabel [rule1.fst label1 ...] [out.fst]\n";
     38 
     39   std::set_new_handler(FailedNewHandler);
     40   SET_FLAGS(usage.c_str(), &argc, &argv, true);
     41   if (argc < 4) {
     42     ShowUsage();
     43     return 1;
     44   }
     45 
     46   string in_fname = argv[1];
     47   string out_fname = argc % 2 == 0 ? argv[argc - 1] : "";
     48 
     49   s::FstClass *ifst = s::FstClass::Read(in_fname);
     50   if (!ifst) return 1;
     51 
     52   typedef int64 Label;
     53   typedef pair<Label, const s::FstClass* > FstTuple;
     54   vector<FstTuple> fst_tuples;
     55   Label root = atoll(argv[2]);
     56   fst_tuples.push_back(make_pair(root, ifst));
     57 
     58   for (size_t i = 3; i < argc - 1; i += 2) {
     59     ifst = s::FstClass::Read(argv[i]);
     60     if (!ifst) return 1;
     61     Label lab = atoll(argv[i + 1]);
     62     fst_tuples.push_back(make_pair(lab, ifst));
     63   }
     64 
     65   s::VectorFstClass ofst(ifst->ArcType());
     66   vector<pair<int64, int64> > parens;
     67   s::PdtReplace(fst_tuples, &ofst, &parens, root);
     68 
     69   if (!FLAGS_pdt_parentheses.empty())
     70     fst::WriteLabelPairs(FLAGS_pdt_parentheses, parens);
     71 
     72   ofst.Write(out_fname);
     73 
     74   return 0;
     75 }
     76