5#include <QtCore/QTemporaryFile>
6#include <QtCore/QRegularExpression>
34#define DEBUG_THIS_FILE true
46namespace LinguisticProcessing
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);
59 #define LOG_MESSAGE(stream, msg) ;
60 #define LOG_MESSAGE_WITH_PROLOG(stream, msg) ;
77 const QString& orig=QString())
87 void tokenize(
const QString& text, std::vector<std::vector<TPrimitiveToken>>& sentences);
91 const QString& current_token,
92 int current_token_offset,
113 std::shared_ptr<segmentation::impl::SegmentationImpl>
m_segm;
149 m_d->m_language = manager->getInitializationParameters().media;
152 m_d->init(unitConfiguration);
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();
167 auto originalText = std::dynamic_pointer_cast<LimaStringText>(analysis.
getData(
"Text"));
168 if (originalText ==
nullptr)
171 LERROR <<
"Can't Process RnnTokenizer: missing data 'Text'";
176 std::vector< std::vector< RnnTokenizerPrivate::TPrimitiveToken > > sentencesTokens;
177 m_d->tokenize(*originalText, sentencesTokens);
181 auto sb = std::make_shared<SegmentationData>(
"AnalysisGraph");
182 analysis.
setData(m_d->m_data.toStdString(), sb);
185 remove_edge(anagraph->firstVertex(),
186 anagraph->lastVertex(),
191 for (
const auto& sentence: sentencesTokens)
193 if (sentence.size() < 1)
198 auto endSentence = std::numeric_limits< LinguisticGraphVertex >::max();
199 for (
const auto& token: sentence)
201 const auto& str = token.wordText;
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)
210 LERROR <<
"RnnFlowTokenizer::process: Can't allocate memory with \"new Token(...)\"";
214 if (token.originalText.size() > 0)
218 auto orig = (*m_d->m_stringsPool)[token.originalText];
222 m_d->computeDefaultStatus(*tToken);
227 auto newVx = add_vertex(*graph);
231 add_edge(m_d->m_currentVx, newVx, *graph);
232 m_d->m_currentVx = newVx;
237 sb->add(
Segment(
"sentence", beginSentence, endSentence, anagraph.get()));
238 beginSentence = endSentence;
241 add_edge(m_d->m_currentVx, anagraph->lastVertex(), *graph);
250 auto model_prefix = QString::fromStdString(
258 auto model_name = model_prefix;
261 LOG_MESSAGE(
LDEBUG,
"RnnTokenizerPrivate::init lang_str=" << lang_str <<
", udlang=" << udlang);
266 "RnnTokenizerPrivate::init: Can't parse language id " << udlang.c_str(),
270 model_name.replace(QString(
"$udlang"), QString::fromStdString(udlang));
273 QString::fromUtf8(
"/RnnTokenizer/%1/%2.pt")
274 .arg(lang_str).arg(model_name));
275 if (model_file_name.isEmpty())
281 if (QFileInfo::exists(model_file_name +
".mwt"))
296 m_segm = std::make_shared<segmentation::impl::SegmentationImpl>();
297 m_segm->load(model_file_name.toStdString());
314 m_mwt.load(file_name.toStdString());
316 catch (
const std::exception& e)
319 LERROR <<
"RnnTokenizerPrivate::load_mwt_dictionary:" << e.what();
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;
329 const QString& current_token,
330 int current_token_offset,
336 std::vector<std::string> words;
342 current_sentence.push_back(
TPrimitiveToken(current_token, current_token_offset));
350 QString concatenated;
351 for (
const auto& w : words)
353 concatenated += QString::fromStdString(w);
355 const bool spelled = (concatenated == current_token);
356 int position = current_token_offset;
358 for (
const auto& w : words)
360 const auto word = QString::fromStdString(w);
362 (n++ == 0) ? current_token : QString()));
365 position += word.size();
379 sentences.reserve(text.size() / 15);
381 std::vector< TPrimitiveToken > current_sentence;
383 auto text_utf8 = text.toStdString();
392 size_t byte_offset = 0;
394 auto advance = [&text_utf8, &byte_offset, &char_offset](
size_t bytes)
396 const auto end = std::min(byte_offset + bytes, text_utf8.size());
397 for (; byte_offset < end; ++byte_offset)
399 const auto b =
static_cast<unsigned char>(text_utf8[byte_offset]);
400 if ((b & 0xC0) != 0x80)
403 char_offset += ((b & 0xF8) == 0xF0) ? 2 : 1;
408 m_segm->register_handler([
this, &sentences, ¤t_sentence, &char_offset, &advance]
409 (
const std::vector<segmentation::token_pos>& tokens,
412 for (
size_t i = 0; i < len; i++)
414 const auto& tok = tokens[i];
417 advance(tok.m_offset);
422 append_new_word(current_sentence, QString::fromUtf8(tok.m_pch, tok.m_len), char_offset,
427 sentences.push_back(current_sentence);
428 current_sentence.clear();
433 size_t bytes_consumed = 0;
434 m_segm->parse_from_stream([&text_utf8, &bytes_consumed]
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;
445 return bytes_consumed < text_utf8.size();
449 if (!current_sentence.empty())
451 sentences.push_back(current_sentence);
#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,...
LinguisticGraph::vertex_descriptor LinguisticGraphVertex
#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.
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 load_mwt_dictionary(const QString &file_name)
deeplima::MwtLexicon m_mwt
LinguisticGraphVertex m_currentVx
virtual ~RnnTokenizerPrivate()
void append_new_word(std::vector< TPrimitiveToken > ¤t_sentence, const QString ¤t_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::function< void()> m_load_fn
FsaStringsPool * m_stringsPool
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.
Holds morphosyntactic informations.
std::string toString() const
holds surface data of a token
void addOrthographicAlternatives(StringsPoolIndex alt)
const TStatus & status() const
static const MediaticData & single()
static MediaticData & changeable()
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 (...
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)
Edit rules for lemmatizing words absent from the lemma dictionary.
TPrimitiveToken(const QString &w, int pos, const QString &orig=QString())