1 2// Licensed under the Apache License, Version 2.0 (the "License"); 3// you may not use this file except in compliance with the License. 4// You may obtain a copy of the License at 5// 6// http://www.apache.org/licenses/LICENSE-2.0 7// 8// Unless required by applicable law or agreed to in writing, software 9// distributed under the License is distributed on an "AS IS" BASIS, 10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11// See the License for the specific language governing permissions and 12// limitations under the License. 13// 14// Copyright 2005-2010 Google, Inc. 15// Author: jpr@google.com (Jake Ratkiewicz) 16 17#include <fst/script/text-io.h> 18 19#include <cstring> 20#include <sstream> 21#include <utility> 22using std::pair; using std::make_pair; 23 24#include <fst/types.h> 25#include <fst/util.h> 26 27namespace fst { 28namespace script { 29 30// Reads vector of weights; returns true on success. 31bool ReadPotentials(const string &weight_type, 32 const string& filename, 33 vector<WeightClass>* potential) { 34 ifstream strm(filename.c_str()); 35 if (!strm) { 36 LOG(ERROR) << "ReadPotentials: Can't open file: " << filename; 37 return false; 38 } 39 40 const int kLineLen = 8096; 41 char line[kLineLen]; 42 size_t nline = 0; 43 44 potential->clear(); 45 while (strm.getline(line, kLineLen)) { 46 ++nline; 47 vector<char *> col; 48 SplitToVector(line, "\n\t ", &col, true); 49 if (col.size() == 0 || col[0][0] == '\0') // empty line 50 continue; 51 if (col.size() != 2) { 52 LOG(ERROR) << "ReadPotentials: Bad number of columns, " 53 << "file = " << filename << ", line = " << nline; 54 return false; 55 } 56 57 ssize_t s = StrToInt64(col[0], filename, nline, false); 58 WeightClass weight(weight_type, col[1]); 59 60 while (potential->size() <= s) 61 potential->push_back(WeightClass::Zero()); 62 (*potential)[s] = weight; 63 } 64 return true; 65} 66 67// Writes vector of weights; returns true on success. 68bool WritePotentials(const string& filename, 69 const vector<WeightClass>& potential) { 70 ostream *strm = &std::cout; 71 if (!filename.empty()) { 72 strm = new ofstream(filename.c_str()); 73 if (!*strm) { 74 LOG(ERROR) << "WritePotentials: Can't open file: " << filename; 75 delete strm; 76 return false; 77 } 78 } 79 80 strm->precision(9); 81 for (ssize_t s = 0; s < potential.size(); ++s) 82 *strm << s << "\t" << potential[s] << "\n"; 83 84 if (!*strm) 85 LOG(ERROR) << "WritePotentials: Write failed: " 86 << (filename.empty() ? "standard output" : filename); 87 bool ret = *strm; 88 if (strm != &std::cout) 89 delete strm; 90 return ret; 91} 92 93 94} // namespace script 95} // namespace fst 96