-
Notifications
You must be signed in to change notification settings - Fork 44
/
path_diff.cc
360 lines (298 loc) · 9.1 KB
/
path_diff.cc
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
//
// Created by Arseny Tolmachev on 2017/12/03.
//
#include <fstream>
#include <iostream>
#include "args.h"
#include "core/analysis/analyzer_impl.h"
#include "jpp_jumandic_cg.h"
#include "jumandic/shared/jumandic_env.h"
struct PathDiffConf {
bool posAreOk;
std::string modelFile;
std::string inputFile;
std::string outputFile;
static PathDiffConf parse(int argc, const char* argv[]) {
args::ArgumentParser parser{"Path Differ"};
args::Positional<std::string> model{parser, "model", "model"};
args::Positional<std::string> input{parser, "input", "input"};
args::Flag negativeOnly{parser, "output pos", "output positive", {"pos"}};
try {
parser.ParseCLI(argc, argv);
} catch (std::exception& e) {
std::cerr << e.what();
exit(1);
}
PathDiffConf inst;
inst.modelFile = model.Get();
inst.inputFile = input.Get();
inst.posAreOk = negativeOnly.Get();
return inst;
}
};
using namespace jumanpp;
struct NamedStringField {
std::string name;
std::shared_ptr<core::analysis::StringField> field;
};
struct ScoredNode {
core::analysis::LatticeNodePtr ptr;
float score;
};
struct RenderContext {
util::FlatMap<i32, NamedStringField> fields;
i32 surfaceIdx;
const core::analysis::OutputManager* om;
Status init(const core::CoreHolder& core,
const core::analysis::OutputManager& om) {
auto& spec = core.spec();
for (auto& trFld : spec.training.fields) {
auto& dicFld = spec.dictionary.fields[trFld.fieldIdx];
if (trFld.weight != 0) {
auto& fld = fields[trFld.dicIdx];
fld.field.reset(new core::analysis::StringField);
JPP_RIE_MSG(om.stringField(dicFld.name, fld.field.get()),
"field=" << dicFld.name);
fld.name = dicFld.name;
}
}
surfaceIdx = spec.training.fields[spec.training.surfaceIdx].dicIdx;
this->om = &om;
return Status::Ok();
}
bool renderFull(std::ostream& os, core::analysis::LatticeNodePtr lnp,
StringPiece prefix) {
auto w = om->nodeWalker();
JPP_RET_CHECK(om->locate(lnp, &w));
auto& sfld = fields[surfaceIdx];
auto surface = (*sfld.field)[w];
os << prefix << surface;
for (auto& f : fields) {
if (f.first == surfaceIdx) {
continue;
}
auto value = (*f.second.field)[w];
if (value.empty()) {
continue;
}
if (value == surface) {
continue;
}
os << "\t" << f.second.name << ":" << value;
}
return true;
}
bool renderSurface(std::ostream& os, core::analysis::LatticeNodePtr lnp) {
auto w = om->nodeWalker();
JPP_RET_CHECK(om->locate(lnp, &w));
auto& sfld = fields[surfaceIdx];
auto surface = (*sfld.field)[w];
os << surface;
return true;
}
};
struct DiffNode {
std::vector<ScoredNode> left;
std::vector<ScoredNode> right;
bool isEqual = true;
bool isEqualNode() const { return isEqual; }
void addLeft(const core::analysis::ConnectionPtr* ptr,
const core::analysis::Lattice* l) {
left.push_back(makeNode(ptr, l));
}
void addRight(const core::analysis::ConnectionPtr* ptr,
const core::analysis::Lattice* l) {
right.push_back(makeNode(ptr, l));
}
static ScoredNode makeNode(const core::analysis::ConnectionPtr* ptr,
const core::analysis::Lattice* l) {
auto bnd = l->boundary(ptr->boundary)->starts();
auto beam = bnd->beamData().row(ptr->right).at(ptr->beam);
return {ptr->latticeNodePtr(), beam.totalScore};
}
std::ostream& render(std::ostream& o, RenderContext& leftCtx,
bool writeRight) const {
if (left.empty()) {
return o;
}
if (isEqual) {
o << "\n";
}
for (auto it = left.rbegin(); it != left.rend(); ++it) {
if (isEqual) {
leftCtx.renderSurface(o, it->ptr);
} else {
leftCtx.renderFull(o, it->ptr, "\n\t");
}
}
return o;
}
std::ostream& renderInvalid(std::ostream& o, RenderContext& leftCtx,
bool writeRight) const {
for (auto it = right.rbegin(); it != right.rend(); ++it) {
if (!isEqual) {
leftCtx.renderFull(o, it->ptr, "\n# ");
}
}
return o;
}
};
struct PathDiffCalculator {
jumanpp::core::JumanppEnv env;
jumanpp::core::analysis::Analyzer full;
jumanpp::core::analysis::Analyzer gbeam;
RenderContext leftCtx;
bool outputPos;
core::analysis::rnn::RnnInferenceConfig rnnConf;
std::vector<DiffNode> nodes;
float topLeft;
float topRight;
PathDiffCalculator() {
rnnConf.rnnWeight = 0;
rnnConf.perceptronWeight = 1;
}
Status init(const PathDiffConf& conf) {
JPP_RETURN_IF_ERROR(env.loadModel(conf.modelFile));
env.setRnnConfig(rnnConf);
jumanpp_generated::JumandicStatic staticFeatures;
JPP_RETURN_IF_ERROR(env.initFeatures(&staticFeatures));
env.setBeamSize(10);
JPP_RETURN_IF_ERROR(env.makeAnalyzer(&full));
env.setBeamSize(5);
env.setGlobalBeam(5, 1, 5);
JPP_RETURN_IF_ERROR(env.makeAnalyzer(&gbeam));
JPP_RETURN_IF_ERROR(leftCtx.init(*env.coreHolder(), full.output()));
outputPos = conf.posAreOk;
return Status::Ok();
}
void fillDiff(const core::analysis::Lattice* l1,
const core::analysis::Lattice* l2,
const core::analysis::ConnectionPtr* top1x,
const core::analysis::ConnectionPtr* top2x) {
nodes.emplace_back();
auto* b = &nodes.back();
auto top1 = top1x;
auto top2 = top2x;
while (top1->boundary >= 2 && top2->boundary >= 2) {
if (top1->latticeNodePtr() == top2->latticeNodePtr()) {
if (!b->isEqualNode()) {
nodes.emplace_back();
b = &nodes.back();
}
if (top1 != top1x) {
b->addLeft(top1, l1);
}
top1 = top1->previous;
top2 = top2->previous;
} else {
if (b->isEqualNode()) {
nodes.emplace_back();
b = &nodes.back();
b->isEqual = false;
}
if (top1->boundary == top2->boundary) {
b->addLeft(top1, l1);
b->addRight(top2, l2);
top1 = top1->previous;
top2 = top2->previous;
} else if (top1->boundary > top2->boundary) {
b->addLeft(top1, l1);
top1 = top1->previous;
} else {
b->addRight(top2, l2);
top2 = top2->previous;
}
}
}
}
bool hasUnks(const core::analysis::ConnectionPtr* element,
const core::analysis::Lattice* lat) {
while (element->boundary > 1) {
auto bnd = lat->boundary(element->boundary)->starts();
auto& info = bnd->nodeInfo().at(element->right);
if (info.entryPtr().isSpecial()) {
return true;
}
element = element->previous;
}
return false;
}
Status computeDiff(StringPiece sentence) {
JPP_RETURN_IF_ERROR(full.analyze(sentence));
JPP_RETURN_IF_ERROR(gbeam.analyze(sentence));
auto l1 = full.impl()->lattice();
auto l2 = gbeam.impl()->lattice();
auto top1 = l1->boundary(l1->createdBoundaryCount() - 1)
->starts()
->beamData()
.at(0);
auto top2 = l2->boundary(l1->createdBoundaryCount() - 1)
->starts()
->beamData()
.at(0);
nodes.clear();
if (hasUnks(top1.ptr.previous, l1) || hasUnks(top2.ptr.previous, l2)) {
// unks should not be here
return Status::Ok();
}
if (outputPos && top2.totalScore > -0.1f) {
return Status::Ok(); // known-ish example
}
if (top1.totalScore - top2.totalScore <= 0.1f) {
return Status::Ok(); // scores are not distant enough
}
fillDiff(l1, l2, &top1.ptr, &top2.ptr);
topLeft = top1.totalScore;
topRight = top2.totalScore;
return Status::Ok();
}
void renderDiff(std::ostream& os) {
for (auto it = nodes.rbegin(); it != nodes.rend(); ++it) {
it->render(os, leftCtx, false);
}
}
void renderInvalid(std::ostream& os) {
for (auto it = nodes.rbegin(); it != nodes.rend(); ++it) {
it->renderInvalid(os, leftCtx, false);
}
}
};
int main(int argc, const char* argv[]) {
auto conf = PathDiffConf::parse(argc, argv);
PathDiffCalculator calc;
Status s = calc.init(conf);
if (!s) {
std::cerr << s;
return 1;
}
std::ifstream ifs{conf.inputFile};
std::string comment;
std::string data;
i64 line = 0;
while (std::getline(ifs, data)) {
++line;
if (data.size() > 2 && data[0] == '#' && data[1] == ' ') {
comment.assign(data.begin() + 2, data.end());
continue;
}
s = calc.computeDiff(data);
if (!s) {
std::cerr << "failed to analyze " << comment << " [" << data << "]: " << s
<< "\n";
continue;
}
if (!calc.nodes.empty()) {
std::cout << "# scores: " << calc.topLeft << " " << calc.topRight;
calc.renderInvalid(std::cout);
if (!comment.empty()) {
std::cout << "\n# " << comment;
} else {
std::cout << "\n# line-" << line;
}
calc.renderDiff(std::cout);
std::cout << "\n\n";
}
comment.clear();
}
return 0;
}