blob: 6b849104ee5b1ab68e47224da5359f7ea8cfb02b [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 Kupietz4cc243a2021-10-11 17:15:16 +020020our $VERSION = '0.4.1.9000';
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 Kupietzf1fdc192021-10-08 13:29:59 +0200107 $morphoOrTokenCommand = "$UNZIP -l $morpho_zip '*/${sigle_pattern}*/*/*/morpho.xml' $zipsiglepattern";
108 if (`$morphoOrTokenCommand` !~ /morpho\.xml/) {
109 $morphoOrTokenCommand =~ s/morpho\.xml/tokens.xml/;
110 } else {
111 $baseOnly = 0;
112 }
113 $morphoOrTokenCommand =~ s/-l/-c/;
114 $morphoOrTokenCommand .= ' |';
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100115 $plaintextAndStructureCommand = "$UNZIP -c $data_zip '*/${sigle_pattern}*/*/[sd][ta]*.xml' $zipsiglepattern |";
Marc Kupietzd8455832021-02-11 17:30:29 +0100116 }
117
118 open (MORPHO_OR_TOKENPIPE, $morphoOrTokenCommand) or die "cannot unzip $morpho_zip";
119 open (PLAINTEXTPIPE, $plaintextAndStructureCommand) or die "cannot unzip $data_zip";
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100120 print "$COMMENT_START foundry = $foundry\n";
Marc Kupietzd8455832021-02-11 17:30:29 +0100121 while (<MORPHO_OR_TOKENPIPE>) {
Marc Kupietz30c41b12020-09-22 14:32:34 +0200122 if (/^ inflating: (.*)/) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100123 $filename=$1;
Marc Kupietzd8455832021-02-11 17:30:29 +0100124 while($processedFilenames{$filename} && !eof(MORPHO_OR_TOKENPIPE)) {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100125 $log->warn("$filename already processed");
Marc Kupietzd8455832021-02-11 17:30:29 +0100126 while (<MORPHO_OR_TOKENPIPE>) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100127 last if(/\s+inflating:\s+(.*)/);
128 }
Marc Kupietzd8455832021-02-11 17:30:29 +0100129 $filename=$1 if(!eof(MORPHO_OR_TOKENPIPE) && /\s+inflating:\s+(.*)/);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100130 }
Marc Kupietz30c41b12020-09-22 14:32:34 +0200131 } elsif(m@^\s*<layer\s+.*docid="([^"]+)"@) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100132 last if($test && $text_no++ > 3);
133 if(!$first) {
134 closeDoc(0);
135 }
136 $processedFilenames{$filename}=1;
137 $docid=$1;
138 @current_lines=();
139 $known=$unknown=0;
140 $current="";
141 if ($first) {
142 $first = 0;
143 }
144 if(!fetch_plaintext($docid)) { # skip this text
Marc Kupietzd8455832021-02-11 17:30:29 +0100145 while (<MORPHO_OR_TOKENPIPE>) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100146 last if(m@</layer>@);
147 }
148 }
149 print STDOUT "$COMMENT_START filename = $filename\n$COMMENT_START text_id = $docid\n";
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100150 $log->debug("Analyzing $docid");
Marc Kupietz30c41b12020-09-22 14:32:34 +0200151 } elsif (m@^\s*<f\s+.*name="([^"]+)">([^<]+)</f>@) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100152 if ($1 eq "lemma") {
153 $conll[$LEMMA_idx] = $2;
154 $conll[$LEMMA_idx] =~ s/[\t\n\r]//g; # make sure that lemmas never contain tabs or newlines
155 if($conll[$LEMMA_idx] eq 'UNKNOWN') {
156 $conll[$LEMMA_idx] = "--";
157 $unknown++;
158 } else {
159 $known++;
160 }
161 } elsif ($1 eq 'pos' || $1 eq "ctag") {
162 $unknown++;
163 $conll[$XPOS_idx] = $conll[$UPOS_idx] = $2;
164 } elsif ($1 eq 'msd') {
165 $conll[$FEATS_idx] = $2;
166 } elsif ($1 eq 'certainty') {
167 $conll[$MISC_idx] = $2;
168 }
169 } elsif (/<span /) {
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100170 my $last_from = $current_from // -1;
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100171 ($current_id) = /id="[^0-9]*([^\"]*)"/;
172 ($current_from) = /from="([^\"]*)"/;
173 ($current_to) = /to="([^\"]*)"/;
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100174 if($extract_attributes_regex) {
175 for (my $i = $last_from + 1; $i <= $current_from; $i++) {
176 if ($extras{$docid}{$i}) {
177 $current .= $extras{$docid}{$i};
178 undef $extras{$docid}{$i};
179 }
180 }
181 }
Marc Kupietz1db65e52021-07-31 23:38:07 +0200182# $log->debug("found span: $current_id $current_from $current_to");
Marc Kupietz7e71a822020-06-22 17:14:30 +0200183 $token = substr($plain_texts{$docid}, $current_from, $current_to - $current_from);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100184 if (!defined $token) {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100185 $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 +0100186 $token = "_";
187 }
188 $token=~s/[\t\n\r]//g; # make sure that tokens never contain tabs or newlines
189 @conll = ("_") x 10;
190 $conll[$FORM_idx] = encode("utf-8", $token);
Marc Kupietzd8455832021-02-11 17:30:29 +0100191 if($baseOnly) {
192 my @vals = ($current_from, $current_to);
Marc Kupietz1db65e52021-07-31 23:38:07 +0200193# $log->debug("joining : ", join(" ", @vals));
Marc Kupietzd8455832021-02-11 17:30:29 +0100194 push @current_lines, \@vals;
195 $known++;
196 $conll[$ID_idx] = $#current_lines+1;
197 $current .= join("\t", @conll) . "\n"; # conll columns
198 fetch_plaintext($docid);
199 if ($sentence_ends{$docid}{$current_to}) {
200 $current .= "\n";
201 printTokenRanges();
202 print STDOUT $current;
203 $current = "";
204 $known = 0;
205 $unknown = 0;
206 @current_lines = ();
207 }
208 }
Marc Kupietz30c41b12020-09-22 14:32:34 +0200209 } elsif (m@^\s*</fs>@) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100210 my @vals = ($current_from, $current_to);
Marc Kupietz1db65e52021-07-31 23:38:07 +0200211# $log->debug("joining : ", join(" ", @vals));
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100212 push @current_lines, \@vals;
213 # convert gathered information to CONLL
214 $conll[$ID_idx] = $#current_lines+1;
215 $current .= join("\t", @conll) . "\n"; # conll columns
216 if($conll[$XPOS_idx] eq '$.' || ($conll[$XPOS_idx] eq 'SENT' && $token eq '.') || $known + $unknown >= $MAX_SENTENCE_LENGTH) {
217 $current .= "\n";
218 if($known + $unknown > 0) { # only print sentence if it contains some words
219 printTokenRanges();
220 print STDOUT $current;
221 }
222 $current=""; $known=0; $unknown=0;
223 @current_lines = ();
224 }
Marc Kupietzd8455832021-02-11 17:30:29 +0100225 while (<MORPHO_OR_TOKENPIPE>) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100226 last if (m@</span>@); # only consider first interpretation
227 }
228 }
229 }
230 $current .= "\n";
231 closeDoc(1);
Marc Kupietzd8455832021-02-11 17:30:29 +0100232 close(MORPHO_OR_TOKENPIPE);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100233 close(PLAINTEXTPIPE);
234}
235exit;
236
237sub printTokenRanges {
238 print "$COMMENT_START start_offsets = ", $current_lines[0]->[0];
239 foreach my $t (@current_lines) {
240 print STDOUT " $t->[0]";
241 }
242 print "\n$COMMENT_START end_offsets = ", $current_lines[$#current_lines]->[1];
243 foreach my $t (@current_lines) {
244 print STDOUT " $t->[1]";
245 }
246 print "\n";
247}
248
249sub closeDoc {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100250 $log->debug("closing doc");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100251 if($known + $unknown > 0) { # only parse a sentence if it has some words
252 chomp $current;
253 chomp $current;
254 chomp $current;
255 $current .= "\n\n";
256 printTokenRanges();
257 print STDOUT $current;
258 }
259}
260
261# read data.xml to figure out the tokens
262# (ideally tokens should also be in in morpho.xml, but they are not)
263sub fetch_plaintext {
264 my ($target_id) = @_;
265 my $docid;
266 my $text_started=0;
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100267 my $text_count = 0;
Marc Kupietzd8455832021-02-11 17:30:29 +0100268 my ($current_id, $current_from, $current_to);
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100269
Marc Kupietzd8455832021-02-11 17:30:29 +0100270 if($plain_texts{$target_id} && (!$baseOnly || $sentence_ends{$target_id}{-1})) {
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100271# print STDERR "already got $target_id\n";
Marc Kupietz1db65e52021-07-31 23:38:07 +0200272 $log->debug("Already got $target_id");
Marc Kupietzd8455832021-02-11 17:30:29 +0100273 return 1;
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100274 }
275 while(<PLAINTEXTPIPE>) {
276 if(/<raw_text[^>]+docid="([^"]*)/) {
277 $docid=$1;
Marc Kupietz1db65e52021-07-31 23:38:07 +0200278 $log->debug("Getting plain text for $docid");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100279 $text_started=0;
Marc Kupietzd8455832021-02-11 17:30:29 +0100280 } elsif(/<layer[^>]+docid="([^"]*)/) {
281 $docid=$1;
282 $sentence_ends{$docid}{-1}=1;
283 } elsif(m@<span @) {
284 ($current_id) = /id="[^0-9]*([^\"]*)"/;
285 ($current_from) = /from="([^\"]*)"/;
286 ($current_to) = /to="([^\"]*)"/;
287 } elsif(m@<f\s[^>]*>s</f>@) {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100288 $log->debug("Found sentence end for $docid \@$current_to");
Marc Kupietzd8455832021-02-11 17:30:29 +0100289 $sentence_ends{$docid}{$current_to}=1;
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100290 } elsif($extract_attributes_regex && m@<f\sname="name"[^>]*>([^<]+)</f>@) {
291 my $current_element = $1;
Marc Kupietz1db65e52021-07-31 23:38:07 +0200292 $log->debug("Looking for matching attributes in $docid");
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100293 while(<PLAINTEXTPIPE>) {
294 last if(m@</fs>@);
295 if(m@<f\sname="([^"]+)"[^>]*>([^<]+)</f>@) {
296 my $current_node = "$current_element/$1";
297 my $value = $2;
298 if ($current_node =~ /$extract_attributes_regex/) {
Marc Kupietz1db65e52021-07-31 23:38:07 +0200299 $log->debug("Found matching attribute: $docid - $current_node = $value");
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100300 $extras{$docid}{$current_from} .= "# $current_node = $value\n";
301 }
302 }
303 }
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100304 } elsif (m@<text>(.*)</text>@) {
305 $_= decode("utf-8", $1, Encode::FB_DEFAULT);
306 s/&lt;/</go;
307 s/&gt;/>/go;
308 s/&amp;/&/go;
309 tr/…•⋅»«ˮ“”„›‹ʼ‘’‚′‐‑‒–—―⁓⁻₋−﹣-/...""""""'''''''-/;
310 $plain_texts{$docid} = $_;
Marc Kupietz093b21c2021-07-31 23:39:51 +0200311 last if(!$extract_attributes_regex && ($text_count++ > 1 && $plain_texts{$target_id}));
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100312 } elsif (m@<text>(.*)@) {
313 $_= decode("utf-8", $1, Encode::FB_DEFAULT);
314 s/&lt;/</go;
315 s/&gt;/>/go;
316 s/&amp;/&/go;
317 tr/…•⋅»«ˮ“”„›‹ʼ‘’‚′‐‑‒–—―⁓⁻₋−﹣-/...""""""'''''''-/;
318 $plain_texts{$docid} = "$_ ";
319 $text_started=1;
320 } elsif ($text_started && m@(.*)</text>@) {
321 $_= decode("utf-8", $1, Encode::FB_DEFAULT);
322 s/&lt;/</go;
323 s/&gt;/>/go;
324 s/&amp;/&/go;
325 tr/…•⋅»«ˮ“”„›‹ʼ‘’‚′‐‑‒–—―⁓⁻₋−﹣-/...""""""'''''''-/;
326 $plain_texts{$docid} .= $_;
327 $text_started=0;
Marc Kupietz093b21c2021-07-31 23:39:51 +0200328 last if(!$extract_attributes_regex && ($text_count++ > 1 && $plain_texts{$target_id}));
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100329 } elsif ($text_started) {
330 chomp;
331 $_ = decode("utf-8", $_, Encode::FB_DEFAULT) . ' ';
332 s/&lt;/</go;
333 s/&gt;/>/go;
334 s/&amp;/&/go;
335 tr/…•⋅»«ˮ“”„›‹ʼ‘’‚′‐‑‒–—―⁓⁻₋−﹣-/...""""""'''''''-/;
336 $plain_texts{$docid} .= $_;
337 }
338 }
Marc Kupietz1db65e52021-07-31 23:38:07 +0200339 $log->debug("Got plain text for $docid");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100340 if(defined($ENV{PLAINTEXTFILTER})) {
341 if ($plain_texts{$docid} !~ $ENV{PLAINTEXTFILTER}) {
342 $plain_texts{$docid} = undef;
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100343 $log->info("Skipping $docid");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100344 return(undef);
345 } else {
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100346 $log->debug("Using $docid");
Marc Kupietz5e7f20a2020-02-17 18:17:11 +0100347 }
348 }
349 return(1);
350}
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100351
352=pod
353
354=encoding utf8
355
356=head1 NAME
357
358korapxml2conllu - Conversion of KorAP-XML zips to CoNLL-U
359
360=head1 SYNOPSIS
361
362 korapxml2conllu zca15.tree_tagger.zip > zca15.conllu
363
364=head1 DESCRIPTION
365
366C<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
367 for reconstruction in comment lines.
368
369=head1 INSTALLATION
370
371 $ cpanm https://github.com/KorAP/KorAP-XML-CoNLL-U.git
372
373=head1 OPTIONS
374
375=over 2
376
377=item B<--sigle-pattern|-p>
378
379Convert 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 +0100380
381=item B<--extract-attribute-pattern|-e>
382
383Extract element/attribute regular expressions to comments.
384
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100385=item B<--help|-h>
386
387Print help information.
388
389=item B<--version|-v>
390
391Print version information.
392
393
394=item B<--log|-l>
395
396Loglevel for I<Log::Any>. Defaults to C<warn>.
397
398=back
399
400=head1 EXAMPLES
Marc Kupietzeb7d06a2021-03-19 16:29:16 +0100401
402 korapxml2conllu -e '(posting/id|div/id)' t/data/wdf19.zip
403
Marc Kupietz6a79cad2021-03-19 16:26:58 +0100404=head1 COPYRIGHT AND LICENSE
405
406Copyright (C) 2021, L<IDS Mannheim|https://www.ids-mannheim.de/>
407
408Author: Marc Kupietz
409
410Contributors: Nils Diewald
411
412L<KorAP::XML::CoNNL-U> is developed as part of the L<KorAP|https://korap.ids-mannheim.de/>
413Corpus Analysis Platform at the
414L<Leibniz Institute for the German Language (IDS)|http://ids-mannheim.de/>,
415member of the
416L<Leibniz-Gemeinschaft|http://www.leibniz-gemeinschaft.de/>.
417
418This program is free software published under the
419L<BSD-2 License|https://opensource.org/licenses/BSD-2-Clause>.