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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env perl
# Reads a CoNLL-U file and tries to fix certain simple errors that would make the file invalid; writes the fixed file to STDOUT.
# Can be used to make a parser output valid.
# * Converts Unicode to the NFC normalized form (i.e., canonical decomposition followed by canonical composition).
# * Makes sure that all sentences have a unique sentence id.
# * Makes sure that all sentences have the full text comment and that it matches the SpaceAfter=No annotations (but if both exist in the input and they don't match, the script gives up).
# Usage: perl conllu-quick-fix.pl < input.conllu > fixed.conllu
# Copyright © 2019, 2020 Dan Zeman <zeman@ufal.mff.cuni.cz>
# License: GNU GPL

use utf8;
use open ':utf8';
binmode(STDIN, ':utf8');
binmode(STDOUT, ':utf8');
binmode(STDERR, ':utf8');
use Unicode::Normalize;
use Getopt::Long;

my $connect_to_root = 0;
GetOptions
(
    'connect-to-root' => \$connect_to_root
);

my @sentence = ();
my $isent = 0;
while(<>)
{
    push(@sentence, NFC($_));
    if(m/^\s*$/)
    {
        process_sentence(@sentence);
        @sentence = ();
    }
}



#------------------------------------------------------------------------------
# Once a sentence has been read, processes it and prints it.
#------------------------------------------------------------------------------
sub process_sentence
{
    $isent++; # global counter
    my @sentence = @_;
    my $sentid;
    my $text;
    my $resttext;
    my $collected_text = '';
    my $mwtto;
    foreach my $line (@sentence)
    {
        $line =~ s/\r?\n$//;
        if($line =~ m/^\#\s*sent_id\s*=\s*(\S+)$/)
        {
            $sentid = $1;
        }
        elsif($line =~ m/^\#\s*text\s*=\s*(.+)$/)
        {
            $text = $1;
            $resttext = $text;
        }
        # All node/token lines must have exactly ten columns.
        if($line =~ m/^\d/)
        {
            my @f = split(/\t/, $line);
            while(scalar(@f)<10)
            {
                push(@f, '_');
            }
            splice(@f, 10);
            # Now check the contents of the columns.
            $f[2] = fix_lemma($f[0], $f[2]);
            $f[3] = fix_upos($f[0], $f[3]);
            $f[4] = fix_xpos($f[0], $f[4]);
            $f[5] = fix_feats($f[0], $f[5]);
            ($f[6], $f[7]) = fix_head_deprel($f[0], $f[6], $f[7]);
            $f[8] = fix_deps($f[0], $f[8]);
            $line = join("\t", @f);
        }
        if($line =~ m/^\d+-(\d+)\t/)
        {
            $mwtto = $1;
            my @f = split(/\t/, $line);
            # Collect text from FORM. We will use it if there was no # text attribute.
            my @misc = split(/\|/, $f[9]);
            $collected_text .= $f[1];
            # If there was a # text attribute, we will check and fix SpaceAfter=No instead.
            if(defined($resttext))
            {
                my $l = length($f[1]);
                if($f[1] eq substr($resttext, 0, $l))
                {
                    $resttext = substr($resttext, $l);
                    # Now check SpaceAfter=No against the resttext. Exception: end of sentence cannot be verified.
                    unless($resttext eq '')
                    {
                        if($resttext =~ s/^\s+//)
                        {
                            # We just removed leading space(s) from $resttext. There must not be SpaceAfter=No in MISC.
                            @misc = grep {!m/^SpaceAfter=No$/} (@misc);
                            if(scalar(@misc) == 0)
                            {
                                push(@misc, '_');
                            }
                        }
                        else
                        {
                            # No spaces follow the form in $resttext. There must be SpaceAfter=No in MISC.
                            if(scalar(@misc) == 1 && $misc[0] eq '_')
                            {
                                $misc[0] = 'SpaceAfter=No';
                            }
                            elsif(!grep {m/^SpaceAfter=No$/} (@misc))
                            {
                                push(@misc, 'SpaceAfter=No');
                            }
                        }
                    }
                }
                else
                {
                    print STDERR ("WARNING: sentence text comment exists and the form '$f[1]' does not match the rest of the text '$resttext'; giving up.\n");
                    $resttext = undef;
                }
            }
            unless(grep {m/^SpaceAfter=No$/} (@misc))
            {
                $collected_text .= ' ';
            }
            $f[9] = join('|', @misc);
            $line = join("\t", @f);
        }
        # Normal nodes (they may or may not be part of a multi-word token).
        elsif($line =~ m/^\d+\t/)
        {
            my @f = split(/\t/, $line);
            unless(defined($mwtto) && $f[0]<=$mwtto)
            {
                # Collect text from FORM. We will use it if there was no # text attribute.
                my @misc = split(/\|/, $f[9]);
                $collected_text .= $f[1];
                # If there was a # text attribute, we will check and fix SpaceAfter=No instead.
                if(defined($resttext))
                {
                    my $l = length($f[1]);
                    if($f[1] eq substr($resttext, 0, $l))
                    {
                        $resttext = substr($resttext, $l);
                        # Now check SpaceAfter=No against the resttext. Exception: end of sentence cannot be verified.
                        unless($resttext eq '')
                        {
                            if($resttext =~ s/^\s+//)
                            {
                                # We just removed leading space(s) from $resttext. There must not be SpaceAfter=No in MISC.
                                @misc = grep {!m/^SpaceAfter=No$/} (@misc);
                                if(scalar(@misc) == 0)
                                {
                                    push(@misc, '_');
                                }
                            }
                            else
                            {
                                # No spaces follow the form in $resttext. There must be SpaceAfter=No in MISC.
                                if(scalar(@misc) == 1 && $misc[0] eq '_')
                                {
                                    $misc[0] = 'SpaceAfter=No';
                                }
                                elsif(!grep {m/^SpaceAfter=No$/} (@misc))
                                {
                                    push(@misc, 'SpaceAfter=No');
                                }
                            }
                        }
                    }
                    else
                    {
                        print STDERR ("WARNING: sentence text comment exists and the form '$f[1]' does not match the rest of the text '$resttext'; giving up.\n");
                        $resttext = undef;
                    }
                }
                unless(grep {m/^SpaceAfter=No$/} (@misc))
                {
                    $collected_text .= ' ';
                }
                $f[9] = join('|', @misc);
            }
            else # MISC of words within a multi-word token must not contain SpaceAfter=No
            {
                my @misc = split(/\|/, $f[9]);
                @misc = grep {!m/^SpaceAfter=No$/} (@misc);
                if(scalar(@misc) == 0)
                {
                    push(@misc, '_');
                }
                $f[9] = join('|', @misc);
            }
            $line = join("\t", @f);
        }
        $line .= "\n";
    }
    # Generate sentence text comment if it is not present.
    if(!defined($text))
    {
        $collected_text =~ s/\s+$//;
        unshift(@sentence, "\# text = $collected_text\n");
    }
    # Generate sentence id if it is not present.
    if(!defined($sentid))
    {
        unshift(@sentence, "\# sent_id = $isent\n");
    }
    # Optionally (with the --connect-to-root switch) add 0:root enhanced relations
    # untill all nodes are reachable from 0.
    if($connect_to_root)
    {
        @sentence = make_all_nodes_reachable(@sentence);
    }
    # Print the fixed sentence.
    print(join('', @sentence));
}



#------------------------------------------------------------------------------
# Makes sure that lemma is valid.
#------------------------------------------------------------------------------
sub fix_lemma
{
    my $id = shift;
    my $lemma = shift;
    # Multi-word token must have the lemma empty.
    if($id =~ m/^\d+-\d+$/)
    {
        return '_';
    }
    # Empty node can have the lemma empty but it is not required.
    if($id =~ m/^\d+\.\d+$/ && $lemma eq '_')
    {
        return $lemma;
    }
    # Normal nodes and empty nodes with non-empty lemmas.
    # Make sure that LEMMA does not contain leading or trailing spaces.
    $lemma =~ s/^\s+//;
    $lemma =~ s/\s+$//;
    $lemma = '_' if($lemma eq '');
    return $lemma;
}



#------------------------------------------------------------------------------
# Makes sure that UPOS is valid.
#------------------------------------------------------------------------------
sub fix_upos
{
    my $id = shift;
    my $upos = shift;
    # Multi-word token must have the UPOS empty.
    if($id =~ m/^\d+-\d+$/)
    {
        return '_';
    }
    # Empty node can have the UPOS empty but it is not required.
    if($id =~ m/^\d+\.\d+$/ && $upos eq '_')
    {
        return $upos;
    }
    # Make sure that UPOS is from the prescribed inventory.
    if($upos !~ m/^(NOUN|PROPN|PRON|ADJ|DET|NUM|VERB|AUX|ADV|ADP|SCONJ|CCONJ|PART|INTJ|SYM|PUNCT|X)$/)
    {
        $upos = 'X';
    }
    return $upos;
}



#------------------------------------------------------------------------------
# Makes sure that XPOS is valid.
#------------------------------------------------------------------------------
sub fix_xpos
{
    my $id = shift;
    my $xpos = shift;
    # Multi-word token must have the XPOS empty.
    if($id =~ m/^\d+-\d+$/)
    {
        return '_';
    }
    # Empty node can have the XPOS empty but it is not required.
    if($id =~ m/^\d+\.\d+$/ && $xpos eq '_')
    {
        return $xpos;
    }
    # Normal nodes and empty nodes with non-empty XPOS.
    # Make sure that XPOS does not contain leading or trailing spaces.
    $xpos =~ s/^\s+//;
    $xpos =~ s/\s+$//;
    $xpos = '_' if($xpos eq '');
    return $xpos;
}



#------------------------------------------------------------------------------
# Makes sure that FEATS is valid.
#------------------------------------------------------------------------------
sub fix_feats
{
    my $id = shift;
    my $feats = shift;
    # Multi-word token must have the FEATS empty.
    if($id =~ m/^\d+-\d+$/)
    {
        return '_';
    }
    # Empty node can have the FEATS empty but it is not required.
    if($id =~ m/^\d+\.\d+$/ && $feats eq '_')
    {
        return $feats;
    }
    # Normal nodes and empty nodes with non-empty FEATS.
    # Make sure that FEATS is either '_' or it follows the prescribed pattern.
    if($feats ne '_')
    {
        my @feats = split(/\|/, $feats);
        # Each element must be a name=value pair.
        # Feature names start with [A-Z] and contain [A-Za-z].
        # Same for feature values, but [0-9] is also allowed there, and comma (',') may separate multi-values.
        # Feature names can additionally contain square brackets with layer ("[psor]").
        foreach my $fv (@feats)
        {
            my ($f, $v);
            if($fv =~ m/^(.+)=(.+)$/)
            {
                $f = $1;
                $v = $2;
            }
            else
            {
                $f = $fv;
                $v = 'Yes';
            }
            $f =~ s/[^A-Za-z\[\]]//g;
            $f =~ s/^(.)/\u\1/;
            $f = 'X'.$f if($f !~ m/^[A-Z]/);
            $v =~ s/[^A-Za-z0-9,]//g;
            $v =~ s/^(.)/\u\1/;
            $v = 'X'.$v if($v !~ m/^[A-Z0-9]/);
            $fv = "$f=$v";
        }
        @feats = sort {lc($a) cmp lc($b)} (@feats);
        $feats = join('|', @feats);
    }
    return $feats;
}



#------------------------------------------------------------------------------
# Makes sure that HEAD and DEPREL are valid.
#------------------------------------------------------------------------------
sub fix_head_deprel
{
    my $id = shift;
    my $head = shift;
    my $deprel = shift;
    # Multi-word tokens and empty nodes must have HEAD and DEPREL empty.
    if($id =~ m/^\d+(-|\.)\d+$/)
    {
        return ('_', '_');
    }
    # Make sure that HEAD is numeric and DEPREL is not empty.
    if($head !~ m/^\d+$/)
    {
        # We will attach node 1 to node 0, and all other nodes to 1.
        # This will produce a valid tree if we apply it to all words,
        # i.e., none of them had a valid parent before. Otherwise, it
        # may not work as we may be introducing cycles!
        if($id == 1)
        {
            $head = 0;
            $deprel = 'root';
        }
        else
        {
            $head = 1;
            if($deprel eq '_' || $deprel eq '')
            {
                $deprel = 'dep';
            }
        }
    }
    # Make sure that DEPREL contains only allowed strings (but no language-specific list is checked).
    my $udeprels = 'nsubj|obj|iobj|csubj|ccomp|xcomp|obl|vocative|expl|dislocated|advcl|advmod|discourse|aux|cop|mark|nmod|appos|nummod|acl|amod|det|clf|case|conj|cc|fixed|flat|compound|list|parataxis|orphan|goeswith|reparandum|punct|root|dep';
    if($deprel =~ m/^root(:|$)/ && $head != 0)
    {
        $deprel = 'dep';
    }
    if($deprel !~ m/^root(:|$)/ && $head == 0)
    {
        $deprel = 'root';
    }
    if($deprel !~ m/^($udeprels)(:[a-z]+)?$/)
    {
        # First attempt: remove the subtype.
        $deprel =~ s/:.*//;
    }
    if($deprel !~ m/^($udeprels)(:[a-z]+)?$/)
    {
        # Second attempt: take 'dep'.
        $deprel = 'dep';
    }
    return ($head, $deprel);
}



#------------------------------------------------------------------------------
# Makes sure that DEPS is valid.
#------------------------------------------------------------------------------
sub fix_deps
{
    my $id = shift;
    my $deps = shift;
    # Multi-word tokens must have DEPS empty.
    if($id =~ m/^\d+-\d+$/)
    {
        return '_';
    }
    # Empty DEPS is OK. But if not empty, then certain rules must be followed.
    unless($deps eq '_')
    {
        my @deps = split(/\|/, $deps);
        # Remove self-loops.
        @deps = grep {my $h; if(m/^(\d+(?:\.\d+)?):/) {$h = $1;} defined($h) && $h!=$id} (@deps);
        if(scalar(@deps)==0)
        {
            # DEPS was not empty, so there is an enhanced graph and we should not make DEPS empty now.
            push(@deps, '0:root');
        }
        # Make sure that the deps do not contain disallowed characters.
        foreach my $dep (@deps)
        {
            my ($h, $d);
            if($dep =~ m/^(\d+(?:\.\d+)?):(.+)$/)
            {
                $h = $1;
                $d = $2;
            }
            else
            {
                $h = 1;
                $d = $dep;
            }
            if($d !~ m/^[a-z]+(:[a-z]+)?(:[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(_[\p{Ll}\p{Lm}\p{Lo}\p{M}]+)*)?(:[a-z]+)?$/)
            {
                # First attempt: just lowercase and remove strange characters.
                $d = lc($d);
                $d =~ s/[^:_a-z\p{Ll}\p{Lm}\p{Lo}\p{M}]//g;
            }
            if($d !~ m/^[a-z]+(:[a-z]+)?(:[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(_[\p{Ll}\p{Lm}\p{Lo}\p{M}]+)*)?(:[a-z]+)?$/)
            {
                # Second attempt: everything after the first colon is simply 'extra'.
                $d =~ s/^([^:]*):.*$/$1:extra/;
            }
            if($d !~ m/^[a-z]+(:[a-z]+)?(:[\p{Ll}\p{Lm}\p{Lo}\p{M}]+(_[\p{Ll}\p{Lm}\p{Lo}\p{M}]+)*)?(:[a-z]+)?$/)
            {
                # Last attempt: just 'dep'.
                $d = 'dep';
            }
            # Finally, if $h is 0, then $d must be root; and  if $h is not 0, then $d must not be root.
            if($h==0 && $d !~ m/^root(:|$)/)
            {
                $d = 'root';
            }
            if($h!=0 && $d =~ m/^root(:|$)/)
            {
                $d = 'dep';
            }
            $dep = "$h:$d";
        }
        # Remove duplicates from @deps.
        my %deps; map {$deps{$_}++} (@deps);
        @deps = keys(%deps);
        @deps = sort
        {
            my @a = split(/:/, $a);
            my @b = split(/:/, $b);
            my $ah = shift(@a);
            my $bh = shift(@b);
            my $r = $ah <=> $bh;
            unless($r)
            {
                my $ad = join(':', @a);
                my $bd = join(':', @b);
                $r = $ad cmp $bd;
            }
            $r
        }
        (@deps);
        $deps = join('|', @deps);
    }
    return $deps;
}



#------------------------------------------------------------------------------
# For each node of the enhanced graph, finds the set of nodes from which the
# node is reachable, i.e., the set of its enhanced ancestors. If node 0 (the
# virtual root) is not among them, adds gradually 0:root relations until all
# nodes are reachable from the root.
#------------------------------------------------------------------------------
sub make_all_nodes_reachable
{
    my @sentence = @_;
    my @nodes = grep {m/^\d+(\.\d+)?\t/} (@sentence);
    my %unreachable;
    my %parents;
    foreach my $node (@nodes)
    {
        my @f = split(/\t/, $node);
        my $id = $f[0];
        $unreachable{$id}++;
        my $deps = $f[8];
        my @nodeparents = map {m/^(.+):/; $1} (split(/\|/, $deps));
        my %nodeparents; map {$nodeparents{$_}++} (@nodeparents);
        @nodeparents = keys(%nodeparents);
        $parents{$id} = \@nodeparents;
    }
    # Find nodes that are reachable from 0.
    my %reachable;
    $reachable{'0'}++;
    my %attach_to_root; # nodes that will have to be attached to 0
    while(1)
    {
        my @unreachable = sort(keys(%unreachable));
        last if(scalar(@unreachable)==0);
        my $found_new = 0;
        foreach my $id (@unreachable)
        {
            foreach my $parent (@{$parents{$id}})
            {
                if($reachable{$parent})
                {
                    $found_new++;
                    $reachable{$id}++;
                    delete($unreachable{$id});
                    last;
                }
            }
        }
        # If we cannot find a new way how to make an unreachable node reachable,
        # try attaching the first unreachable node directly to the root.
        # We will first try to attach to root the first node (by id, lexicographically).
        # There might be better solutions, e.g., if the unreachable nodes form
        # a component whose root is the last node (with highest id). But we are
        # not trying to find the optimal solution. We just want to make the file
        # valid.
        @unreachable = sort(keys(%unreachable));
        if(scalar(@unreachable)>0 && !$found_new)
        {
            my $node = shift(@unreachable);
            $attach_to_root{$node}++;
            $reachable{$node}++;
            delete($unreachable{$node});
            $found_new = 1;
        }
    }
    # Now take the nodes that should be attached to the root and attach them there.
    foreach my $line (@sentence)
    {
        if($line =~ m/^\d+(\.\d+)?\t/)
        {
            my @f = split(/\t/, $line);
            if($attach_to_root{$f[0]})
            {
                my @deps = split(/\|/, $f[8]);
                @deps = () if(scalar(@deps)==1 && $deps[0] eq '_');
                unshift(@deps, '0:root');
                $f[8] = join('|', @deps);
            }
            $line = join("\t", @f);
        }
    }
    return @sentence;
}