LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
ConllDumper.cpp
Go to the documentation of this file.
1// Copyright 2002-2020 CEA LIST
2// SPDX-FileCopyrightText: 2022 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
6#include "ConllDumper.h"
13#include "common/misc/escaper.h"
30
31#include <QQueue>
32#include <QSet>
33#include <QStringList>
34
35#include <fstream>
36#include <sstream>
38
39using namespace Lima::Common;
40using namespace Lima::Common::MediaticData;
41using namespace Lima::Common::Misc;
42using namespace Lima::Common::PropertyCode;
44using namespace Lima::Common::AnnotationGraphs;
49
52
53namespace Lima
54{
55
57{
58
59namespace AnalysisDumpers
60{
61
62QStringList FORMATS = {"CoNLL-U", "CoNLL-03"};
63
64// A FORM or LEMMA on one line: a token can span a line break of the text (a
65// tokenizer joining "27" and "000" across one), and a newline or a tab there
66// breaks the line of the token. A space is valid in a CoNLL-U FORM or LEMMA.
67// (Escaping the bytes that are not printable, as before, also escaped every
68// non-ASCII UTF-8 byte and left the LEMMA as it was.)
69static QString oneLine(QString field)
70{
71 return field.replace("\r\n", " ").replace('\r', ' ').replace('\n', ' ').replace('\t', ' ');
72}
73
75
76class ConllDumperPrivate
77{
78 friend class ConllDumper;
79 ConllDumperPrivate();
80
81 ~ConllDumperPrivate() = default;
82
83 LimaStatusCode dumpPosGraphVertex(
84 std::shared_ptr<DumperStream>& dstream,
86 int& tokenId,
87 LinguisticGraphVertex vEndDone,
88 std::map<LinguisticGraphVertex,int>& segmentationMapping,
89 const QString& neType,
90 bool first,
91 const Automaton::EntityFeatures* parentFeatures = nullptr);
92
96 const SpecificEntityAnnotation* posGraphEntity(LinguisticGraphVertex v) const;
97
102 void entityTokenVertices(LinguisticGraphVertex v,
103 std::vector<LinguisticGraphVertex>& out,
104 int depth = 0) const;
105
109 LimaStatusCode dumpAnalysisGraphVertex(
110 std::shared_ptr<DumperStream>& dstream,
112 LinguisticGraphVertex posGraphVertex,
113 int& tokenId,
114 LinguisticGraphVertex vEndDone,
115 const QString& parentNeType,
116 bool first,
117 const Automaton::EntityFeatures& features);
118
122 QString getNeType(LinguisticGraphVertex posGraphVertex);
123
124 std::pair<QString, QString> getConllRelName(
126 std::map<LinguisticGraphVertex,int>& segmentationMapping);
127
128 QStringList getPredicate(LinguisticGraphVertex v);
129
130 bool hasSpaceAfter(LinguisticGraphVertex v, LinguisticGraph* graph);
131
132 QString getMicro(MorphoSyntacticData* morphoData);
133
134 QString getFeats(MorphoSyntacticData* morphoData);
135
138 void flushMultiwordToken(std::shared_ptr<DumperStream>& dstream);
139
143 void dumpNamedEntity(std::shared_ptr<DumperStream>& dstream,
145 int& tokenId,
146 LinguisticGraphVertex vEndDone,
147 std::map<LinguisticGraphVertex,int>& segmentationMapping,
148 const QString& neType);
149
154 void collectPredicateTokens(
155 Lima::AnalysisContent& analysis,
156 LinguisticGraphVertex sentenceBegin,
157 LinguisticGraphVertex sentenceEnd);
158
159 void dumpToken(
160 std::shared_ptr<DumperStream>& dstream,
161 int tokenId, // ID
162 const QString& inflectedToken, // FORM
163 const QString& lemmatizedToken, // LEMMA
164 const QString& micro, // UPOS
165 const QString& xpos, // XPOS
166 const QString& features,// FEATS
167 const QString& targetConllIdString, // HEAD
168 const QString& conllRelName, // DEPREL
169 const QString& deps, // DEPS @TODO
170 const QStringList& miscField,
171 const QString& neType,
172 const QString& previousNeType,
173 const Token* ft = nullptr);
174
175 const SpecificEntityAnnotation* getSpecificEntityAnnotation(
176 LinguisticGraphVertex v) const;
177
178 QString m_format = "CoNLL-U";
179
180 MediaId m_language;
181 bool m_withColsHeader;
182 QString m_graph;
183 QMap<QString, QString> m_conllLimaDepMapping;
184 const Common::PropertyCode::PropertyAccessor* m_propertyAccessor;
185 LinguisticGraph* posGraph;
186 LinguisticGraph* anaGraph;
187 DependencyGraph* depGraph;
188 AnnotationData* annotationData;
189 const LanguageData* languageData;
190 const PropertyCodeManager* propertyCodeManager;
191 const PropertyManager* microManager;
192 const std::map< std::string, PropertyManager >* managers;
193 const FsaStringsPool* sp;
194 QMultiMap<LinguisticGraphVertex, AnnotationGraphVertex> predicates;
195 QString previousNeType;
201 struct MultiwordToken
202 {
203 int firstId = 0;
204 uint64_t begin = 0;
205 uint64_t end = 0;
206 QString surface;
207 std::vector<std::string> lines;
208 };
209 MultiwordToken m_multiword;
210 std::map< LinguisticGraphVertex,
211 std::pair<LinguisticGraphVertex,
212 std::string> > vertexDependencyInformations;
213};
214
215ConllDumperPrivate::ConllDumperPrivate():
216 m_language(0),
217 m_withColsHeader(false),
218 m_graph("PosGraph"),
219 m_conllLimaDepMapping(),
220 posGraph(nullptr),
221 anaGraph(nullptr),
222 depGraph(nullptr),
223 annotationData(nullptr),
224 previousNeType("_")
225{
226}
227
233
235{
236 delete m_d;
237}
238
240 Manager* manager)
241{
243 AbstractTextualAnalysisDumper::init(unitConfiguration, manager);
244
245 try
246 {
247 m_d->m_graph = QString::fromUtf8(unitConfiguration.getParamsValueAtKey("graph").c_str());
248 }
249 catch (NoSuchParam& ) {} // keep default value
250
251 m_d->m_language = manager->getInitializationParameters().media;
252 m_d->languageData = &static_cast<const LanguageData&>(MedData::single().mediaData(m_d->m_language));
253 m_d->propertyCodeManager = &m_d->languageData->getPropertyCodeManager();
254 m_d->microManager = &m_d->propertyCodeManager->getPropertyManager("MICRO");
255 m_d->managers = &m_d->propertyCodeManager->getPropertyManagers();
256 m_d->m_propertyAccessor = &m_d->propertyCodeManager->getPropertyAccessor("MICRO");
257 m_d->sp = &MedData::single().stringsPool(m_d->m_language);
258
259 try
260 {
261 m_d->m_withColsHeader= QString(
262 unitConfiguration.getParamsValueAtKey(
263 "withColsHeader").c_str() ).toLower() == "true";
264 }
265 catch (NoSuchParam& ) {} // keep default value
266
267 try
268 {
269 auto resourcePath = MedData::single().getResourcesPath();
270 auto mappingFile = findFileInPaths(resourcePath.c_str(),
271 unitConfiguration.getParamsValueAtKey(
272 "mappingFile").c_str());
273 std::ifstream ifs(mappingFile.toStdString(), std::ifstream::binary);
274 if (!ifs.good())
275 {
276 LERROR << "ERROR: cannot open" << mappingFile;
277 throw InvalidConfiguration();
278 }
279 while (ifs.good() && !ifs.eof())
280 {
281 auto line = readLine(ifs);
282 QStringList strs = QString::fromUtf8(line.c_str()).split('\t');
283 if (strs.size() == 2)
284 {
285 m_d->m_conllLimaDepMapping.insert(strs[0],strs[1]);
286 }
287 }
288
289 }
291 {
292 LINFO << "no parameter 'mappingFile' in ConllDumper group" << " !";
293// throw InvalidConfiguration();
294 }
295
296 try
297 {
298 m_d->m_format = QString::fromStdString(
299 unitConfiguration.getParamsValueAtKey("format") );
300 if (!FORMATS.contains(m_d->m_format))
301 {
302 QString errorMessage;
303 QTextStream qts(&errorMessage);
304 qts << "Invalid CoNLL dumper configuration. Known formats are"
305 << FORMATS.join(",") << ". Got" << m_d->m_format;
307 LERROR << errorMessage;
308 throw InvalidConfiguration(errorMessage.toStdString());
309 }
310 }
311 catch (NoSuchParam& ) {} // keep default value
312}
313
315{
316#ifdef DEBUG_LP
318 LDEBUG << "ConllDumper::process";
319#endif
320 // The dumper is reused by the analyses of its pipeline, and the vertex ids
321 // of a new analysis start again from 0: the relations of the previous one,
322 // kept (std::map::insert does not replace), gave its heads and relations
323 // to the next one
324 m_d->vertexDependencyInformations.clear();
325
326 auto metadata = std::dynamic_pointer_cast<LinguisticMetaData>(analysis.getData("LinguisticMetaData"));
327 if (metadata == 0)
328 {
330 LERROR << "ConllDumper::process no LinguisticMetaData ! abort";
331 return MISSING_DATA;
332 }
333
334 auto annotationData = std::dynamic_pointer_cast<AnnotationData>(analysis.getData("AnnotationData"));
335 if (annotationData == nullptr)
336 {
338 LINFO << "ConllDumper::process no AnnotationData ! Will not contain NE nor predicates";
339 }
340 m_d->annotationData = annotationData.get();
341 auto posGraphData=std::dynamic_pointer_cast<AnalysisGraph>(analysis.getData(m_d->m_graph.toStdString()));
342 // posGraphData est de type PosGraph et non pas AnalysisGraph
343 if (posGraphData==0)
344 {
346 LERROR << "ConllDumper::process graph" << m_d->m_graph << "has not been produced: check pipeline";
347 return MISSING_DATA;
348 }
349 auto posGraph = posGraphData->getGraph();
350 m_d->posGraph = posGraph;
351
352 auto anaGraphData=std::dynamic_pointer_cast<AnalysisGraph>(analysis.getData("AnalysisGraph"));
353 if (anaGraphData==0)
354 {
356 LERROR << "ConllDumper::process graph AnalysisGraph has not been produced: check pipeline";
357 return MISSING_DATA;
358 }
359 auto anaGraph = anaGraphData->getGraph();
360 m_d->anaGraph = anaGraph;
361
362 auto sd = std::dynamic_pointer_cast<SegmentationData>(analysis.getData("SentenceBoundaries"));
363 if (sd == nullptr)
364 {
366 LERROR << "ConllDumper::process no SentenceBoundaries! abort";
367 return MISSING_DATA;
368 }
369
370 auto syntacticData = std::dynamic_pointer_cast<SyntacticData>(analysis.getData("SyntacticData"));
371 if (syntacticData == nullptr)
372 {
373 syntacticData = std::make_shared<SyntacticData>(posGraphData.get(), nullptr);
374 syntacticData->setupDependencyGraph();
375 analysis.setData("SyntacticData", syntacticData);
376 }
377 auto depGraph = syntacticData-> dependencyGraph();
378 m_d->depGraph = depGraph;
379
380 auto dstream = initialize(analysis);
381
382 uint64_t nbSentences((sd->getSegments()).size());
383 if (nbSentences == 0)
384 {
386 LERROR << "ConllDumper::process 0 sentence to process";
387 return SUCCESS_ID;
388 }
389
390 auto sbItr = sd->getSegments().begin();
391#ifdef DEBUG_LP
392 LDEBUG << "ConllDumper::process There are "<< nbSentences << " sentences";
393#endif
394 auto sentenceBegin = sbItr->getFirstVertex();
395 auto sentenceEnd = sbItr->getLastVertex();
396
397 auto limaConllTokenIdMapping = std::dynamic_pointer_cast<LimaConllTokenIdMapping>(
398 analysis.getData("LimaConllTokenIdMapping"));
399 if (limaConllTokenIdMapping == nullptr)
400 {
401 limaConllTokenIdMapping = std::make_shared<LimaConllTokenIdMapping>();
402 analysis.setData("LimaConllTokenIdMapping", limaConllTokenIdMapping);
403 }
404 int sentenceNb = 0;
405 LinguisticGraphVertex vEndDone = 0;
406
407 const auto originalText = std::dynamic_pointer_cast<LimaStringText>(analysis.getData("Text"));
408
409 if (m_d->m_format == "CoNLL-U")
410 {
411 }
412 else if (m_d->m_format == "CoNLL-03")
413 {
414 dstream->out() << "-DOCSTART- -X- O O" << std::endl << std::endl;
415 }
416 else
417 {
419 QString errorMessage;
420 QTextStream qts(&errorMessage);
421 qts << "ConllDumper::process unknown format" << m_d->m_format;
422 LERROR << errorMessage;
423 return UNKNOWN_FORMAT;
424 }
425 while (sbItr != sd->getSegments().end()) //for each sentence
426 {
427 sentenceNb++;
428 // The cols list below is optionnal
429 if (m_d->m_format == "CoNLL-U")
430 {
431 if( sentenceNb==1 && m_d->m_withColsHeader )
432 {
433 dstream->out()
434 << "# global.columns = ID\tFORM\tLEMMA\tUPOS\tXPOS\tFEATS\tHEAD\tDEPREL\tDEPS\tMISC"
435 << std::endl;
436 }
437 dstream->out() << "# sent_id = " << sentenceNb << std::endl;
438 }
439 else if (m_d->m_format == "CoNLL-03")
440 {
441 }
442 else
443 {
445 QString errorMessage;
446 QTextStream qts(&errorMessage);
447 qts << "ConllDumper::process unknown format" << m_d->m_format;
448 LERROR << errorMessage;
449 return UNKNOWN_FORMAT;
450 }
451 sentenceBegin=sbItr->getFirstVertex();
452 sentenceEnd=sbItr->getLastVertex();
453 std::map<LinguisticGraphVertex,int> segmentationMapping;//mapping the two types of segmentations (Lima and conll)
454 std::map<int,LinguisticGraphVertex> segmentationMappingReverse;
455
456#ifdef DEBUG_LP
457 LDEBUG << "ConllDumper::process begin - end: " << sentenceBegin
458 << " - " << sentenceEnd;
459#endif
460
461 LinguisticGraphOutEdgeIt outItr,outItrEnd;
462 QQueue<LinguisticGraphVertex> toVisit;
463 QSet<LinguisticGraphVertex> visited;
464 toVisit.enqueue(sentenceBegin);
465 int vertexId = 0;
467 while (v != sentenceEnd && !toVisit.empty())
468 {
469 v = toVisit.dequeue();
470#ifdef DEBUG_LP
471 LDEBUG << "ConllDumper::process Vertex index : " << v;
472#endif
473 visited.insert(v);
474 // Collects the dependency relations of the token vertex tv
475 auto collectDependencies = [&](LinguisticGraphVertex tv)
476 {
477 auto dcurrent = syntacticData->depVertexForTokenVertex(tv);
478 DependencyGraphOutEdgeIt dit, dit_end;
479 boost::tie(dit,dit_end) = boost::out_edges(dcurrent,*depGraph);
480 for (; dit != dit_end; dit++)
481 {
482#ifdef DEBUG_LP
483 LDEBUG << "ConllDumper::process Dumping dependency edge "
484 << (*dit).m_source << " -> " << (*dit).m_target;
485#endif
486 try
487 {
488 auto typeMap = get(edge_deprel_type, *depGraph);
489 auto type = typeMap[*dit];
490 auto syntRelName = m_d->languageData->getSyntacticRelationName(type);
491#ifdef DEBUG_LP
492 LDEBUG << "ConllDumper::process relation = " << syntRelName;
493 LDEBUG << "ConllDumper::process Src : Dep vertex= "
494 << boost::source(*dit, *depGraph);
495 auto src = syntacticData->tokenVertexForDepVertex(
496 boost::source(*dit, *depGraph));
497 LDEBUG << "ConllDumper::process Src : Morph vertex= " << src;
498 LDEBUG << "ConllDumper::process Targ : Dep vertex= "
499 << boost::target(*dit, *depGraph);
500#endif
501 auto dest = syntacticData->tokenVertexForDepVertex(
502 boost::target(*dit, *depGraph));
503#ifdef DEBUG_LP
504 LDEBUG << "ConllDumper::process Targ : Morph vertex= " << dest;
505#endif
506 if (syntRelName!="")
507 {
508#ifdef DEBUG_LP
509 LDEBUG << "ConllDumper::process saving target for"
510 << tv << ":" << dest << syntRelName;
511#endif
512 m_d->vertexDependencyInformations.insert(
513 std::make_pair(tv, std::make_pair(dest, syntRelName)));
514 }
515 }
516 catch (const std::range_error& )
517 {
518 }
519 catch (...)
520 {
521#ifdef DEBUG_LP
522 LDEBUG << "ConllDumper::process: catch others.....";
523#endif
524 throw;
525 }
526 }
527 };
528 // A specific entity recognized on the PosGraph (ModEx rules applied
529 // after PoS tagging and parsing, as in the deepud pipelines) is dumped
530 // as one line per component token, and the parser relations are attached
531 // to these tokens: number them and collect their dependencies. Otherwise
532 // (and for entities recognized on the AnalysisGraph), v is its only
533 // token.
534 std::vector<LinguisticGraphVertex> tokenVertices;
535 m_d->entityTokenVertices(v, tokenVertices);
536 segmentationMapping.insert(std::make_pair(v,vertexId));
537 for (size_t i = 0; i < tokenVertices.size(); ++i)
538 {
539 if (i > 0)
540 ++vertexId;
541 segmentationMapping.insert(std::make_pair(tokenVertices[i], vertexId));
542 segmentationMappingReverse.insert(std::make_pair(vertexId, tokenVertices[i]));
543#ifdef DEBUG_LP
544 LDEBUG << "ConllDumper::process conll id : " << vertexId
545 << " Lima id : " << tokenVertices[i];
546#endif
547 collectDependencies(tokenVertices[i]);
548 }
549 if (v == sentenceEnd)
550 {
551 continue;
552 }
553 LinguisticGraphOutEdgeIt outItr,outItrEnd;
554 for (boost::tie(outItr,outItrEnd)=boost::out_edges(v, *posGraph);
555 outItr!=outItrEnd; outItr++)
556 {
557 LinguisticGraphVertex next=boost::target(*outItr,*posGraph);
558 if (!visited.contains(next) && next != posGraphData->lastVertex())
559 {
560 toVisit.enqueue(next);
561 }
562 }
563 ++vertexId;
564 }
565
566 // instead of looking to all vertices, follow the graph (in
567 // morphological graph, some vertices are not related to main graph:
568 // idiomatic expressions parts and named entity parts)
569
570 toVisit.clear();
571 visited.clear();
572
573 sentenceBegin=sbItr->getFirstVertex();
574 sentenceEnd=sbItr->getLastVertex();
575
576 // get the list of predicates for the current sentence
577 m_d->collectPredicateTokens( analysis,
578 sentenceBegin,
579 sentenceEnd );
580#ifdef DEBUG_LP
581 LDEBUG << "ConllDumper::process predicates for sentence between"
582 << sentenceBegin << "and" << sentenceEnd << "are:" << m_d->predicates;
583#endif
584 auto keys = m_d->predicates.keys();
585
586 v = sentenceBegin;
587 bool firstTime = true;
588 uint64_t pStart = 0;
589 uint64_t pEnd = 0;
590 while (v != sentenceEnd)
591 {
592 auto vIn = v;
593 //as long as there are vertices in the sentence
594 auto ft = get(vertex_token,*posGraph,v);
595 if( ft != nullptr && v != sentenceBegin )
596 {
597 if(firstTime)
598 {
599 pStart = ft->position();
600 firstTime = false;
601 }
602 pEnd = ft->position() + ft->length();
603 }
604 LinguisticGraphOutEdgeIt outIter,outIterEnd;
605 for (boost::tie(outIter,outIterEnd) = boost::out_edges(v,*posGraph);
606 outIter!=outIterEnd; outIter++)
607 {
608 v = boost::target(*outIter,*posGraph);
609 }
610 if (v == vIn)
611 {
613 LERROR << "ConllDumper::process sentence traversal loop stalls on" << v << "; breaking out.";
614 break;
615 }
616 }
617 auto curSentenceText = originalText->mid(pStart-1, pEnd-pStart+1);
618
619 if (m_d->m_format == "CoNLL-U")
620 {
621 // The text below is mandatory for CONLL-U format
622 dstream->out() << "# text = "
623 << curSentenceText.replace("\r\n"," ").replace("\n"," ").toStdString()
624 << std::endl;
625 }
626 else if (m_d->m_format == "CoNLL-03") {}
627 else
628 {
630 QString errorMessage;
631 QTextStream qts(&errorMessage);
632 qts << "ConllDumper::process unknown format" << m_d->m_format;
633 LERROR << errorMessage;
634 return UNKNOWN_FORMAT;
635 }
636
637 toVisit.enqueue(sentenceBegin);
638 int tokenId = 1;
639 v = 0;
640 while (!toVisit.empty() && v!=sentenceEnd)
641 { //as long as there are vertices in the sentence
642 v = toVisit.dequeue();
643
644 m_d->dumpPosGraphVertex(dstream,
645 v,
646 tokenId,
647 vEndDone,
648 segmentationMapping,
649 "",
650 false);
651
652
653#ifdef DEBUG_LP
654 LDEBUG << "ConllDumper::process look at out edges of" << v;
655#endif
656 LinguisticGraphOutEdgeIt outIter,outIterEnd;
657 for (boost::tie(outIter,outIterEnd) = boost::out_edges(v,*posGraph);
658 outIter != outIterEnd; outIter++)
659 {
660 LinguisticGraphVertex next = boost::target(*outIter,*posGraph);
661#ifdef DEBUG_LP
662 LDEBUG << "ConllDumper::process looking out vertex" << next;
663#endif
664 if (!visited.contains(next))
665 {
666#ifdef DEBUG_LP
667 LDEBUG << "ConllDumper::process enqueuing" << next;
668#endif
669 visited.insert(next);
670 toVisit.enqueue(next);
671 }
672 }
673 if (v == sentenceEnd)
674 {
675 vEndDone = v;
676 continue;
677 }
678 }
679 m_d->flushMultiwordToken(dstream);
680 limaConllTokenIdMapping->insert(std::make_pair(sentenceNb,
681 segmentationMappingReverse));
682
683 sbItr++;
684 if (sbItr != sd->getSegments().end())
685 {
686 dstream->out() << std::endl;
687 }
688 }
689
690 return SUCCESS_ID;
691}
692
693const SpecificEntityAnnotation* ConllDumperPrivate::posGraphEntity(
694 LinguisticGraphVertex v) const
695{
696 if (annotationData == nullptr)
697 return nullptr;
698 for (const auto& vx: annotationData->matches(m_graph.toStdString(), v, "annot"))
699 {
700 if (annotationData->hasAnnotation(vx, QString::fromUtf8("SpecificEntity")))
701 {
702 auto se = annotationData->annotation(
703 vx, QString::fromUtf8("SpecificEntity")).pointerValue<SpecificEntityAnnotation>();
704 if (se != nullptr)
705 return se;
706 }
707 }
708 return nullptr;
709}
710
711void ConllDumperPrivate::entityTokenVertices(
713 std::vector<LinguisticGraphVertex>& out,
714 int depth) const
715{
716 // Mirrors dumpNamedEntity/dumpPosGraphVertex: an entity recognized on the
717 // PosGraph is dumped as its component vertices, recursively.
718 const auto se = (depth < 16) ? posGraphEntity(v) : nullptr;
719 if (se == nullptr || se->vertices().empty())
720 {
721 out.push_back(v);
722 return;
723 }
724 for (const auto& vse : se->vertices())
725 {
726 entityTokenVertices(vse, out, depth + 1);
727 }
728}
729
730const SpecificEntityAnnotation* ConllDumperPrivate::getSpecificEntityAnnotation(
731 LinguisticGraphVertex v) const
732{
733 // check only entity found in current graph (not previous graph such as AnalysisGraph)
734
735 for (const auto& vx: annotationData->matches("PosGraph", v, "annot"))
736 {
737 if (annotationData->hasAnnotation(vx, QString::fromUtf8("SpecificEntity")))
738 {
739 //BoWToken* se = createSpecificEntity(v,*it, annotationData, anagraph, posgraph, offsetBegin);
740 auto se = annotationData->annotation(
741 vx,
742 QString::fromUtf8("SpecificEntity")).pointerValue<SpecificEntityAnnotation>();
743 if (se != nullptr)
744 {
745 return se;
746 }
747 }
748 }
749 return nullptr;
750
751}
752
753LimaStatusCode ConllDumperPrivate::dumpPosGraphVertex(
754 std::shared_ptr<DumperStream>& dstream,
756 int& tokenId,
757 LinguisticGraphVertex vEndDone,
758 std::map<LinguisticGraphVertex,int>& segmentationMapping,
759 const QString& parentNeType,
760 bool first,
761 const Automaton::EntityFeatures* parentFeatures)
762{
763#ifdef DEBUG_LP
765 LDEBUG << "ConllDumperPrivate::dumpPosGraphVertex IN" << v;
766#endif
767 if (anaGraph == nullptr || posGraph == nullptr || depGraph == nullptr
768 || annotationData == nullptr)
769 {
771 LERROR << "ConllDumperPrivate::dumpPosGraphVertex missing data";
772 return MISSING_DATA;
773 }
774 bool notDone(true);
775 if( v == vEndDone )
776 notDone = false;
777
778 auto ft = get(vertex_token, *posGraph, v);
779 auto morphoData = get(vertex_data, *posGraph, v);
780 if( morphoData != 0 && ft != 0
781 && ((!morphoData->empty()) || ft->length() > 0) && notDone )
782 {
783#ifdef DEBUG_LP
784 LDEBUG << "ConllDumperPrivate::dumpPosGraphVertex PosGraph nb different LinguisticCode"
785 << morphoData->size();
786#endif
787
788 auto micro = getMicro(morphoData);
789#ifdef DEBUG_LP
790 LDEBUG << "ConllDumperPrivate::dumpPosGraphVertex graphTag:" << micro;
791#endif
792
793 auto feats = getFeats(morphoData);
794#ifdef DEBUG_LP
795 LDEBUG << "ConllDumperPrivate::dumpPosGraphVertex feats:" << feats;
796#endif
797
798 // Made one line in dumpToken
799 auto inflectedToken = ft->stringForm().toStdString();
800
801 QString lemmatizedToken;
802 if (morphoData != 0 && !morphoData->empty())
803 {
804 lemmatizedToken = (*sp)[(*morphoData)[0].lemma];
805 }
806 // @TODO Should follow instructions here to output all MWE:
807 // https://universaldependencies.org/format.html#words-tokens-and-empty-nodes
808 QString neType = getNeType(v);
809
810 // Collect NE vertices and output them instead of a single line for
811 // current v. NE vertices can not only be PosGraph
812 // vertices (and thus can just call dumpPosGraphVertex
813 // recursively) but also AnalysisGraph vertices. In the latter case, data
814 // come partly from the AnalysisGraph and partly from the PosGraph
815 // Furthermore, named entities can be recursive...
816 const SpecificEntityAnnotation* nestedEntity = nullptr;
817 if (neType != "_" && !parentNeType.isEmpty())
818 {
819 nestedEntity = posGraphEntity(v);
820 }
821 if (nestedEntity != nullptr)
822 {
823 // Entity recognized on the PosGraph inside another one (e.g. a number in
824 // a date): its tokens are part of the enclosing entity.
825 bool firstNested = first;
826 for (const auto& vse : nestedEntity->vertices())
827 {
828 dumpPosGraphVertex(dstream, vse, tokenId, vEndDone, segmentationMapping,
829 parentNeType, firstNested, parentFeatures);
830 firstNested = false;
831 }
832 }
833 else if (neType != "_")
834 {
835 dumpNamedEntity(dstream, v, tokenId, vEndDone, segmentationMapping, neType);
836 }
837 else
838 {
839 if (!parentNeType.isEmpty())
840 {
841 neType = parentNeType;
842 }
843
844 QString conllRelName;
845 QString targetConllIdString;
846 std::tie(conllRelName,
847 targetConllIdString) = getConllRelName(v, segmentationMapping);
848
849 QStringList miscField;
850 if (neType != "_")
851 {
852#ifdef DEBUG_LP
853 LDEBUG << "ConllDumperPrivate::dumpPosGraphVertex specific entity type is"
854 << neType;
855#endif
856 miscField << (QString("NE=") + (first?"B-":"I-") + neType);
857 const auto annot = getSpecificEntityAnnotation(v);
858#ifdef DEBUG_LP
859 LDEBUG << "ConllDumperPrivate::dumpPosGraphVertex specific entity annotation is"
860 << annot;
861#endif
862 // The tokens of an entity recognized on the PosGraph carry the
863 // features of this entity
864 const Automaton::EntityFeatures* entityFeatures =
865 (annot != nullptr) ? &annot->getFeatures() : parentFeatures;
866 if (entityFeatures != nullptr)
867 {
868 const auto& features = *entityFeatures;
869 for (const auto& feature: features)
870 {
871 QString featureString;
872 QTextStream qts(&featureString);
873 if(feature.getPosition() == UNDEFPOSITION
874 && !feature.getName().empty()
875 && !feature.getValueString().empty())
876 {
877 qts << "NE-" << QString::fromStdString(feature.getName()) << "=";
879 QString::fromStdString(feature.getValueString()));
880 }
881 qts.flush();
882 if (!featureString.isEmpty())
883 {
884 miscField << featureString;
885 }
886 }
887 }
888 }
889
890 miscField << (QString("Pos=") + QString::number(ft->position()) );
891 miscField << (QString("Len=") + QString::number(ft->length()) );
892
893 if(!hasSpaceAfter(v, posGraph))
894 {
895 miscField << QString("SpaceAfter=No");
896 }
897
898 miscField << getPredicate(v);
899
900 if (miscField.empty())
901 {
902 miscField << "_";
903 }
904
905 dumpToken(dstream,
906 tokenId++, // ID
907 QString::fromStdString(inflectedToken), // FORM
908 lemmatizedToken, // LEMMA
909 micro, // UPOS
910 "_", // XPOS
911 feats, // FEATS
912 targetConllIdString, // HEAD
913 conllRelName, // DEPREL
914 "_", // DEPS @TODO
915 miscField, // MISC
916 neType,
917 previousNeType,
918 ft
919 );
920 previousNeType = neType;
921 }
922 }
923 return SUCCESS_ID;
924}
925
926void ConllDumperPrivate::collectPredicateTokens(Lima::AnalysisContent& analysis,
927 LinguisticGraphVertex sentenceBegin,
928 LinguisticGraphVertex sentenceEnd)
929{
930#ifdef DEBUG_LP
932#endif
933 QMultiMap<LinguisticGraphVertex, AnnotationGraphVertex> result;
934
935 auto annotationData = std::dynamic_pointer_cast<AnnotationData>(analysis.getData("AnnotationData"));
936 if (annotationData == nullptr)
937 {
939 LERROR << "No annotation data exists: check pipeline";
940 predicates = result;
941 return;
942 }
943
944 auto tokenList = std::dynamic_pointer_cast<AnalysisGraph>(analysis.getData(m_graph.toStdString()));
945 if (tokenList == nullptr)
946 {
948 LERROR << "graph" << m_graph << "has not been produced: check pipeline";
949 predicates = result;
950 return;
951 }
952 auto graph = tokenList->getGraph();
953
954 QQueue<LinguisticGraphVertex> toVisit;
955 QSet<LinguisticGraphVertex> visited;
956 toVisit.enqueue(sentenceBegin);
958 while (v != sentenceEnd && !toVisit.empty())
959 {
960 v = toVisit.dequeue();
961#ifdef DEBUG_LP
962 LDEBUG << "ConllDumperPrivate::collectPredicateTokens vertex:" << v;
963#endif
964 visited.insert(v);
965
966 auto vMatches = annotationData->matches(m_graph.toStdString(), v, "annot");
967 for (const auto& vMatch : vMatches)
968 {
969 if (annotationData->hasStringAnnotation(vMatch, "Predicate"))
970 {
971#ifdef DEBUG_LP
972 LDEBUG << "ConllDumperPrivate::collectPredicateTokens insert"
973 << v << vMatch;
974#endif
975 result.insert(v, vMatch);
976 }
977 }
978 LinguisticGraphOutEdgeIt outItr,outItrEnd;
979 for (boost::tie(outItr,outItrEnd)=boost::out_edges(v,*graph);
980 outItr!=outItrEnd; outItr++)
981 {
982 auto next = boost::target(*outItr, *graph);
983 if (!visited.contains(next) && next != tokenList->lastVertex())
984 {
985 toVisit.enqueue(next);
986 }
987 }
988 }
989 predicates = result;
990}
991
992QString ConllDumperPrivate::getNeType(LinguisticGraphVertex posGraphVertex)
993{
994 auto neType = QString::fromUtf8("_") ;
995 if (annotationData != nullptr)
996 {
997 // Check if the PosGraph vertex holds a specific entity
998 auto matches = annotationData->matches(m_graph.toStdString(), posGraphVertex, "annot");
999 for (const auto& vx: matches)
1000 {
1001 if (annotationData->hasAnnotation(
1002 vx, QString::fromUtf8("SpecificEntity")))
1003 {
1004 auto se = annotationData->annotation(vx, QString::fromUtf8("SpecificEntity")).
1005 pointerValue<SpecificEntityAnnotation>();
1006 neType = MedData::single().getEntityName(se->getType());
1007 break;
1008 }
1009 }
1010 if (neType == "_")
1011 {
1012 // The PosGraph vertex did not hold a specific entity,
1013 // check if the AnalysisGraph vertex does
1014 auto anaVertices = annotationData->matches(m_graph.toStdString(), posGraphVertex,
1015 "AnalysisGraph");
1016 // note: anaVertices size should be 0 or 1
1017 for (const auto& anaVertex: anaVertices)
1018 {
1019 auto matches = annotationData->matches("AnalysisGraph",
1020 anaVertex,
1021 "annot");
1022 for (const auto& vx: matches)
1023 {
1024 if (annotationData->hasAnnotation(
1025 vx, QString::fromUtf8("SpecificEntity")))
1026 {
1027 auto se = annotationData->annotation(
1028 vx, QString::fromUtf8("SpecificEntity"))
1029 .pointerValue<SpecificEntityAnnotation>();
1030 neType = MedData::single().getEntityName(se->getType());
1031 break;
1032 }
1033 }
1034 if (neType != "_") break;
1035 }
1036 }
1037 }
1038 return neType;
1039}
1040
1041std::pair<QString, QString> ConllDumperPrivate::getConllRelName(
1043 std::map<LinguisticGraphVertex,int>& segmentationMapping)
1044{
1045#ifdef DEBUG_LP
1047 LDEBUG << "ConllDumperPrivate::getConllRelName" << v;
1048#endif
1049 QString conllRelName = "_";
1050 int targetConllId = 0;
1051 if (vertexDependencyInformations.count(v) != 0)
1052 {
1053 auto target = vertexDependencyInformations.find(v)->second.first;
1054#ifdef DEBUG_LP
1055 LDEBUG << "ConllDumper::process target saved for"
1056 << v << "is" << target;
1057#endif
1058 if (segmentationMapping.find(target) != segmentationMapping.end())
1059 {
1060 targetConllId = segmentationMapping.find(target)->second;
1061 }
1062 else
1063 {
1065 LERROR << "ConllDumper::process target" << target
1066 << "not found in segmentation mapping";
1067 }
1068#ifdef DEBUG_LP
1069 LDEBUG << "ConllDumper::process conll target saved for "
1070 << v << " is " << targetConllId;
1071#endif
1072 auto relName = QString::fromUtf8(
1073 vertexDependencyInformations.find(v)->second.second.c_str());
1074#ifdef DEBUG_LP
1075 LDEBUG << "ConllDumper::process the lima dependency tag for "
1076 << v << " is " << relName;
1077#endif
1078 if (m_conllLimaDepMapping.contains(relName))
1079 {
1080 conllRelName = m_conllLimaDepMapping[relName];
1081 }
1082 else
1083 {
1084 conllRelName = relName;
1085// LERROR << "ConllDumper::process" << relName << "not found in mapping";
1086 }
1087
1088 // There is no way for vertex to have 0 as head.
1089 if (conllRelName == "root")
1090 {
1091 targetConllId = 0;
1092 }
1093 }
1094 QString targetConllIdString = QString(QLatin1String("%1")).arg(targetConllId);
1095
1096 return { conllRelName, targetConllIdString };
1097}
1098
1099QStringList ConllDumperPrivate::getPredicate(LinguisticGraphVertex v)
1100{
1101#ifdef DEBUG_LP
1103 LDEBUG << "ConllDumperPrivate::getPredicate" << v;
1104#endif
1105 QStringList miscField;
1106 if (annotationData != nullptr && predicates.contains(v))
1107 {
1108 auto keys = predicates.keys();
1109 auto predicate = annotationData->stringAnnotation(predicates.value(v),
1110 "Predicate");
1111
1112 // Now output the roles supported by the current PoS graph token
1113#ifdef DEBUG_LP
1114 LDEBUG << "ConllDumper::process output the roles for the"
1115 << keys.size() << "predicates";
1116#endif
1117 for (int i = 0; i < keys.size(); i++)
1118 {
1119 auto predicateVertex = predicates.value(keys[keys.size()-1-i]);
1120
1121 auto vMatches = annotationData->matches(m_graph.toStdString(), v, "annot");
1122 if (!vMatches.empty())
1123 {
1124#ifdef DEBUG_LP
1125 LDEBUG << "ConllDumper::process there is" << vMatches.size()
1126 << "nodes matching PoS graph vertex" << v
1127 << "in the annotation graph.";
1128#endif
1129 QString roleAnnotation;
1130 for (auto it = vMatches.begin(); it != vMatches.end(); it++)
1131 {
1132 auto vMatch = *it;
1133 AnnotationGraphInEdgeIt vMatchInEdgesIt, vMatchInEdgesIt_end;
1134 boost::tie(vMatchInEdgesIt, vMatchInEdgesIt_end) =
1135 boost::in_edges(vMatch,annotationData->getGraph());
1136 for (; vMatchInEdgesIt != vMatchInEdgesIt_end; vMatchInEdgesIt++)
1137 {
1138 auto inVertex = boost::source(*vMatchInEdgesIt,
1139 annotationData->getGraph());
1140 auto inVertexAnnotPosGraphMatches = annotationData->matches(
1141 "annot",inVertex,m_graph.toStdString());
1142 if (inVertex == predicateVertex
1143 && !inVertexAnnotPosGraphMatches.empty())
1144 {
1145 // Current edge is holding a role of the current predicate
1146 roleAnnotation =
1147 annotationData->stringAnnotation(*vMatchInEdgesIt,
1148 "SemanticRole");
1149 break;
1150 }
1151 }
1152 }
1153 if (!roleAnnotation.isEmpty() )
1154 predicate = roleAnnotation + ":" + predicate;
1155 }
1156 }
1157 if (!predicate.isEmpty())
1158 {
1159 miscField << predicate;
1160 }
1161 }
1162 return miscField;
1163}
1164
1165bool ConllDumperPrivate::hasSpaceAfter(LinguisticGraphVertex v,
1166 LinguisticGraph* graph)
1167{
1168 auto ft = get(vertex_token, *graph, v);
1169 bool SpaceAfter = true;
1170 LinguisticGraphOutEdgeIt outIter, outIterEnd;
1171 for (boost::tie(outIter,outIterEnd) = boost::out_edges(v, *graph);
1172 outIter!=outIterEnd; outIter++)
1173 {
1174 auto next = boost::target(*outIter, *graph);
1175 auto nt = get(vertex_token, *graph, next);
1176 if( nt != nullptr
1177 && (nt->position() == ft->position()+ft->length()) )
1178 {
1179 SpaceAfter = false;
1180 break;
1181 }
1182 }
1183 return SpaceAfter;
1184}
1185
1186QString ConllDumperPrivate::getMicro(MorphoSyntacticData* morphoData)
1187{
1188 return QString::fromUtf8(static_cast<const LangData&>(
1189 MedData::single().mediaData(m_language)).getPropertyCodeManager()
1190 .getPropertyManager("MICRO")
1191 .getPropertySymbolicValue(morphoData->firstValue(
1192 *m_propertyAccessor)).c_str());
1193}
1194
1195QString ConllDumperPrivate::getFeats(MorphoSyntacticData* morphoData)
1196{
1197#ifdef DEBUG_LP
1199#endif
1200
1201 QStringList featuresList;
1202 for (auto i = managers->cbegin(); i != managers->cend(); i++)
1203 {
1204 auto key = QString::fromUtf8(i->first.c_str());
1205 if (key != "MACRO" && key != "MICRO")
1206 {
1207 const auto& pa = propertyCodeManager->getPropertyAccessor(key.toStdString());
1208 LinguisticCode lc = morphoData->firstValue(pa);
1209 auto value = QString::fromUtf8(i->second.getPropertySymbolicValue(lc).c_str());
1210 if (value != "NONE")
1211 {
1212 featuresList << QString("%1=%2").arg(key).arg(value);
1213 }
1214 }
1215 }
1216
1217 featuresList.sort();
1218 QString features;
1219 QTextStream featuresStream(&features);
1220 if (featuresList.isEmpty())
1221 {
1222 features = "_";
1223 }
1224 else
1225 {
1226 for (auto featuresListIt = featuresList.cbegin(); featuresListIt != featuresList.cend(); featuresListIt++)
1227 {
1228 if (featuresListIt != featuresList.cbegin())
1229 {
1230 featuresStream << "|";
1231 }
1232 featuresStream << *featuresListIt;
1233 }
1234 }
1235#ifdef DEBUG_LP
1236 LDEBUG << "ConllDumper::process features:" << features;
1237#endif
1238
1239 return features;
1240}
1241
1242QString matchesS(const std::set<AnnotationGraphVertex>& s)
1243{
1244 QString result;
1245 QTextStream qts(&result);
1246 for (auto i: s) {qts << i << ",";}
1247 return result;
1248}
1249
1250void ConllDumperPrivate::dumpNamedEntity(std::shared_ptr<DumperStream>& dstream,
1252 int& tokenId,
1253 LinguisticGraphVertex vEndDone,
1254 std::map<LinguisticGraphVertex,int>& segmentationMapping,
1255 const QString& neType)
1256{
1257#ifdef DEBUG_LP
1259 LDEBUG << "ConllDumperPrivate::dumpNamedEntity" << v << tokenId << vEndDone
1260 << neType;
1261#endif
1262 // Check if the named entity is on AnalysisGraph.
1263 // If so, then we have to recursively get all analysis graph tokens and
1264 // collect the information about them, chosing randomly the "right" category
1265 // Otherwise, will retrieve the pos graph tokens and recursively do the same.
1266 // For final tokens that are on pos graph, the category will be unique.
1267
1268 if (annotationData != nullptr)
1269 {
1270 // Check if the PosGraph vertex holds a specific entity
1271 auto matches = annotationData->matches(m_graph.toStdString(), v, "annot");
1272#ifdef DEBUG_LP
1273 LDEBUG << "ConllDumperPrivate::dumpNamedEntity matches PosGraph" << v
1274 << "annot:" << matchesS(matches);
1275#endif
1276 for (const auto& vx: matches)
1277 {
1278 if (annotationData->hasAnnotation(
1279 vx, QString::fromUtf8("SpecificEntity")))
1280 {
1281 auto se = annotationData->annotation(vx,
1282 QString::fromUtf8("SpecificEntity"))
1284 previousNeType = "O";
1285 bool first = true;
1286 for (const auto& vse : se->vertices())
1287 {
1288 dumpPosGraphVertex(dstream, vse, tokenId, vEndDone,
1289 segmentationMapping, neType, first,
1290 &se->getFeatures());
1291 first = false;
1292 }
1293#ifdef DEBUG_LP
1294 LDEBUG << "ConllDumperPrivate::dumpNamedEntity return after SpecificEntity annotation on PosGraph";
1295#endif
1296 return;
1297 }
1298 }
1299 auto anaVertices = annotationData->matches(m_graph.toStdString(), v, "AnalysisGraph");
1300#ifdef DEBUG_LP
1301 LDEBUG << "ConllDumperPrivate::dumpNamedEntity anaVertices for" << v
1302 << ":" << matchesS(anaVertices);
1303#endif
1304
1305 assert(anaVertices.size() == 1);
1306 auto anaVertex = *anaVertices.begin();
1307#ifdef DEBUG_LP
1308 LDEBUG << "ConllDumperPrivate::dumpNamedEntity anaVertex is" << anaVertex;
1309#endif
1310 if (annotationData->hasAnnotation(
1311 anaVertex, QString::fromUtf8("SpecificEntity")))
1312 {
1313 auto se = annotationData->annotation(anaVertex,
1314 QString::fromUtf8("SpecificEntity"))
1315 .pointerValue<SpecificEntityAnnotation>();
1316#ifdef DEBUG_LP
1317 LDEBUG << "ConllDumperPrivate::dumpNamedEntity anaVertex se ("
1318 << (*sp)[se->getString()]
1319 << ") annotation vertices are" << se->vertices()
1320 << "and normalized form:" << (*sp)[se->getNormalizedForm()]
1321 << "and features:" << se->getFeatures();
1322#endif
1323 // All retrieved lines/tokens have the same netype. Depending on the
1324 // output style (CoNLL 2003, CoNLL-U, …), the generated line is different
1325 // and the ne-Type includes or not BIO information using in this case the
1326 // previousNeType member.
1327 previousNeType = "O";
1328 bool first = true;
1329 for (const auto& vse : se->vertices())
1330 {
1331 dumpAnalysisGraphVertex(dstream, vse, v, tokenId, vEndDone, neType,
1332 first, se->getFeatures());
1333 first = false;
1334 }
1335 previousNeType = neType;
1336 }
1337 }
1338}
1339
1340// TODO Split idiomatic alternative tokens and compound tokens
1341LimaStatusCode ConllDumperPrivate::dumpAnalysisGraphVertex(
1342 std::shared_ptr<DumperStream>& dstream,
1344 LinguisticGraphVertex posGraphVertex,
1345 int& tokenId,
1346 LinguisticGraphVertex vEndDone,
1347 const QString& neType,
1348 bool first,
1349 const Automaton::EntityFeatures& features)
1350{
1351 LIMA_UNUSED(posGraphVertex);
1352#ifdef DEBUG_LP
1354 LDEBUG << "ConllDumperPrivate::dumpAnalysisGraphVertex" << v << posGraphVertex
1355 << neType;
1356#endif
1357 if (anaGraph == nullptr || posGraph == nullptr || depGraph == nullptr
1358 || annotationData == nullptr)
1359 {
1361 LERROR << "ConllDumperPrivate::dumpAnalysisGraphVertex missing data";
1362 return MISSING_DATA;
1363 }
1364 bool notDone(true);
1365 if( v == vEndDone )
1366 notDone = false;
1367
1368 auto ft = get(vertex_token, *anaGraph, v);
1369 auto morphoData = get(vertex_data, *anaGraph, v);
1370#ifdef DEBUG_LP
1371 LDEBUG << "ConllDumperPrivate::dumpAnalysisGraphVertex PosGraph token" << v;
1372#endif
1373 if( morphoData != 0 && ft != 0
1374 && ((!morphoData->empty()) || ft->length() > 0) && notDone )
1375 {
1376#ifdef DEBUG_LP
1377 LDEBUG << "ConllDumperPrivate::dumpAnalysisGraphVertex PosGraph nb different LinguisticCode"
1378 << morphoData->size();
1379#endif
1380
1381 auto micro = getMicro(morphoData);
1382#ifdef DEBUG_LP
1383 LDEBUG << "ConllDumperPrivate::dumpAnalysisGraphVertex micro:" << micro;
1384#endif
1385
1386 auto feats = getFeats(morphoData);
1387#ifdef DEBUG_LP
1388 LDEBUG << "ConllDumperPrivate::dumpAnalysisGraphVertex feats:" << feats;
1389#endif
1390
1391 // Made one line in dumpToken
1392 auto inflectedToken = ft->stringForm().toStdString();
1393
1394 QString lemmatizedToken;
1395 if (morphoData != 0 && !morphoData->empty())
1396 {
1397 lemmatizedToken = (*sp)[(*morphoData)[0].lemma];
1398 }
1399 // @TODO Should follow instructions here to output all MWE:
1400 // https://universaldependencies.org/format.html#words-tokens-and-empty-nodes
1401
1402 // TODO Get correct UD dep relation for relations inside the named entity
1403 // and for the token that must be linked to the outside. For this one, the
1404 // relation is the one which links to posGraphVertex to the rest of the pos
1405 // graph.
1406 QString conllRelName = "_";
1407 QString targetConllIdString = "_";
1408
1409 QStringList miscField;
1410 if (neType != "_")
1411 {
1412#ifdef DEBUG_LP
1413 LDEBUG << "ConllDumperPrivate::dumpAnalysisGraphVertex specific entity type is" << neType;
1414 LDEBUG << "ConllDumperPrivate::dumpAnalysisGraphVertex posGraphVertex is" << posGraphVertex;
1415#endif
1416 miscField << (QString("NE=") + (first?"B-":"I-") + neType);
1417 for (const auto& feature: features)
1418 {
1419 if(!feature.getName().empty()
1420 && !feature.getValueString().empty())
1421 {
1422 QString featureString;
1423 QTextStream qts(&featureString);
1424 qts << "NE-" << QString::fromStdString(feature.getName()) << "=";
1426 QString::fromStdString(feature.getValueString()));
1427 miscField << featureString;
1428 }
1429 }
1430 }
1431
1432 miscField << (QString("Pos=") + QString::number(ft->position()) );
1433 miscField << (QString("Len=") + QString::number(ft->length()) );
1434
1435 if(!hasSpaceAfter(v, anaGraph))
1436 {
1437 miscField << QString("SpaceAfter=No");
1438 }
1439
1440 miscField << getPredicate(v);
1441
1442 if (miscField.empty())
1443 {
1444 miscField << "_";
1445 }
1446 dumpToken(dstream,
1447 tokenId++, // ID
1448 QString::fromStdString(inflectedToken), // FORM
1449 lemmatizedToken, // LEMMA
1450 micro, // UPOS
1451 "_", // XPOS
1452 feats, // FEATS
1453 targetConllIdString, // HEAD
1454 conllRelName, // DEPREL
1455 "_", // DEPS @TODO
1456 miscField, // MISC
1457 neType,
1458 previousNeType,
1459 ft
1460 );
1461 }
1462 return SUCCESS_ID;
1463}
1464
1465void ConllDumperPrivate::flushMultiwordToken(std::shared_ptr<DumperStream>& dstream)
1466{
1467 if (m_multiword.lines.empty())
1468 {
1469 return;
1470 }
1471 if (m_multiword.lines.size() > 1)
1472 {
1473 // SpaceAfter=No belongs to the multiword token (UD), not to its words:
1474 // the token's is the last word's
1475 bool noSpaceAfter = false;
1476 for (size_t k = 0; k < m_multiword.lines.size(); ++k)
1477 {
1478 auto& line = m_multiword.lines[k];
1479 const auto tab = line.rfind('\t');
1480 if (tab == std::string::npos)
1481 continue;
1482 auto misc = QString::fromStdString(line.substr(tab + 1)).trimmed().split('|');
1483 const bool had = misc.removeAll(QString("SpaceAfter=No")) > 0;
1484 if (k + 1 == m_multiword.lines.size())
1485 noSpaceAfter = had;
1486 if (misc.isEmpty())
1487 misc << "_";
1488 line = line.substr(0, tab + 1) + misc.join('|').toStdString() + "\n";
1489 }
1490 dstream->out() << m_multiword.firstId << "-"
1491 << (m_multiword.firstId + m_multiword.lines.size() - 1)
1492 << "\t" << oneLine(m_multiword.surface).toStdString() // FORM
1493 << "\t_\t_\t_\t_\t_\t_\t_"
1494 << "\t" << (noSpaceAfter ? "SpaceAfter=No" : "_") // MISC
1495 << std::endl;
1496 }
1497 for (const auto& line : m_multiword.lines)
1498 {
1499 dstream->out() << line;
1500 }
1501 m_multiword = MultiwordToken();
1502}
1503
1504void ConllDumperPrivate::dumpToken(
1505 std::shared_ptr<DumperStream>& dstream,
1506 int tokenId, // ID
1507 const QString& inflectedToken, // FORM
1508 const QString& lemmatizedToken, // LEMMA
1509 const QString& micro, // UPOS
1510 const QString& xpos, // XPOS
1511 const QString& features,// FEATS @TODO
1512 const QString& targetConllIdString, // HEAD
1513 const QString& conllRelName, // DEPREL
1514 const QString& deps, // DEPS @TODO
1515 const QStringList& miscField,
1516 const QString& neType,
1517 const QString& previousNeType,
1518 const Token* ft)
1519{
1520#ifdef DEBUG_LP
1522 LDEBUG << "ConllDumperPrivate::dumpToken" << tokenId;
1523#endif
1524 if (m_format == "CoNLL-U")
1525 {
1526 // CONLL-U format
1527 // https://universaldependencies.org/format.html
1528 //
1529 // ID: Word index, integer starting at 1 for each new sentence; may be a
1530 // range for multiword tokens; may be a decimal number for empty
1531 // nodes (decimal numbers can be lower than 1 but must be greater
1532 // than 0).
1533 // FORM: Word form or punctuation symbol.
1534 // LEMMA: Lemma or stem of word form.
1535 // UPOS: Universal part-of-speech tag.
1536 // XPOS: Language-specific part-of-speech tag; underscore if not
1537 // available.
1538 // FEATS: List of morphological features from the universal feature
1539 // inventory or from a defined language-specific extension;
1540 // underscore if not available (this is the case currently in
1541 // LIMA).
1542 // HEAD: Head of the current word, which is either a value of ID or
1543 // zero (0).
1544 // DEPREL: Universal dependency relation to the HEAD (root iff HEAD = 0)
1545 // or a defined language-specific subtype of one.
1546 // DEPS: Enhanced dependency graph in the form of a list of head-deprel
1547 // pairs. Currently unavailable in LIMA, thus underscore.
1548 // MISC: Any other annotation. In LIMA, named entities and SRL
1549 // information.
1550
1551 std::ostringstream line;
1552 line << tokenId // ID
1553 << "\t" << oneLine(inflectedToken).toStdString() // FORM
1554 << "\t" << oneLine(lemmatizedToken).toStdString() // LEMMA
1555 << "\t" << micro.toStdString() // UPOS
1556 << "\t" << xpos.toStdString() // XPOS
1557 << "\t" << features.toStdString() // FEATS @TODO
1558 << "\t" << targetConllIdString.toStdString() // HEAD
1559 << "\t" << conllRelName.toStdString() // DEPREL
1560 << "\t" << deps.toStdString() // DEPS @TODO
1561 << "\t" << miscField.join('|').toStdString() // MISC
1562 << "\n";
1563
1564 // A word of the multiword token being collected: it starts inside the
1565 // surface
1566 if (!m_multiword.lines.empty())
1567 {
1568 if (ft != nullptr && ft->position() >= m_multiword.begin
1569 && ft->position() < m_multiword.end)
1570 {
1571 m_multiword.lines.push_back(line.str());
1572 return;
1573 }
1574 flushMultiwordToken(dstream);
1575 }
1576 // The first word of a multiword token carries its surface
1577 if (ft != nullptr && !ft->orthographicAlternatives().empty())
1578 {
1579 const auto surface = (*sp)[*(ft->orthographicAlternatives().begin())];
1580 m_multiword.firstId = tokenId;
1581 m_multiword.begin = ft->position();
1582 m_multiword.end = ft->position() + surface.size();
1583 m_multiword.surface = surface;
1584 m_multiword.lines.push_back(line.str());
1585 return;
1586 }
1587 dstream->out() << line.str();
1588 }
1589 else if (m_format == "CoNLL-03")
1590 {
1591 // CONLL 2003 format
1592 //
1593 // -DOCSTART- -X- O O
1594 //
1595 // CRICKET NNP I-NP O
1596 // - : O O
1597 // LEICESTERSHIRE NNP I-NP I-ORG
1598 // TAKE NNP I-NP O
1599
1600
1601#ifdef DEBUG_LP
1602 LDEBUG << "ConllDumperPrivate::dumpToken" << tokenId
1603 << inflectedToken.toStdString() << neType << previousNeType;
1604#endif
1605 QString inflectedTokenEscaped = oneLine(inflectedToken);
1606 inflectedTokenEscaped.replace(" ", "_");
1607 dstream->out() << inflectedTokenEscaped.toStdString() // FORM
1608 << " " << micro.toStdString() // UPOS
1609 << " " << "I-NP";
1610 if (neType.isEmpty() || neType == "_")
1611 {
1612 dstream->out() << " " << "O";
1613 }
1614 else
1615 {
1616 if (neType == previousNeType)
1617 {
1618 dstream->out() << " " << "I-";
1619 }
1620 else
1621 {
1622 dstream->out() << " " << "B-";
1623 }
1624 dstream->out() << neType.toStdString();
1625 }
1626 dstream->out() << std::endl;
1627 }
1628 else
1629 {
1631 QString errorMessage;
1632 QTextStream qts(&errorMessage);
1633 qts << "ConllDumper::dumpToken unknown format" << m_format;
1634 LERROR << errorMessage;
1635 throw std::runtime_error(errorMessage.toStdString());
1636 }
1637}
1638
1639} // end namespace
1640} // end namespace
1641} // end namespace
This file is the main header file for the data related to annotation graphs.
A graph that stores any data (annotations) referencing primarily nodes of a text anlaysis.
#define CONLLDUMPER_CLASSID
Definition ConllDumper.h:19
DependencyGraph::out_edge_iterator DependencyGraphOutEdgeIt
boost::adjacency_list< boost::vecS, boost::vecS, boost::bidirectionalS, DepVertexProperties, DepEdgeProperties > DependencyGraph
The dependency graph class.
@ edge_deprel_type
#define UNDEFPOSITION
#define LIMA_UNUSED(x)
Definition LimaCommon.h:224
#define LDEBUG
Definition LimaCommon.h:157
#define LINFO
Definition LimaCommon.h:158
#define LERROR
Definition LimaCommon.h:161
A graph structure for linguistic analysis.
@ vertex_token
LinguisticGraph::vertex_descriptor LinguisticGraphVertex
@ vertex_data
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
Defines a Factory to create Object of type Base.
Data used for the syntactic analyzis of texts.
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 an annotation graph and gives an API to manipulate it.
std::set< AnnotationGraphVertex > matches(const std::string &first, AnnotationGraphVertex firstVx, const std::string &second) const
Gets the set of vertices matched in the second graph by the given vertex of the first graph.
const GenericAnnotation & annotation(AnnotationGraphVertex v1, AnnotationGraphVertex v2, const LimaString &annot) const
Holds linguistic data for one language.
const PropertyCode::PropertyCodeManager & getPropertyCodeManager() const
holds data about codes and names for grammatical categories, etc.
const FsaStringsPool & stringsPool(MediaId med) const
const std::string & getResourcesPath() const
const MediaData & mediaData(MediaId media) 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.
const PropertyManager & getPropertyManager(const std::string &propertyName) const
Get the PropertyManager associated to a property.
Provide tools to manage a specific property.
const PropertyAccessor & getPropertyAccessor() const
give the corresponding PropertyAccessor
return a message when a 'param' was not found
InitializableObjectManager< MediaProcessUnit, MediaProcessUnitInitializationParameters > Manager
Use this exception to signal an error in one of the configuration files.
Definition LimaCommon.h:345
std::shared_ptr< DumperStream > initialize(AnalysisContent &analysis) const
virtual void init(Common::XMLConfigurationFiles::GroupConfigurationStructure &unitConfiguration, Manager *manager) override
LimaStatusCode process(AnalysisContent &analysis) const override
Process on data in analysisContent.
void init(Common::XMLConfigurationFiles::GroupConfigurationStructure &unitConfiguration, Manager *manager) override
a list of generic features: each feature is unique (only one feature for a name)
LinguisticCode firstValue(const Common::PropertyCode::PropertyAccessor &propertyAccessor) const
Return the first non empty value for the given accessor.
const std::vector< StringsPoolIndex > & orthographicAlternatives() const
Definition Token.h:112
A representation of a specific entity to store in the annotation graph.
static const MediaticData & single()
Definition Singleton.h:51
AnnotationGraph::in_edge_iterator AnnotationGraphInEdgeIt
bool hasAnnotation(AnnotationGraphVertex v, const LimaString &annot) const
Lima::Common::MediaticData::LanguageData LangData
Definition lima.cpp:120
Lima::Common::MediaticData::MediaticData MedData
Definition lima.cpp:121
std::string readLine(std::istream &inputFile)
LimaString transcodeToXmlEntities(const LimaString &str)
QString findFileInPaths(const QString &paths, const QString &fileName, const QChar &separator)
Find the given file in the given paths.
SimpleFactory< MediaProcessUnit, ConllDumper > conllDumperFactory(CONLLDUMPER_CLASSID)
QString matchesS(const std::set< AnnotationGraphVertex > &s)
static QString oneLine(QString field)
NAUTITIA.
LimaStatusCode
Definition LimaCommon.h:236
@ UNKNOWN_FORMAT
Definition LimaCommon.h:244
@ SUCCESS_ID
Definition LimaCommon.h:237
@ MISSING_DATA
Definition LimaCommon.h:243
launch exception related to the configuration file parsing