Imported Upstream version 1.6.4
[platform/upstream/openfst.git] / src / script / text-io.cc
1 // See www.openfst.org for extensive documentation on this weighted
2 // finite-state transducer library.
3
4 #include <fst/script/text-io.h>
5
6 #include <cstring>
7 #include <fstream>
8 #include <ostream>
9 #include <sstream>
10 #include <utility>
11
12 #include <fst/types.h>
13 #include <fst/log.h>
14 #include <fstream>
15 #include <fst/util.h>
16
17 namespace fst {
18 namespace script {
19
20 // Reads vector of weights; returns true on success.
21 bool ReadPotentials(const string &weight_type, const string &filename,
22                     std::vector<WeightClass> *potentials) {
23   std::ifstream istrm(filename);
24   if (!istrm.good()) {
25     LOG(ERROR) << "ReadPotentials: Can't open file: " << filename;
26     return false;
27   }
28   static const int kLineLen = 8096;
29   char line[kLineLen];
30   size_t nline = 0;
31   potentials->clear();
32   while (!istrm.getline(line, kLineLen).fail()) {
33     ++nline;
34     std::vector<char *> col;
35     SplitToVector(line, "\n\t ", &col, true);
36     if (col.empty() || col[0][0] == '\0') continue;
37     if (col.size() != 2) {
38       FSTERROR() << "ReadPotentials: Bad number of columns, "
39                  << "file = " << filename << ", line = " << nline;
40       return false;
41     }
42     const ssize_t s = StrToInt64(col[0], filename, nline, false);
43     const WeightClass weight(weight_type, col[1]);
44     while (potentials->size() <= s) {
45       potentials->push_back(WeightClass::Zero(weight_type));
46     }
47     potentials->back() = weight;
48   }
49   return true;
50 }
51
52 // Writes vector of weights; returns true on success.
53 bool WritePotentials(const string &filename,
54                      const std::vector<WeightClass> &potentials) {
55   std::ofstream ostrm;
56   if (!filename.empty()) {
57     ostrm.open(filename);
58     if (!ostrm.good()) {
59       LOG(ERROR) << "WritePotentials: Can't open file: " << filename;
60       return false;
61     }
62   }
63   std::ostream &strm = ostrm.is_open() ? ostrm : std::cout;
64   strm.precision(9);
65   for (size_t s = 0; s < potentials.size(); ++s) {
66     strm << s << "\t" << potentials[s] << "\n";
67   }
68   if (strm.fail()) {
69     LOG(ERROR) << "WritePotentials: Write failed: "
70                << (filename.empty() ? "standard output" : filename);
71     return false;
72   }
73   return true;
74 }
75
76 }  // namespace script
77 }  // namespace fst