LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
RnnTokenizer.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2022 CEA LIST <gael.de-chalendar@cea.fr>
2//
3// SPDX-License-Identifier: MIT
4
5#include <QtCore/QTemporaryFile>
6#include <QtCore/QRegularExpression>
7#include <QDir>
8#include <QFile>
9#include <QFileInfo>
10
17
25
26#include "RnnTokenizer.h"
27
30#include "deeplima/token_type.h"
31
32
33
34#define DEBUG_THIS_FILE true
35
37using namespace Lima::Common::PropertyCode;
38using namespace Lima::Common::MediaticData;
39using namespace Lima::Common::Misc;
41
42using namespace deeplima;
43
44namespace Lima
45{
46namespace LinguisticProcessing
47{
48namespace DeepLimaUnits
49{
50namespace RnnTokenizer
51{
52
54
55#if defined(DEBUG_LP) && defined(DEBUG_THIS_FILE)
56 #define LOG_MESSAGE(stream, msg) stream << msg;
57 #define LOG_MESSAGE_WITH_PROLOG(stream, msg) TOKENIZERLOGINIT; LOG_MESSAGE(stream, msg);
58#else
59 #define LOG_MESSAGE(stream, msg) ;
60 #define LOG_MESSAGE_WITH_PROLOG(stream, msg) ;
61#endif
62
64
66{
67 friend RnnTokenizer;
68public:
70 virtual ~RnnTokenizerPrivate();
71
73 {
75 TPrimitiveToken(const QString& w,
76 int pos,
77 const QString& orig=QString())
78 : wordText(w), originalText(orig), start(pos)
79 { }
80
81 QString wordText;
82 QString originalText;
83 int start;
84 };
85
86 void init(GroupConfigurationStructure& unitConfiguration);
87 void tokenize(const QString& text, std::vector<std::vector<TPrimitiveToken>>& sentences);
88
89protected:
90 void append_new_word(std::vector< TPrimitiveToken >& current_sentence,
91 const QString& current_token,
92 int current_token_offset,
93 token_flags_t flags) const;
94 void load_mwt_dictionary(const QString& file_name);
95
96 MediaId m_language;
99 QString m_data;
100
102
103 // Multiword tokens: surface -> syntactic words (French "du" -> "de", "le"),
104 // from the dictionary and affix rules beside the model, <model>.pt.mwt
106 // Expand only the tokens the segmenter flags as multiword, when its model
107 // predicts them (trained with --mwt); otherwise, every dictionary match
108 bool m_mwt_require_flag = false;
109
110 // Parameters
112
113 std::shared_ptr<segmentation::impl::SegmentationImpl> m_segm;
114
115 std::function<void()> m_load_fn;
117};
118
120 ConfigurationHelper("RnnTokenizerPrivate", THIS_FILE_LOGGING_CATEGORY()),
121 m_stringsPool(nullptr),
122 m_currentVx(0),
123 m_ignoreEOL(false),
124 m_segm(nullptr),
125 m_loaded(false)
126{
127}
128
132
137
139{
140 delete m_d;
141}
142
144 GroupConfigurationStructure& unitConfiguration,
145 Manager* manager)
146{
147 LOG_MESSAGE_WITH_PROLOG(LDEBUG, "RnnTokenizer::init");
148
149 m_d->m_language = manager->getInitializationParameters().media;
150 m_d->m_stringsPool = &MediaticData::changeable().stringsPool(m_d->m_language);
151
152 m_d->init(unitConfiguration);
153}
154
156{
158 LOG_MESSAGE_WITH_PROLOG(LINFO, "start tokenizer process");
159 TimeUtilsController RnnTokenizerProcessTime("RnnTokenizer");
160
161
162 auto anagraph = std::make_shared<AnalysisGraph>("AnalysisGraph", m_d->m_language, true, true);
163 analysis.setData("AnalysisGraph", anagraph);
164 auto graph = anagraph->getGraph();
165 m_d->m_currentVx = anagraph->firstVertex();
166 // Get text from analysis
167 auto originalText = std::dynamic_pointer_cast<LimaStringText>(analysis.getData("Text"));
168 if (originalText == nullptr)
169 {
171 LERROR << "Can't Process RnnTokenizer: missing data 'Text'";
172 return MISSING_DATA;
173 }
174
175 // Execute model on the text
176 std::vector< std::vector< RnnTokenizerPrivate::TPrimitiveToken > > sentencesTokens;
177 m_d->tokenize(*originalText, sentencesTokens);
178 LOG_MESSAGE(LDEBUG, " Number of token '" << sentencesTokens.size() << "'");
179
180 // Insert the tokens in the graph and create sentence limits
181 auto sb = std::make_shared<SegmentationData>("AnalysisGraph");
182 analysis.setData(m_d->m_data.toStdString(), sb);
183
184 // Remove the default 0 -> 1 edge before adding tokens
185 remove_edge(anagraph->firstVertex(),
186 anagraph->lastVertex(),
187 *graph);
188 LinguisticGraphVertex beginSentence = 0;
189
190 // Insert the tokens in the graph and create sentence limits
191 for (const auto& sentence: sentencesTokens)
192 {
193 if (sentence.size() < 1)
194 {
195 continue;
196 }
197
198 auto endSentence = std::numeric_limits< LinguisticGraphVertex >::max();
199 for (const auto& token: sentence)
200 {
201 const auto& str = token.wordText;
202
203 LOG_MESSAGE(LDEBUG, " Adding token '" << str << "'");
204
205 auto form = (*m_d->m_stringsPool)[str];
206 Token *tToken = new Token(form, str, token.start+1, token.wordText.size());
207 if (tToken == nullptr)
208 {
210 LERROR << "RnnFlowTokenizer::process: Can't allocate memory with \"new Token(...)\"";
211 throw MemoryErrorException();
212 }
213
214 if (token.originalText.size() > 0)
215 {
216 // tranduced token
217 // save original word as orthographic alternative
218 auto orig = (*m_d->m_stringsPool)[token.originalText];
219 tToken->addOrthographicAlternatives(orig);
220 }
221
222 m_d->computeDefaultStatus(*tToken);
223
224 LOG_MESSAGE(LDEBUG, " status is " << tToken->status().toString());
225
226 // Adds on the path
227 auto newVx = add_vertex(*graph);
228 endSentence = newVx;
229 put(vertex_token, *graph, newVx, tToken);
230 put(vertex_data, *graph, newVx, new MorphoSyntacticData());
231 add_edge(m_d->m_currentVx, newVx, *graph);
232 m_d->m_currentVx = newVx;
233 }
234
235 LOG_MESSAGE(LDEBUG, "adding sentence" << beginSentence << endSentence);
236
237 sb->add(Segment("sentence", beginSentence, endSentence, anagraph.get()));
238 beginSentence = endSentence;
239 }
240
241 add_edge(m_d->m_currentVx, anagraph->lastVertex(), *graph);
242
243 TimeUtils::logElapsedTime("RnnTokenizer");
244 return SUCCESS_ID;
245}
246
248{
249 m_data = QString(getStringParameter(unitConfiguration, "data", 0, "SentenceBoundaries").c_str());
250 auto model_prefix = QString::fromStdString(
251 getStringParameter(unitConfiguration, "model_prefix",
253
254 LOG_MESSAGE_WITH_PROLOG(LDEBUG, "RnnTokenizerPrivate::init" << model_prefix);
255
256 auto lang_str = QString::fromStdString(MediaticData::single().media(m_language));
257 auto resources_path = QString::fromStdString(MediaticData::single().getResourcesPath());
258 auto model_name = model_prefix;
259 std::string udlang;
260 MediaticData::single().getOptionValue("udlang", udlang);
261 LOG_MESSAGE(LDEBUG, "RnnTokenizerPrivate::init lang_str=" << lang_str << ", udlang=" << udlang);
262
263 if (!fix_lang_codes(lang_str, udlang))
264 {
266 "RnnTokenizerPrivate::init: Can't parse language id " << udlang.c_str(),
268 }
269
270 model_name.replace(QString("$udlang"), QString::fromStdString(udlang));
271
272 auto model_file_name = findFileInPaths(resources_path,
273 QString::fromUtf8("/RnnTokenizer/%1/%2.pt")
274 .arg(lang_str).arg(model_name));
275 if (model_file_name.isEmpty())
276 {
277 throw InvalidConfiguration("RnnTokenizerPrivate::init: tokenizer model file not found.");
278 }
279
280 // As the deeplima command does: the dictionary beside the model itself
281 if (QFileInfo::exists(model_file_name + ".mwt"))
282 {
283 load_mwt_dictionary(model_file_name + ".mwt");
284 }
285
286 // The segmenter is loaded once and reused by every text: it was created and
287 // its model loaded again for each text (about 0.14 s per analysis), as long
288 // as it stalled on a second text (aymara/lima#172)
289 m_load_fn = [this, model_file_name]()
290 {
291 if (m_loaded)
292 {
293 return;
294 }
295
296 m_segm = std::make_shared<segmentation::impl::SegmentationImpl>();
297 m_segm->load(model_file_name.toStdString());
298 m_segm->init(1, 16*1024); // threads, buffer size per thread
299
300 m_loaded = true;
301 };
302
303 // if (!isInitLazy())
304 // {
305 // m_load_fn();
306 // }
307}
308
309void RnnTokenizerPrivate::load_mwt_dictionary(const QString& file_name)
310{
311 // deeplima-mwt-dict's format, see deeplima/mwt_lexicon.h
312 try
313 {
314 m_mwt.load(file_name.toStdString());
315 }
316 catch (const std::exception& e)
317 {
319 LERROR << "RnnTokenizerPrivate::load_mwt_dictionary:" << e.what();
320 return;
321 }
323 LINFO << "RnnTokenizerPrivate::load_mwt_dictionary:" << m_mwt.size()
324 << "multiword tokens and" << m_mwt.rules_size() << "affix rules"
325 << (m_mwt.has_seq2seq() ? "and a seq2seq fallback" : "") << "in" << file_name;
326}
327
328void RnnTokenizerPrivate::append_new_word(std::vector< TPrimitiveToken >& current_sentence,
329 const QString& current_token,
330 int current_token_offset,
331 token_flags_t flags) const
332{
333 // When the segmenter predicts multiword tokens, only the flagged ones are
334 // expanded, from the dictionary then by the affix rules; otherwise, every
335 // dictionary match (never by the rules)
336 std::vector<std::string> words;
337 const bool flagged = (flags & token_flags_t::multiword);
338 if ((m_mwt_require_flag && !flagged)
339 || !m_mwt.expand(current_token.toStdString(), words, m_mwt_require_flag)
340 || words.size() < 2)
341 {
342 current_sentence.push_back(TPrimitiveToken(current_token, current_token_offset));
343 }
344 else
345 {
346 // The first word carries the surface: ConllDumper writes the words as one
347 // multiword token (N-M line). When the words spell the surface (English
348 // "Apple's" -> "Apple" "'s"), each one gets its own position in it;
349 // otherwise (French "du" -> "de" "le"), they share the surface's position
350 QString concatenated;
351 for (const auto& w : words)
352 {
353 concatenated += QString::fromStdString(w);
354 }
355 const bool spelled = (concatenated == current_token);
356 int position = current_token_offset;
357 size_t n = 0;
358 for (const auto& w : words)
359 {
360 const auto word = QString::fromStdString(w);
361 current_sentence.push_back(TPrimitiveToken(word, position,
362 (n++ == 0) ? current_token : QString()));
363 if (spelled)
364 {
365 position += word.size();
366 }
367 }
368 }
369}
370
371void RnnTokenizerPrivate::tokenize(const QString& text, std::vector<std::vector<TPrimitiveToken>>& sentences)
372{
373 m_load_fn();
374 m_mwt_require_flag = m_segm->predicts_mwt();
375
376 LOG_MESSAGE_WITH_PROLOG(LDEBUG, "RnnTokenizerPrivate::tokenize" << text.left(100));
378 sentences.clear();
379 sentences.reserve(text.size() / 15);
380
381 std::vector< TPrimitiveToken > current_sentence;
382
383 auto text_utf8 = text.toStdString();
384
385 // Token positions, in the QString units of the text (LIMA's positions; the
386 // token lengths are QString sizes too). deeplima gives, per token, the
387 // number of UTF-8 bytes since the end of the previous one (m_offset: the
388 // spaces before it) and its own byte length: the position was the previous
389 // token's end, before its spaces were added, and in bytes, so that every
390 // token after a space was one character early and every non-ASCII
391 // character shifted the rest of the text (lima-python spans cut words).
392 size_t byte_offset = 0; // in text_utf8
393 int char_offset = 0; // in text
394 auto advance = [&text_utf8, &byte_offset, &char_offset](size_t bytes)
395 {
396 const auto end = std::min(byte_offset + bytes, text_utf8.size());
397 for (; byte_offset < end; ++byte_offset)
398 {
399 const auto b = static_cast<unsigned char>(text_utf8[byte_offset]);
400 if ((b & 0xC0) != 0x80)
401 {
402 // A character's first byte; one beyond the BMP is two QChars
403 char_offset += ((b & 0xF8) == 0xF0) ? 2 : 1;
404 }
405 }
406 };
407
408 m_segm->register_handler([this, &sentences, &current_sentence, &char_offset, &advance]
409 (const std::vector<segmentation::token_pos>& tokens,
410 uint32_t len)
411 {
412 for (size_t i = 0; i < len; i++)
413 {
414 const auto& tok = tokens[i];
415 // An empty token may still carry an offset (the decoder splits long
416 // gaps so that m_offset does not overflow)
417 advance(tok.m_offset);
418 if (0 == tok.m_len)
419 {
420 continue;
421 }
422 append_new_word(current_sentence, QString::fromUtf8(tok.m_pch, tok.m_len), char_offset,
423 tok.m_flags);
424 advance(tok.m_len);
425 if (tok.m_flags & token_flags_t::sentence_brk)
426 {
427 sentences.push_back(current_sentence);
428 current_sentence.clear();
429 }
430 }
431 });
432
433 size_t bytes_consumed = 0;
434 m_segm->parse_from_stream([&text_utf8, &bytes_consumed]
435 (uint8_t* buffer,
436 int32_t& read,
437 size_t max)
438 {
439 read = (text_utf8.size() - bytes_consumed) > max ? max : (text_utf8.size() - bytes_consumed);
440 memcpy(buffer, text_utf8.c_str() + bytes_consumed, read);
441 bytes_consumed += read;
442 // Whether there is more to read. It was "more than one buffer left",
443 // which stopped before the last, partial buffer of any text longer than
444 // one buffer, and lost its end
445 return bytes_consumed < text_utf8.size();
446 });
447 // The text may end without a sentence break on its last token: its last
448 // sentence was dropped
449 if (!current_sentence.empty())
450 {
451 sentences.push_back(current_sentence);
452 }
453
454 LOG_MESSAGE(LINFO, "End of Tokenizer");
455 TimeUtils::logElapsedTime("RnnTokenizerPrivate");
456}
457
458} // namespace RnnTokenizer
459} // namespace DeepLimaUnits
460} // namespace LinguisticProcessing
461} // namespace Lima
#define CONFIGURATIONHELPER_LOGGING_INIT(X)
#define LOG_MESSAGE_WITH_PROLOG(stream, msg)
#define LOG_MESSAGE(stream, msg)
#define LIMA_EXCEPTION_SELECT_LOGINIT(X, Y, Z)
This macro writes the message Y to the error stream configured by its first parameter X,...
Definition LimaCommon.h:332
#define LDEBUG
Definition LimaCommon.h:157
#define LINFO
Definition LimaCommon.h:158
#define LERROR
Definition LimaCommon.h:161
@ vertex_token
LinguisticGraph::vertex_descriptor LinguisticGraphVertex
@ vertex_data
#define TOKENIZERLOGINIT
#define RNNTOKENIZER_CLASSID
Defines a Factory to create Object of type Base.
Holds all data that pass through the ProcessUnits Analysis data are shared pointers,...
std::shared_ptr< AnalysisData > getData(const QString &id)
return AnalysisData by id
void setData(const QString &id, std::shared_ptr< AnalysisData > data)
set an analysisData with the given id.
InitializableObjectManager< MediaProcessUnit, MediaProcessUnitInitializationParameters > Manager
Use this exception to signal an error in one of the configuration files.
Definition LimaCommon.h:345
void getStringParameter(Common::XMLConfigurationFiles::GroupConfigurationStructure &unitConfiguration, const std::string &name, std::string &value, int flags=Flags::REQUIRED, std::string default_value="")
ConfigurationHelper(const std::string &processUnitName, const std::string &loggingCategory)
void append_new_word(std::vector< TPrimitiveToken > &current_sentence, const QString &current_token, int current_token_offset, token_flags_t flags) const
void init(GroupConfigurationStructure &unitConfiguration)
void tokenize(const QString &text, std::vector< std::vector< TPrimitiveToken > > &sentences)
std::shared_ptr< segmentation::impl::SegmentationImpl > m_segm
This is a MediaProcessUnit that is usually the first element of the pipeline.
void init(Lima::Common::XMLConfigurationFiles::GroupConfigurationStructure &unitConfiguration, Manager *manager) override
LimaStatusCode process(AnalysisContent &analysis) const override
Process on data in analysisContent.
static const MediaticData & single()
Definition Singleton.h:51
static MediaticData & changeable()
Definition Singleton.h:71
This file contains a class to control log of informations about time, such as logging cumulated time ...
static void logElapsedTime(const std::string &mess, const std::string &taskCategory=std::string(""))
log the number of microseconds since last UpdateCurrentTime
static void updateCurrentTime(const std::string &taskCategory=std::string(""))
store current time for new elapsed time computation
Multiword-token (MWT) lexicon: how to expand a surface token (French "du") into its syntactic words (...
Definition mwt_lexicon.h:64
QString findFileInPaths(const QString &paths, const QString &fileName, const QChar &separator)
Find the given file in the given paths.
static SimpleFactory< MediaProcessUnit, RnnTokenizer > rnntokenizerFactory(RNNTOKENIZER_CLASSID)
bool fix_lang_codes(QString &lang_str, std::string &udlang)
NAUTITIA.
LimaStatusCode
Definition LimaCommon.h:236
@ SUCCESS_ID
Definition LimaCommon.h:237
@ MISSING_DATA
Definition LimaCommon.h:243
Edit rules for lemmatizing words absent from the lemma dictionary.
@ sentence_brk
Definition token_type.h:21