blob: 366b0b160fd19bd0494cf282b242cb9ef62a45ce [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 Kupietza7d90c62021-07-31 23:48:13 +020020our $VERSION = '0.4.1';
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 = ''),
Marc Kupietzeb7d06a2021-03-19 16:29:16 +010031 'extract-attributes-regex|e=s' => \(my $extract_attributes_regex = ''),
Marc Kupietz6a79cad2021-03-19 16:26:58 +010032 'log|l=s' => \(my $log_level = 'warn'),
Marc Kupietzd8455832021-02-11 17:30:29 +010033
Marc Kupietz6a79cad2021-03-19 16:26:58 +010034 'help|h' => sub {
35 pod2usage(
36 -verbose => 99,
37 -sections => 'NAME|DESCRIPTION|SYNOPSIS|ARGUMENTS|OPTIONS|EXAMPLES',
38 -msg => $VERSION_MSG,
39 -output => '-'
40 )
41 },
42 'version|v' => sub {
43 pod2usage(
44 -verbose => 0,
45 -msg => $VERSION_MSG,
46 -output => '-'
47 );
48 }
49);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010050
Marc Kupietz6a79cad2021-03-19 16:26:58 +010051# Establish logger
52binmode(STDERR, ':encoding(UTF-8)');
53Log::Any::Adapter->set('Stderr', log_level => $log_level);
54$log->notice('Debugging is activated') if DEBUG;
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010055
56my $docid="";
57my ($current_id, $current_from, $current_to, $token);
58my $current;
59my ($unknown, $known) = (0, 0);
60my @current_lines;
61my %processedFilenames;
62my $zipsiglepattern = (defined($ENV{ZIPSIGLEPATTERN})? $ENV{ZIPSIGLEPATTERN} : "");
Marc Kupietzd8455832021-02-11 17:30:29 +010063my $baseOnly;
Marc Kupietzeb7d06a2021-03-19 16:29:16 +010064my %extras;
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010065
66my ($ID_idx, $FORM_idx, $LEMMA_idx, $UPOS_idx, $XPOS_idx, $FEATS_idx, $HEAD_idx, $DEPREC_idx, $DEPS_idx, $MISC_idx) = (0..9);
67
Marc Kupietzc7d1b932020-09-23 13:17:17 +020068my $UNZIP = `sh -c 'command -v unzip'`;
69chomp $UNZIP;
70
71
72if ($UNZIP eq '') {
73 warn('No unzip executable found in PATH.');
74 return 0;
75};
76
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010077foreach my $morpho_zip (@ARGV) {
78 die "cannot open $morpho_zip" if(! -r $morpho_zip);
79 my $data_zip = $morpho_zip;
80 if ($data_zip !~ /\.zip/ && $data_zip =~ /\.conllu?/i) {
81 open(CONLL, "<$data_zip") or die "cannot open $data_zip";
82 while(<CONLL>) {
83 print;
84 }
85 close(CONLL);
86 next;
87 }
88 $data_zip =~ s/\.([^.]+)\.zip$/.zip/;
89 my $foundry = $1;
90 die "cannot open data file $data_zip corresponding to $morpho_zip" if(! -r $data_zip);
91
92 my $first=1;
Marc Kupietz5e7f20a2020-02-17 18:17:11 +010093 my @conll = ("_") x 10;
94 my $filename;
95
Marc Kupietzd8455832021-02-11 17:30:29 +010096 $baseOnly = $morpho_zip eq $data_zip;
97 my ($morphoOrTokenCommand, $plaintextAndStructureCommand);
Marc Kupietzeb7d06a2021-03-19 16:29:16 +010098 if (!$baseOnly) {
99 $morphoOrTokenCommand = "$UNZIP -c $morpho_zip '*/${sigle_pattern}*/*/*/morpho.xml' $zipsiglepattern |";
100 if ($extract_attributes_regex) {
101 $plaintextAndStructureCommand = "$UNZIP -c $data_zip '*/${sigle_pattern}*/*/[sd][ta]*.xml' $zipsiglepattern |";
102 } else {
103 $plaintextAndStructureCommand = "$UNZIP -c $data_zip '*/${sigle_pattern}*/*/data.xml' $zipsiglepattern |";
104 }
Marc Kupietzd8455832021-02-11 17:30:29 +0100105 } else {
106 $foundry = "base";
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100107 $morphoOrTokenCommand = "$UNZIP -c $morpho_zip '*/${sigle_pattern}*/*/*/tokens.xml' $zipsiglepattern |";
108 $plaintextAndStructureCommand = "$UNZIP -c $data_zip '*/${sigle_pattern}*/*/[sd][ta]*.xml' $zipsiglepattern |";
Marc Kupietzd8455832021-02-11 17:30:29 +0100109 }
110
111 open (MORPHO_OR_TOKENPIPE, $morphoOrTokenCommand) or die "cannot unzip $morpho_zip";
112 open (PLAINTEXTPIPE, $plaintextAndStructureCommand) or die "cannot unzip $data_zip";
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100113 print "$COMMENT_START foundry = $foundry\n";
Marc Kupietzd8455832021-02-11 17:30:29 +0100114 while (<MORPHO_OR_TOKENPIPE>) {
Marc Kupietz30c41b12020-09-22 14:32:34 +0200115 if (/^ inflating: (.*)/) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100116 $filename=$1;
Marc Kupietzd8455832021-02-11 17:30:29 +0100117 while($processedFilenames{$filename} && !eof(MORPHO_OR_TOKENPIPE)) {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100118 $log->warn("$filename already processed");
Marc Kupietzd8455832021-02-11 17:30:29 +0100119 while (<MORPHO_OR_TOKENPIPE>) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100120 last if(/\s+inflating:\s+(.*)/);
121 }
Marc Kupietzd8455832021-02-11 17:30:29 +0100122 $filename=$1 if(!eof(MORPHO_OR_TOKENPIPE) && /\s+inflating:\s+(.*)/);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100123 }
Marc Kupietz30c41b12020-09-22 14:32:34 +0200124 } elsif(m@^\s*<layer\s+.*docid="([^"]+)"@) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100125 last if($test && $text_no++ > 3);
126 if(!$first) {
127 closeDoc(0);
128 }
129 $processedFilenames{$filename}=1;
130 $docid=$1;
131 @current_lines=();
132 $known=$unknown=0;
133 $current="";
134 if ($first) {
135 $first = 0;
136 }
137 if(!fetch_plaintext($docid)) { # skip this text
Marc Kupietzd8455832021-02-11 17:30:29 +0100138 while (<MORPHO_OR_TOKENPIPE>) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100139 last if(m@</layer>@);
140 }
141 }
142 print STDOUT "$COMMENT_START filename = $filename\n$COMMENT_START text_id = $docid\n";
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100143 $log->debug("Analyzing $docid");
Marc Kupietz30c41b12020-09-22 14:32:34 +0200144 } elsif (m@^\s*<f\s+.*name="([^"]+)">([^<]+)</f>@) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100145 if ($1 eq "lemma") {
146 $conll[$LEMMA_idx] = $2;
147 $conll[$LEMMA_idx] =~ s/[\t\n\r]//g; # make sure that lemmas never contain tabs or newlines
148 if($conll[$LEMMA_idx] eq 'UNKNOWN') {
149 $conll[$LEMMA_idx] = "--";
150 $unknown++;
151 } else {
152 $known++;
153 }
154 } elsif ($1 eq 'pos' || $1 eq "ctag") {
155 $unknown++;
156 $conll[$XPOS_idx] = $conll[$UPOS_idx] = $2;
157 } elsif ($1 eq 'msd') {
158 $conll[$FEATS_idx] = $2;
159 } elsif ($1 eq 'certainty') {
160 $conll[$MISC_idx] = $2;
161 }
162 } elsif (/<span /) {
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100163 my $last_from = $current_from // -1;
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100164 ($current_id) = /id="[^0-9]*([^\"]*)"/;
165 ($current_from) = /from="([^\"]*)"/;
166 ($current_to) = /to="([^\"]*)"/;
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100167 if($extract_attributes_regex) {
168 for (my $i = $last_from + 1; $i <= $current_from; $i++) {
169 if ($extras{$docid}{$i}) {
170 $current .= $extras{$docid}{$i};
171 undef $extras{$docid}{$i};
172 }
173 }
174 }
Marc Kupietz1db65e52021-07-31 23:38:07 +0200175# $log->debug("found span: $current_id $current_from $current_to");
Marc Kupietz7e71a822020-06-22 17:14:30 +0200176 $token = substr($plain_texts{$docid}, $current_from, $current_to - $current_from);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100177 if (!defined $token) {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100178 $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 +0100179 $token = "_";
180 }
181 $token=~s/[\t\n\r]//g; # make sure that tokens never contain tabs or newlines
182 @conll = ("_") x 10;
183 $conll[$FORM_idx] = encode("utf-8", $token);
Marc Kupietzd8455832021-02-11 17:30:29 +0100184 if($baseOnly) {
185 my @vals = ($current_from, $current_to);
Marc Kupietz1db65e52021-07-31 23:38:07 +0200186# $log->debug("joining : ", join(" ", @vals));
Marc Kupietzd8455832021-02-11 17:30:29 +0100187 push @current_lines, \@vals;
188 $known++;
189 $conll[$ID_idx] = $#current_lines+1;
190 $current .= join("\t", @conll) . "\n"; # conll columns
191 fetch_plaintext($docid);
192 if ($sentence_ends{$docid}{$current_to}) {
193 $current .= "\n";
194 printTokenRanges();
195 print STDOUT $current;
196 $current = "";
197 $known = 0;
198 $unknown = 0;
199 @current_lines = ();
200 }
201 }
Marc Kupietz30c41b12020-09-22 14:32:34 +0200202 } elsif (m@^\s*</fs>@) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100203 my @vals = ($current_from, $current_to);
Marc Kupietz1db65e52021-07-31 23:38:07 +0200204# $log->debug("joining : ", join(" ", @vals));
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100205 push @current_lines, \@vals;
206 # convert gathered information to CONLL
207 $conll[$ID_idx] = $#current_lines+1;
208 $current .= join("\t", @conll) . "\n"; # conll columns
209 if($conll[$XPOS_idx] eq '$.' || ($conll[$XPOS_idx] eq 'SENT' && $token eq '.') || $known + $unknown >= $MAX_SENTENCE_LENGTH) {
210 $current .= "\n";
211 if($known + $unknown > 0) { # only print sentence if it contains some words
212 printTokenRanges();
213 print STDOUT $current;
214 }
215 $current=""; $known=0; $unknown=0;
216 @current_lines = ();
217 }
Marc Kupietzd8455832021-02-11 17:30:29 +0100218 while (<MORPHO_OR_TOKENPIPE>) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100219 last if (m@</span>@); # only consider first interpretation
220 }
221 }
222 }
223 $current .= "\n";
224 closeDoc(1);
Marc Kupietzd8455832021-02-11 17:30:29 +0100225 close(MORPHO_OR_TOKENPIPE);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100226 close(PLAINTEXTPIPE);
227}
228exit;
229
230sub printTokenRanges {
231 print "$COMMENT_START start_offsets = ", $current_lines[0]->[0];
232 foreach my $t (@current_lines) {
233 print STDOUT " $t->[0]";
234 }
235 print "\n$COMMENT_START end_offsets = ", $current_lines[$#current_lines]->[1];
236 foreach my $t (@current_lines) {
237 print STDOUT " $t->[1]";
238 }
239 print "\n";
240}
241
242sub closeDoc {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100243 $log->debug("closing doc");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100244 if($known + $unknown > 0) { # only parse a sentence if it has some words
245 chomp $current;
246 chomp $current;
247 chomp $current;
248 $current .= "\n\n";
249 printTokenRanges();
250 print STDOUT $current;
251 }
252}
253
254# read data.xml to figure out the tokens
255# (ideally tokens should also be in in morpho.xml, but they are not)
256sub fetch_plaintext {
257 my ($target_id) = @_;
258 my $docid;
259 my $text_started=0;
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100260 my $text_count = 0;
Marc Kupietzd8455832021-02-11 17:30:29 +0100261 my ($current_id, $current_from, $current_to);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100262
Marc Kupietzd8455832021-02-11 17:30:29 +0100263 if($plain_texts{$target_id} && (!$baseOnly || $sentence_ends{$target_id}{-1})) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100264# print STDERR "already got $target_id\n";
Marc Kupietz1db65e52021-07-31 23:38:07 +0200265 $log->debug("Already got $target_id");
Marc Kupietzd8455832021-02-11 17:30:29 +0100266 return 1;
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100267 }
268 while(<PLAINTEXTPIPE>) {
269 if(/<raw_text[^>]+docid="([^"]*)/) {
270 $docid=$1;
Marc Kupietz1db65e52021-07-31 23:38:07 +0200271 $log->debug("Getting plain text for $docid");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100272 $text_started=0;
Marc Kupietzd8455832021-02-11 17:30:29 +0100273 } elsif(/<layer[^>]+docid="([^"]*)/) {
274 $docid=$1;
275 $sentence_ends{$docid}{-1}=1;
276 } elsif(m@<span @) {
277 ($current_id) = /id="[^0-9]*([^\"]*)"/;
278 ($current_from) = /from="([^\"]*)"/;
279 ($current_to) = /to="([^\"]*)"/;
280 } elsif(m@<f\s[^>]*>s</f>@) {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100281 $log->debug("Found sentence end for $docid \@$current_to");
Marc Kupietzd8455832021-02-11 17:30:29 +0100282 $sentence_ends{$docid}{$current_to}=1;
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100283 } elsif($extract_attributes_regex && m@<f\sname="name"[^>]*>([^<]+)</f>@) {
284 my $current_element = $1;
Marc Kupietz1db65e52021-07-31 23:38:07 +0200285 $log->debug("Looking for matching attributes in $docid");
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100286 while(<PLAINTEXTPIPE>) {
287 last if(m@</fs>@);
288 if(m@<f\sname="([^"]+)"[^>]*>([^<]+)</f>@) {
289 my $current_node = "$current_element/$1";
290 my $value = $2;
291 if ($current_node =~ /$extract_attributes_regex/) {
Marc Kupietz1db65e52021-07-31 23:38:07 +0200292 $log->debug("Found matching attribute: $docid - $current_node = $value");
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100293 $extras{$docid}{$current_from} .= "# $current_node = $value\n";
294 }
295 }
296 }
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100297 } elsif (m@<text>(.*)</text>@) {
298 $_= decode("utf-8", $1, Encode::FB_DEFAULT);
299 s/&lt;/</go;
300 s/&gt;/>/go;
301 s/&amp;/&/go;
302 tr/…•⋅»«ˮ“”„›‹ʼ‘’‚′‐‑‒–—―⁓⁻₋−﹣-/...""""""'''''''-/;
303 $plain_texts{$docid} = $_;
Marc Kupietz093b21c2021-07-31 23:39:51 +0200304 last if(!$extract_attributes_regex && ($text_count++ > 1 && $plain_texts{$target_id}));
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100305 } elsif (m@<text>(.*)@) {
306 $_= decode("utf-8", $1, Encode::FB_DEFAULT);
307 s/&lt;/</go;
308 s/&gt;/>/go;
309 s/&amp;/&/go;
310 tr/…•⋅»«ˮ“”„›‹ʼ‘’‚′‐‑‒–—―⁓⁻₋−﹣-/...""""""'''''''-/;
311 $plain_texts{$docid} = "$_ ";
312 $text_started=1;
313 } elsif ($text_started && m@(.*)</text>@) {
314 $_= decode("utf-8", $1, Encode::FB_DEFAULT);
315 s/&lt;/</go;
316 s/&gt;/>/go;
317 s/&amp;/&/go;
318 tr/…•⋅»«ˮ“”„›‹ʼ‘’‚′‐‑‒–—―⁓⁻₋−﹣-/...""""""'''''''-/;
319 $plain_texts{$docid} .= $_;
320 $text_started=0;
Marc Kupietz093b21c2021-07-31 23:39:51 +0200321 last if(!$extract_attributes_regex && ($text_count++ > 1 && $plain_texts{$target_id}));
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100322 } elsif ($text_started) {
323 chomp;
324 $_ = decode("utf-8", $_, Encode::FB_DEFAULT) . ' ';
325 s/&lt;/</go;
326 s/&gt;/>/go;
327 s/&amp;/&/go;
328 tr/…•⋅»«ˮ“”„›‹ʼ‘’‚′‐‑‒–—―⁓⁻₋−﹣-/...""""""'''''''-/;
329 $plain_texts{$docid} .= $_;
330 }
331 }
Marc Kupietz1db65e52021-07-31 23:38:07 +0200332 $log->debug("Got plain text for $docid");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100333 if(defined($ENV{PLAINTEXTFILTER})) {
334 if ($plain_texts{$docid} !~ $ENV{PLAINTEXTFILTER}) {
335 $plain_texts{$docid} = undef;
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100336 $log->info("Skipping $docid");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100337 return(undef);
338 } else {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100339 $log->debug("Using $docid");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100340 }
341 }
342 return(1);
343}
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100344
345=pod
346
347=encoding utf8
348
349=head1 NAME
350
351korapxml2conllu - Conversion of KorAP-XML zips to CoNLL-U
352
353=head1 SYNOPSIS
354
355 korapxml2conllu zca15.tree_tagger.zip > zca15.conllu
356
357=head1 DESCRIPTION
358
359C<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
360 for reconstruction in comment lines.
361
362=head1 INSTALLATION
363
364 $ cpanm https://github.com/KorAP/KorAP-XML-CoNLL-U.git
365
366=head1 OPTIONS
367
368=over 2
369
370=item B<--sigle-pattern|-p>
371
372Convert only texts from the KorAP XML zip files with folder names (i.e. sigles) matching the glob pattern.
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100373
374=item B<--extract-attribute-pattern|-e>
375
376Extract element/attribute regular expressions to comments.
377
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100378=item B<--help|-h>
379
380Print help information.
381
382=item B<--version|-v>
383
384Print version information.
385
386
387=item B<--log|-l>
388
389Loglevel for I<Log::Any>. Defaults to C<warn>.
390
391=back
392
393=head1 EXAMPLES
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100394
395 korapxml2conllu -e '(posting/id|div/id)' t/data/wdf19.zip
396
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100397=head1 COPYRIGHT AND LICENSE
398
399Copyright (C) 2021, L<IDS Mannheim|https://www.ids-mannheim.de/>
400
401Author: Marc Kupietz
402
403Contributors: Nils Diewald
404
405L<KorAP::XML::CoNNL-U> is developed as part of the L<KorAP|https://korap.ids-mannheim.de/>
406Corpus Analysis Platform at the
407L<Leibniz Institute for the German Language (IDS)|http://ids-mannheim.de/>,
408member of the
409L<Leibniz-Gemeinschaft|http://www.leibniz-gemeinschaft.de/>.
410
411This program is free software published under the
412L<BSD-2 License|https://opensource.org/licenses/BSD-2-Clause>.