-
Notifications
You must be signed in to change notification settings - Fork 46
/
conllu-stats.pl
executable file
·2637 lines (2542 loc) · 108 KB
/
conllu-stats.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env perl
# Reads CoNLL(-U) data from STDIN, collects all features (FEAT column, delimited by vertical bars) and prints them sorted to STDOUT.
# Copyright © 2013-2017 Dan Zeman <[email protected]>
# License: GNU GPL
use utf8;
sub usage
{
print STDERR ("perl conllu-stats.pl *.conllu > stats.xml\n");
print STDERR ("... generates the basic statistics that accompany each treebank.\n");
print STDERR ("... sizes of train, dev, and test data are based on file names.\n");
print STDERR ("cat *.conllu | perl conllu-stats.pl > stats.xml\n");
print STDERR ("... if no files are given, standard input will be read but train/dev/test won't be distinguished.\n");
print STDERR ("perl conllu-stats.pl --oformat detailed --data .. --docs ../docs --lang pt\n");
print STDERR ("... adds detailed statistics of each tag, feature and relation to the documentation source pages.\n");
print STDERR (" data = parent folder of the data repositories, e.g. of UD_English\n");
print STDERR (" The script will analyze all treebanks of the given language.\n");
print STDERR ("cat *.conllu | perl conllu-stats.pl --oformat hub\n");
print STDERR ("... generates statistics parallel to the language-specific documentation hub.\n");
print STDERR ("perl conllu-stats.pl --oformat hubcompare UD_Czech UD_Czech-CAC > docs/treebanks/cs-comparison.md\n");
print STDERR ("... similar to hub but compares two or more treebanks side-by-side.\n");
print STDERR ("... each treebank is either one CoNLL-U file, or a folder with CoNLL-U files.\n");
print STDERR ("perl conllu-stats.pl --oformat newdetailed --release 2.4 --treebank UD_Czech --docs docs\n");
print STDERR ("... generates a number of treebank-specific files in docs/treebanks.\n");
}
use open ':utf8';
binmode(STDIN, ':utf8');
binmode(STDOUT, ':utf8');
binmode(STDERR, ':utf8');
use Getopt::Long;
# Make sure that the tools folder is searched for Perl modules. Then use udlib from there.
# Without it, we could not run this script from other folders.
BEGIN
{
our $toolsdir = $0;
unless($toolsdir =~ s:[/\\][^/\\]*$::)
{
$toolsdir = '.';
}
}
use lib "$toolsdir";
use udlib;
# Read options.
$konfig{iformat} = '';
$konfig{oformat} = 'simple'; # simple = stats.xml; hub = markdown one-page summary; detailed = markdown, separate page for each tag/feat/rel
$konfig{relative} = 0; # relative frequencies of POS tags instead of absolute counts (affects only simple XML statistics)
$konfig{datapath} = '.'; # if detailed: parent folder of the data repositories (of UD_$language).
$konfig{docspath} = '../docs'; # if detailed: where is the docs repository? We will modify the page sources there.
$konfig{langcode} = ''; # if detailed; used to identify docs that shall be modified, and also in links inside
$konfig{permalink} = ''; # permalink property of the generated hub page; only needed if the path to the MarkDown source is different from the path to the HTML page
$konfig{release} = ''; # e.g. '2.4'; needed in the download link in the generated hub page.
GetOptions
(
'iformat=s' => \$konfig{iformat},
'oformat=s' => \$konfig{oformat},
'relative' => \$konfig{relative},
'data=s' => \$konfig{datapath},
'docs=s' => \$konfig{docspath},
'language=s' => \$konfig{langcode},
'treebank=s' => \$konfig{treebank},
'permalink=s' => \$konfig{permalink},
'release=s' => \$konfig{release},
'help' => \$konfig{help}
);
exit(usage()) if($konfig{help});
if($konfig{oformat} eq 'detailed' && $konfig{langcode} eq '')
{
usage();
die("Missing language code for detailed analysis");
}
# Format "2009" toggles the CoNLL 2009 data format.
my $i_feat_column = $konfig{iformat} eq '2009' ? 6 : 5;
my %universal_features =
(
'PronType' => ['Prs', 'Rcp', 'Art', 'Int', 'Rel', 'Dem', 'Tot', 'Neg', 'Ind'],
'NumType' => ['Card', 'Ord', 'Mult', 'Frac', 'Sets', 'Dist', 'Range', 'Gen'],
'Poss' => ['Yes'],
'Reflex' => ['Yes'],
'Foreign' => ['Yes'],
'Abbr' => ['Yes'],
'Gender' => ['Masc', 'Fem', 'Neut', 'Com'],
'Animacy' => ['Anim', 'Hum', 'Nhum', 'Inan'],
'Number' => ['Sing', 'Coll', 'Dual', 'Plur', 'Ptan'],
'Case' => ['Nom', 'Acc', 'Abs', 'Erg', 'Dat', 'Gen', 'Voc', 'Loc', 'Ins', 'Par', 'Dis', 'Ess', 'Tra', 'Com', 'Abe', 'Ine', 'Ill', 'Ela', 'Add', 'Ade', 'All', 'Abl', 'Sup', 'Sub', 'Del', 'Lat', 'Tem', 'Ter', 'Cau', 'Ben'],
'Definite' => ['Ind', 'Def', 'Red', 'Com'],
'Degree' => ['Pos', 'Cmp', 'Sup', 'Abs'],
'VerbForm' => ['Fin', 'Inf', 'Sup', 'Part', 'Trans', 'Ger'],
'Mood' => ['Ind', 'Imp', 'Cnd', 'Pot', 'Sub', 'Jus', 'Qot', 'Opt', 'Des', 'Nec'],
'Tense' => ['Pres', 'Fut', 'Past', 'Imp', 'Nar', 'Pqp'],
'Aspect' => ['Imp', 'Perf', 'Pro', 'Prog'],
'Voice' => ['Act', 'Pass', 'Rcp', 'Cau'],
'Evident' => ['Nfh'],
'Person' => ['1', '2', '3'],
'Polite' => ['Infm', 'Form'],
'Polarity' => ['Pos', 'Neg'],
);
my %languages =
( # i ... should we use italics when displaying examples from this language?
# c ... the character to be used as example-separating comma.
'am' => {'name' => 'Amharic', 'i' => 0, 'c' => ','},
'grc' => {'name' => 'Ancient Greek', 'i' => 1, 'c' => ','},
'ar' => {'name' => 'Arabic', 'i' => 0, 'c' => '،'},
'eu' => {'name' => 'Basque', 'i' => 1, 'c' => ','},
'be' => {'name' => 'Belarusian', 'i' => 1, 'c' => ','},
'bho' => {'name' => 'Bhojpuri', 'i' => 0, 'c' => ','},
'bg' => {'name' => 'Bulgarian', 'i' => 1, 'c' => ','},
'yue' => {'name' => 'Cantonese', 'i' => 0, 'c' => '、'},
'ca' => {'name' => 'Catalan', 'i' => 1, 'c' => ','},
'zh' => {'name' => 'Chinese', 'i' => 0, 'c' => '、'},
'lzh' => {'name' => 'Classical Chinese', 'i' => 0, 'c' => '、'},
'cop' => {'name' => 'Coptic', 'i' => 0, 'c' => ','},
'hr' => {'name' => 'Croatian', 'i' => 1, 'c' => ','},
'cs' => {'name' => 'Czech', 'i' => 1, 'c' => ','},
'da' => {'name' => 'Danish', 'i' => 1, 'c' => ','},
'nl' => {'name' => 'Dutch', 'i' => 1, 'c' => ','},
'en' => {'name' => 'English', 'i' => 1, 'c' => ','},
'et' => {'name' => 'Estonian', 'i' => 1, 'c' => ','},
'fi' => {'name' => 'Finnish', 'i' => 1, 'c' => ','},
'fr' => {'name' => 'French', 'i' => 1, 'c' => ','},
'gl' => {'name' => 'Galician', 'i' => 1, 'c' => ','},
'de' => {'name' => 'German', 'i' => 1, 'c' => ','},
'got' => {'name' => 'Gothic', 'i' => 1, 'c' => ','},
'el' => {'name' => 'Greek', 'i' => 1, 'c' => ','},
'he' => {'name' => 'Hebrew', 'i' => 0, 'c' => ','},
'hi' => {'name' => 'Hindi', 'i' => 0, 'c' => ','},
'hu' => {'name' => 'Hungarian', 'i' => 1, 'c' => ','},
'id' => {'name' => 'Indonesian', 'i' => 1, 'c' => ','},
'ga' => {'name' => 'Irish', 'i' => 1, 'c' => ','},
'it' => {'name' => 'Italian', 'i' => 1, 'c' => ','},
'ja' => {'name' => 'Japanese', 'i' => 0, 'c' => ','},
'kk' => {'name' => 'Kazakh', 'i' => 1, 'c' => ','},
'ko' => {'name' => 'Korean', 'i' => 0, 'c' => ','},
'la' => {'name' => 'Latin', 'i' => 1, 'c' => ','},
'lv' => {'name' => 'Latvian', 'i' => 1, 'c' => ','},
'lt' => {'name' => 'Lithuanian', 'i' => 1, 'c' => ','},
'no' => {'name' => 'Norwegian', 'i' => 1, 'c' => ','},
'cu' => {'name' => 'Old Church Slavonic', 'i' => 1, 'c' => ','},
'fa' => {'name' => 'Persian', 'i' => 0, 'c' => '،'},
'pl' => {'name' => 'Polish', 'i' => 1, 'c' => ','},
'pt' => {'name' => 'Portuguese', 'i' => 1, 'c' => ','},
'ro' => {'name' => 'Romanian', 'i' => 1, 'c' => ','},
'ru' => {'name' => 'Russian', 'i' => 1, 'c' => ','},
'sa' => {'name' => 'Sanskrit', 'i' => 0, 'c' => ','},
'sr' => {'name' => 'Serbian', 'i' => 1, 'c' => ','},
'sk' => {'name' => 'Slovak', 'i' => 1, 'c' => ','},
'sl' => {'name' => 'Slovenian', 'i' => 1, 'c' => ','},
'es' => {'name' => 'Spanish', 'i' => 1, 'c' => ','},
'sv' => {'name' => 'Swedish', 'i' => 1, 'c' => ','},
'swl' => {'name' => 'Swedish Sign Language', 'i' => 1, 'c' => ','},
'gsw' => {'name' => 'Swiss German', 'i' => 1, 'c' => ','},
'tg' => {'name' => 'Tagalog', 'i' => 1, 'c' => ','},
'ta' => {'name' => 'Tamil', 'i' => 0, 'c' => ','},
'te' => {'name' => 'Telugu', 'i' => 0, 'c' => ','},
'th' => {'name' => 'Thai', 'i' => 0, 'c' => ','},
'tr' => {'name' => 'Turkish', 'i' => 1, 'c' => ','},
'uk' => {'name' => 'Ukrainian', 'i' => 1, 'c' => ','},
'hsb' => {'name' => 'Upper Sorbian', 'i' => 1, 'c' => ','},
'ur' => {'name' => 'Urdu', 'i' => 0, 'c' => '،'},
'ug' => {'name' => 'Uyghur', 'i' => 0, 'c' => '،'},
'vi' => {'name' => 'Vietnamese', 'i' => 1, 'c' => ','},
'wbp' => {'name' => 'Warlpiri', 'i' => 1, 'c' => ','},
'cy' => {'name' => 'Welsh', 'i' => 1, 'c' => ','},
'wo' => {'name' => 'Wolof', 'i' => 1, 'c' => ','},
'yo' => {'name' => 'Yoruba', 'i' => 1, 'c' => ','},
);
if($konfig{oformat} eq 'detailed')
{
if(!exists($languages{$konfig{langcode}}))
{
die("Unknown language code '$konfig{langcode}'");
}
my $language = $languages{$konfig{langcode}}{name};
$language =~ s/ /_/g;
@treebanks = glob("$konfig{datapath}/UD_$language*");
print STDERR ("Treebanks to analyze: ", join(', ', @treebanks), "\n");
$mode = '>';
foreach my $treebank (@treebanks)
{
local $treebank_id = $treebank;
$treebank_id =~ s-^.*/--;
@ARGV = glob("$treebank/*.conllu");
if(scalar(@ARGV)==0)
{
print STDERR ("WARNING: No CoNLL-U files found in $treebank.\n");
next;
}
print STDERR ("Files to read: ", join(', ', @ARGV), "\n");
my $target_path = "$konfig{docspath}/_includes/stats/$konfig{langcode}";
# We set mode '>' for the first treebank in the language but it is not enough.
# If a label occurs only in the second treebank, nothing will be written with the '>' mode and the new statistics will be appended to the old ones!
# And if a label was used in the past but has become obsolete now, we must remove the corresponding file.
# Therefore we will now remove the entire folder subtree and start from scratch.
if(-d $target_path)
{
# But do not remove the subtree after the first treebank has been processed.
if($mode eq '>')
{
system("rm -rf $target_path");
mkdir($target_path) or die("Cannot create folder $target_path: $!");
}
}
else
{
mkdir($target_path) or die("Cannot create folder $target_path: $!");
mkdir("$target_path/pos") or die("Cannot create folder $target_path/pos: $!");
mkdir("$target_path/feat") or die("Cannot create folder $target_path/feat: $!");
mkdir("$target_path/dep") or die("Cannot create folder $target_path/dep: $!");
}
process_treebank();
$mode = '>>';
}
}
elsif($konfig{oformat} eq 'newdetailed')
{
if(!defined($konfig{treebank}))
{
usage();
die("Missing treebank option.\n");
}
local $treebank_id = $konfig{treebank};
$treebank_id =~ s-^.*/--;
local $tbkrecord = udlib::get_ud_files_and_codes($konfig{treebank});
# The language code is used downstream to decide about italics and the correct comma character.
$konfig{langcode} = $tbkrecord->{lcode};
@ARGV = map {"$konfig{treebank}/$_"} (@{$tbkrecord->{files}});
if(scalar(@ARGV)==0)
{
print STDERR ("WARNING: No CoNLL-U files found in $konfig{treebank}.\n");
}
else
{
print STDERR ("Files to read: ", join(', ', @ARGV), "\n");
my $target_path = "$konfig{docspath}/treebanks/$tbkrecord->{code}";
$mode = '>';
process_treebank();
}
}
elsif($konfig{oformat} eq 'hubcompare')
{
print <<EOF
---
layout: base
title: 'Comparison of Treebank Statistics'
udver: '2'
---
EOF
;
my @treebanks = @ARGV;
my $n_treebanks = scalar(@treebanks);
my $width_percent = sprintf("%d", 100/$n_treebanks);
my @tbkhubs;
print STDERR ("The following treebanks will be compared: ", join(', ', @treebanks), "\n");
foreach my $treebank (@treebanks)
{
print STDERR ("Processing $treebank...\n");
local $tbkrecord;
# If the path leads to a folder, read all CoNLL-U files in that folder. Otherwise it is just one CoNLL-U file.
if(-d $treebank)
{
opendir(DIR, $treebank) or die("Cannot read folder $treebank: $!");
@ARGV = map {"$treebank/$_"} (grep {m/\.conllu$/} (readdir(DIR)));
closedir(DIR);
# The language code is used downstream to decide about italics and the correct comma character.
$tbkrecord = udlib::get_ud_files_and_codes($treebank);
$konfig{langcode} = $tbkrecord->{lcode};
}
else
{
@ARGV = ($treebank);
}
my $cells = process_treebank();
insert_heading_cell($cells, "<h1>$treebank</h1>\n");
push(@tbkhubs, $cells);
}
my $table = create_table(@tbkhubs);
print("<table>\n");
foreach my $row (@{$table})
{
print(" <tr>\n");
foreach my $cell (@{$row})
{
print(" <td width=\"$width_percent\%\" valign=\"top\">\n");
print(indent($cell, 6));
print(" </td>\n");
}
print(" </tr>\n");
}
print("</table>\n");
}
else
{
# Take either STDIN or the CoNLL-U files specified on the command line.
if(scalar(@ARGV)>0)
{
print STDERR ("[conllu-stats] The following files will be processed: ", join(', ', @ARGV), "\n");
}
else
{
print STDERR ("[conllu-stats] No command-line arguments found. Standard input will be processed.\n");
}
process_treebank();
}
#------------------------------------------------------------------------------
# Indents lines in a given text by a given number of spaces. Makes sure that
# the last non-empty line is terminated by a LF character regardless of whether
# it was terminated in the input. Any subsequent empty lines will be removed.
#------------------------------------------------------------------------------
sub indent
{
my $text = shift;
my $nspaces = shift;
$text =~ s/\s+$//s;
my $space = ' ' x $nspaces;
my @lines = split(/\r?\n/, $text);
@lines = map {$space.$_} (@lines);
$text = join("\n", @lines)."\n";
return $text;
}
#==============================================================================
# We collect counts and examples of a large number of phenomena. This is an
# attempt to keep them all in one large hash.
#
# %stats
# Absolute count of some sort of unit:
# {nsent} ... number of sentences (trees) in the corpus
# {ntok} .... number of tokens in the corpus
# {ntoksano} ... number of tokens not followed by a space
# {nfus} .... number of fused multi-word tokens in the corpus
# {nword} ... number of syntactic words (nodes) in the corpus
# Inventories of individual data items and their frequencies
# (hashes: item => frequency):
# {words} ... inventory of word forms
# {fusions} ... inventory of multi-word token forms
# {lemmas} ... inventory of lemmas
# {tags} ... inventory of UPOS tags
# {features} ... inventory of feature names
# {fvpairs} ... inventory of feature-value pairs
# {deprels} ... inventory of dependency relation labels
# Examples of words that appeared with a particular property. Right now we
# have just one huge hash but it might be useful to split it in the future
# (hash: property => {exampleWord => frequency}):
# {example}{tag} ... inventory of words that occurred with a particular tag
# {pverbs}{word + expl:pv children} ... pronominal, i.e., inherently reflexive verbs
# {expass}{word + expl:pass children} ... reflexive passive verbs
# {rflobj}{word + reflexive children} ... verbs with reflexive core object
# {norfl}{word} ... verbs without reflexive dependent (used to confirm that a reflexive verb never occurred without the reflexive)
# Combinations of annotation items and their frequencies
# (hashes: item1 => item2 ... => frequency):
# {tlw}{$tag}{$lemma}{$word} ... tag + lemma + word form
# {tf}{$tag}{$feature} ... tag + feature name
# {tfv}{$tag}{$fvpair} ... tag + feature-value pair
# {td}{$tag}{$deprel} ... tag + deprel
# {fw}{$feature}{$word} ... feature name + word
# {fl}{$feature}{$lemma} ... feature name + lemma
# {ft}{$feature}{$tag} ... feature name + tag
# {fvt}{$fvpair}{$tag} ... feature-value pair + tag
# {fvtverbform}{$fvpair}{$tag} ... feature-value pair with UPOS tag and VerbForm if nonempty
# {dtt}{$deprel}{"$ptag-$ctag"} ... deprel + parent tag and child tag
# {dtvftcase}{$deprel}{$tag}{$tag} ... deprel + parent tag with VerbForm + child tag with Case
#==============================================================================
sub reset_counters
{
my $stats = shift;
$stats->{nsent} = 0;
$stats->{ntok} = 0;
$stats->{ntoksano} = 0;
$stats->{nfus} = 0;
$stats->{nword} = 0;
$stats->{train}{nsent} = 0;
$stats->{train}{ntok} = 0;
$stats->{train}{nfus} = 0;
$stats->{train}{nword} = 0;
$stats->{dev}{nsent} = 0;
$stats->{dev}{ntok} = 0;
$stats->{dev}{nfus} = 0;
$stats->{dev}{nword} = 0;
$stats->{test}{nsent} = 0;
$stats->{test}{ntok} = 0;
$stats->{test}{nfus} = 0;
$stats->{test}{nword} = 0;
$stats->{words} = {};
$stats->{fusions} = {};
$stats->{lemmas} = {};
$stats->{tags} = {};
$stats->{features} = {};
$stats->{fvpairs} = {};
$stats->{deprels} = {};
# example words and lemmas
$stats->{examples} = {};
$stats->{pverbs} = {};
$stats->{expass} = {};
$stats->{rflobj} = {};
$stats->{norfl} = {};
# combinations
$stats->{tlw} = {};
$stats->{tf} = {};
$stats->{tfv} = {};
$stats->{td} = {};
$stats->{fw} = {};
$stats->{fl} = {};
$stats->{ft} = {};
$stats->{fvt} = {};
$stats->{fvtverbform} = {};
$stats->{dtt} = {};
$stats->{dtvftcase} = {};
}
#------------------------------------------------------------------------------
# Reads the standard input (simple stats) or all CoNLL-U files in one treebank
# (detailed stats) and analyzes them.
#------------------------------------------------------------------------------
sub process_treebank
{
local %stats;
reset_counters(\%stats);
# Counters visible to the summarizing functions.
local %wordtag;
local %lemmatag;
local %exentwt;
local %exentlt;
local %tfset;
local %tfsetjoint;
local %paradigm;
local %fv;
local %ltrdeprel;
local %deprellen;
local %parenttag;
local %exentdtt;
local %exconlludtt;
local %exentlt;
local %maxtagdegree;
local %nchildren;
local %tagdegree;
local %childtag;
local %childtagdeprel;
local %agreement;
local %disagreement;
# Read the input and collect statistics about it. Either take the files
# listed in the global array @ARGV, or, if @ARGV is empty, read STDIN.
process_files();
# Now prepare the output.
prune_examples($stats{fusions});
local @fusions = sort {my $r = $stats{fusions}{$b} <=> $stats{fusions}{$a}; unless($r) {$r = $a cmp $b}; $r} (keys(%{$stats{fusions}}));
prune_examples($stats{words});
local @words = sort {my $r = $stats{words}{$b} <=> $stats{words}{$a}; unless($r) {$r = $a cmp $b}; $r} (keys(%{$stats{words}}));
prune_examples($stats{lemmas});
local @lemmas = sort {my $r = $stats{lemmas}{$b} <=> $stats{lemmas}{$a}; unless($r) {$r = $a cmp $b}; $r} (keys(%{$stats{lemmas}}));
# Sort the features alphabetically before printing them.
local @tagset = sort(keys(%{$stats{tags}}));
local @featureset = sort {lc($a) cmp lc($b)} (keys(%{$stats{features}}));
local @fvset = sort {lc($a) cmp lc($b)} (keys(%{$stats{fvpairs}}));
local @deprelset = sort(keys(%{$stats{deprels}}));
# Examples may contain uppercase letters only if all-lowercase version does not exist.
my @ltagset = map {$_.'-lemma'} (@tagset);
foreach my $key (keys(%{$stats{examples}}))
{
my @examples = keys(%{$stats{examples}{$key}});
foreach my $example (@examples)
{
if(lc($example) ne $example && exists($stats{examples}{$key}{lc($example)}))
{
$stats{examples}{$key}{lc($example)} += $stats{examples}{$key}{$example};
delete($stats{examples}{$key}{$example});
}
}
}
foreach my $tag (@tagset)
{
my @lemmas = keys(%{$stats{tlw}{$tag}});
foreach my $lemma (@lemmas)
{
prune_examples($stats{tlw}{$tag}{$lemma});
}
}
# Prepare MarkDown hyperlinks that can be used in the generated pages.
# Statlinks lead to pages with statistics from the current treebank.
# Doclinks lead to pages with universal documentation.
local %statlinks;
local %doclinks;
foreach my $tag (@tagset)
{
$statlinks{$tag} = "<tt><a href=\"$tbkrecord->{code}-pos-$tag.html\">$tag</a></tt>";
$doclinks{$tag} = "[$tag]()";
}
foreach my $feature (@featureset)
{
my $feature1 = $feature;
$feature1 =~ s/\[(.+?)\]/-$1/;
$statlinks{$feature} = "<tt><a href=\"$tbkrecord->{code}-feat-$feature1.html\">$feature</a></tt>";
$doclinks{$feature} = "[$feature]()";
}
foreach my $deprel (@deprelset)
{
my $deprel1 = $deprel;
$deprel1 =~ s/:/-/g;
$statlinks{$deprel} = "<tt><a href=\"$tbkrecord->{code}-dep-$deprel1.html\">$deprel</a></tt>";
$doclinks{$deprel} = "[$deprel]()";
}
# Actual generation of output starts here.
if($konfig{oformat} eq 'hub')
{
# The hub_statistics() function returns a reference to an array of MarkDown sections.
print(get_column_text(hub_statistics()));
}
elsif($konfig{oformat} eq 'hubcompare')
{
# Only collect a structured report and return it.
# Multiple treebanks will be scanned and their reports combined by the caller.
return hub_statistics();
}
elsif($konfig{oformat} eq 'detailed' || $konfig{oformat} eq 'newdetailed')
{
# All generated files about one treebank will reside in one folder.
# Make sure that the folder exists.
unless(-d "$konfig{docspath}/treebanks/$tbkrecord->{code}")
{
mkdir("$konfig{docspath}/treebanks/$tbkrecord->{code}") or die("Cannot create folder $konfig{docspath}/treebanks/$tbkrecord->{code}: $!");
}
my $pages = detailed_statistics_tags();
foreach my $tag (keys(%{$pages}))
{
my $path = "$konfig{docspath}/_includes/stats/$konfig{langcode}/pos";
mkdir($path) unless(-d $path);
my $file = "$path/$tag.md";
$file =~ s/AUX\.md/AUX_.md/;
if($konfig{oformat} eq 'newdetailed')
{
$file = "$konfig{docspath}/treebanks/$tbkrecord->{code}/$tbkrecord->{code}-pos-$tag.md";
}
my $page = $pages->{$tag};
print STDERR ("Writing $file\n");
open(PAGE, "$mode$file") or die("Cannot write $file: $!");
print PAGE <<EOF
---
layout: base
title: 'Statistics of $tag in $konfig{treebank}'
udver: '2'
---
EOF
;
print PAGE ($page);
close(PAGE);
}
$pages = detailed_statistics_features();
foreach my $feature (keys(%{$pages}))
{
my $path = "$konfig{docspath}/_includes/stats/$konfig{langcode}/feat";
mkdir($path) unless(-d $path);
my $file = "$path/$feature.md";
if($konfig{oformat} eq 'newdetailed')
{
$file = "$konfig{docspath}/treebanks/$tbkrecord->{code}/$tbkrecord->{code}-feat-$feature.md";
}
# Layered features do not have the brackets in their file names.
$file =~ s/\[(.+)\]/-$1/;
my $page = $pages->{$feature};
print STDERR ("Writing $file\n");
open(PAGE, "$mode$file") or die("Cannot write $file: $!");
print PAGE <<EOF
---
layout: base
title: 'Statistics of $feature in $konfig{treebank}'
udver: '2'
---
EOF
;
print PAGE ($page);
close(PAGE);
}
$pages = detailed_statistics_relations();
foreach my $deprel (@deprelset)
{
my $path = "$konfig{docspath}/_includes/stats/$konfig{langcode}/dep";
mkdir($path) unless(-d $path);
my $file = "$path/$deprel.md";
if($konfig{oformat} eq 'newdetailed')
{
$file = "$konfig{docspath}/treebanks/$tbkrecord->{code}/$tbkrecord->{code}-dep-$deprel.md";
}
else
{
$file =~ s/aux\.md/aux_.md/;
}
# Language-specific relations do not have the colon in their file names.
$file =~ s/:/-/;
my $page = $pages->{$deprel};
print STDERR ("Writing $file\n");
open(PAGE, "$mode$file") or die("Cannot write $file: $!");
print PAGE <<EOF
---
layout: base
title: 'Statistics of $deprel in $konfig{treebank}'
udver: '2'
---
EOF
;
print PAGE ($page);
close(PAGE);
}
if($konfig{oformat} eq 'newdetailed')
{
my $file = "$konfig{docspath}/treebanks/$tbkrecord->{code}/index.md";
print STDERR ("Writing $file\n");
open(PAGE, ">$file") or die("Cannot write $file: $!");
my $treebank_name = $konfig{treebank};
$treebank_name =~ s/[-_]/ /g;
print PAGE <<EOF
---
layout: base
title: '$konfig{treebank}'
udver: '2'
---
<!-- This page is automatically generated from the README file and from
the data files in the latest release.
Please do not edit this page directly. -->
EOF
;
print PAGE (udlib::generate_markdown_treebank_overview($konfig{treebank}, $konfig{release}));
print PAGE ("\n");
print PAGE ("\# Statistics of $treebank_name\n\n");
print PAGE ("\#\# POS Tags\n\n");
print PAGE (join(' – ', map {"[$_]($tbkrecord->{code}-pos-$_.html)"} (@tagset)), "\n\n");
print PAGE ("\#\# Features\n\n");
print PAGE (join(' – ', map {my $x = $_; $x =~ s/\[(.*)\]/-$1/; "[$_]($tbkrecord->{code}-feat-$x.html)"} (@featureset)), "\n\n");
print PAGE ("\#\# Relations\n\n");
print PAGE (join(' – ', map {my $x = $_; $x =~ s/:/-/g; "[$_]($tbkrecord->{code}-dep-$x.html)"} (@deprelset)), "\n\n");
# The hub_statistics() function returns a column object with MarkDown sections inside.
print PAGE (get_column_text(hub_statistics()));
close(PAGE);
}
}
else # stats.xml
{
simple_xml_statistics();
}
}
#------------------------------------------------------------------------------
# Reads one or more CoNLL-U files and collects statistics about them. The list
# of files is controlled by the global variable @ARGV. If it is empty, the
# standard input is read. The statistic counters are local in the Perl sense.
# Unlike the function process_input() below, here we still know what file we
# are reading and we can tell the nested functions to collect partial
# statistics about that file.
#------------------------------------------------------------------------------
sub process_files
{
local $current_portion = 'other';
# If we have a list of input files, process them one-by-one so that we can
# also collect partial statistics about different portions of the data.
if(scalar(@ARGV) > 0)
{
my @files = @ARGV;
foreach my $file (@files)
{
@ARGV = ($file);
if($file =~ m/ud-train/)
{
$current_portion = 'train';
}
elsif($file =~ m/ud-dev/)
{
$current_portion = 'dev';
}
elsif($file =~ m/ud-test/)
{
$current_portion = 'test';
}
else
{
$current_portion = 'other';
}
process_input();
}
}
else # process STDIN
{
process_input();
}
}
#------------------------------------------------------------------------------
# Reads the files listed in @ARGV, or STDIN, if @ARGV is empty. The statistic
# counters are local in the Perl sense.
#------------------------------------------------------------------------------
sub process_input
{
my @sentence;
while(<>)
{
# Skip comment lines (new in CoNLL-U).
next if(m/^\#/);
# Skip lines with empty nodes of enhanced graphs. We are collecting statistics about basic dependencies.
next if(m/^\d+\./);
# Empty lines separate sentences. There must be an empty line after every sentence including the last one.
if(m/^\s*$/)
{
if(@sentence)
{
process_sentence(@sentence);
}
$stats{nsent}++;
$stats{$current_portion}{nsent}++;
splice(@sentence);
}
# Lines with fused tokens do not contain features but we want to count the fusions.
elsif(m/^(\d+)-(\d+)\t(\S+)/)
{
my $i0 = $1;
my $i1 = $2;
my $fusion = $3;
my $size = $i1-$i0+1;
$stats{ntok} -= $size-1;
$stats{$current_portion}{ntok} -= $size-1;
$stats{ntoksano}++ if(m/SpaceAfter=No/);
$stats{nfus}++;
$stats{$current_portion}{nfus}++;
# Remember the occurrence of the fusion.
$stats{fusions}{$fusion}++ unless($fusion eq '_');
}
else
{
$stats{ntok}++;
$stats{$current_portion}{ntok}++;
$stats{nword}++;
$stats{$current_portion}{nword}++;
# Get rid of the line break.
s/\r?\n$//;
# Split line into columns.
# Since UD 2.0 the FORM and LEMMA may contain the space character,
# hence we cannot split on /\s+/ but we must use /\t/ only!
my @columns = split(/\t/, $_);
push(@sentence, \@columns);
}
}
# Process the last sentence even if it is not correctly terminated.
if(@sentence)
{
print STDERR ("WARNING! The last sentence is not properly terminated by an empty line.\n");
print STDERR (" (An empty line means two consecutive LF characters, not just one!)\n");
print STDERR (" Counting the words from the bad sentence anyway.\n");
process_sentence(@sentence);
$stats{nsent}++;
$stats{$current_portion}{nsent}++;
splice(@sentence);
}
}
#------------------------------------------------------------------------------
# Collects statistics from one sentence after the sentence has been read
# completely. We need to read the sentence first so we can save the entire
# sentence as an example of a word's usage.
#------------------------------------------------------------------------------
sub process_sentence
{
my @sentence = @_;
my $sentence = join(' ', map {$_->[1]} (@sentence));
my $slength = length($sentence);
# Add to every node the links to its children.
foreach my $node (@sentence)
{
my $id = $node->[0];
my $head = $node->[6];
if($head > 0)
{
# The eleventh column [10] is unused and we will use it for the child links.
push(@{$sentence[$head-1][10]}, $id);
}
}
foreach my $node (@sentence)
{
my $id = $node->[0];
my $word = $node->[1];
my $lemma = $node->[2];
my $tag = $node->[3];
my $tagcase = $tag;
my $features = $node->[$i_feat_column];
my $head = $node->[6];
my $deprel = $node->[7];
my @children = @{$node->[10]};
$stats{ntoksano}++ if($node->[9] =~ m/SpaceAfter=No/);
# Remember the occurrence of the word form (syntactic word).
$stats{words}{$word}++ unless($word eq '_');
# Remember the occurrence of the lemma.
$stats{lemmas}{$lemma}++ unless($lemma eq '_');
# Remember the occurrence of the universal POS tag.
$stats{tags}{$tag}++;
$stats{tlw}{$tag}{$lemma}{$word}++;
# We can also print example forms and lemmas that had the tag.
$stats{examples}{$tag}{$word}++;
$stats{examples}{$tag.'-lemma'}{$lemma}++;
# How many times is a particular form or lemma classified as a particular part of speech?
$wordtag{$word}{$tag}++;
$lemmatag{$lemma}{$tag}++;
if(!exists($exentwt{$word}{$tag}) || length($exentwt{$word}{$tag}) > 80 && $slength < length($exentwt{$word}{$tag}))
{
$exentwt{$word}{$tag} = join(' ', map {($_->[1] eq $word && $_->[3] eq $tag) ? "<b>$_->[1]</b>" : $_->[1]} (@sentence));
}
$exentlt{$lemma}{$tag} = $sentence unless(exists($exentlt{$lemma}{$tag}));
# Remember the occurrence of each feature-value pair.
my $tagfeatures = "$tag\t$features";
$tfset{$tag}{$features}++;
$tfsetjoint{$tagfeatures}++;
$stats{examples}{$tagfeatures}{$word}++;
# Skip if there are no features.
my %features_found_here;
unless($features eq '_')
{
my @features = split(/\|/, $features);
my $tagverbform = $tag;
my @verbforms = map {my $x = $_; $x =~ s/^VerbForm=//; $x} (grep {m/^VerbForm=/} (@features));
if(scalar(@verbforms) > 0)
{
$tagverbform .= "-$verbforms[0]";
}
foreach my $fv (@features)
{
$stats{fvpairs}{$fv}++;
# We can also list tags with which the feature occurred.
$stats{fvt}{$fv}{$tag}++;
$stats{fvtverbform}{$fv}{$tagverbform}++;
$stats{tfv}{$tag}{$fv}++;
# We can also print example words that had the feature.
$stats{examples}{$fv}{$word}++;
$stats{examples}{"$tag\t$fv"}{$word}++;
$stats{examples}{"$tagverbform\t$fv"}{$word}++ if($tagverbform ne $tag);
# Aggregate feature names over all values.
my ($f, $v) = split(/=/, $fv);
$stats{features}{$f}++;
$stats{tf}{$tag}{$f}++;
$stats{ft}{$f}{$tag}++;
$stats{fw}{$f}{$word}++;
$stats{fl}{$f}{$lemma}++;
my @other_features = grep {!m/$f/} (@features);
my $other_features = scalar(@other_features) > 0 ? join('|', @other_features) : '_';
$paradigm{$tag}{$f}{$lemma}{$v}{$other_features}{$word}++;
$fv{$f}{$v}++;
$features_found_here{$f}++;
if($f eq 'Case')
{
$tagcase .= '-'.$v;
}
}
}
# Remember examples of empty values of features.
foreach my $f (keys(%universal_features))
{
if(!exists($features_found_here{$f}))
{
$stats{examples}{"$tag\t$f=EMPTY"}{$word}++;
}
}
# Remember the occurrence of each dependency relation.
$stats{deprels}{$deprel}++;
$ltrdeprel{$deprel}++ if($head < $id);
$deprellen{$deprel} += abs($id - $head);
$stats{td}{$tag}{$deprel}++;
$stats{examples}{$deprel.'-lemma'}{$lemma}++;
my $parent_tag = 'ROOT';
my $parent_tag_vf = $parent_tag;
if($head != 0)
{
$parent_tag = $parent_tag_vf = $sentence[$head-1][3];
if($sentence[$head-1][5] =~ m/VerbForm=(.+?)(\||$)/)
{
$parent_tag_vf .= '-'.$1;
}
}
$parenttag{$tag}{$parent_tag}++;
$stats{dtt}{$deprel}{"$parent_tag-$tag"}++;
if(!exists($exentdtt{$deprel}{$parent_tag}{$tag}) || length($exentdtt{$deprel}{$parent_tag}{$tag}) > 80 && $slength < length($exentdtt{$deprel}{$parent_tag}{$tag}))
{
$exentdtt{$deprel}{$parent_tag}{$tag} = join(' ', map {($_->[0] == $id || $_->[0] == $head) ? "<b>$_->[1]</b>" : $_->[1]} (@sentence));
my $visualstyle = "# visual-style $id\tbgColor:blue\n";
$visualstyle .= "# visual-style $id\tfgColor:white\n";
$visualstyle .= "# visual-style $head\tbgColor:blue\n";
$visualstyle .= "# visual-style $head\tfgColor:white\n";
$visualstyle .= "# visual-style $head $id $deprel\tcolor:blue\n";
$exconlludtt{$deprel}{$parent_tag}{$tag} = $visualstyle.join("\n", map {my @f = @{$_}; join("\t", (@f[0..9]))} (@sentence))."\n\n";
}
$exentlt{$lemma}{$tag} = $sentence unless(exists($exentlt{$lemma}{$tag}));
# Children from the perspective of their parent.
my $nchildren = scalar(@children);
$maxtagdegree{$tag} = $nchildren if(!defined($maxtagdegree{$tag}) || $nchildren > $maxtagdegree{$tag});
$nchildren{$tag} += $nchildren;
$nchildren = 3 if($nchildren > 3);
$tagdegree{$tag}{$nchildren}++;
my @casedeps;
my @explpvdeps;
my @explpassdeps;
my @rflobjdeps;
foreach my $child (@children)
{
my $cnode = $sentence[$child-1];
my $ctag = $cnode->[3];
my $cdeprel = $cnode->[7];
$childtag{$tag}{$ctag}++;
$childtagdeprel{$tag}{$cdeprel}++;
if($cdeprel eq 'case')
{
push(@casedeps, "ADP($cnode->[2])");
}
elsif($cdeprel eq 'expl:pv')
{
push(@explpvdeps, lc($cnode->[1]));
}
elsif($cdeprel eq 'expl:pass')
{
push(@explpassdeps, lc($cnode->[1]));
}
elsif($cdeprel =~ m/obj/ && $cnode->[5] =~ m/Reflex=Yes/)
{
push(@rflobjdeps, lc($cnode->[1]));
}
}
if(scalar(@casedeps) > 0)
{
$tagcase .= '-'.join('-', @casedeps);
}
$stats{dtvftcase}{$deprel}{$parent_tag_vf}{$tagcase}++;
if(scalar(@explpvdeps) > 0)
{
$stats{pverbs}{join(' ', ($lemma, sort(@explpvdeps)))}++;
}
if(scalar(@explpassdeps) > 0)
{
$stats{expass}{join(' ', ($lemma, sort(@explpassdeps)))}++;
}
if(scalar(@rflobjdeps) > 0)
{
$stats{rflobj}{join(' ', ($lemma, sort(@rflobjdeps)))}++;
}
if(scalar(@explpvdeps)==0 && scalar(@explpassdeps)==0 && scalar(@rflobjdeps)==0)
{
$stats{norfl}{$lemma}++;
}
# Feature agreement between parent and child.
unless($head==0)
{
my $relation = "$parent_tag --[$deprel]--> $tag";
my $parent_features = $sentence[$head-1][5];
my @pfvs = $parent_features eq '_' ? () : split(/\|/, $parent_features);
my @cfvs = $features eq '_' ? () : split(/\|/, $features);
my %pf;
foreach my $pfv (@pfvs)
{
my ($f, $v) = split(/=/, $pfv);
$pf{$f} = $v;
}
my %cf;
foreach my $cfv (@cfvs)
{
my ($f, $v) = split(/=/, $cfv);
$cf{$f} = $v;
# Does the parent have the same value of the feature?
if($pf{$f} eq $v)
{
$agreement{$f}{$relation}++;
}
else
{
$disagreement{$f}{$relation}++;
}
}
foreach my $f (keys(%pf))
{
if(!exists($cf{$f}))
{
$disagreement{$f}{$relation}++;
}
}
}
}
}