OpenFst Example: Using User Defined Flags

In this OpenFst sample I will show you how to create a tool in the style of the library tools and add a custom command option (user define flag) that does not require the compilation of the whole library.

The below testfst.cpp file calls parses the command options and calls a main function that essentially does nothing. The DEFINE_double macros is used to define our flag names test_flag in this case.

 

#include "test-main.h"

 

namespace fst

{

  REGISTER_FST_MAIN(TestMain, StdArc); 

  REGISTER_FST_MAIN(TestMain, LogArc);

 

DEFINE_double(myflag, 1234, "My Flag");

using fst::CallFstMain;

int main(int argc, char **argv)

{

  string usage = "Test flags \n\n  Usage: ";

  usage += argv[0];

  usage += "  Flags: myflag\n";

  std::set_new_handler(FailedNewHandler);

  SetFlags(usage.c_str(), &argc, &argv, true);

  if (argc !=1)

  {

    ShowUsage();

    return 1;

  }

  return CallFstMain("TestMain", argc, argv, FLAGS_arc_type);

}

The corresponding test-main.h files is the actual main function that just echo value of myflag a corresponding DECLAR_double macro.

#ifndef TEST_MAIN_H__

#define TEST_MAIN_H__

 

#include <fst/main.h>

DECLARE_double(myflag);

DECLARE_string(arc_type);

 

namespace fst

{

 

  template <class Arc>

  int TestMain(int argc, char **argv, istream&, const FstReadOptions&)

  {

 

    cout << "myflag=" << FLAGS_myflag << endl;

      return 0;

  }

#endif 

Next compile with:

g++ fsttest.cpp -lfstmain -lfst -ldl -o fsttest

Running the help option we see our new flag in the help options.

fsttest –help

..

..

--delta: type = double, default = 0.000976562
      Comparison/quantization delta
    --height: type = double, default = 11
      Set height
    --myflag: type = double, default = 1234
      My Flag
    --nodesep: type = double, default = 0.25
      Set minimum separation between nodes (see dot documentation)
    --ranksep: type = double, default = 0.4

..

And double check for a few values

$/fsttest --myflag=10
myflag=10

$ ./fsttest --myflag=-2.2134234
myflag=-2.21342

My two feature request are the shorthand versions, for example –i for –isymbols and that a tool only displays it relevant options.

This entry was posted by Edobashira. Bookmark the permalink.