LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
dumper_conllu.h
Go to the documentation of this file.
1// Copyright 2021 CEA LIST
2// SPDX-FileCopyrightText: 2022 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
6#ifndef DEEPLIMA_DUMPER_CONLLU_H
7#define DEEPLIMA_DUMPER_CONLLU_H
8
9#include <iostream>
10
11// #include "deeplima/segmentation/impl/segmentation_impl.h"
12
13#include "deeplima/token_type.h"
14
15namespace deeplima
16{
17namespace dumper
18{
19
21{
22 ConllToken() = default;
23 ConllToken(const ConllToken&) = default;
24 ConllToken& operator=(const ConllToken&) = default;
25 ~ConllToken() = default;
26
27 // ID: Word index, integer starting at 1 for each new sentence; may be a range for multiword tokens; may be a decimal number for empty nodes (decimal numbers can be lower than 1 but must be greater than 0).
28 uint32_t id = 0;
29 // FORM: Word form or punctuation symbol.
30 std::string form = "_";
31 // LEMMA: Lemma or stem of word form.
32 std::string lemma = "_";
33 // UPOS: Universal part-of-speech tag.
34 std::string upos = "_";
35 // XPOS: Language-specific part-of-speech tag; underscore if not available.
36 std::string xpos = "_";
37 // FEATS: List of morphological features from the universal feature inventory or from a defined language-specific extension; underscore if not available.
38 std::string feats = "_";
39 // HEAD: Head of the current word, which is either a value of ID or zero (0).
40 int head = 0;
41 // DEPREL: Universal dependency relation to the HEAD (root iff HEAD = 0) or a defined language-specific subtype of one.
42 std::string deprel = "dep";
43 // DEPS: Enhanced dependency graph in the form of a list of head-deprel pairs.
44 std::string deps = "_";
45 // MISC: Any other annotation.
46 std::string misc = "_";
47
48 // Multiword-token range. When mwt_last > 0, this token is the first sub-word
49 // of an expanded multiword token, and a UD "id-mwt_last mwt_surface" range
50 // line is emitted just before this token's own line.
51 uint32_t mwt_last = 0;
52 std::string mwt_surface;
53};
54
55std::ostream& operator<<(std::ostream& oss, const ConllToken& token)
56{
57 if (token.mwt_last > 0)
58 {
59 // UD multiword-token range line: "N-M\tsurface\t_\t_\t_\t_\t_\t_\t_\t_"
60 oss << token.id << "-" << token.mwt_last << "\t"
61 << token.mwt_surface
62 << "\t_\t_\t_\t_\t_\t_\t_\t_" << std::endl;
63 }
64 oss << token.id << "\t"
65 << token.form << "\t"
66 << token.lemma << "\t"
67 << token.upos << "\t"
68 << token.xpos << "\t"
69 << token.feats << "\t"
70 << token.head << "\t"
71 << token.deprel << "\t"
72 << token.deps << "\t"
73 << token.misc << std::endl << std::flush;
74 return oss;
75}
76
77
81inline std::string conllu_field(const char* s)
82{
83 std::string result(s);
84 for (char& c : result)
85 {
86 if (c == '\r' || c == '\n' || c == '\t')
87 {
88 c = ' ';
89 }
90 }
91 return result;
92}
93
94template <typename T>
95std::ostream& operator<< (std::ostream& out, const std::vector<T>& v)
96{
97 out << '[';
98 if ( !v.empty() )
99 {
100 std::copy (v.begin(), v.end(), std::ostream_iterator<T>(out, ", "));
101 }
102 out << "]";
103 return out;
104}
105
106bool dfs(int v, std::vector<uint32_t>& heads, std::vector<int>& color,
107 uint32_t& cycle_start, uint32_t& cycle_end)
108{
109 // std::cerr << "dfs " << v << ", " << heads << ", " << color << ", " << cycle_start << ", " << cycle_end << std::endl;
110 color[v] = 1;
111 auto u = heads[v];
112 // A predicted head can be out of range (>= number of tokens) when the model
113 // produces a bad arc; treat it like "no head" so the cycle walk never
114 // indexes color[]/heads[] out of bounds.
115 if (u == 0 || u >= heads.size())
116 {
117 color[v] = 2;
118 return false;
119 }
120 if (color[u] == 0) {
121 // parent[u] = v;
122 if (dfs(u, heads, color, cycle_start, cycle_end))
123 return true;
124 } else if (color[u] == 1) {
125 cycle_end = v;
126 cycle_start = u;
127 return true;
128 }
129
130 color[v] = 2;
131 return false;
132}
133
134bool find_cycle(std::vector<uint32_t>& heads, uint32_t root)
135{
136 // std::cerr << "find_cycle " << heads << ", " << root << std::endl;
137 uint32_t n = heads.size();
138 std::vector<int> color;
139 uint32_t cycle_start = std::numeric_limits<uint32_t>::max();
140 uint32_t cycle_end = 0;
141 color.assign(n, 0);
142
143 for (uint32_t v = 1; v < n; v++)
144 {
145 if (v == root) continue;
146 if (color[v] == 0 && dfs(v, heads, color, cycle_start, cycle_end))
147 break;
148 }
149
150 if (cycle_start == std::numeric_limits<uint32_t>::max() || cycle_start == root)
151 {
152 // std::cerr << "Acyclic" << std::endl;
153 return false;
154 }
155 else
156 {
157 // if (cycle_start > 0 && cycle_start != root)
158 // heads[cycle_start] = root;
159 if (cycle_end > 0 && cycle_end != root && cycle_end < n)
160 {
161 // std::cerr << "Cycle found from " << cycle_start << ", " << cycle_end << " in " << heads << " with root: " << root << std::endl;
162 heads[cycle_end] = root;
163 return true;
164 }
165 else
166 {
167 // std::cerr << "Cycle not found from " << cycle_start << ", " << cycle_end << " in " << heads << " with root: " << root << std::endl;
168 return false;
169 }
170 }
171}
172
174{
175protected:
177
179 {
181 }
182
183public:
184 virtual void operator()(const std::vector<deeplima::segmentation::token_pos>& tokens, uint32_t len) = 0;
185
186 uint64_t get_token_counter() const
187 {
188 return m_token_counter;
189 }
190
193
194 virtual ~AbstractDumper() { }
195
196 void reset()
197 {
198 m_token_counter = 0;
199 }
200};
201
203{
204public:
206 {}
207
208 virtual void operator()(const std::vector<deeplima::segmentation::token_pos>& tokens, uint32_t len)
209 {
210 std::string temp;
211 for (size_t i = 0; i < len; i++)
212 {
213 const char* ptoken = tokens[i].m_pch;
214 std::ostringstream s;
215 if (temp.size() > 0)
216 {
217 s << temp;
218 temp.clear();
219 }
220
221 for (size_t j = 0; j < tokens[i].m_len; j++)
222 {
223 if (*ptoken == '\r' || *ptoken == '\n' || *ptoken == '\t')
224 {
225 s << " ";
226 }
227 else
228 {
229 s << *ptoken;
230 }
231 ptoken++;
232 }
233 std::string str = s.str();
234 if (std::string::npos == str.find_first_not_of(' '))
235 {
236 temp = str;
237 continue;
238 }
239 std::cout << str << " ";
240
241 if (tokens[i].m_flags & token_flags_t::sentence_brk ||
242 tokens[i].m_flags & token_flags_t::paragraph_brk)
243 {
244 // std::cerr << "Horizontal endl" << std::endl;
245 std::cout << std::endl;
246 }
247 }
248 }
249};
250
252{
253public:
257
259 {
260 if (m_next_token_idx > 1)
261 {
262 // std::cerr << "on destructor" << std::endl;
263 std::cout << std::endl;
264 }
265 }
266
267 virtual void operator()(const std::vector<deeplima::segmentation::token_pos>& tokens, uint32_t len)
268 {
269 std::string temp;
270 for (size_t i = 0; i < len; i++)
271 {
272 const char* ptoken = tokens[i].m_pch;
273 std::ostringstream s;
274 if (temp.size() > 0)
275 {
276 s << temp;
277 temp.clear();
278 }
279 for (size_t j = 0; j < tokens[i].m_len; j++)
280 {
281 if (*ptoken == '\r' || *ptoken == '\n' || *ptoken == '\t')
282 {
283 s << " ";
284 }
285 else
286 {
287 s << *ptoken;
288 }
289 ptoken++;
290 }
291 std::string str = s.str();
292 if (std::string::npos == str.find_first_not_of(' '))
293 {
294 temp = str;
295 continue;
296 }
297 // First sub-word of an expanded multiword token: emit the UD range line
298 // "N-M\tsurface\t_..." just before this sub-word's own line, so the
299 // tokenization-only output carries MWT (e.g. "28-29 au" then "à"/"le").
300 if (tokens[i].m_mwt_len > 0 && nullptr != tokens[i].m_mwt_surface_pch)
301 {
302 std::string surface;
303 const char* psurf = tokens[i].m_mwt_surface_pch;
304 for (size_t j = 0; j < tokens[i].m_mwt_surface_len; j++)
305 {
306 surface += (*psurf == '\r' || *psurf == '\n' || *psurf == '\t') ? ' ' : *psurf;
307 psurf++;
308 }
309 std::cout << m_next_token_idx << "-"
310 << (m_next_token_idx + tokens[i].m_mwt_len - 1) << "\t"
311 << surface << "\t_\t_\t_\t_\t_\t_\t_\t_" << std::endl;
312 }
313 std::cout << m_next_token_idx << "\t";
314 std::cout << str;
315 std::cout << "\t_\t_\t_\t_\t";
316 std::cout << m_next_token_idx - 1;
317 // std::cerr << "TokensToConllU::operator end of token" << std::endl;
318 std::cout << "\t_\t_\t_" << std::endl;
319
321
322 m_next_token_idx += 1;
323 if (tokens[i].m_flags & token_flags_t::sentence_brk ||
324 tokens[i].m_flags & token_flags_t::paragraph_brk)
325 {
326 // std::cerr << "TokensToConllU end of sentence" << std::endl;
327 std::cout << std::endl;
329 }
330 }
331 }
332
333protected:
335};
336
338{
339public:
340 virtual ~DumperBase() = default;
341 virtual uint64_t get_token_counter() const = 0;
342 virtual void flush() = 0;
343 virtual void reset() = 0;
344};
345
346template <class I>
348{
349protected:
352 std::vector<ConllToken> m_tokens;
353 uint32_t m_root;
354
355 void reset()
356 {
357 m_token_counter = 0;
358 }
359
361 {
363 }
364
365 std::vector<std::string> m_class_names;
366 std::vector<std::vector<std::string>> m_classes;
368
370
371public:
373 : m_token_counter(0),
375 m_root(0),
376 m_has_feats(false),
378 {
379 // std::cerr << "AnalysisToConllU()" << (void*)this << std::endl;
380 }
381
383 {
384 // std::cerr << "~AnalysisToConllU " << (void*)this << std::endl;
385 // if (m_next_token_idx > 1)
386 // {
387 // std::cout << std::endl;
388 // }
389 }
390
391 const std::vector<std::vector<std::string>> &getMClasses() const {
392 return m_classes;
393 }
394
395 virtual uint64_t get_token_counter() const
396 {
397 return m_token_counter;
398 }
399
400 void set_classes(size_t idx, const std::string& class_name, const std::vector<std::string>& data)
401 {
402 m_class_names.push_back(class_name);
403
404 if (idx + 1 > m_classes.size())
405 {
406 m_classes.resize(idx + 1);
407 }
408 assert(0 == m_classes[idx].size());
409 m_classes[idx] = data;
410
411 if (m_classes.size() > 1)
412 {
413 m_has_feats = true;
414 for (size_t i = 0; i < m_class_names.size(); ++i)
415 {
416 const std::string& feat_name = m_class_names[i];
417 if (feat_name == "upos" || feat_name == "xpos" || feat_name == "eos")
418 {
419 continue;
420 }
422 break;
423 }
424 }
425 }
426
427 std::string generate_feats(const I& iter)
428 {
429 std::string feat_str;
430
431 for (size_t i = m_first_feature_to_print; i < m_classes.size(); ++i)
432 {
433 if (0 != iter.token_class(i))
434 {
435 if (!feat_str.empty())
436 {
437 feat_str += "|";
438 }
439
440 feat_str += m_class_names[i];
441 feat_str += "=";
442 feat_str += m_classes[i][iter.token_class(i)];
443 }
444 }
445
446 return feat_str;
447 }
448
449 virtual void flush()
450 {
451 // Nothing pending: emit no separator. flush() is also called once at EOF
452 // (apps/deeplima.cpp) after the last sentence already flushed on its
453 // sentence break, so without this guard that final call would append a
454 // stray blank line, leaving a doubled blank at end-of-file that strict
455 // CoNLL-U scorers read as a trailing empty sentence. A genuinely pending
456 // last sentence with no sentence-break flag still has tokens here and is
457 // emitted normally.
458 if (m_tokens.empty())
459 {
460 return;
461 }
463 std::vector<uint32_t> heads(m_tokens.size()+1);
464 heads[0] = 0;
465 for (size_t i = 1; i < heads.size(); i++)
466 {
467 heads[i] = m_tokens[i-1].head;
468 }
469 // std::cerr << "AnalysisToConllU::flush() heads before find_cycle: " << heads << std::endl;
470 while (find_cycle(heads, m_root))
471 {
472 // std::cerr << "AnalysisToConllU::flush() heads after cycle found: " << heads << std::endl;
473 }
474 // std::cerr << "AnalysisToConllU::flush() heads after no more cycle: " << heads << std::endl;
475 for (size_t i = 1; i < heads.size(); i++)
476 {
477 m_tokens[i-1].head = heads[i];
478 }
479 for (const auto& token: m_tokens)
480 {
481 // std::cerr << "AnalysisToConllU::flush():567 " << token ;
482 std::cout << token ;
483 }
484 m_tokens.clear();
485 // std::cerr << "after clearing tokens. m_next_token_idx=" << m_next_token_idx << std::endl;
486 std::cout << std::endl;
487 m_root = 0;
488 }
489
490 void operator()(I& iter, uint32_t begin, uint32_t end, bool hasDeps = false)
491 {
492 // std::cerr << "AnalysisToConllU::operator() " << iter.form() << ", " << begin << ", " << end << ", "
493 // << m_next_token_idx << ", " << m_tokens << std::endl;
494 m_tokens.reserve(end);
495 // Inter-sentence blank lines are emitted by flush() only. When the previous
496 // buffer ended exactly on a sentence break, flush() already wrote the
497 // separator and reset m_next_token_idx to 1 and m_root to 0; emitting
498 // another std::endl here produced *doubled* blank lines between sentences at
499 // buffer boundaries, which strict CoNLL-U scorers (conll18) read as empty
500 // sentences. So only initialize on the very first call (m_next_token_idx==0).
501 if (m_next_token_idx == 0)
502 {
504 }
505 std::string temp;
506 while (!iter.end())
507 {
508 const char* ptoken = iter.form();
509 if (std::string(ptoken) == "<ROOT>")
510 {
511 iter.next();
512 continue;
513 }
514 ConllToken token;
515 std::ostringstream s;
516 if (temp.size() > 0)
517 {
518 s << temp;
519 temp.clear();
520 }
521 while (0 != *ptoken)
522 {
523 if (*ptoken == '\r' || *ptoken == '\n' || *ptoken == '\t')
524 {
525 s << " ";
526 }
527 else
528 {
529 s << *ptoken;
530 }
531 ptoken++;
532 }
533 std::string str = s.str();
534 if (std::string::npos == str.find_first_not_of(' '))
535 {
536 temp = str;
537 continue;
538 }
539 // std::cerr << m_next_token_idx << "\t" << str << "\t" << iter.lemma()
540 // << "\t" << m_classes[0][iter.token_class(0)] << std::endl;
541 token.id = m_next_token_idx;
542 token.form = str;
543 token.lemma = conllu_field(iter.lemma());
544 token.upos = m_classes[0][iter.token_class(0)];
545 // First sub-word of an expanded multiword token: record the "N-M surface"
546 // range to emit before this token's line (ids N..M are the sub-words).
547 if (iter.mwt_len() > 0)
548 {
549 token.mwt_last = m_next_token_idx + iter.mwt_len() - 1;
550 token.mwt_surface = conllu_field(iter.mwt_surface());
551 }
552 // std::cout << m_next_token_idx << "\t";
553 // std::cout << str << "\t";
554 // std::cout << iter.lemma();
555 // if (true)
556 // {
557 // std::cout << "\t" << m_classes[0][iter.token_class(0)];
558 // }
559 // else
560 // {
561 // std::cout << "\t_";
562 // }
563
564 // std::cerr << "\t_\t";
565 // std::cout << "\t_\t";
566
567 if (m_has_feats)
568 {
569 // std::cerr << generate_feats(iter);
570 // std::cout << generate_feats(iter);
571 token.feats = generate_feats(iter);
572 }
573 else
574 {
575 // std::cerr << "_";
576 // std::cout << "_";
577 }
578
579 // std::cerr << "\t";
580 // std::cout << "\t";
581 if (hasDeps)
582 {
583 // m_root is 0 until the sentence's root is written (flush() resets it).
584 // begin and end are the slot's columns in the parser's output: they
585 // were 0 and the token count only while every slot started at 0
586 if ((m_root == 0) && (iter.head() == 0))
587 {
589 token.head = 0;
590 token.deprel = "root";
591 }
592 else if (iter.head() >= end - begin)
593 {
594 // std::cerr << "head is out of sentence. rehead to root or set it as root if no root is set " << m_root << "\tdep"<< std::endl;
595 if (m_root == 0)
596 {
597 token.head = 0;
598 token.deprel = "root";
600 }
601 else
602 {
603 // std::cout << root << "\tdep";
604 token.head = m_root;
605 token.deprel = "dep";
606 }
607 }
608 else if ((m_root != 0) && (iter.head() == 0))
609 {
610 // std::cerr << "multiple roots in the sentence. rehead to the first root" << std::endl;
611 // std::cerr << m_root << "\tdep";
612 // std::cout << root << "\tdep";
613 token.head = m_root;
614 token.deprel = "dep";
615 }
616 else if (iter.head() == m_next_token_idx)
617 {
618 token.head = m_root;
619 token.deprel = "dep";
620 }
621 else
622 {
623 // std::cerr << iter.head() << "\tdep";
624 // std::cout << iter.head() << "\tdep";
625 token.head = iter.head();
626 // Use the deprel predicted by the label decoder when available
627 // (falls back to "dep" if the model has no label decoder).
628 token.deprel = iter.deprel();
629 }
630 }
631 else
632 {
633 // std::cerr << m_next_token_idx - 1 << "\t_";
634 // std::cout << m_next_token_idx - 1 << "\t_";
635 token.head = m_next_token_idx - 1;
636 if (token.head == 0)
637 token.deprel = "root";
638 }
639 // std::cerr << "\t_\t_" << std::endl;
640 // std::cout << "\t_\t_" << std::endl;
641 m_tokens.push_back(token);
643
644 m_next_token_idx += 1;
645 if (iter.flags() & token_flags_t::sentence_brk ||
646 iter.flags() & token_flags_t::paragraph_brk)
647 {
648 // std::cerr << "AnalysisToConllU::operator() on sent/para break. m_next_token_idx="
649 // << m_next_token_idx << std::endl;
650 flush();
651 }
652 iter.next();
653 }
654 }
655};
656
657} // namespace dumper
658} // namespace deeplima
659
660#endif
virtual void operator()(const std::vector< deeplima::segmentation::token_pos > &tokens, uint32_t len)=0
void set_classes(size_t idx, const std::string &class_name, const std::vector< std::string > &data)
const std::vector< std::vector< std::string > > & getMClasses() const
std::string generate_feats(const I &iter)
std::vector< ConllToken > m_tokens
std::vector< std::string > m_class_names
std::vector< std::vector< std::string > > m_classes
void operator()(I &iter, uint32_t begin, uint32_t end, bool hasDeps=false)
virtual uint64_t get_token_counter() const
virtual uint64_t get_token_counter() const =0
virtual ~DumperBase()=default
virtual void operator()(const std::vector< deeplima::segmentation::token_pos > &tokens, uint32_t len)
virtual void operator()(const std::vector< deeplima::segmentation::token_pos > &tokens, uint32_t len)
std::string conllu_field(const char *s)
A CoNLL-U field with its tabs and line breaks turned into spaces.
bool dfs(int v, std::vector< uint32_t > &heads, std::vector< int > &color, uint32_t &cycle_start, uint32_t &cycle_end)
std::ostream & operator<<(std::ostream &oss, const ConllToken &token)
bool find_cycle(std::vector< uint32_t > &heads, uint32_t root)
Edit rules for lemmatizing words absent from the lemma dictionary.
@ paragraph_brk
Definition token_type.h:22
@ sentence_brk
Definition token_type.h:21
ConllToken(const ConllToken &)=default
ConllToken & operator=(const ConllToken &)=default