forked from HIT-SCIR/ltp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser_dll.cpp
101 lines (79 loc) · 2.6 KB
/
parser_dll.cpp
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
#include "parser_dll.h"
#include "parser.h"
#include "settings.h"
#include "logging.hpp"
#include "codecs.hpp"
#include <iostream>
class ParserWrapper : public ltp::parser::Parser {
public:
ParserWrapper() {}
~ParserWrapper() {}
bool load(const char * model_file) {
std::ifstream mfs(model_file, std::ifstream::binary);
if (!mfs) {
return false;
}
model = new ltp::parser::Model;
if (!model->load(mfs)) {
delete model;
return false;
}
// ltp::parser::Parser::build_decoder();
return true;
}
int parse(const std::vector<std::string> & words,
const std::vector<std::string> & postags,
std::vector<int> & heads,
std::vector<std::string> & deprels) {
if (words.size() != postags.size()) {
return -1;
}
ltp::parser::Instance * inst = new ltp::parser::Instance;
inst->forms.push_back( ltp::parser::ROOT_FORM );
inst->postags.push_back( ltp::parser::ROOT_POSTAG );
for (int i = 0; i < words.size(); ++ i) {
inst->forms.push_back(words[i]);
inst->postags.push_back(postags[i]);
}
ltp::parser::Parser::extract_features(inst);
ltp::parser::Parser::calculate_score(inst, ltp::parser::Parser::model->param);
ltp::parser::Decoder * deco;
deco = build_decoder();
deco->decode(inst);
int len = inst->size();
heads.resize(len - 1);
deprels.resize(len - 1);
for (int i = 1; i < len; ++ i) {
heads[i - 1] = inst->predicted_heads[i];
deprels[i - 1] = ltp::parser::Parser::model->deprels.at(
inst->predicted_deprelsidx[i]);
}
delete inst;
delete deco;
return inst->size();
}
};
void * parser_create_parser(const char * path) {
ParserWrapper * wrapper = new ParserWrapper();
if (!wrapper->load(path)) {
return 0;
}
return reinterpret_cast<void *>(wrapper);
}
int parser_release_parser(void * parser) {
if (!parser) {
return -1;
}
delete reinterpret_cast<ParserWrapper *>(parser);
return 0;
}
int parser_parse(void * parser,
const std::vector<std::string> & words,
const std::vector<std::string> & postags,
std::vector<int> & heads,
std::vector<std::string> & deprels) {
// std::cout << "input str = " << str << std::endl;
ParserWrapper * wrapper = 0;
wrapper = reinterpret_cast<ParserWrapper *>(parser);
return wrapper->parse(words, postags, heads, deprels);
}