-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlima.cpp
More file actions
1630 lines (1488 loc) · 58 KB
/
lima.cpp
File metadata and controls
1630 lines (1488 loc) · 58 KB
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2022 CEA LIST
// SPDX-FileCopyrightText: 2019-2022 CEA LIST <gael.de-chalendar@cea.fr>
//
// SPDX-License-Identifier: MIT
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt for Python examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "lima.h"
#include "Doc.h"
#include "Doc_private.h"
#include "Span.h"
#include "Token.h"
#include "common/AbstractFactoryPattern/AmosePluginsManager.h"
#include "common/LimaCommon.h"
#include "common/LimaVersion.h"
#include "common/Data/strwstrtools.h"
#include "common/MediaticData/mediaticData.h"
#include "common/MediaProcessors/MediaProcessors.h"
#include "common/MediaProcessors/MediaProcessUnit.h"
#include <common/ProcessUnitFramework/AnalysisContent.h>
#include "common/QsLog/QsLog.h"
#include "common/QsLog/QsLogDest.h"
#include "common/QsLog/QsLogCategories.h"
#include "common/QsLog/QsDebugOutput.h"
#include "common/XMLConfigurationFiles/groupConfigurationStructure.h"
#include "common/XMLConfigurationFiles/xmlConfigurationFileParser.h"
#include "common/time/traceUtils.h"
#include "common/tools/FileUtils.h"
#include "common/tools/LimaMainTaskRunner.h"
#include "linguisticProcessing/common/annotationGraph/AnnotationData.h"
#include "linguisticProcessing/common/linguisticData/languageData.h"
#include <linguisticProcessing/common/linguisticData/LimaStringText.h>
#include "linguisticProcessing/common/PropertyCode/PropertyCodeManager.h"
#include "linguisticProcessing/client/LinguisticProcessingClientFactory.h"
#include "linguisticProcessing/client/AnalysisHandlers/BowTextWriter.h"
#include "linguisticProcessing/client/AnalysisHandlers/BowTextHandler.h"
#include "linguisticProcessing/client/AnalysisHandlers/SimpleStreamHandler.h"
#include "linguisticProcessing/client/AnalysisHandlers/LTRTextHandler.h"
#include "linguisticProcessing/core/Automaton/SpecificEntityAnnotation.h"
#include <linguisticProcessing/core/LinguisticAnalysisStructure/AnalysisGraph.h>
#include "linguisticProcessing/core/LinguisticAnalysisStructure/MorphoSyntacticData.h"
#include "linguisticProcessing/core/LinguisticProcessors/LinguisticMetaData.h"
#include "linguisticProcessing/core/LinguisticResources/AbstractResource.h"
#include "linguisticProcessing/core/LinguisticResources/LinguisticResources.h"
#include "linguisticProcessing/core/SyntacticAnalysis/DependencyGraph.h"
#include "linguisticProcessing/core/SyntacticAnalysis/SyntacticData.h"
#include "linguisticProcessing/core/TextSegmentation/SegmentationData.h"
#include <deque>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find_format.hpp>
#include <boost/algorithm/string/finder.hpp>
#include <boost/format.hpp>
#include <QtCore/QCoreApplication>
#include <QtCore/QString>
#include <QtCore>
#define DEBUG_LP
using namespace Lima::LinguisticProcessing;
using namespace Lima::LinguisticProcessing::SpecificEntities;
using namespace Lima::LinguisticProcessing::SyntacticAnalysis;
using namespace Lima::Common::AnnotationGraphs;
using namespace Lima::Common::MediaticData;
using LangData = Lima::Common::MediaticData::LanguageData;
using MedData = Lima::Common::MediaticData::MediaticData ;
using namespace Lima::Common::Misc;
using namespace Lima::Common::PropertyCode;
using namespace Lima::Common::XMLConfigurationFiles;
using namespace Lima;
struct character_escaper
{
template<typename FindResultT>
std::string operator()(const FindResultT& Match) const
{
std::string s;
for (typename FindResultT::const_iterator i = Match.begin();
i != Match.end();
i++) {
s += boost::str(boost::format("\\x%02x") % static_cast<int>(*i));
}
return s;
}
};
std::shared_ptr< std::ostringstream > openHandlerOutputString(
AbstractTextualAnalysisHandler* handler,
const std::set<std::string>&dumpers,
const std::string& dumperId);
int run(int aargc,char** aargv);
class LimaAnalyzerPrivate
{
friend class LimaAnalyzer;
public:
LimaAnalyzerPrivate(const QStringList& qlangs,
const QStringList& qpipelines,
const QString& modulePath,
const QString& user_config_path,
const QString& user_resources_path,
const QString& meta);
~LimaAnalyzerPrivate() = default;
LimaAnalyzerPrivate(const LimaAnalyzerPrivate& a) = delete;
LimaAnalyzerPrivate& operator=(const LimaAnalyzerPrivate& a) = delete;
const std::string analyzeText(const std::string& text,
const std::string& lang,
const std::string& pipeline,
const std::string& meta);
Doc operator()(const std::string& text,
const std::string& lang="eng",
const std::string& pipeline="main",
const std::string& meta="");
bool addPipelineUnit(const std::string& pipeline,
const std::string& media,
const std::string& jsonGroupString);
void collectDependencyInformations(std::shared_ptr<Lima::AnalysisContent> analysis);
void collectVertexDependencyInformations(LinguisticGraphVertex v,
std::shared_ptr<Lima::AnalysisContent> analysis);
Doc docFrom_analysis(std::shared_ptr<Lima::AnalysisContent> analysis);
int dumpPosGraphVertex(Doc& doc,
LinguisticGraphVertex v,
int& tokenId,
LinguisticGraphVertex vEndDone,
const QString& parentNeType,
bool first);
int dumpAnalysisGraphVertex(Doc& doc,
LinguisticGraphVertex v,
LinguisticGraphVertex posGraphVertex,
int& tokenId,
LinguisticGraphVertex vEndDone,
const QString& neType,
bool first,
const Automaton::EntityFeatures& features);
void dumpNamedEntity(Doc& doc,
LinguisticGraphVertex v,
int& tokenId,
LinguisticGraphVertex vEndDone,
const QString& neType);
/** Gets the named entity type for the PosGraph vertex @ref posGraphVertex
* if it is a specific entity. Return "_" otherwise
*/
QString getNeType(LinguisticGraphVertex posGraphVertex);
std::pair<QString, int> getConllRelName(LinguisticGraphVertex v);
const SpecificEntityAnnotation* getSpecificEntityAnnotation(LinguisticGraphVertex v) const;
bool hasSpaceAfter(LinguisticGraphVertex v, LinguisticGraph* graph);
QString getMicro(LinguisticAnalysisStructure::MorphoSyntacticData& morphoData);
QString getFeats(const LinguisticAnalysisStructure::MorphoSyntacticData& morphoData);
/** Reset all members used to store analysis states. To be called before handling a new analysis. */
void reset();
std::map<std::string, std::string> parseMetaData(const QString& meta,
QChar comma = ',',
QChar colon = ':',
const std::map<std::string, std::string>& append = {});
QString previousNeType;
const FsaStringsPool* sp = nullptr;
MediaId medId;
const LanguageData* languageData = nullptr;
const Common::PropertyCode::PropertyAccessor* propertyAccessor = nullptr;
LinguisticGraph* posGraph = nullptr;
LinguisticGraph* anaGraph = nullptr;
std::shared_ptr<AnnotationData> annotationData = nullptr;
std::shared_ptr<SyntacticData> syntacticData = nullptr;
std::map< LinguisticGraphVertex,
std::pair<LinguisticGraphVertex,
std::string> > vertexDependencyInformations;
QMap<QString, QString> conllLimaDepMapping;
std::map<LinguisticGraphVertex, int> vertexToToken;
const PropertyCodeManager* propertyCodeManager = nullptr;
// Fixed members that do not change at each analysis
std::map<std::string, AbstractAnalysisHandler*> handlers;
std::unique_ptr<BowTextWriter> bowTextWriter = nullptr;
std::unique_ptr<BowTextHandler> bowTextHandler = nullptr;
std::unique_ptr<SimpleStreamHandler> simpleStreamHandler = nullptr;
std::unique_ptr<SimpleStreamHandler> fullXmlSimpleStreamHandler = nullptr;
std::unique_ptr<LTRTextHandler> ltrTextHandler = nullptr;
std::set<std::string> dumpers = {"text"};
std::shared_ptr< AbstractLinguisticProcessingClient > m_client;
std::map<std::string,std::string> metaData;
// Store constructor parameters to be able to implement copy constructor
QStringList qlangs;
QStringList qpipelines;
QString modulePath;
QString user_config_path;
QString user_resources_path;
QString meta;
bool error = false;
std::string errorMessage = "";
};
LimaAnalyzerPrivate::LimaAnalyzerPrivate(const QStringList& iqlangs,
const QStringList& iqpipelines,
const QString& imodulePath,
const QString& iuser_config_path,
const QString& iuser_resources_path,
const QString& imeta) :
qlangs(iqlangs), qpipelines(iqpipelines), modulePath(imodulePath),
user_config_path(iuser_config_path), user_resources_path(iuser_resources_path), meta(imeta)
{
int argc = 1;
char* argv[2] = {(char*)("LimaAnalyzer"), NULL};
QCoreApplication app(argc, argv);
if(iqlangs.size() == 0)
{
throw LimaException("Must initialize at least one language");
}
if(iqpipelines.size() == 0)
{
throw LimaException("Must initialize at least one pipeline");
}
QStringList additionalPaths({modulePath+"/config"});
// Add here LIMA_CONF content in front, otherwise it will be ignored
auto limaConf = QString::fromUtf8(qgetenv("LIMA_CONF").constData());
if (!limaConf.isEmpty())
additionalPaths = limaConf.split(LIMA_PATH_SEPARATOR,
Qt::SkipEmptyParts) + additionalPaths;
// Add then the user path in front again such that it takes precedence on environment variable
if (!user_config_path.isEmpty())
additionalPaths.push_front(user_config_path);
auto configDirs = buildConfigurationDirectoriesList(QStringList({"lima"}),
additionalPaths);
auto configPath = configDirs.join(LIMA_PATH_SEPARATOR);
QStringList additionalResourcePaths({modulePath+"/resources"});
// Add here LIMA_RESOURCES content in front, otherwise it will be ignored
auto limaRes = QString::fromUtf8(qgetenv("LIMA_RESOURCES").constData());
if (!limaRes.isEmpty())
additionalResourcePaths = limaRes.split(LIMA_PATH_SEPARATOR, Qt::SkipEmptyParts) + additionalResourcePaths;
if (!user_resources_path.isEmpty())
additionalResourcePaths.push_front(user_resources_path);
auto resourcesDirs = buildResourcesDirectoriesList(QStringList({"lima"}),
additionalResourcePaths);
auto resourcesPath = resourcesDirs.join(LIMA_PATH_SEPARATOR);
QsLogging::initQsLog(configPath);
// std::cerr << "QsLog initialized" << std::endl;
// Necessary to initialize factories
Lima::AmosePluginsManager::single();
// std::cerr << "LimaAnalyzerPrivate::LimaAnalyzerPrivate() plugins manager created" << std::endl;
if (!Lima::AmosePluginsManager::changeable().loadPlugins(configPath))
{
throw InvalidConfiguration("loadLibrary method failed.");
}
// std::cerr << "Amose plugins are now initialized hop" << std::endl;
// qDebug() << "Amose plugins are now initialized";
std::string lpConfigFile = "lima-analysis.xml";
std::string commonConfigFile = "lima-common.xml";
std::string clientId = "lima-coreclient";
std::string strConfigPath;
// parse 'meta' argument to add metadata
metaData = parseMetaData(meta, ',', ':', metaData);
std::deque<std::string> pipelines;
for (const auto& pipeline: qpipelines)
pipelines.push_back(pipeline.toStdString());
uint64_t beginTime=TimeUtils::getCurrentTime();
std::deque<std::string> langs;
for (const auto& lang: qlangs)
langs.push_back(lang.toStdString());
// std::cerr << "LimaAnalyzerPrivate::LimaAnalyzerPrivate()"
// << "\tresources path: " << resourcesPath.toUtf8().constData() << "," << std::endl
// << "\tconfig path: " << configPath.toUtf8().constData() << "," << std::endl
// << "\tconfig file: " << commonConfigFile << "," << std::endl
// << "\tfirst lang: " << langs.front() << "," << std::endl
// << "\tfirst pipeline: " << pipelines.front() << "," << std::endl
// << "\tmetadata:" << std::endl;
// for (const auto& elem: metaData)
// {
// std::cerr << "\t\t" << elem.first << " : " << elem.second << std::endl;
// }
// initialize common
Common::MediaticData::MediaticData::changeable().init(
resourcesPath.toUtf8().constData(),
configPath.toUtf8().constData(),
commonConfigFile,
langs,
metaData);
// std::cerr << "MediaticData initialized" << std::endl;
bool clientFactoryConfigured = false;
Q_FOREACH(QString configDir, configDirs)
{
if (QFileInfo::exists(configDir + "/" + lpConfigFile.c_str()))
{
// std::cerr << "LimaAnalyzerPrivate::LimaAnalyzerPrivate() configuring "
// << (configDir + "/" + lpConfigFile.c_str()).toStdString() << ", "
// << clientId << std::endl;
// initialize linguistic processing
Lima::Common::XMLConfigurationFiles::XMLConfigurationFileParser lpconfig(
(configDir + "/" + lpConfigFile.c_str()));
LinguisticProcessingClientFactory::changeable().configureClientFactory(
clientId,
lpconfig,
langs,
pipelines);
clientFactoryConfigured = true;
break;
}
}
if(!clientFactoryConfigured)
{
std::cerr << "No LinguisticProcessingClientFactory were configured with"
<< configDirs.join(LIMA_PATH_SEPARATOR).toStdString()
<< "and" << lpConfigFile << std::endl;
throw LimaException("Configuration failure");
}
// std::cerr << "Client factory configured" << std::endl;
m_client = std::dynamic_pointer_cast<AbstractLinguisticProcessingClient>(
LinguisticProcessingClientFactory::single().createClient(clientId));
// Set the handlers
bowTextWriter = std::make_unique<BowTextWriter>();
handlers.insert(std::make_pair("bowTextWriter", bowTextWriter.get()));
bowTextHandler = std::make_unique<BowTextHandler>();
handlers.insert(std::make_pair("bowTextHandler", bowTextHandler.get()));
simpleStreamHandler = std::make_unique<SimpleStreamHandler>();
handlers.insert(std::make_pair("simpleStreamHandler", simpleStreamHandler.get()));
fullXmlSimpleStreamHandler = std::make_unique<SimpleStreamHandler>();
handlers.insert(std::make_pair("fullXmlSimpleStreamHandler", fullXmlSimpleStreamHandler.get()));
ltrTextHandler= std::make_unique<LTRTextHandler>();
handlers.insert(std::make_pair("ltrTextHandler", ltrTextHandler.get()));
// std::cerr << "LimaAnalyzerPrivate constructor done" << std::endl;
}
LimaAnalyzer::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)
{
try
{
QStringList qlangs = QString::fromStdString(langs).split(",",
Qt::SkipEmptyParts);
QStringList qpipelines = QString::fromStdString(pipelines).split(
",", Qt::SkipEmptyParts);
m_d = new LimaAnalyzerPrivate(qlangs, qpipelines,
QString::fromStdString(modulePath),
QString::fromStdString(user_config_path),
QString::fromStdString(user_resources_path),
QString::fromStdString(meta));
}
catch (const Lima::LimaException& e)
{
std::cerr << "Lima internal error: " << e.what() << std::endl;
m_d = nullptr;
}
catch (const std::runtime_error& e)
{
std::cerr << "Lima internal error: " << e.what() << std::endl;
m_d = nullptr;
}
}
LimaAnalyzer::~LimaAnalyzer()
{
delete m_d;
}
LimaAnalyzer::LimaAnalyzer(const LimaAnalyzer& a)
{
try
{
m_d = new LimaAnalyzerPrivate(a.m_d->qlangs, a.m_d->qpipelines,
a.m_d->modulePath,
a.m_d->user_config_path,
a.m_d->user_resources_path,
a.m_d->meta);
}
catch (const Lima::LimaException& e)
{
std::cerr << "Lima internal error: " << e.what() << std::endl;
m_d = nullptr;
}
catch (const std::runtime_error& e)
{
std::cerr << "Lima internal error: " << e.what() << std::endl;
m_d = nullptr;
}
// std::cerr << "LimaAnalyzer::LimaAnalyzer copy constructor" << std::endl;
}
LimaAnalyzer& LimaAnalyzer::operator=(const LimaAnalyzer& a)
{
try
{
// std::cerr << "LimaAnalyzer::operator=" << std::endl;
delete m_d;
m_d = new LimaAnalyzerPrivate(a.m_d->qlangs, a.m_d->qpipelines,
a.m_d->modulePath,
a.m_d->user_config_path,
a.m_d->user_resources_path,
a.m_d->meta);
return *this;
}
catch (const Lima::LimaException& e)
{
std::cerr << "Lima internal error: " << e.what() << std::endl;
m_d = nullptr;
}
catch (const std::runtime_error& e)
{
std::cerr << "Lima internal error: " << e.what() << std::endl;
m_d = nullptr;
}
return *this;
}
/** return true if an error occured */
bool LimaAnalyzer::error()
{
return m_d == nullptr || m_d->error;
}
/** return the error message if an error occured and reset the error state */
std::string LimaAnalyzer::errorMessage()
{
if (m_d == nullptr)
{
return "Error during constructor";
}
std::string result = m_d->errorMessage;
m_d->reset();
return result;
}
void LimaAnalyzerPrivate::reset()
{
previousNeType = "O";
sp = nullptr;
medId = 0;
languageData = nullptr;
syntacticData = nullptr;
propertyAccessor = nullptr;
posGraph = nullptr;
anaGraph = nullptr;
annotationData = nullptr;
propertyCodeManager = nullptr;
vertexDependencyInformations.clear();
conllLimaDepMapping.clear();
vertexToToken.clear();
error = false;
errorMessage = "";
}
Doc LimaAnalyzer::operator()(const std::string& text,
const std::string& lang,
const std::string& pipeline,
const std::string& meta)
{
if (m_d == nullptr)
{
auto doc = Doc(true, "No analyzer available");
return doc;
}
else if (m_d->error)
{
m_d->error = true;
m_d->errorMessage = "Invalid Lima analyzer. Previous error message was: " + m_d->errorMessage;
auto doc = Doc(true, m_d->errorMessage);
return doc;
}
try
{
return (*m_d)(text, lang, pipeline, meta);
}
catch (const Lima::LimaException& e)
{
std::cerr << "Lima internal error: " << e.what() << std::endl;
m_d->error = true;
m_d->errorMessage = e.what();
auto doc = Doc(m_d->error, m_d->errorMessage);
return doc;
}
catch (const std::runtime_error& e)
{
std::cerr << "Lima internal error: " << e.what() << std::endl;
m_d->error = true;
m_d->errorMessage = e.what();
auto doc = Doc(m_d->error, m_d->errorMessage);
return doc;
}
}
std::string LimaAnalyzer::analyzeText(const std::string& text,
const std::string& lang,
const std::string& pipeline,
const std::string& meta) const
{
// std::cerr << "LimaAnalyzer::analyzeText" << std::endl;
if (m_d == nullptr)
{
return "";
}
else if (m_d->error)
{
m_d->errorMessage = "Invalid Lima analyzer. Previous error message was: " + m_d->errorMessage;
return "";
}
try
{
return m_d->analyzeText(text, lang, pipeline, meta);
}
catch (const Lima::LimaException& e)
{
std::cerr << "Lima internal error: " << e.what() << std::endl;
m_d->error = true;
m_d->errorMessage = e.what();
return "";
}
catch (const std::runtime_error& e)
{
std::cerr << "Lima internal error: " << e.what() << std::endl;
m_d->error = true;
m_d->errorMessage = e.what();
return "";
}
}
Doc LimaAnalyzerPrivate::operator()(
const std::string& text,
const std::string& lang,
const std::string& pipeline,
const std::string& meta)
{
auto localMetaData = metaData;
localMetaData["FileName"]="param";
auto qmeta = QString::fromStdString(meta).split(",", Qt::SkipEmptyParts);
for (const auto& m: qmeta)
{
auto kv = m.split(":", Qt::SkipEmptyParts);
if (kv.size() == 2)
localMetaData[kv[0].toStdString()] = kv[1].toStdString();
}
auto localLang = lang;
if (localLang.size() == 0)
{
localLang = qlangs[0].toStdString();
}
auto localPipeline = pipeline;
if (localPipeline.size() == 0)
{
localPipeline = qpipelines[0].toStdString();
}
localMetaData["Lang"] = localLang;
QString contentText = QString::fromUtf8(text.c_str());
if (contentText.isEmpty())
{
std::cerr << "Empty input ! " << std::endl;
return Doc();
}
else
{
// analyze it
// std::cerr << "Analyzing " << contentText.toStdString() << std::endl;
auto analysis = m_client->analyze(contentText, localMetaData, localPipeline, handlers);
return docFrom_analysis(analysis);
}
}
// std::shared_ptr<Lima::AnalysisContent> LimaAnalyzerPrivate::operator()(
// const std::string& text,
// const std::string& lang,
// const std::string& pipeline,
// const std::string& meta) const
// {
// // qDebug() << "LimaAnalyzerPrivate::analyzeText" << text << lang << pipeline;
// // ("output,o",
// // po::value< std::vector<std::string> >(&outputsv),
// // "where to write dumpers output. By default, each dumper writes its results on a file whose name is the input file with a predefined suffix appended. This option allows to chose another suffix or to write on standard output. Its syntax is the following: <dumper>:<destination> with <dumper> a dumper name and destination, either the value 'stdout' or a suffix.")
// std::vector<std::string> outputsv;
// QMap< QString, QString > outputs;
// for(std::vector<std::string>::const_iterator outputsIt = outputsv.begin();
// outputsIt != outputsv.end(); outputsIt++)
// {
// QStringList output = QString::fromUtf8((*outputsIt).c_str()).split(":");
// if (output.size()==2)
// {
// outputs[output[0]] = output[1];
// }
// else
// {
// // Option syntax error
// std::cerr << "syntax error in output setting:" << *outputsIt << std::endl;
// }
// }
//
//
// // auto bowofs = openHandlerOutputString(bowTextWriter, os, dumpers, "bow");
// auto txtofs = openHandlerOutputString(simpleStreamHandler, dumpers, "text");
// // *txtofs << "hello";
// // auto fullxmlofs = openHandlerOutputString(fullXmlSimpleStreamHandler, os, dumpers, "fullxml");
//
// auto localMetaData = metaData;
// localMetaData["FileName"]="param";
// auto qmeta = QString::fromStdString(meta).split(",");
// for (const auto& m: qmeta)
// {
// auto kv = m.split(":");
// if (kv.size() == 2)
// localMetaData[kv[0].toStdString()] = kv[1].toStdString();
// }
//
// localMetaData["Lang"]=lang;
//
// QString contentText = QString::fromUtf8(text.c_str());
// if (contentText.isEmpty())
// {
// std::cerr << "Empty input ! " << std::endl;
// return std::make_shared<AnalysisContent>();
// }
// else
// {
// // analyze it
// // std::cerr << "Analyzing " << contentText.toStdString() << std::endl;
// try
// {
// return m_client->analyze(contentText, localMetaData, pipeline, handlers, inactiveUnits);
// }
// catch (const Lima::LimaException& e)
// {
// std::cerr << "Lima internal error: " << e.what() << std::endl;
// return std::make_shared<AnalysisContent>();
// }
// }
// }
const std::string LimaAnalyzerPrivate::analyzeText(const std::string& text,
const std::string& lang,
const std::string& pipeline,
const std::string& meta)
{
auto txtofs = openHandlerOutputString(simpleStreamHandler.get(), dumpers, "text");
auto localMetaData = parseMetaData(QString::fromStdString(meta), ',', ':', metaData);
localMetaData["FileName"]="param";
auto qmeta = QString::fromStdString(meta).split(",", Qt::SkipEmptyParts);
for (const auto& m: qmeta)
{
auto kv = m.split(":", Qt::SkipEmptyParts);
if (kv.size() == 2)
localMetaData[kv[0].toStdString()] = kv[1].toStdString();
}
auto localLang = lang;
if (localLang.size() == 0)
{
localLang = qlangs[0].toStdString();
}
auto localPipeline = pipeline;
if (localPipeline.size() == 0)
{
localPipeline = qpipelines[0].toStdString();
}
localMetaData["Lang"] = localLang;
QString contentText = QString::fromUtf8(text.c_str());
if (contentText.isEmpty())
{
std::cerr << "Empty input ! " << std::endl;
}
else
{
// analyze it
// std::cerr << "Analyzing " << contentText.toStdString() << std::endl;
m_client->analyze(contentText, localMetaData, localPipeline, handlers);
}
auto result = txtofs->str();
// std::cerr << "LimaAnalyzerPrivate::analyzeText result: " << result << std::endl;
simpleStreamHandler->setOut(nullptr);
return result;
}
bool LimaAnalyzer::addPipelineUnit(const std::string& pipeline,
const std::string& media,
const std::string& jsonGroupString)
{
return m_d->addPipelineUnit(pipeline, media, jsonGroupString);
}
bool LimaAnalyzerPrivate::addPipelineUnit(const std::string& pipeline,
const std::string& media,
const std::string& jsonGroupString)
{
try
{
QJsonParseError jsonError;
auto jsonDoc = QJsonDocument::fromJson(QByteArray::fromStdString(
jsonGroupString), &jsonError);
if (jsonDoc.isNull())
{
error = true;
errorMessage = std::string("Failed to load json " + jsonGroupString + ":\n" + jsonError.errorString().toStdString());
return false;
}
auto jsonGroup = jsonDoc.object();
auto mediaid = Lima::Common::MediaticData::MediaticData::single().getMediaId(
media);
auto pipe = Lima::MediaProcessors::changeable().getPipelineForId(mediaid,
pipeline);
auto managers = Lima::MediaProcessors::single().managers();
// QString jsonGroupString =
// "{ \"name\":\"cpptftokenizer\", "
// " \"class\":\"CppUppsalaTensorFlowTokenizer\", "
// " \"model_prefix\": \"tokenizer-eng\" }";
GroupConfigurationStructure unitConfig(jsonGroup);
// managers (Manager*) used in init of ProcessUnits are stored in
// m_pipelineManagers of MediaProcessors
auto pu = MediaProcessUnit::Factory::getFactory(
jsonGroup["class"].toString().toStdString())->create(
unitConfig,
managers[mediaid]);
pipe->push_back(pu);
return true;
}
catch (const Lima::LimaException& e)
{
std::cerr << "!!!!!!!!!!! Lima internal error: " << e.what() << std::endl;
error = true;
errorMessage = std::string("Lima internal error:") + e.what();
return false;
}
catch (const std::runtime_error& e)
{
std::cerr << "Lima internal error: " << e.what() << std::endl;
error = true;
errorMessage = std::string("Lima internal error:") + e.what();
return false;
}
}
std::shared_ptr< std::ostringstream > openHandlerOutputString(
AbstractTextualAnalysisHandler* handler,
const std::set<std::string>&dumpers,
const std::string& dumperId)
{
auto ofs = std::make_shared< std::ostringstream >();
if (dumpers.find(dumperId)!=dumpers.end())
{
handler->setOut(ofs.get());
}
else
{
DUMPERLOGINIT;
LERROR << dumperId << "is not in the dumpers list";
}
return ofs;
}
QString LimaAnalyzerPrivate::getFeats(const LinguisticAnalysisStructure::MorphoSyntacticData& morphoData)
{
#ifdef DEBUG_LP
DUMPERLOGINIT;
LDEBUG << "getFeats";
#endif
auto managers = propertyCodeManager->getPropertyManagers();
QStringList featuresList;
for (auto i = managers.cbegin(); i != managers.cend(); i++)
{
auto key = QString::fromUtf8(i->first.c_str());
if (key != "MACRO" && key != "MICRO")
{
const auto& pa = propertyCodeManager->getPropertyAccessor(key.toStdString());
LinguisticCode lc = morphoData.firstValue(pa);
auto value = QString::fromUtf8(i->second.getPropertySymbolicValue(lc).c_str());
if (value != "NONE")
{
featuresList << QString("%1=%2").arg(key).arg(value);
}
}
}
featuresList.sort();
QString features;
QTextStream featuresStream(&features);
if (featuresList.isEmpty())
{
features = "_";
}
else
{
for (auto featuresListIt = featuresList.cbegin(); featuresListIt != featuresList.cend(); featuresListIt++)
{
if (featuresListIt != featuresList.cbegin())
{
featuresStream << "|";
}
featuresStream << *featuresListIt;
}
}
#ifdef DEBUG_LP
LDEBUG << "LimaAnalyzerPrivate::getFeats features:" << features;
#endif
return features;
}
void LimaAnalyzerPrivate::collectDependencyInformations(std::shared_ptr<Lima::AnalysisContent> analysis)
{
#ifdef DEBUG_LP
DUMPERLOGINIT;
LDEBUG << "LimaAnalyzerPrivate::collectVertexDependencyInformations";
#endif
auto posGraphData = std::dynamic_pointer_cast<LinguisticAnalysisStructure::AnalysisGraph>(analysis->getData("PosGraph"));
if (posGraphData == nullptr)
{
std::cerr << "Error: PosGraph has not been produced: check pipeline";
return;
}
auto firstVertex = posGraphData->firstVertex();
auto lastVertex = posGraphData->lastVertex();
auto v = firstVertex;
auto [it, it_end] = boost::out_edges(v, *posGraph);
if (it != it_end)
{
v = boost::target(*it, *posGraph);
}
else
{
v = lastVertex;
}
syntacticData = std::dynamic_pointer_cast<SyntacticData>(analysis->getData("SyntacticData"));
if (syntacticData == nullptr)
{
syntacticData = std::make_shared<SyntacticData>(posGraphData.get(), nullptr);
syntacticData->setupDependencyGraph();
analysis->setData("SyntacticData", syntacticData.get());
}
int tokenId = 0;
while (v != lastVertex)
{
QString neType = getNeType(v);
QString neIOB = "O";
// Collect NE vertices and output them instead of a single line for
// current v. NE vertices can not only be PosGraph
// vertices (and thus can just call dumpPosGraphVertex
// recursively) but also AnalysisGraph vertices. In the latter case, data
// come partly from the AnalysisGraph and partly from the PosGraph
// Furthermore, named entities can be recursive...
if (neType != "_")
{
auto matches = annotationData->matches("PosGraph", v, "annot");
if (!matches.empty())
{
for (const auto& vx: matches)
{
if (annotationData->hasAnnotation(vx, QString::fromUtf8("SpecificEntity")))
{
auto se = annotationData->annotation(vx, QString::fromUtf8("SpecificEntity"))
.pointerValue<SpecificEntityAnnotation>();
previousNeType = "O";
bool first = true;
for (const auto& vse : se->vertices())
{
collectVertexDependencyInformations(vse, analysis);
vertexToToken[vse] = tokenId;
first = false;
}
break;
}
}
}
else
{
auto anaVertices = annotationData->matches("PosGraph", v, "AnalysisGraph");
auto anaVertex = *anaVertices.begin();
if (annotationData->hasAnnotation(anaVertex, QString::fromUtf8("SpecificEntity")))
{
auto se = annotationData->annotation(anaVertex, QString::fromUtf8("SpecificEntity"))
.pointerValue<SpecificEntityAnnotation>();
// All retrieved lines/tokens have the same netype. Depending on the
// output style (CoNLL 2003, CoNLL-U, …), the generated line is different
// and the ne-Type includes or not BIO information using in this case the
// previousNeType member.
previousNeType = "O";
bool first = true;
vertexToToken[v] = tokenId;
tokenId++;
for (const auto& vse : se->vertices())
{
auto posVertices = annotationData->matches("AnalysisGraph", vse, "PosGraph");
auto posVertex = *posVertices.begin();
// @TODO Should follow instructions here to output all MWE:
// https://universaldependencies.org/format.html#words-tokens-and-empty-nodes
// TODO Get correct UD dep relation for relations inside the named entity
// and for the token that must be linked to the outside. For this one, the
// relation is the one which links to posGraphVertex to the rest of the pos
// graph.
auto [conllRelName, targetConllId] = getConllRelName(v);