blob: 707db18c5a80e5cdf96dea67b914b3926375c6ec [file] [log] [blame]
Marc Kupietz5e7f20a2020-02-17 18:17:11 +01001#!/usr/bin/env perl
2use strict;
3use warnings;
4use POSIX;
Marc Kupietz6a79cad2021-03-19 16:26:58 +01005use Log::Any '$log';
6use Log::Any::Adapter;
7use Pod::Usage;
8use Getopt::Long qw(GetOptions :config no_auto_abbrev);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +01009use Encode;
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010010
11my $MAX_SENTENCE_LENGTH=10000;
12my $COMMENT_START="#";
13
14my $test=0;
15my $text_no=0;
16my %opts;
17my %plain_texts;
Marc Kupietzd8455832021-02-11 17:30:29 +010018my %sentence_ends;
19
Marc Kupietz0ab8a2c2021-03-19 16:21:00 +010020our $VERSION = '0.3.900';
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010021
Marc Kupietz0ab8a2c2021-03-19 16:21:00 +010022our $VERSION_MSG = "\nkorapxml2conllu - v$VERSION\n";
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010023
Marc Kupietz6a79cad2021-03-19 16:26:58 +010024use constant {
25 # Set to 1 for minimal more debug output (no need to be parametrized)
26 DEBUG => $ENV{KORAPXMLCONLLU_DEBUG} // 0
27};
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010028
Marc Kupietz6a79cad2021-03-19 16:26:58 +010029GetOptions(
30 'sigle-pattern|p=s' => \(my $sigle_pattern = ''),
31 'log|l=s' => \(my $log_level = 'warn'),
Marc Kupietzd8455832021-02-11 17:30:29 +010032
Marc Kupietz6a79cad2021-03-19 16:26:58 +010033 'help|h' => sub {
34 pod2usage(
35 -verbose => 99,
36 -sections => 'NAME|DESCRIPTION|SYNOPSIS|ARGUMENTS|OPTIONS|EXAMPLES',
37 -msg => $VERSION_MSG,
38 -output => '-'
39 )
40 },
41 'version|v' => sub {
42 pod2usage(
43 -verbose => 0,
44 -msg => $VERSION_MSG,
45 -output => '-'
46 );
47 }
48);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010049
50 ZIPSIGLEPATTERN='-x "*15/FEB*" "*15/MAR*"' $0 /vol/corpora/DeReKo/current/KorAP/zip/zca15.tree_tagger.zip
51
52 Results will be written to stdout
53EOF
54
55getopts('dhp:', \%opts);
56die $usage if($opts{h} || @ARGV == 0);
57my $debug=($opts{d}? 1 : 0);
Marc Kupietz6a79cad2021-03-19 16:26:58 +010058# Establish logger
59binmode(STDERR, ':encoding(UTF-8)');
60Log::Any::Adapter->set('Stderr', log_level => $log_level);
61$log->notice('Debugging is activated') if DEBUG;
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010062
63my $docid="";
64my ($current_id, $current_from, $current_to, $token);
65my $current;
66my ($unknown, $known) = (0, 0);
67my @current_lines;
68my %processedFilenames;
69my $zipsiglepattern = (defined($ENV{ZIPSIGLEPATTERN})? $ENV{ZIPSIGLEPATTERN} : "");
Marc Kupietzd8455832021-02-11 17:30:29 +010070my $baseOnly;
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010071
72my ($ID_idx, $FORM_idx, $LEMMA_idx, $UPOS_idx, $XPOS_idx, $FEATS_idx, $HEAD_idx, $DEPREC_idx, $DEPS_idx, $MISC_idx) = (0..9);
73
Marc Kupietzc7d1b932020-09-23 13:17:17 +020074my $UNZIP = `sh -c 'command -v unzip'`;
75chomp $UNZIP;
76
77
78if ($UNZIP eq '') {
79 warn('No unzip executable found in PATH.');
80 return 0;
81};
82
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010083foreach my $morpho_zip (@ARGV) {
84 die "cannot open $morpho_zip" if(! -r $morpho_zip);
85 my $data_zip = $morpho_zip;
86 if ($data_zip !~ /\.zip/ && $data_zip =~ /\.conllu?/i) {
87 open(CONLL, "<$data_zip") or die "cannot open $data_zip";
88 while(<CONLL>) {
89 print;
90 }
91 close(CONLL);
92 next;
93 }
94 $data_zip =~ s/\.([^.]+)\.zip$/.zip/;
95 my $foundry = $1;
96 die "cannot open data file $data_zip corresponding to $morpho_zip" if(! -r $data_zip);
97
98 my $first=1;
99 my $pattern = (defined($opts{p})? $opts{p} : '');
100 my @conll = ("_") x 10;
101 my $filename;
102
Marc Kupietzd8455832021-02-11 17:30:29 +0100103 $baseOnly = $morpho_zip eq $data_zip;
104 my ($morphoOrTokenCommand, $plaintextAndStructureCommand);
105 if(!$baseOnly) {
106 $morphoOrTokenCommand = "$UNZIP -c $morpho_zip '*/${pattern}*/*/*/morpho.xml' $zipsiglepattern |";
107 $plaintextAndStructureCommand = "$UNZIP -c $data_zip '*/${pattern}*/*/data.xml' $zipsiglepattern |";
108 } else {
109 $foundry = "base";
110 $morphoOrTokenCommand = "$UNZIP -c $morpho_zip '*/${pattern}*/*/*/tokens.xml' $zipsiglepattern |";
111 $plaintextAndStructureCommand = "$UNZIP -c $data_zip '*/${pattern}*/*/[sd][ta]*.xml' $zipsiglepattern |";
112 }
113
114 open (MORPHO_OR_TOKENPIPE, $morphoOrTokenCommand) or die "cannot unzip $morpho_zip";
115 open (PLAINTEXTPIPE, $plaintextAndStructureCommand) or die "cannot unzip $data_zip";
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100116 print "$COMMENT_START foundry = $foundry\n";
Marc Kupietzd8455832021-02-11 17:30:29 +0100117 while (<MORPHO_OR_TOKENPIPE>) {
Marc Kupietz30c41b12020-09-22 14:32:34 +0200118 if (/^ inflating: (.*)/) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100119 $filename=$1;
Marc Kupietzd8455832021-02-11 17:30:29 +0100120 while($processedFilenames{$filename} && !eof(MORPHO_OR_TOKENPIPE)) {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100121 $log->warn("$filename already processed");
Marc Kupietzd8455832021-02-11 17:30:29 +0100122 while (<MORPHO_OR_TOKENPIPE>) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100123 last if(/\s+inflating:\s+(.*)/);
124 }
Marc Kupietzd8455832021-02-11 17:30:29 +0100125 $filename=$1 if(!eof(MORPHO_OR_TOKENPIPE) && /\s+inflating:\s+(.*)/);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100126 }
Marc Kupietz30c41b12020-09-22 14:32:34 +0200127 } elsif(m@^\s*<layer\s+.*docid="([^"]+)"@) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100128 last if($test && $text_no++ > 3);
129 if(!$first) {
130 closeDoc(0);
131 }
132 $processedFilenames{$filename}=1;
133 $docid=$1;
134 @current_lines=();
135 $known=$unknown=0;
136 $current="";
137 if ($first) {
138 $first = 0;
139 }
140 if(!fetch_plaintext($docid)) { # skip this text
Marc Kupietzd8455832021-02-11 17:30:29 +0100141 while (<MORPHO_OR_TOKENPIPE>) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100142 last if(m@</layer>@);
143 }
144 }
145 print STDOUT "$COMMENT_START filename = $filename\n$COMMENT_START text_id = $docid\n";
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100146 $log->debug("Analyzing $docid");
Marc Kupietz30c41b12020-09-22 14:32:34 +0200147 } elsif (m@^\s*<f\s+.*name="([^"]+)">([^<]+)</f>@) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100148 if ($1 eq "lemma") {
149 $conll[$LEMMA_idx] = $2;
150 $conll[$LEMMA_idx] =~ s/[\t\n\r]//g; # make sure that lemmas never contain tabs or newlines
151 if($conll[$LEMMA_idx] eq 'UNKNOWN') {
152 $conll[$LEMMA_idx] = "--";
153 $unknown++;
154 } else {
155 $known++;
156 }
157 } elsif ($1 eq 'pos' || $1 eq "ctag") {
158 $unknown++;
159 $conll[$XPOS_idx] = $conll[$UPOS_idx] = $2;
160 } elsif ($1 eq 'msd') {
161 $conll[$FEATS_idx] = $2;
162 } elsif ($1 eq 'certainty') {
163 $conll[$MISC_idx] = $2;
164 }
165 } elsif (/<span /) {
166 ($current_id) = /id="[^0-9]*([^\"]*)"/;
167 ($current_from) = /from="([^\"]*)"/;
168 ($current_to) = /to="([^\"]*)"/;
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100169 $log->debug("found span: $current_id $current_from $current_to");
Marc Kupietz7e71a822020-06-22 17:14:30 +0200170 $token = substr($plain_texts{$docid}, $current_from, $current_to - $current_from);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100171 if (!defined $token) {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100172 $log->warn("could not retrieve token for $docid at $current_from-$current_to/", length($plain_texts{$docid}), " - ending with: ", substr($plain_texts{$docid},length($plain_texts{$docid})-10));
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100173 $token = "_";
174 }
175 $token=~s/[\t\n\r]//g; # make sure that tokens never contain tabs or newlines
176 @conll = ("_") x 10;
177 $conll[$FORM_idx] = encode("utf-8", $token);
Marc Kupietzd8455832021-02-11 17:30:29 +0100178 if($baseOnly) {
179 my @vals = ($current_from, $current_to);
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100180 $log->debug("joining : ", join(" ", @vals));
Marc Kupietzd8455832021-02-11 17:30:29 +0100181 push @current_lines, \@vals;
182 $known++;
183 $conll[$ID_idx] = $#current_lines+1;
184 $current .= join("\t", @conll) . "\n"; # conll columns
185 fetch_plaintext($docid);
186 if ($sentence_ends{$docid}{$current_to}) {
187 $current .= "\n";
188 printTokenRanges();
189 print STDOUT $current;
190 $current = "";
191 $known = 0;
192 $unknown = 0;
193 @current_lines = ();
194 }
195 }
Marc Kupietz30c41b12020-09-22 14:32:34 +0200196 } elsif (m@^\s*</fs>@) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100197 my @vals = ($current_from, $current_to);
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100198 $log->debug("joining : ", join(" ", @vals));
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100199 push @current_lines, \@vals;
200 # convert gathered information to CONLL
201 $conll[$ID_idx] = $#current_lines+1;
202 $current .= join("\t", @conll) . "\n"; # conll columns
203 if($conll[$XPOS_idx] eq '$.' || ($conll[$XPOS_idx] eq 'SENT' && $token eq '.') || $known + $unknown >= $MAX_SENTENCE_LENGTH) {
204 $current .= "\n";
205 if($known + $unknown > 0) { # only print sentence if it contains some words
206 printTokenRanges();
207 print STDOUT $current;
208 }
209 $current=""; $known=0; $unknown=0;
210 @current_lines = ();
211 }
Marc Kupietzd8455832021-02-11 17:30:29 +0100212 while (<MORPHO_OR_TOKENPIPE>) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100213 last if (m@</span>@); # only consider first interpretation
214 }
215 }
216 }
217 $current .= "\n";
218 closeDoc(1);
Marc Kupietzd8455832021-02-11 17:30:29 +0100219 close(MORPHO_OR_TOKENPIPE);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100220 close(PLAINTEXTPIPE);
221}
222exit;
223
224sub printTokenRanges {
225 print "$COMMENT_START start_offsets = ", $current_lines[0]->[0];
226 foreach my $t (@current_lines) {
227 print STDOUT " $t->[0]";
228 }
229 print "\n$COMMENT_START end_offsets = ", $current_lines[$#current_lines]->[1];
230 foreach my $t (@current_lines) {
231 print STDOUT " $t->[1]";
232 }
233 print "\n";
234}
235
236sub closeDoc {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100237 $log->debug("closing doc");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100238 if($known + $unknown > 0) { # only parse a sentence if it has some words
239 chomp $current;
240 chomp $current;
241 chomp $current;
242 $current .= "\n\n";
243 printTokenRanges();
244 print STDOUT $current;
245 }
246}
247
248# read data.xml to figure out the tokens
249# (ideally tokens should also be in in morpho.xml, but they are not)
250sub fetch_plaintext {
251 my ($target_id) = @_;
252 my $docid;
253 my $text_started=0;
Marc Kupietzd8455832021-02-11 17:30:29 +0100254 my ($current_id, $current_from, $current_to);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100255
Marc Kupietzd8455832021-02-11 17:30:29 +0100256 if($plain_texts{$target_id} && (!$baseOnly || $sentence_ends{$target_id}{-1})) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100257# print STDERR "already got $target_id\n";
Marc Kupietzd8455832021-02-11 17:30:29 +0100258 return 1;
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100259 }
260 while(<PLAINTEXTPIPE>) {
261 if(/<raw_text[^>]+docid="([^"]*)/) {
262 $docid=$1;
263 $text_started=0;
Marc Kupietzd8455832021-02-11 17:30:29 +0100264 } elsif(/<layer[^>]+docid="([^"]*)/) {
265 $docid=$1;
266 $sentence_ends{$docid}{-1}=1;
267 } elsif(m@<span @) {
268 ($current_id) = /id="[^0-9]*([^\"]*)"/;
269 ($current_from) = /from="([^\"]*)"/;
270 ($current_to) = /to="([^\"]*)"/;
271 } elsif(m@<f\s[^>]*>s</f>@) {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100272 $log->debug("Found sentence end for $docid \@$current_to");
Marc Kupietzd8455832021-02-11 17:30:29 +0100273 $sentence_ends{$docid}{$current_to}=1;
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100274 } elsif (m@<text>(.*)</text>@) {
275 $_= decode("utf-8", $1, Encode::FB_DEFAULT);
276 s/&lt;/</go;
277 s/&gt;/>/go;
278 s/&amp;/&/go;
279 tr/…•⋅»«ˮ“”„›‹ʼ‘’‚′‐‑‒–—―⁓⁻₋−﹣-/...""""""'''''''-/;
280 $plain_texts{$docid} = $_;
281 last if($docid eq $target_id);
282 } elsif (m@<text>(.*)@) {
283 $_= decode("utf-8", $1, Encode::FB_DEFAULT);
284 s/&lt;/</go;
285 s/&gt;/>/go;
286 s/&amp;/&/go;
287 tr/…•⋅»«ˮ“”„›‹ʼ‘’‚′‐‑‒–—―⁓⁻₋−﹣-/...""""""'''''''-/;
288 $plain_texts{$docid} = "$_ ";
289 $text_started=1;
290 } elsif ($text_started && m@(.*)</text>@) {
291 $_= decode("utf-8", $1, Encode::FB_DEFAULT);
292 s/&lt;/</go;
293 s/&gt;/>/go;
294 s/&amp;/&/go;
295 tr/…•⋅»«ˮ“”„›‹ʼ‘’‚′‐‑‒–—―⁓⁻₋−﹣-/...""""""'''''''-/;
296 $plain_texts{$docid} .= $_;
297 $text_started=0;
298 last if($docid eq $target_id);
299 } elsif ($text_started) {
300 chomp;
301 $_ = decode("utf-8", $_, Encode::FB_DEFAULT) . ' ';
302 s/&lt;/</go;
303 s/&gt;/>/go;
304 s/&amp;/&/go;
305 tr/…•⋅»«ˮ“”„›‹ʼ‘’‚′‐‑‒–—―⁓⁻₋−﹣-/...""""""'''''''-/;
306 $plain_texts{$docid} .= $_;
307 }
308 }
309 if(defined($ENV{PLAINTEXTFILTER})) {
310 if ($plain_texts{$docid} !~ $ENV{PLAINTEXTFILTER}) {
311 $plain_texts{$docid} = undef;
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100312 $log->info("Skipping $docid");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100313 return(undef);
314 } else {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100315 $log->debug("Using $docid");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100316 }
317 }
318 return(1);
319}
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100320
321=pod
322
323=encoding utf8
324
325=head1 NAME
326
327korapxml2conllu - Conversion of KorAP-XML zips to CoNLL-U
328
329=head1 SYNOPSIS
330
331 korapxml2conllu zca15.tree_tagger.zip > zca15.conllu
332
333=head1 DESCRIPTION
334
335C<korapxml2conllu> is a script to Convert L<KorAP-XML format|https://github.com/KorAP/KorAP-XML-Krill#about-korap-xml> base or morpho zips to CoNLL(-U) format with all information necessary
336 for reconstruction in comment lines.
337
338=head1 INSTALLATION
339
340 $ cpanm https://github.com/KorAP/KorAP-XML-CoNLL-U.git
341
342=head1 OPTIONS
343
344=over 2
345
346=item B<--sigle-pattern|-p>
347
348Convert only texts from the KorAP XML zip files with folder names (i.e. sigles) matching the glob pattern.
349=item B<--help|-h>
350
351Print help information.
352
353=item B<--version|-v>
354
355Print version information.
356
357
358=item B<--log|-l>
359
360Loglevel for I<Log::Any>. Defaults to C<warn>.
361
362=back
363
364=head1 EXAMPLES
365=head1 COPYRIGHT AND LICENSE
366
367Copyright (C) 2021, L<IDS Mannheim|https://www.ids-mannheim.de/>
368
369Author: Marc Kupietz
370
371Contributors: Nils Diewald
372
373L<KorAP::XML::CoNNL-U> is developed as part of the L<KorAP|https://korap.ids-mannheim.de/>
374Corpus Analysis Platform at the
375L<Leibniz Institute for the German Language (IDS)|http://ids-mannheim.de/>,
376member of the
377L<Leibniz-Gemeinschaft|http://www.leibniz-gemeinschaft.de/>.
378
379This program is free software published under the
380L<BSD-2 License|https://opensource.org/licenses/BSD-2-Clause>.