LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
RnnTokensAnalyzer.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
9
14
23
24#include "RnnTokensAnalyzer.h"
26#include "deeplima/token_type.h"
31
32#include <set>
33
34#define DEBUG_THIS_FILE true
35
37using namespace Lima::Common::PropertyCode;
38using namespace Lima::Common::MediaticData;
39using namespace Lima::Common::Misc;
41using namespace Lima::Common::AnnotationGraphs;
42using namespace std;
43using namespace deeplima;
44
45
47{
48#if defined(DEBUG_LP) && defined(DEBUG_THIS_FILE)
49#define LOG_MESSAGE(stream, msg) stream << msg;
50#define LOG_MESSAGE_WITH_PROLOG(stream, msg) LEMMALOGINIT; LOG_MESSAGE(stream, msg);
51#else
52 #define LOG_MESSAGE(stream, msg) ;
53 #define LOG_MESSAGE_WITH_PROLOG(stream, msg) ;
54#endif
55
57
59
61{
62public:
65 void init(GroupConfigurationStructure& unitConfiguration);
66 void analyzer(vector<segmentation::token_pos>& buffer);
69 void reset();
70
72 MediaId m_language;
74 QString m_data;
75 std::shared_ptr< TokenSequenceAnalyzer<> > m_tokensAnalyzer;
76 std::function<void()> m_load_fn;
79 std::vector< std::map<std::string, std::string> > m_tags;
80 std::vector<QString> m_lemmas;
83 // Features predicted by the model but missing from the property codes,
84 // already reported
85 std::set<std::string> m_unknownFeatures;
86 // TokenSequenceAnalyzer<>::OutputMatrix* m_matrix;
87};
88
90 "RnnTokensAnalyzerPrivate", THIS_FILE_LOGGING_CATEGORY()),
91 m_stringsPool(nullptr), m_stridx(),
92 m_pResolver(MediaticData::single().getResourcesPath()),
93 m_loaded(false)
94{
95}
96
98
99
103
105{
106 delete m_d;
107}
108
110{
111 LOG_MESSAGE_WITH_PROLOG(LDEBUG, "RnnTokensAnalyzer::init");
112
113 m_d->m_language = manager->getInitializationParameters().media;
114 m_d->m_stringsPool = &MediaticData::changeable().stringsPool(m_d->m_language);
115
116 m_d->init(unitConfiguration);
117}
118
120{
122 TimeUtilsController RnnTokensAnalyzerProcessTime("RnnTokensAnalyzer");
123 LOG_MESSAGE_WITH_PROLOG(LDEBUG, "RnnTokensAnalyzer::process");
124 // Ensure the models are loaded (no-op if already loaded)
125 if (m_d->m_load_fn)
126 {
127 m_d->m_load_fn();
128 }
129 m_d->m_analysis = &analysis;
130 auto anagraph = std::dynamic_pointer_cast<AnalysisGraph>(analysis.getData("AnalysisGraph"));
131 if (anagraph == nullptr)
132 {
134 LERROR << "Can't Process RnnTokensAnalyzer: missing data 'AnalysisGraph'";
135 return MISSING_DATA;
136 }
137 auto srcgraph = anagraph->getGraph();
138 auto endVx = anagraph->lastVertex();
143 auto posgraph = new LinguisticAnalysisStructure::AnalysisGraph("PosGraph",
144 m_d->m_language,
145 false,
146 true);
147 analysis.setData("PosGraph", posgraph);
148 const auto& propertyCodeManager = dynamic_cast<const LanguageData&>(
149 MediaticData::single().mediaData(m_d->m_language)).getPropertyCodeManager();
150 const auto& microManager = propertyCodeManager.getPropertyManager("MICRO");
152 auto annotationData = std::dynamic_pointer_cast< AnnotationData >(analysis.getData("AnnotationData"));
153 if (annotationData == nullptr)
154 {
155 annotationData = std::make_shared<AnnotationData>();
159 if (std::dynamic_pointer_cast<AnalysisGraph>(analysis.getData("AnalysisGraph")) != nullptr)
160 {
161 std::dynamic_pointer_cast<AnalysisGraph>(analysis.getData("AnalysisGraph"))->populateAnnotationGraph(
162 annotationData.get(), "AnalysisGraph");
163 }
164 analysis.setData("AnnotationData", annotationData);
165 }
166 if (num_vertices(*srcgraph)<=2)
167 {
168 return SUCCESS_ID;
169 }
170
171 auto vTokens = get(vertex_token, *srcgraph);
172 auto currentVx = anagraph->firstVertex();
173 auto resultgraph = posgraph->getGraph();
174 remove_edge(posgraph->firstVertex(), posgraph->lastVertex(), *resultgraph);
175
176 // Sentence boundaries are stored in SegmentationData (not in token statuses),
177 // so collect the last real token of each sentence here. We mark those with the
178 // deeplima sentence_brk flag so downstream units fed by this token stream
179 // (e.g. the dependency parser) split the text per sentence instead of parsing
180 // it as one long sequence. Segment::getLastVertex() is the vertex *after* the
181 // last token, so the sentence-final token is its in-neighbour.
182 std::set<LinguisticGraphVertex> sentenceFinalVertices;
183 {
184 auto sd = std::dynamic_pointer_cast<SegmentationData>(
185 analysis.getData("SentenceBoundaries"));
186 if (sd != nullptr)
187 {
188 for (const auto& segment : sd->getSegments())
189 {
190 const auto endV = segment.getLastVertex();
191 if (vTokens[endV] != nullptr)
192 {
193 // getLastVertex() is itself the sentence's last token.
194 sentenceFinalVertices.insert(endV);
195 }
196 else
197 {
198 // getLastVertex() is the boundary after the last token: mark
199 // its in-neighbour token(s).
200 LinguisticGraphInEdgeIt ie, ie_end;
201 for (boost::tie(ie, ie_end) = boost::in_edges(endV, *srcgraph);
202 ie != ie_end; ++ie)
203 {
204 const auto s = boost::source(*ie, *srcgraph);
205 if (vTokens[s] != nullptr)
206 {
207 sentenceFinalVertices.insert(s);
208 }
209 }
210 }
211 }
212 }
213 }
214
215 std::vector<segmentation::token_pos> buffer;
216 std::vector< LinguisticGraphVertex > anaVertices;
217 std::vector<std::string> v;
218
219 while(currentVx != endVx)
220 {
221 if (currentVx != 0 && vTokens[currentVx] != nullptr)
222 {
223 const auto& src = vTokens[currentVx];
224 v.push_back(src->stringForm().toStdString());
225 buffer.emplace_back();
226 anaVertices.push_back(currentVx);
227 }
228 LinguisticGraphOutEdgeIt it, it_end;
229 boost::tie(it, it_end) = boost::out_edges(currentVx, *srcgraph);
230 if (it != it_end)
231 {
232 currentVx = boost::target(*it, *srcgraph);
233 }
234 else
235 {
236 currentVx = endVx;
237 }
238 }
242 for(unsigned long k = 0; k < anaVertices.size(); k++)
243 {
244 currentVx = anaVertices[k];
245 if (currentVx != 0 && vTokens[currentVx] != nullptr)
246 {
247 const auto& src = vTokens[currentVx];
248 auto& token = buffer[k];
249 token.m_offset = src->position();
250 // deeplima's token_pos::m_len is a BYTE length and m_pch points to the
251 // UTF-8 bytes of v[k]. src->length() is the LIMA character count, which
252 // truncates multi-byte UTF-8 forms (e.g. "à" → 1 instead of 2 bytes),
253 // leaving the downstream form an incomplete byte sequence that decodes
254 // to an empty string (and crashed the neural lemmatizer). Use the UTF-8
255 // byte length so m_len matches m_pch.
256 token.m_len = v[k].size();
257 token.m_pch = v[k].c_str();
258 // Mark the last token of each sentence (from SegmentationData) so the
259 // stream carries real sentence breaks. The previous code AND-ed the
260 // sequential StatusType enum against a deeplima bit flag, which never
261 // produced a valid sentence_brk.
262 token.m_flags = (sentenceFinalVertices.count(currentVx) > 0)
265 }
266 }
267 m_d->analyzer(buffer);
268 std::vector<LinguisticGraphVertex>::size_type anaVerticesIndex = 0;
269 auto previousPosVertex = posgraph->firstVertex();
270 /*
271 * Here we add the part of speech data to the tokens
272 * Adding link beetween the node in the analysis graph and the pos graph.
273 */
274 while (anaVerticesIndex < anaVertices.size())
275 {
276 auto anaVertex = anaVertices[anaVerticesIndex];
277 auto newVx = boost::add_vertex(*resultgraph);
278 auto agv = annotationData->createAnnotationVertex();
279 annotationData->addMatching("PosGraph", newVx, "annot", agv);
280 annotationData->addMatching("AnalysisGraph", anaVertex, "PosGraph", newVx);
281 annotationData->annotate(agv, QString::fromUtf8("PosGraph"), newVx);
282
283 auto srcToken = get(vertex_token,*srcgraph,anaVertex);
284
285 auto posData = new MorphoSyntacticData();
286
288 for(const auto& name: m_d->m_tokensAnalyzer->get_class_names())
289 {
290 const PropertyManager* propertyManager = &microManager;
291 if(name == "upos")
292 {
293 propertyManager = &microManager;
294 }
295 else if(name=="ExtPos" || name=="Style" || name=="xpos")
296 {
297 // xpos is a treebank-specific tagset, not LIMA's MACRO: MACRO is
298 // the parent of MICRO, so writing an xpos there replaced the
299 // macro category of the UPOS just written. A model whose xpos
300 // classes include UPOS-like names (merged corpora mixing
301 // treebanks with and without xpos, e.g. Greek GDT and GUD)
302 // turned whole texts into ADJ (its xpos class 0). The CoNLL-U
303 // dumper prints no xpos anyway.
304 continue;
305 }
306 else
307 {
308 // A feature the model predicts but the media's property code
309 // file does not define (e.g. a feature added by a newer UD
310 // release) cannot be stored: skip it instead of aborting the
311 // analysis, and warn once per feature.
312 const auto& managers = propertyCodeManager.getPropertyManagers();
313 auto it = managers.find(name);
314 if (it == managers.end())
315 {
316 if (m_d->m_unknownFeatures.insert(name).second)
317 {
319 LWARN << "RnnTokensAnalyzer: feature" << name
320 << "is not defined in the property codes of this media: ignored";
321 std::cerr << "Warning: feature \"" << name
322 << "\" is not defined in the property codes: ignored" << std::endl;
323 }
324 continue;
325 }
326 propertyManager = &it->second;
327 }
328 auto value = propertyManager->getPropertyValue(m_d->m_tags[anaVerticesIndex][name]);
329 if(value.toBool())
330 {
331 LOG_MESSAGE(LDEBUG, "value: " << value);
332 propertyManager->getPropertyAccessor().writeValue(value, lElement.properties);
333 }
334 }
335 auto sp = &MediaticData::changeable().stringsPool(m_d->m_language);
336 lElement.lemma = (*sp)[m_d->m_lemmas[anaVerticesIndex]];
337 // The rule-based units (ModEx named entities normalization, BoW...)
338 // use the inflected and normalized forms, as filled by the legacy
339 // morphological analysis: normalized form is the lemma, or the form
340 // when no lemmatizer model is available.
341 if (srcToken != nullptr)
342 {
343 lElement.inflectedForm = (*sp)[srcToken->stringForm()];
344 lElement.normalizedForm = m_d->m_lemmas[anaVerticesIndex].isEmpty()
345 ? lElement.inflectedForm : lElement.lemma;
346 }
347 posData->push_back(lElement);
348
349 put(vertex_data, *resultgraph, newVx, posData);
350 put(vertex_token, *resultgraph, newVx, srcToken);
351
352 boost::add_edge(previousPosVertex, newVx, *resultgraph);
353
354 previousPosVertex = newVx;
355 anaVerticesIndex++;
356 }
357 boost::add_edge(previousPosVertex, posgraph->lastVertex(), *resultgraph);
358 LOG_MESSAGE(LDEBUG, "RnnPosLemmatizer postagging done.");
359 TimeUtils::logElapsedTime("RnnTokensAnalyzer");
360 return SUCCESS_ID;
361}
362
364{
365 m_data = QString(getStringParameter(unitConfiguration, "data", 0, "SentenceBoundaries").c_str());
366 QString tagger_model_prefix = getStringParameter(unitConfiguration, "tagger_model_prefix", ConfigurationHelper::REQUIRED | ConfigurationHelper::NOT_EMPTY).c_str();
367 QString lemmatizer_model_prefix = getStringParameter(unitConfiguration, "lemmatizer_model_prefix", ConfigurationHelper::REQUIRED | ConfigurationHelper::NOT_EMPTY).c_str();
368 LOG_MESSAGE_WITH_PROLOG(LDEBUG, "RnnTokensAnalyzerPrivate::init tagger model: " << tagger_model_prefix << " lemmatizer model: " << lemmatizer_model_prefix);
369
370 QString lang_str = MediaticData::single().media(m_language).c_str();
371 QString resources_path = MediaticData::single().getResourcesPath().c_str();
372 QString tagger_model_name = tagger_model_prefix;
373 QString lemmatizer_model_name = lemmatizer_model_prefix;
374 string udlang;
375 MediaticData::single().getOptionValue("udlang", udlang);
376
377 if (!fix_lang_codes(lang_str, udlang))
378 {
380 "RnnTokensAnalyzerPrivate::init: Can't parse language id " << udlang.c_str(),
382 }
383
384 tagger_model_name.replace(QString("$udlang"), QString(udlang.c_str()));
385 lemmatizer_model_name.replace(QString("$udlang"), QString(udlang.c_str()));
386
387 auto tagger_model_file_name = findFileInPaths(resources_path,
388 QString::fromUtf8("/RnnTagger/%1/%2.pt")
389 .arg(lang_str, tagger_model_name));
390 auto lemmatizer_model_file_name = findFileInPaths(resources_path,
391 QString::fromUtf8("/RnnLemmatizer/%1/%2.pt")
392 .arg(lang_str, lemmatizer_model_name));
393 auto lemmatizer_dictionary_file_name = findFileInPaths(resources_path,
394 QString::fromUtf8("/RnnLemmatizer/%1/%2.dic")
395 .arg(lang_str, lemmatizer_model_name));
396 // Optional: suffix edit rules for the words missing from the dictionary
397 auto lemmatizer_rules_file_name = findFileInPaths(resources_path,
398 QString::fromUtf8("/RnnLemmatizer/%1/%2.rules")
399 .arg(lang_str, lemmatizer_model_name));
400 if (tagger_model_file_name.isEmpty())
401 {
402 throw InvalidConfiguration("RnnTokensAnalyzerPrivate::init: tagger model file not found.");
403 }
404 if (lemmatizer_model_file_name.isEmpty())
405 {
406 //throw InvalidConfiguration("RnnTokensAnalyzerPrivate::init: lemmatizer model file not found.");
407 lemmatizer_model_file_name = "";
408 }
409
410 m_load_fn = [this, tagger_model_file_name, lemmatizer_model_file_name, lemmatizer_dictionary_file_name,
411 lemmatizer_rules_file_name]()
412 {
413 if (m_loaded)
414 {
415 return;
416 }
417 // TODO give the correct parameters for fixed_ini, lower_ini and lower_lemm
418 m_tokensAnalyzer = std::make_shared< TokenSequenceAnalyzer<> >(tagger_model_file_name.toStdString(),
419 lemmatizer_model_file_name.toStdString(),
420 lemmatizer_dictionary_file_name.toStdString(),
421 "", "", "",
422 lemmatizer_rules_file_name.toStdString(),
423 m_pResolver, 1024, 8);
424 for (size_t i = 0; i < m_tokensAnalyzer->get_classes().size(); ++i)
425 {
426 m_dumper.set_classes(i, m_tokensAnalyzer->get_class_names()[i], m_tokensAnalyzer->get_classes()[i]);
427 }
428 m_loaded = true;
429 };
430
431 // With lazy initialization (e.g. in the GUI), the models are loaded by
432 // the first process call
433 if (!isInitLazy())
434 {
435 m_load_fn();
436 }
437}
438
440{
441 m_tags.clear();
442 m_lemmas.clear();
443}
444
445void RnnTokensAnalyzerPrivate::analyzer(std::vector<segmentation::token_pos> &buffer)
446{
447 reset();
448 // Every batch, for the dependency parser: setting only the current one
449 // left it the last batch of the text
450 auto tiData = std::make_shared<TokenIteratorData>();
451 m_analysis->setData("TokenIterator", tiData);
452 m_tokensAnalyzer->register_handler([this, tiData](std::shared_ptr< StringIndex > stridx,
453 const token_buffer_t<>& tokens,
454 const std::vector<StringIndex::idx_t>& lemmata,
455 std::shared_ptr< StdMatrix<uint8_t> > classes,
456 size_t begin,
457 size_t end)
458 {
459 auto ti = std::make_shared<TokenSequenceAnalyzer<>::TokenIterator>(*stridx, tokens, lemmata, classes, begin, end);
460 tiData->setStringIndex(stridx);
461 tiData->addBatch(tokens, lemmata, classes, begin, end);
462 insertTokenInfo(*ti);
463 });
464 LOG_MESSAGE_WITH_PROLOG(LDEBUG, buffer[0].m_pch);
465 (*m_tokensAnalyzer)(buffer, buffer.size());
466 m_tokensAnalyzer->finalize();
467}
468
470{
471 auto classes = m_dumper.getMClasses();
472 auto class_names = m_tokensAnalyzer->get_class_names();
473 LOG_MESSAGE_WITH_PROLOG(LDEBUG, "classes: " << class_names);
474 while(!ti.end())
475 {
476 auto tag = std::map<std::string, std::string>();
477 LOG_MESSAGE(LDEBUG, ti.lemma());
478 for(uint cat = 0; cat < class_names.size(); cat++)
479 {
480 tag.insert({class_names[cat], classes[cat][ti.token_class(cat)]});
481 }
482 m_tags.push_back(tag);
483 m_lemmas.emplace_back(ti.lemma());
484 ti.next();
485 }
486 ti.reset();
487}
488
489
490}
This file is the main header file for the data related to annotation graphs.
#define CONFIGURATIONHELPER_LOGGING_INIT(X)
#define LOG_MESSAGE_WITH_PROLOG(stream, msg)
#define LOG_MESSAGE(stream, msg)
#define LWARN
Definition LimaCommon.h:160
#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 LERROR
Definition LimaCommon.h:161
A graph structure for linguistic analysis.
LinguisticGraph::in_edge_iterator LinguisticGraphInEdgeIt
@ vertex_token
@ vertex_data
LinguisticGraph::out_edge_iterator LinguisticGraphOutEdgeIt
#define LEMMALOGINIT
#define RNNTOKENSANALYZER_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.
Holds linguistic data for one language.
Provide function to read write and check a property.
void writeValue(const LinguisticCode &value, LinguisticCode &code) const
write a property value in a coded int.
Provide tools to manage a specific property.
const PropertyAccessor & getPropertyAccessor() const
give the corresponding PropertyAccessor
LinguisticCode getPropertyValue(const std::string &symbolicValue) const
Get the coded property value from the symbolic value.
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)
dumper::AnalysisToConllU< TokenSequenceAnalyzer<>::TokenIterator > m_dumper
LimaStatusCode process(AnalysisContent &analysis) const override
Process on data in analysisContent.
void init(Lima::Common::XMLConfigurationFiles::GroupConfigurationStructure &unitConfiguration, Manager *manager) override
An AnalysisData containing a LinguisticGraph with a language and an id.
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
QString findFileInPaths(const QString &paths, const QString &fileName, const QChar &separator)
Find the given file in the given paths.
static SimpleFactory< MediaProcessUnit, RnnTokensAnalyzer > RnnTokensAnalyzerFactory(RNNTOKENSANALYZER_CLASSID)
bool fix_lang_codes(QString &lang_str, std::string &udlang)
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.
TStringIndex< std::string, std::u32string, uint32_t > StringIndex
Definition str_index.h:119
@ sentence_brk
Definition token_type.h:21
STL namespace.