File size: 6,968 Bytes
55f12b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/*
   Moses - statistical machine translation system
   Copyright (C) 2005-2015 University of Edinburgh

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/


#include <vector>
#include <string>
#include <sstream>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
#include <boost/program_options.hpp>
#include "util/file_stream.hh"
#include "util/file.hh"
#include "util/file_piece.hh"
#include "util/string_piece.hh"
#include "util/tokenize_piece.hh"

namespace po = boost::program_options;


int main(int argc, char **argv)
{
  util::FileStream err(2);

  std::string filenameNBestListIn, filenameFeatureNamesOut, filenameIgnoreFeatureNames;
  size_t maxNBestSize;

  try {

    po::options_description descr("Usage");
    descr.add_options()
      ("help,h", "produce help message")
      ("n-best-list,n", po::value<std::string>(&filenameNBestListIn)->required(), 
       "input n-best list file")
      ("write-feature-names-file,f", po::value<std::string>(&filenameFeatureNamesOut)->required(), 
       "output file for mapping between feature names and indices")
      ("ignore-features-file,i", po::value<std::string>(&filenameIgnoreFeatureNames)->required(), 
       "input file containing list of feature names to be ignored")
      ("n-best-size-limit,l", po::value<size_t>(&maxNBestSize)->default_value(100), 
       "limit of n-best list entries to be considered")
      ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, descr), vm);

    if (vm.count("help")) {
      std::ostringstream os;
      os << descr;
      std::cout << os.str() << '\n';
      exit(0);
    }

    po::notify(vm);

  } catch(std::exception& e) {

    err << "Error: " << e.what() << '\n';
    err.flush();
    exit(1);
  }

  util::FilePiece ifsNBest(filenameNBestListIn.c_str());
  util::FilePiece ifsIgnoreFeatureNames(filenameIgnoreFeatureNames.c_str());
  util::scoped_fd fdFeatureNames(util::CreateOrThrow(filenameFeatureNamesOut.c_str()));
  util::FileStream ofsFeatureNames(fdFeatureNames.get());
  util::FileStream ofsNBest(1);

  boost::unordered_set<std::string> ignoreFeatureNames;
  StringPiece line;

  while ( ifsIgnoreFeatureNames.ReadLineOrEOF(line) )
  {
    if ( !line.empty() ) {
      util::TokenIter<util::AnyCharacter> item(line, " \t=");
      if ( item != item.end() )
      {
        ignoreFeatureNames.insert(item->as_string());
      }
      err << "ignoring " << *item << '\n';
    }
  }

  size_t maxFeatureNamesIdx = 0;
  boost::unordered_map<std::string, size_t> featureNames;

  size_t sentenceIndex = 0;
  size_t nBestSizeCount = 0;
  size_t globalIndex = 0;

  while ( ifsNBest.ReadLineOrEOF(line) )
  {
    util::TokenIter<util::MultiCharacter> item(line, " ||| ");

    if ( item == item.end() )
    {
      err << "Error: flawed content in " << filenameNBestListIn << '\n';
      exit(1);
    }

    size_t sentenceIndexCurrent = atol( item->as_string().c_str() );

    if ( sentenceIndex != sentenceIndexCurrent )
    {
      nBestSizeCount = 0;
      sentenceIndex = sentenceIndexCurrent;
    }

    if ( nBestSizeCount < maxNBestSize )
    {
      // process n-best list entry
      
      StringPiece scores;
      StringPiece decoderScore;
      for (size_t nItem=1; nItem<=3; ++nItem) 
      {
        if ( ++item == item.end() ) {
          err << "Error: flawed content in " << filenameNBestListIn << '\n';
          exit(1);
        }
        if (nItem == 2) {
          scores = *item;
        }
        if (nItem == 3) {
          decoderScore = *item;
        }
      }

      ofsNBest << sentenceIndex << ' ' 
               << decoderScore;

      util::TokenIter<util::SingleCharacter> token(scores, ' ');
      std::string featureNameCurrent("ERROR");
      std::string featureNameCurrentBase("ERROR");
      bool ignore = false;
      int scoreComponentIndex = 0;
      
      while ( token != token.end() )
      {
        if ( token->ends_with("=") )
        {
          scoreComponentIndex = 0;
          featureNameCurrent = token->substr(0,token->size()-1).as_string();
          size_t idx = featureNameCurrent.find_first_of('_');
          if ( idx == StringPiece::npos ) {
            featureNameCurrentBase = featureNameCurrent;
          } else {
            featureNameCurrentBase = featureNameCurrent.substr(0,idx+1);
          }
          ignore = false;
          if ( ignoreFeatureNames.find(featureNameCurrentBase) != ignoreFeatureNames.end() )
          {
            ignore = true;
          } else {
            if ( (featureNameCurrent.compare(featureNameCurrentBase)) &&
                 (ignoreFeatureNames.find(featureNameCurrent) != ignoreFeatureNames.end()) )
            {
              ignore = true;
            } 
          }
        }
        else
        {
          if ( !ignore )
          {
            float featureValueCurrent = atof( token->as_string().c_str() );;
            if ( scoreComponentIndex > 0 )
            {
              std::ostringstream oss;
              oss << scoreComponentIndex;
              featureNameCurrent.append("+");
            }
            if ( featureValueCurrent != 0 )
            {
              boost::unordered_map<std::string, size_t>::iterator featureName = featureNames.find(featureNameCurrent);

              if ( featureName == featureNames.end() )
              {
                std::pair< boost::unordered_map<std::string, size_t>::iterator, bool> inserted = 
                  featureNames.insert( std::make_pair(featureNameCurrent, maxFeatureNamesIdx) );
                ++maxFeatureNamesIdx;
                featureName = inserted.first;
              }

              ofsNBest << ' ' << featureName->second // feature name index
                       << ' ' << *token;             // feature value
            }
            ++scoreComponentIndex;
          }
        }
        ++token;
      }
      ofsNBest << '\n';
      ++nBestSizeCount;
    }
    ++globalIndex;
  }

  ofsFeatureNames << maxFeatureNamesIdx << '\n';
  for (boost::unordered_map<std::string, size_t>::const_iterator featureNamesIt=featureNames.begin();
       featureNamesIt!=featureNames.end(); ++featureNamesIt)
  {
    ofsFeatureNames << featureNamesIt->second << ' ' << featureNamesIt->first << '\n';
  }

}