LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
lima.cpp
Go to the documentation of this file.
1// Copyright 2019-2022 CEA LIST
2// SPDX-FileCopyrightText: 2019-2022 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
6/****************************************************************************
7**
8** Copyright (C) 2018 The Qt Company Ltd.
9** Contact: https://www.qt.io/licensing/
10**
11** This file is part of the Qt for Python examples of the Qt Toolkit.
12**
13** $QT_BEGIN_LICENSE:BSD$
14** Commercial License Usage
15** Licensees holding valid commercial Qt licenses may use this file in
16** accordance with the commercial license agreement provided with the
17** Software or, alternatively, in accordance with the terms contained in
18** a written agreement between you and The Qt Company. For licensing terms
19** and conditions see https://www.qt.io/terms-conditions. For further
20** information use the contact form at https://www.qt.io/contact-us.
21**
22** BSD License Usage
23** Alternatively, you may use this file under the terms of the BSD license
24** as follows:
25**
26** "Redistribution and use in source and binary forms, with or without
27** modification, are permitted provided that the following conditions are
28** met:
29** * Redistributions of source code must retain the above copyright
30** notice, this list of conditions and the following disclaimer.
31** * Redistributions in binary form must reproduce the above copyright
32** notice, this list of conditions and the following disclaimer in
33** the documentation and/or other materials provided with the
34** distribution.
35** * Neither the name of The Qt Company Ltd nor the names of its
36** contributors may be used to endorse or promote products derived
37** from this software without specific prior written permission.
38**
39**
40** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
41** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
42** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
43** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
44** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
46** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
47** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
48** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
49** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
50** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
51**
52** $QT_END_LICENSE$
53**
54****************************************************************************/
55
56#include "lima.h"
58#include "common/LimaCommon.h"
59#include "common/LimaVersion.h"
65#include "common/QsLog/QsLog.h"
74
93#include <deque>
94#include <fstream>
95#include <iostream>
96#include <iomanip>
97#include <map>
98#include <memory>
99#include <mutex>
100#include <set>
101#include <string>
102#include <vector>
103
104#include <boost/algorithm/string.hpp>
105#include <boost/algorithm/string/find_format.hpp>
106#include <boost/algorithm/string/finder.hpp>
107#include <boost/format.hpp>
108
109#include <QtCore/QCoreApplication>
110#include <QtCore/QtGlobal>
111#include <QtCore/QString>
112
113#include <QtCore>
114
115using namespace Lima::LinguisticProcessing;
118using namespace Lima::Common::AnnotationGraphs;
119using namespace Lima::Common::MediaticData;
122using namespace Lima::Common::Misc;
123using namespace Lima::Common::PropertyCode;
125using namespace Lima;
126
128{
129 template<typename FindResultT>
130 std::string operator()(const FindResultT& Match) const
131 {
132 std::string s;
133 for (typename FindResultT::const_iterator i = Match.begin();
134 i != Match.end();
135 i++) {
136 s += boost::str(boost::format("\\x%02x") % static_cast<int>(*i));
137 }
138 return s;
139 }
140};
141
142std::shared_ptr< std::ostringstream > openHandlerOutputString(
144 const std::set<std::string>&dumpers,
145 const std::string& dumperId);
146
147int run(int aargc,char** aargv);
148
149namespace
150{
151// The number of living analyzers of each media. The process units of a media
152// (and the models they load) are shared by its analyzers in the
153// MediaProcessors singleton: they are released with the last one. Never
154// destroyed, to stay usable by analyzers destroyed at the process exit.
155std::mutex& mediaUsersMutex()
156{
157 static auto* mutex = new std::mutex();
158 return *mutex;
159}
160std::map<std::string, int>& mediaUsers()
161{
162 static auto* users = new std::map<std::string, int>();
163 return *users;
164}
165}
166
168{
169 friend class LimaAnalyzer;
170public:
171 LimaAnalyzerPrivate(const QStringList& qlangs,
172 const QStringList& qpipelines,
173 const QString& modulePath,
174 const QString& user_config_path,
175 const QString& user_resources_path,
176 const QString& meta);
180
181 void initMetaData();
182
183 bool addPipelineUnit(const std::string& pipeline,
184 const std::string& media,
185 const std::string& jsonGroupString);
186
187 const std::string analyzeText(const std::string& text,
188 const std::string& lang,
189 const std::string& pipeline,
190 const std::string& meta);
191
192 void collectDependencyInformations(std::shared_ptr<Lima::AnalysisContent> analysis);
194 std::shared_ptr<Lima::AnalysisContent> analysis);
195
199 QString getNeType(LinguisticGraphVertex posGraphVertex);
200
201 std::pair<QString, int> getConllRelName(LinguisticGraphVertex v);
202
204
206
208
210
212 void reset();
213
214 QJsonObject objectFromString(const QString& in);
215
217
218 const FsaStringsPool* sp = nullptr;
219 MediaId medId;
220
221
222 const LanguageData* languageData = nullptr;
227 std::shared_ptr<SyntacticData> syntacticData = nullptr;
228 std::map< LinguisticGraphVertex,
229 std::pair<LinguisticGraphVertex,
231 QMap<QString, QString> conllLimaDepMapping;
232
233
234 std::map<LinguisticGraphVertex, int> vertexToToken;
235
237 // Fixed members that do not change at each analysis
238 std::map<std::string, AbstractAnalysisHandler*> handlers;
239 std::unique_ptr<BowTextWriter> bowTextWriter = nullptr;
240 std::unique_ptr<BowTextHandler> bowTextHandler = nullptr;
241 std::unique_ptr<SimpleStreamHandler> simpleStreamHandler = nullptr;
242 std::unique_ptr<SimpleStreamHandler> fullXmlSimpleStreamHandler = nullptr;
243 std::unique_ptr<LTRTextHandler> ltrTextHandler = nullptr;
244 std::set<std::string> dumpers = {"text"};
245 std::shared_ptr< AbstractLinguisticProcessingClient > m_client;
246 std::map<std::string,std::string> metaData;
247 // Store constructor parameters to be able to implement copy constructor
248 QStringList qlangs;
249 QStringList qpipelines;
250 QString modulePath;
253 QString meta;
254};
255
256
257namespace
258{
259QtMessageHandler previousQtMessageHandler = nullptr;
260
261// The QCoreApplication of the analyzer lives only while it is built (a
262// program may create its own one later, e.g. a PySide QApplication), while
263// the file watchers of the logging configuration are process-wide: at exit,
264// Qt warns that their event dispatcher "has already been destroyed". This
265// harmless warning is dropped; the other messages go to the previous handler.
266void filterQtMessages(QtMsgType type, const QMessageLogContext& context,
267 const QString& message)
268{
269 if (message.contains(QLatin1String("event dispatcher has already been destroyed")))
270 {
271 return;
272 }
273 if (previousQtMessageHandler != nullptr)
274 {
275 previousQtMessageHandler(type, context, message);
276 }
277 else
278 {
279 std::cerr << message.toStdString() << std::endl;
280 }
281}
282
283void installQtMessageFilter()
284{
285 static bool installed = false;
286 if (!installed)
287 {
288 previousQtMessageHandler = qInstallMessageHandler(filterQtMessages);
289 installed = true;
290 }
291}
292}
293
295 const QStringList& iqpipelines,
296 const QString& imodulePath,
297 const QString& iuser_config_path,
298 const QString& iuser_resources_path,
299 const QString& imeta) :
300 qlangs(iqlangs), qpipelines(iqpipelines), modulePath(imodulePath),
301 user_config_path(iuser_config_path), user_resources_path(iuser_resources_path), meta(imeta)
302{
303 int argc = 1;
304 char* argv[2] = {(char*)("LimaAnalyzer"), NULL};
305 QCoreApplication app(argc, argv);
306 installQtMessageFilter();
307
308 if(iqlangs.size() == 0)
309 {
310 throw LimaException("Must initialize at least one language");
311 }
312 if(iqpipelines.size() == 0)
313 {
314 throw LimaException("Must initialize at least one pipeline");
315 }
316
317 QStringList additionalPaths({modulePath+"/config"});
318 // Add here LIMA_CONF content in front, otherwise it will be ignored
319 auto limaConf = QString::fromUtf8(qgetenv("LIMA_CONF").constData());
320 if (!limaConf.isEmpty())
321 additionalPaths = limaConf.split(LIMA_PATH_SEPARATOR, Qt::SkipEmptyParts) + additionalPaths;
322 // Add then the user path in front again such that it takes precedence on environment variable
323 if (!user_config_path.isEmpty())
324 additionalPaths.push_front(user_config_path);
325 auto configDirs = buildConfigurationDirectoriesList(QStringList({"lima"}),
326 additionalPaths);
327 auto configPath = configDirs.join(LIMA_PATH_SEPARATOR);
328
329 QStringList additionalResourcePaths({modulePath+"/resources"});
330 // Add here LIMA_RESOURCES content in front, otherwise it will be ignored
331 auto limaRes = QString::fromUtf8(qgetenv("LIMA_RESOURCES").constData());
332 if (!limaRes.isEmpty())
333 additionalResourcePaths = limaRes.split(LIMA_PATH_SEPARATOR, Qt::SkipEmptyParts) + additionalResourcePaths;
334 if (!user_resources_path.isEmpty())
335 additionalResourcePaths.push_front(user_resources_path);
336 auto resourcesDirs = buildResourcesDirectoriesList(QStringList({"lima"}),
337 additionalResourcePaths);
338 auto resourcesPath = resourcesDirs.join(LIMA_PATH_SEPARATOR);
339
340 QsLogging::initQsLog(configPath);
341 // std::cerr << "QsLog initialized " << configPath.toStdString() << std::endl;
342 // Necessary to initialize factories
344 // std::cerr << "LimaAnalyzerPrivate::LimaAnalyzerPrivate() plugins manager created" << std::endl;
345 if (!Lima::AmosePluginsManager::changeable().loadPlugins(configPath))
346 {
347 throw InvalidConfiguration("loadLibrary method failed.");
348 }
349 // qDebug() << "Amose plugins are now initialized";
350
351
352 std::string lpConfigFile = "lima-analysis.xml";
353 std::string commonConfigFile = "lima-common.xml";
354 std::string clientId = "lima-coreclient";
355
356 std::string strConfigPath;
357
358 initMetaData();
359
360 std::deque<std::string> pipelines;
361 for (const auto& pipeline: qpipelines)
362 pipelines.push_back(pipeline.toStdString());
363
364
365 // uint64_t beginTime=TimeUtils::getCurrentTime();
366
367 std::deque<std::string> langs;
368 for (const auto& lang: qlangs)
369 langs.push_back(lang.toStdString());
370 // std::cerr << "LimaAnalyzerPrivate::LimaAnalyzerPrivate() "
371 // << resourcesPath.toUtf8().constData() << ", "
372 // << configPath.toUtf8().constData() << ", "
373 // << commonConfigFile << ", "
374 // << qlangs.join(",").toStdString() << std::endl;
375 // initialize common. Forward the parsed meta data as options so that e.g.
376 // "udlang" (the treebank selecting the deeplima models, passed as
377 // meta "udlang:eng-UD_English-EWT") is available to the process units at init
378 // time via MediaticData::getOptionValue.
380 resourcesPath.toUtf8().constData(),
381 configPath.toUtf8().constData(),
382 commonConfigFile,
383 langs,
384 metaData);
385 // std::cerr << "MediaticData initialized" << std::endl;
386
387 bool clientFactoryConfigured = false;
388 Q_FOREACH(QString configDir, configDirs)
389 {
390 if (QFileInfo::exists(configDir + "/" + lpConfigFile.c_str()))
391 {
392 // std::cerr << "LimaAnalyzerPrivate::LimaAnalyzerPrivate() configuring "
393 // << (configDir + "/" + lpConfigFile.c_str()).toUtf8().constData() << ", "
394 // << clientId << std::endl;
395
396 // initialize linguistic processing
398 (configDir + "/" + lpConfigFile.c_str()));
399 LinguisticProcessingClientFactory::changeable().configureClientFactory(
400 clientId,
401 lpconfig,
402 langs,
403 pipelines);
404 clientFactoryConfigured = true;
405 break;
406 }
407 }
408 if(!clientFactoryConfigured)
409 {
410 std::cerr << "No LinguisticProcessingClientFactory were configured with"
411 << configDirs.join(LIMA_PATH_SEPARATOR).toStdString()
412 << "and" << lpConfigFile << std::endl;
413 throw LimaException("Configuration failure");
414 }
415 // std::cerr << "Client factory configured" << std::endl;
416
417 m_client = std::shared_ptr< AbstractLinguisticProcessingClient >(
418 std::dynamic_pointer_cast<AbstractLinguisticProcessingClient>(
419 LinguisticProcessingClientFactory::single().createClient(clientId)));
420
421 // Set the handlers
422 bowTextWriter = std::make_unique<BowTextWriter>();
423 handlers.insert(std::make_pair("bowTextWriter", bowTextWriter.get()));
424 bowTextHandler = std::make_unique<BowTextHandler>();
425 handlers.insert(std::make_pair("bowTextHandler", bowTextHandler.get()));
426 simpleStreamHandler = std::make_unique<SimpleStreamHandler>();
427 handlers.insert(std::make_pair("simpleStreamHandler", simpleStreamHandler.get()));
428 fullXmlSimpleStreamHandler = std::make_unique<SimpleStreamHandler>();
429 handlers.insert(std::make_pair("fullXmlSimpleStreamHandler", fullXmlSimpleStreamHandler.get()));
430 ltrTextHandler= std::make_unique<LTRTextHandler>();
431 handlers.insert(std::make_pair("ltrTextHandler", ltrTextHandler.get()));
432 std::lock_guard<std::mutex> lock(mediaUsersMutex());
433 for (const auto& lang: QSet<QString>(qlangs.begin(), qlangs.end()))
434 ++mediaUsers()[lang.toStdString()];
435 // std::cerr << "LimaAnalyzerPrivate constructor done" << std::endl;
436
437}
438
440{
441 // Release the process units of the medias no other analyzer uses: they
442 // would stay in the MediaProcessors singleton until the end of the process
443 std::lock_guard<std::mutex> lock(mediaUsersMutex());
444 for (const auto& lang: QSet<QString>(qlangs.begin(), qlangs.end()))
445 {
446 auto& users = mediaUsers();
447 auto it = users.find(lang.toStdString());
448 if (it == users.end() || --it->second > 0)
449 continue;
450 users.erase(it);
451 try
452 {
453 MediaProcessors::changeable().releaseMedia(
454 MediaticData::single().getMediaId(lang.toStdString()));
455 }
456 catch (const std::exception& e)
457 {
458 std::cerr << "LimaAnalyzer: cannot release media " << lang.toStdString()
459 << ": " << e.what() << std::endl;
460 }
461 }
462}
463
464LimaAnalyzer::LimaAnalyzer(const std::string& langs,
465 const std::string& pipelines,
466 const std::string& modulePath,
467 const std::string& user_config_path,
468 const std::string& user_resources_path,
469 const std::string& meta)
470{
471 try
472 {
473 QStringList qlangs = QString::fromStdString(langs).split(",", Qt::SkipEmptyParts);
474 QStringList qpipelines = QString::fromStdString(pipelines).split(",", Qt::SkipEmptyParts);
475 m_d = new LimaAnalyzerPrivate(qlangs, qpipelines,
476 QString::fromStdString(modulePath),
477 QString::fromStdString(user_config_path),
478 QString::fromStdString(user_resources_path),
479 QString::fromStdString(meta));
480 }
481 catch (const std::exception& e) // deeplima throws std exceptions (missing files): not std::terminate
482 {
483 std::cerr << "Lima internal error: " << e.what() << std::endl;
484 m_d = nullptr;
485 error = true;
486 errorMessage = e.what();
487 }
488}
489
491{
492 delete m_d;
493}
494
496{
497 try
498 {
499 m_d = new LimaAnalyzerPrivate(a.m_d->qlangs, a.m_d->qpipelines,
500 a.m_d->modulePath,
501 a.m_d->user_config_path,
502 a.m_d->user_resources_path,
503 a.m_d->meta);
504 }
505 catch (const std::exception& e) // deeplima throws std exceptions (missing files): not std::terminate
506 {
507 std::cerr << "Lima internal error: " << e.what() << std::endl;
508 m_d = nullptr;
509 error = true;
510 errorMessage = e.what();
511 }
512 // std::cerr << "LimaAnalyzer::LimaAnalyzer copy constructor" << std::endl;
513}
514
516{
517 try
518 {
519 // std::cerr << "LimaAnalyzer::operator=" << std::endl;
520 delete m_d;
521 m_d = new LimaAnalyzerPrivate(a.m_d->qlangs, a.m_d->qpipelines,
522 a.m_d->modulePath,
523 a.m_d->user_config_path,
524 a.m_d->user_resources_path,
525 a.m_d->meta);
526 return *this;
527 }
528 catch (const std::exception& e) // deeplima throws std exceptions (missing files): not std::terminate
529 {
530 std::cerr << "Lima internal error: " << e.what() << std::endl;
531 m_d = nullptr;
532 error = true;
533 errorMessage = e.what();
534 }
535 return *this;
536}
537
539{
540 previousNeType = "O";
541 sp = nullptr;
542 medId = 0;
543 languageData = nullptr;
544 syntacticData = nullptr;
545 propertyAccessor = nullptr;
546 posGraph = nullptr;
547 anaGraph = nullptr;
548 annotationData = nullptr;
549 propertyCodeManager = nullptr;
551 conllLimaDepMapping.clear();
552 vertexToToken.clear();
553}
554
556{
557 // parse 'meta' argument to add metadata
558 if (!meta.isEmpty())
559 {
560 auto metas = meta.split(",", Qt::SkipEmptyParts);
561 for (const auto& aMeta: metas)
562 {
563 auto kv = aMeta.split(":");
564 if (kv.size() != 2)
565 {
566 std::cerr << "meta argument '"<< aMeta.toStdString() << "' is not of the form XXX:YYY: ignored" << std::endl;
567 }
568 else
569 {
570 metaData[kv[0].toStdString()] = kv[1].toStdString();
571 }
572 }
573 }
574}
575
576bool LimaAnalyzer::addPipelineUnit(const std::string& pipeline,
577 const std::string& media,
578 const std::string& jsonGroupString)
579{
580 if (! m_d->addPipelineUnit(pipeline, media, jsonGroupString))
581 {
582 error = true;
583 errorMessage = std::string("addPipelineUnit failed:") + pipeline + ", "
584 + media + ",\n" + jsonGroupString;
585 return false;
586 }
587 return true;
588}
589
590QJsonObject LimaAnalyzerPrivate::objectFromString(const QString& in)
591{
592 QJsonObject obj;
593
594 QJsonDocument doc = QJsonDocument::fromJson(in.toUtf8());
595
596 // check validity of the document
597 if(!doc.isNull())
598 {
599 if(doc.isObject())
600 {
601 obj = doc.object();
602 }
603 else
604 {
605 qDebug() << "Document is not an object" << Qt::endl;
606 }
607 }
608 else
609 {
610 qDebug() << "Invalid JSON...\n" << in << Qt::endl;
611 }
612
613 return obj;
614}
615
616bool LimaAnalyzerPrivate::addPipelineUnit(const std::string& pipeline,
617 const std::string& media,
618 const std::string& jsonGroupString)
619{
620 auto jsonGroup = QJsonDocument::fromJson(QByteArray::fromStdString(jsonGroupString)).object();
622 auto pipe = MediaProcessors::changeable().getPipelineForId(mediaid, pipeline);
623 auto managers = Lima::MediaProcessors::single().managers();
624 // QString jsonGroupString =
625 // "{ \"name\":\"cpptftokenizer\", "
626 // " \"class\":\"CppUppsalaTensorFlowTokenizer\", "
627 // " \"model_prefix\": \"tokenizer-eng\" }";
628
629 GroupConfigurationStructure unitConfig(jsonGroup);
630
631 // managers (Manager*) used in init of ProcessUnits are stored in
632 // m_pipelineManagers of MediaProcessors
634 jsonGroup["class"].toString().toStdString())->create(
635 unitConfig,
636 managers[mediaid]);
637 pipe->push_back(pu);
638
639 return true;
640}
641
642std::string LimaAnalyzer::analyzeText(const std::string& text,
643 const std::string& lang,
644 const std::string& pipeline,
645 const std::string& meta)
646{
647 // std::cerr << "LimaAnalyzer::analyzeText" << std::endl;
648 if (m_d == nullptr || error)
649 {
650 error = true;
651 errorMessage = "Invalid Lima analyzer. Previous error message was: " + errorMessage;
652 return "";
653 }
654 try
655 {
656 return m_d->analyzeText(text, lang, pipeline, meta);
657 }
658 catch (const std::exception& e) // deeplima throws std exceptions (missing files): not std::terminate
659 {
660 std::cerr << "Lima internal error: " << e.what() << std::endl;
661 error = true;
662 errorMessage = e.what();
663 return "";
664 }
665}
666
667const std::string LimaAnalyzerPrivate::analyzeText(const std::string& text,
668 const std::string& lang,
669 const std::string& pipeline,
670 const std::string& meta)
671{
672 auto txtofs = openHandlerOutputString(simpleStreamHandler.get(), dumpers, "text");
673
674 auto localMetaData = metaData;
675 localMetaData["FileName"]="param";
676 auto qmeta = QString::fromStdString(meta).split(",", Qt::SkipEmptyParts);
677 for (const auto& m: qmeta)
678 {
679 auto kv = m.split(":");
680 if (kv.size() == 2)
681 localMetaData[kv[0].toStdString()] = kv[1].toStdString();
682 }
683
684 auto localLang = lang;
685 if (localLang.size() == 0)
686 {
687 localLang = qlangs[0].toStdString();
688 }
689 auto localPipeline = pipeline;
690 if (localPipeline.size() == 0)
691 {
692 localPipeline = qpipelines[0].toStdString();
693 }
694 localMetaData["Lang"] = localLang;
695
696 QString contentText = QString::fromUtf8(text.c_str());
697 if (contentText.isEmpty())
698 {
699 std::cerr << "Empty input ! " << std::endl;
700 }
701 else
702 {
703 // analyze it
704 // std::cerr << "Analyzing " << contentText.toStdString() << std::endl;
705 m_client->analyze(contentText, localMetaData, localPipeline, handlers);
706 }
707 auto result = txtofs->str();
708 // std::cerr << "LimaAnalyzerPrivate::analyzeText result: " << result << std::endl;
709 simpleStreamHandler->setOut(nullptr);
710 return result;
711}
712
713std::shared_ptr< std::ostringstream > openHandlerOutputString(
715 const std::set<std::string>&dumpers,
716 const std::string& dumperId)
717{
718 auto ofs = std::make_shared< std::ostringstream >();
719 if (dumpers.find(dumperId)!=dumpers.end())
720 {
721 handler->setOut(ofs.get());
722 }
723 else
724 {
726 LERROR << dumperId << "is not in the dumpers list";
727 }
728 return ofs;
729}
730
732{
733#ifdef DEBUG_LP
735 LDEBUG << "getFeats";
736#endif
737 auto managers = propertyCodeManager->getPropertyManagers();
738
739 QStringList featuresList;
740 for (auto i = managers.cbegin(); i != managers.cend(); i++)
741 {
742 auto key = QString::fromUtf8(i->first.c_str());
743 if (key != "MACRO" && key != "MICRO")
744 {
745 const auto& pa = propertyCodeManager->getPropertyAccessor(key.toStdString());
746 LinguisticCode lc = morphoData.firstValue(pa);
747 auto value = QString::fromUtf8(i->second.getPropertySymbolicValue(lc).c_str());
748 if (value != "NONE")
749 {
750 featuresList << QString("%1=%2").arg(key).arg(value);
751 }
752 }
753 }
754
755 featuresList.sort();
756 QString features;
757 QTextStream featuresStream(&features);
758 if (featuresList.isEmpty())
759 {
760 features = "_";
761 }
762 else
763 {
764 for (auto featuresListIt = featuresList.cbegin(); featuresListIt != featuresList.cend(); featuresListIt++)
765 {
766 if (featuresListIt != featuresList.cbegin())
767 {
768 featuresStream << "|";
769 }
770 featuresStream << *featuresListIt;
771 }
772 }
773#ifdef DEBUG_LP
774 LDEBUG << "LimaAnalyzerPrivate::getFeats features:" << features;
775#endif
776
777 return features;
778}
779
780void LimaAnalyzerPrivate::collectDependencyInformations(std::shared_ptr<Lima::AnalysisContent> analysis)
781{
782#ifdef DEBUG_LP
784 LDEBUG << "LimaAnalyzerPrivate::collectVertexDependencyInformations";
785#endif
786
787 auto posGraphData = std::dynamic_pointer_cast<LinguisticAnalysisStructure::AnalysisGraph>(analysis->getData("PosGraph"));
788 if (posGraphData == nullptr)
789 {
790 std::cerr << "Error: PosGraph has not been produced: check pipeline";
791 return;
792 }
793
794 auto firstVertex = posGraphData->firstVertex();
795 auto lastVertex = posGraphData->lastVertex();
796 auto v = firstVertex;
797 auto [it, it_end] = boost::out_edges(v, *posGraph);
798 if (it != it_end)
799 {
800 v = boost::target(*it, *posGraph);
801 }
802 else
803 {
804 v = lastVertex;
805 }
806
807 syntacticData = std::dynamic_pointer_cast<SyntacticData>(analysis->getData("SyntacticData"));
808 if (syntacticData == nullptr)
809 {
810 syntacticData = std::make_shared<SyntacticData>(posGraphData.get(), nullptr);
811 syntacticData->setupDependencyGraph();
812 analysis->setData("SyntacticData", syntacticData);
813 }
814 int tokenId = 0;
815
816 while (v != lastVertex)
817 {
818 QString neType = getNeType(v);
819 QString neIOB = "O";
820 // Collect NE vertices and output them instead of a single line for
821 // current v. NE vertices can not only be PosGraph
822 // vertices (and thus can just call dumpPosGraphVertex
823 // recursively) but also AnalysisGraph vertices. In the latter case, data
824 // come partly from the AnalysisGraph and partly from the PosGraph
825 // Furthermore, named entities can be recursive...
826 if (neType != "_")
827 {
828 auto matches = annotationData->matches("PosGraph", v, "annot");
829 if (!matches.empty())
830 {
831 for (const auto& vx: matches)
832 {
833 if (annotationData->hasAnnotation(vx, QString::fromUtf8("SpecificEntity")))
834 {
835 auto se = annotationData->annotation(vx, QString::fromUtf8("SpecificEntity"))
836 .pointerValue<SpecificEntityAnnotation>();
837 previousNeType = "O";
838 // bool first = true;
839 for (const auto& vse : se->vertices())
840 {
842 vertexToToken[vse] = tokenId;
843 // first = false;
844 }
845 break;
846 }
847 }
848 }
849 else
850 {
851 auto anaVertices = annotationData->matches("PosGraph", v, "AnalysisGraph");
852 auto anaVertex = *anaVertices.begin();
853 if (annotationData->hasAnnotation(anaVertex, QString::fromUtf8("SpecificEntity")))
854 {
855 auto se = annotationData->annotation(anaVertex, QString::fromUtf8("SpecificEntity"))
856 .pointerValue<SpecificEntityAnnotation>();
857 // All retrieved lines/tokens have the same netype. Depending on the
858 // output style (CoNLL 2003, CoNLL-U, …), the generated line is different
859 // and the ne-Type includes or not BIO information using in this case the
860 // previousNeType member.
861 previousNeType = "O";
862 // bool first = true;
863 vertexToToken[v] = tokenId;
864 tokenId++;
865 for (const auto& vse : se->vertices())
866 {
867 auto posVertices = annotationData->matches("AnalysisGraph", vse, "PosGraph");
868 auto posVertex = *posVertices.begin();
869 // @TODO Should follow instructions here to output all MWE:
870 // https://universaldependencies.org/format.html#words-tokens-and-empty-nodes
871
872 // TODO Get correct UD dep relation for relations inside the named entity
873 // and for the token that must be linked to the outside. For this one, the
874 // relation is the one which links to posGraphVertex to the rest of the pos
875 // graph.
876 auto [conllRelName, targetConllId] = getConllRelName(v);
877
878 vertexToToken[posVertex] = tokenId;
879 // std::cerr << "docFrom_analysis pushing token" << std::endl;
880 // first = false;
881 }
882 previousNeType = neType;
883 }
884 }
885 }
886 else
887 {
888 vertexToToken[v] = tokenId;
889 tokenId++;
890 }
891
893
894 auto [it, it_end] = boost::out_edges(v, *posGraph);
895 if (it != it_end)
896 {
897 v = boost::target(*it, *posGraph);
898 }
899 else
900 {
901 v = lastVertex;
902 }
903
904 }
905}
906
908 std::shared_ptr<Lima::AnalysisContent> /*analysis*/)
909{
910 auto dcurrent = syntacticData->depVertexForTokenVertex(v);
911 auto depGraph = syntacticData->dependencyGraph();
912 for (auto [dit, dit_end] = boost::out_edges(dcurrent, *depGraph); dit != dit_end; dit++)
913 {
914 auto typeMap = get(edge_deprel_type, *depGraph);
915 auto type = typeMap[*dit];
916 auto syntRelName = languageData->getSyntacticRelationName(type);
917 auto dest = syntacticData->tokenVertexForDepVertex(
918 boost::target(*dit, *depGraph));
919 if (syntRelName != "")
920 {
921 vertexDependencyInformations.insert(std::make_pair(v, std::make_pair(dest, syntRelName)));
922 }
923 }
924}
925
927{
928 // std::cerr << "LimaAnalyzerPrivate::getNeType "<< posGraphVertex << std::endl;
929 auto neType = QString::fromUtf8("_") ;
930 if (annotationData != nullptr)
931 {
932 // Check if the PosGraph vertex holds a specific entity
933 // std::cerr << "LimaAnalyzerPrivate::getNeType call matches with " << "PosGraph"
934 // << " and " << posGraphVertex << std::endl;
935 auto matches = annotationData->matches("PosGraph", posGraphVertex, "annot");
936 // std::cerr << "LimaAnalyzerPrivate::getNeType got" << matches.size() << " matches" << std::endl;
937 for (const auto& vx: matches)
938 {
939 // std::cerr << "LimaAnalyzerPrivate::getNeType on match " << vx << std::endl;
940 if (annotationData->hasAnnotation(vx, QString::fromUtf8("SpecificEntity")))
941 {
942 auto se = annotationData->annotation(vx, QString::fromUtf8("SpecificEntity")).
943 pointerValue<SpecificEntityAnnotation>();
944 neType = MedData::single().getEntityName(se->getType());
945 break;
946 }
947 }
948 if (neType == "_")
949 {
950 // The PosGraph vertex did not hold a specific entity,
951 // check if the AnalysisGraph vertex does
952 // std::cerr << "LimaAnalyzerPrivate::getNeType checking AnalysisGraph" << std::endl;
953 auto anaVertices = annotationData->matches("PosGraph", posGraphVertex, "AnalysisGraph");
954 // note: anaVertices size should be 0 or 1
955 for (const auto& anaVertex: anaVertices)
956 {
957 // std::cerr << "LimaAnalyzerPrivate::getNeType on AnalysisGraph vertex " << anaVertex << std::endl;
958 auto matches = annotationData->matches("AnalysisGraph", anaVertex, "annot");
959 for (const auto& vx: matches)
960 {
961 // std::cerr << "LimaAnalyzerPrivate::getNeType on ana match " << vx << std::endl;
962 if (annotationData->hasAnnotation(vx, QString::fromUtf8("SpecificEntity")))
963 {
964 auto se = annotationData->annotation(vx, QString::fromUtf8("SpecificEntity"))
965 .pointerValue<SpecificEntityAnnotation>();
966 neType = MedData::single().getEntityName(se->getType());
967 break;
968 }
969 }
970 if (neType != "_") break;
971 }
972 }
973 }
974 // std::cerr << "LimaAnalyzerPrivate::getNeType for " << posGraphVertex << ". result = " << neType << std::endl;
975 return neType;
976}
977
979{
980#ifdef DEBUG_LP
982 LDEBUG << "LimaAnalyzerPrivate::getConllRelName" << v << vertexDependencyInformations.count(v);
983#endif
984 QString conllRelName = "_";
985 int targetConllId = 0;
986 if (vertexDependencyInformations.count(v) != 0)
987 {
988 auto target = vertexDependencyInformations.find(v)->second.first;
989#ifdef DEBUG_LP
990 LDEBUG << "LimaAnalyzerPrivate::getConllRelName target saved for" << v << "is" << target;
991#endif
992 if (vertexToToken.find(target) != vertexToToken.end())
993 {
994 targetConllId = vertexToToken.find(target)->second;
995 }
996 else if (vertexDependencyInformations.find(v)->second.second != "root"
997 && vertexDependencyInformations.find(v)->second.second != "ROOT")
998 {
999 // The root's target is the sentence boundary vertex, not a token
1001 LERROR << "LimaAnalyzerPrivate::getConllRelName target" << target << "not found in segmentation mapping";
1002 }
1003#ifdef DEBUG_LP
1004 LDEBUG << "LimaAnalyzerPrivate::getConllRelName conll target saved for " << v << " is " << targetConllId;
1005#endif
1006 auto relName = QString::fromStdString(vertexDependencyInformations.find(v)->second.second);
1007#ifdef DEBUG_LP
1008 LDEBUG << "LimaAnalyzerPrivate::getConllRelName the lima dependency tag for " << v << " is " << relName;
1009#endif
1010 if (conllLimaDepMapping.contains(relName))
1011 {
1012 conllRelName = conllLimaDepMapping[relName];
1013 }
1014 else
1015 {
1016 conllRelName = relName;
1017// LERROR << "LimaAnalyzerPrivate::getConllRelName" << relName << "not found in mapping";
1018 }
1019
1020 // There is no way for vertex to have 0 as head.
1021 if (conllRelName == "root")
1022 {
1023 targetConllId = 0;
1024 }
1025 }
1026 else
1027 {
1028#ifdef DEBUG_LP
1029 LDEBUG << "LimaAnalyzerPrivate::getConllRelName no target saved for" << v;
1030#endif
1031 }
1032#ifdef DEBUG_LP
1033 LDEBUG << "LimaAnalyzerPrivate::getConllRelName result for" << v << "is" << conllRelName << targetConllId;
1034#endif
1035 return { conllRelName, targetConllId };
1036}
1037
1039 LinguisticGraphVertex v) const
1040{
1041 // check only entity found in current graph (not previous graph such as AnalysisGraph)
1042
1043 for (const auto& vx: annotationData->matches("PosGraph", v, "annot"))
1044 {
1045 if (annotationData->hasAnnotation(vx, QString::fromUtf8("SpecificEntity")))
1046 {
1047 //BoWToken* se = createSpecificEntity(v,*it, annotationData, anagraph, posgraph, offsetBegin);
1048 auto se = annotationData->annotation(
1049 vx,
1050 QString::fromUtf8("SpecificEntity")).pointerValue<SpecificEntityAnnotation>();
1051 if (se != nullptr)
1052 {
1053 return se;
1054 }
1055 }
1056 }
1057 return nullptr;
1058
1059}
1060
1062{
1063 auto ft = get(vertex_token, *graph, v);
1064 bool SpaceAfter = true;
1065 LinguisticGraphOutEdgeIt outIter, outIterEnd;
1066 for (auto [outIter, outIterEnd] = boost::out_edges(v, *graph);
1067 outIter != outIterEnd; outIter++)
1068 {
1069 auto next = boost::target(*outIter, *graph);
1070 auto nt = get(vertex_token, *graph, next);
1071 if( nt != nullptr && (nt->position() == ft->position()+ft->length()) )
1072 {
1073 SpaceAfter = false;
1074 break;
1075 }
1076 }
1077 return SpaceAfter;
1078}
1079
1081{
1082 return QString::fromUtf8(static_cast<const LangData&>(
1083 MedData::single().mediaData(medId)).getPropertyCodeManager()
1084 .getPropertyManager("MICRO")
1085 .getPropertySymbolicValue(morphoData.firstValue(
1086 *propertyAccessor)).c_str());
1087}
This file is the main header file for the data related to annotation graphs.
A graph that stores the relations of syntactic dependency between the elements of a DependencyGraph.
@ edge_deprel_type
#define LIMA_PATH_SEPARATOR
Definition FileUtils.h:25
#define LDEBUG
Definition LimaCommon.h:157
#define LERROR
Definition LimaCommon.h:161
@ vertex_token
LinguisticGraph::vertex_descriptor LinguisticGraphVertex
LinguisticGraph::out_edge_iterator LinguisticGraphOutEdgeIt
boost::adjacency_list< boost::vecS, boost::vecS, boost::bidirectionalS, LinguisticVertexProperties > LinguisticGraph
Property to identify the chains in the graph.
#define DUMPERLOGINIT
Data used for the syntactic analyzis of texts.
const FsaStringsPool * sp
Definition lima.cpp:218
LinguisticGraph * posGraph
Definition lima.cpp:224
std::unique_ptr< LTRTextHandler > ltrTextHandler
Definition lima.cpp:243
std::unique_ptr< BowTextWriter > bowTextWriter
Definition lima.cpp:239
void initMetaData()
Definition lima.cpp:555
QMap< QString, QString > conllLimaDepMapping
Definition lima.cpp:231
QString getNeType(LinguisticGraphVertex posGraphVertex)
Gets the named entity type for the PosGraph vertex posGraphVertex if it is a specific entity.
Definition lima.cpp:926
const std::string analyzeText(const std::string &text, const std::string &lang, const std::string &pipeline, const std::string &meta)
Definition lima.cpp:667
LimaAnalyzerPrivate & operator=(const LimaAnalyzerPrivate &a)=delete
QString previousNeType
Definition lima.cpp:216
const LanguageData * languageData
Definition lima.cpp:222
friend class LimaAnalyzer
Definition lima.cpp:169
std::map< LinguisticGraphVertex, int > vertexToToken
Definition lima.cpp:234
AnnotationData * annotationData
Definition lima.cpp:226
QStringList qlangs
Definition lima.cpp:248
void collectDependencyInformations(std::shared_ptr< Lima::AnalysisContent > analysis)
Definition lima.cpp:780
std::unique_ptr< SimpleStreamHandler > fullXmlSimpleStreamHandler
Definition lima.cpp:242
std::map< std::string, AbstractAnalysisHandler * > handlers
Definition lima.cpp:238
std::shared_ptr< SyntacticData > syntacticData
Definition lima.cpp:227
QJsonObject objectFromString(const QString &in)
Definition lima.cpp:590
const SpecificEntityAnnotation * getSpecificEntityAnnotation(LinguisticGraphVertex v) const
Definition lima.cpp:1038
LimaAnalyzerPrivate(const LimaAnalyzerPrivate &a)=delete
QString modulePath
Definition lima.cpp:250
std::unique_ptr< BowTextHandler > bowTextHandler
Definition lima.cpp:240
std::pair< QString, int > getConllRelName(LinguisticGraphVertex v)
Definition lima.cpp:978
bool addPipelineUnit(const std::string &pipeline, const std::string &media, const std::string &jsonGroupString)
Definition lima.cpp:616
const Common::PropertyCode::PropertyAccessor * propertyAccessor
Definition lima.cpp:223
QString getFeats(const LinguisticAnalysisStructure::MorphoSyntacticData &morphoData)
Definition lima.cpp:731
const PropertyCodeManager * propertyCodeManager
Definition lima.cpp:236
void reset()
Reset all members used to store analysis states.
Definition lima.cpp:538
QString getMicro(LinguisticAnalysisStructure::MorphoSyntacticData &morphoData)
Definition lima.cpp:1080
QStringList qpipelines
Definition lima.cpp:249
std::shared_ptr< AbstractLinguisticProcessingClient > m_client
Definition lima.cpp:245
void collectVertexDependencyInformations(LinguisticGraphVertex v, std::shared_ptr< Lima::AnalysisContent > analysis)
Definition lima.cpp:907
std::set< std::string > dumpers
Definition lima.cpp:244
std::map< std::string, std::string > metaData
Definition lima.cpp:246
LinguisticGraph * anaGraph
Definition lima.cpp:225
LimaAnalyzerPrivate(const QStringList &qlangs, const QStringList &qpipelines, const QString &modulePath, const QString &user_config_path, const QString &user_resources_path, const QString &meta)
Definition lima.cpp:294
QString user_resources_path
Definition lima.cpp:252
std::unique_ptr< SimpleStreamHandler > simpleStreamHandler
Definition lima.cpp:241
bool hasSpaceAfter(LinguisticGraphVertex v, LinguisticGraph *graph)
Definition lima.cpp:1061
QString user_config_path
Definition lima.cpp:251
std::map< LinguisticGraphVertex, std::pair< LinguisticGraphVertex, std::string > > vertexDependencyInformations
Definition lima.cpp:230
std::string errorMessage
Definition lima.h:102
LimaAnalyzer & operator=(const LimaAnalyzer &a)
Definition lima.cpp:515
LimaAnalyzer(const std::string &langs, const std::string &pipelines, const std::string &modulePath, const std::string &user_config_path="", const std::string &user_resources_path="", const std::string &meta="")
Definition lima.cpp:464
friend class LimaAnalyzerPrivate
Definition lima.h:79
~LimaAnalyzer()
Definition lima.cpp:490
std::string analyzeText(const std::string &text, const std::string &lang="", const std::string &pipeline="", const std::string &meta="")
Definition lima.cpp:642
bool addPipelineUnit(const std::string &pipeline, const std::string &media, const std::string &jsonGroupString)
Definition lima.cpp:576
bool error
Definition lima.h:101
virtual void setOut(std::ostream *out)=0
set the output stream.
Holds an annotation graph and gives an API to manipulate it.
Holds linguistic data for one language.
holds data about codes and names for grammatical categories, etc.
const std::string & getMediaId(MediaId idNum) const
LimaString getEntityName(const EntityType &type) const
Provide function to read write and check a property.
Provide tools to parse a property file, and deal with the property coding system.
Parser class for the lima's xml configuration files.
Use this exception to signal an error in one of the configuration files.
Definition LimaCommon.h:345
The main LIMA exception class.
Definition LimaCommon.h:262
LinguisticCode firstValue(const Common::PropertyCode::PropertyAccessor &propertyAccessor) const
Return the first non empty value for the given accessor.
A representation of a specific entity to store in the annotation graph.
const std::map< MediaId, MediaProcessUnit::Manager * > & managers() const
static std::shared_ptr< InitializableObjectFactory< MediaProcessUnit > > getFactory(const std::string &id)
static const AmosePluginsManager & single()
Definition Singleton.h:51
static AmosePluginsManager & changeable()
Definition Singleton.h:71
originally detectGroupConfigurationStructure.h in detectlibraries
int run(int aargc, char **aargv)
Definition main.cpp:31
std::shared_ptr< std::ostringstream > openHandlerOutputString(AbstractTextualAnalysisHandler *handler, const std::set< std::string > &dumpers, const std::string &dumperId)
Definition lima.cpp:713
Lima::Common::MediaticData::LanguageData LangData
Definition lima.cpp:120
Lima::Common::MediaticData::MediaticData MedData
Definition lima.cpp:121
QStringList buildResourcesDirectoriesList(const QStringList &projects, const QStringList &paths)
Build a list of resources directories from a list of project names and a list of paths.
QStringList buildConfigurationDirectoriesList(const QStringList &projects, const QStringList &paths)
Build a list of configuration directories from a list of project names and a list of paths.
NAUTITIA.
LIMA_COMMONQSLOG_EXPORT bool initQsLog(const QString &configString)
std::string operator()(const FindResultT &Match) const
Definition lima.cpp:130