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
|
/* Copyright (C) 2020 J.F.Dockes
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
// Specialized Korean text splitter using konlpy running in a Python
// subprocess. konlpy can use several different backends. We support
// Okt (Twitter) and Mecab at this point. Unfortunately the different
// backends have different POS TAG names, so that things are not
// completly transparent when using another (need to translate the tag
// names in the Python program).
#include "autoconfig.h"
#include "kosplitter.h"
#include <iostream>
#include <string>
#include <cstring>
#include <unordered_set>
#include <mutex>
#include <algorithm>
#include "textsplit.h"
#include "log.h"
//#define UTF8ITER_CHECK
#include "utf8iter.h"
#include "smallut.h"
#include "rclconfig.h"
#include "cmdtalk.h"
using namespace std;
// Separator char used in words and tags lists.
static const string sepchars("\t");
static CmdTalk *o_talker;
static bool o_starterror{false};
static string o_cmdpath;
static vector<string> o_cmdargs;
static std::mutex o_mutex;
static string o_taggername{"Okt"};
static bool isKomoran{false};
// The Python/Java splitter is leaking memory. We restart it from time to time
static uint64_t restartcount;
static uint64_t restartthreshold = 5 * 1000 * 1000;
static const string magicpage{"NEWPPPAGE"};
void koStaticConfInit(RclConfig *config, const string& tagger)
{
std::vector<std::string> cmdvec{"kosplitter.py"};
if (config->processFilterCmd(cmdvec)) {
auto it = cmdvec.begin();
o_cmdpath = *it++;
o_cmdargs.clear();
o_cmdargs.insert(o_cmdargs.end(), it, cmdvec.end());
}
if (tagger == "Okt" || tagger == "Mecab" || tagger == "Komoran") {
o_taggername = tagger;
if (tagger == "Komoran")
isKomoran = true;
} else {
LOGERR("TextSplit::koStaticConfInit: unknown tagger [" << tagger << "], using Okt\n");
}
}
// Start the Python subprocess
static bool initCmd()
{
if (o_starterror) {
// No use retrying
return false;
}
if (o_talker) {
if (restartcount > restartthreshold) {
delete o_talker;
o_talker = nullptr;
restartcount = 0;
} else {
return true;
}
}
if (o_cmdpath.empty()) {
return false;
}
if (nullptr == (o_talker = new CmdTalk(300))) {
o_starterror = true;
return false;
}
if (!o_talker->startCmd(o_cmdpath, o_cmdargs)) {
delete o_talker;
o_talker = nullptr;
o_starterror = true;
return false;
}
return true;
}
#define LOGKO LOGDEB1
#define STRSZT std::string::size_type
#define ISASCIIPUNCTORCTL(c) (c <= 0x7f && \
!((c >= 'A' && c <= 'Z') || \
(c >= 'a' && c <= 'z') || \
(c >= '0' && c <= '9')))
bool KOSplitter::text_to_words(Utf8Iter& it, unsigned int *cp, int& wordpos)
{
LOGDEB1("ko_to_words\n");
int flags = m_sink.flags();
std::unique_lock<std::mutex> mylock(o_mutex);
initCmd();
if (nullptr == o_talker) {
return false;
}
LOGDEB1("k_to_words: wordpos " << wordpos << "\n");
unsigned int c = 0;
unordered_map<string, string> args;
args.insert(pair<string,string>{"data", string()});
string& inputdata(args.begin()->second);
// We send the tagger name every time but it's only used the first
// one: can't change it after init. We could avoid sending it
// every time, but I don't think that the performance hit is
// significant
args.insert(pair<string,string>{"tagger", o_taggername});
// Walk the Korean characters section, and accumulate tagger
// input.
// While doing this, we compute spans (space-less chunks), which
// we will index in addition to the parts.
// We also strip some useless chars, and prepare page number computations.
STRSZT orgbytepos = it.getBpos();
bool wasspace{true};
STRSZT spanstart{0};
std::vector<std::pair<STRSZT, STRSZT>> spans;
for (; !it.eof() && !it.error(); it++) {
c = *it;
if (!TextSplit::isHANGUL(c) && !ISASCIIPUNCTORCTL(c)) {
// Non-Korean: we keep on if encountering space and other
// ASCII punctuation. Allows sending longer pieces of text
// to the splitter (perf). Else break, process this piece,
// and return to the main splitter
LOGKO("ko_to_words: broke on " << (std::string)it << endl);
break;
} else {
if (c == '\f') {
if (!wasspace) {
// End of span
spans.push_back({spanstart, inputdata.size()});
wasspace = true;
}
inputdata += magicpage + " ";
} else {
// Alpha was taken care of above. Keep only ascii
// numbers, replace all punctuation with spaces.
if (ISASCIIPUNCTORCTL(c)) {
if (!wasspace) {
// End of span
spans.push_back({spanstart, inputdata.size()});
wasspace = true;
}
inputdata += ' ';
} else {
if (wasspace) {
// Beginning of span
spanstart = inputdata.size();
wasspace = false;
}
it.appendchartostring(inputdata);
}
}
}
}
// Possible dangling span
if (!wasspace && inputdata.size() != spanstart) {
spans.push_back({spanstart, inputdata.size()});
}
LOGKO("TextSplit::k_to_words: sending out " << inputdata.size() <<
" bytes " << inputdata << endl);
// Overall data counter for slave restarts
restartcount += inputdata.size();
// Have the slave analyse the data, check that we get a result,
unordered_map<string,string> result;
if (!o_talker->talk(args, result)) {
LOGERR("Python splitter for Korean failed for [" << inputdata << "]\n");
return false;
}
// Split the resulting words and tags strings into vectors. This
// could be optimized (less data copying) by using positions
// instead.
auto resit = result.find("text");
if (resit == result.end()) {
LOGERR("No text in Python splitter for Korean\n");
return false;
}
string& outtext = resit->second;
vector<string> words;
stringToTokens(outtext, words, sepchars);
#if 0
// Actually we don't use the tags (word kind) any more, so don't
// compute them. KEEP the code around in case we want to show the
// tagger output further below
resit = result.find("tags");
if (resit == result.end()) {
LOGERR("No tags in Python splitter for Korean\n");
return false;
}
string& outtags = resit->second;
vector<string> tags;
stringToTokens(outtags, tags, sepchars);
#endif
// Process the words and their tags. Some versions selected on tag
// type (did not index everything, only Nouns, Verbs etc, but we
// just now process everything.
// bytepos is the position in the local fragment, not in the whole
// text which is orgbytepos + bytepos
STRSZT bytepos{0};
// Adjustment for our page markers
STRSZT pagefix{0};
// Current span
string span;
for (unsigned int i = 0; i < words.size(); i++) {
// The POS tagger strips characters from the input (e.g. multiple
// spaces, sometimes new lines, possibly other stuff). This
// means that we can't easily reconstruct the byte position
// from the concatenated terms. The output seems to be always
// shorter than the input, so we try to look ahead for the
// term. Can't be too sure that this works though, depending
// on exactly what transformation may have been applied from
// the original input to the term.
string word = words[i];
trimstring(word);
if (word == magicpage) {
LOGDEB1("ko_to_words: NEWPAGE\n");
m_sink.newpage(wordpos);
bytepos += word.size() + 1;
pagefix += word.size();
continue;
}
// Find the actual start position of the word in the section.
STRSZT newpos = inputdata.find(word, bytepos);
if (newpos != string::npos) {
bytepos = newpos;
} else {
LOGINF("textsplitko: word [" << word << "] not found in text\n");
}
STRSZT abspos = orgbytepos + bytepos - pagefix;
// See if we are at a span start position, emit a span if we are.
auto it = std::find_if(spans.begin(), spans.end(),
[bytepos] (const std::pair<STRSZT, STRSZT>& e){
return e.first == bytepos;
});
if (it != spans.end()) {
span = inputdata.substr(it->first, it->second-it->first);
LOGKO("KO: SPAN: [" << span << "] pos " << wordpos <<
" bytepos " << bytepos << "\n");
// Xapian max term length is 245 bytes. textsplit default
// max word is 40 bytes. Let's take into account the
// longer utf-8 Korean chars (usually 3 bytes).
if (int(span.size()) > 3 * m_sink.maxwordlength()) {
LOGINF("kosplitter: dropping span too long: " << span);
} else if (!m_sink.takeword(span, wordpos, abspos, abspos + span.size())) {
return false;
}
}
// Possibly emit a part of span word.
LOGKO("KO: WORD: [" << word << "] pos " << wordpos <<
" bytepos " << bytepos << "\n");
// Emit words only if not in onlyspans mode, and different
// from span. Else, just increase the position
if (!(flags & TextSplit::TXTS_ONLYSPANS) &&
(it == spans.end() || word != span)) {
if (!m_sink.takeword(word, wordpos, abspos, abspos + word.size())) {
return false;
}
} else {
LOGKO("KO: WORD: SKIP\n");
}
wordpos++;
bytepos += word.size();
}
#if DO_CHECK_THINGS
int sizediff = inputdata.size() - (bytepos - orgbytepos);
if (sizediff < 0)
sizediff = -sizediff;
if (sizediff > 1) {
LOGERR("ORIGINAL TEXT SIZE: " << inputdata.size() <<
" FINAL BYTE POS " << bytepos - orgbytepos <<
" TEXT [" << inputdata << "]\n");
}
#endif
// Return the found non-cjk Unicode character value. The current input byte offset is kept in
// the utf8Iter
*cp = c;
LOGDEB1("ko_to_words: returning\n");
return true;
}
|