blob: a68acedc1e453cd4cbbf1ffa7b2463634f904ce1 [file] [log] [blame]
Marc Kupietz79ba1e52021-02-12 17:26:54 +01001#!/usr/bin/env perl
2use strict;
3use warnings;
4use POSIX;
Marc Kupietzaeb84a02021-10-11 17:57:29 +02005use Getopt::Long qw(GetOptions :config no_auto_abbrev);
6use Log::Any '$log';
7use Log::Any::Adapter;
Marc Kupietz79ba1e52021-02-12 17:26:54 +01008use Encode;
9use IO::Compress::Zip qw(zip $ZipError :constants);
10use File::Basename;
Marc Kupietzaeb84a02021-10-11 17:57:29 +020011use Pod::Usage;
Marc Kupietz79ba1e52021-02-12 17:26:54 +010012
13my $_COMPRESSION_METHOD = ZIP_CM_DEFLATE;
14my %opts;
15my %processedFilenames;
16
Akronf3efc9e2026-06-03 10:46:37 +020017our $VERSION = '0.7.0';
Marc Kupietzaeb84a02021-10-11 17:57:29 +020018our $VERSION_MSG = "\nconllu2korapxml - v$VERSION\n";
Marc Kupietz4cc243a2021-10-11 17:15:16 +020019
Marc Kupietzaeb84a02021-10-11 17:57:29 +020020use constant {
21 # Set to 1 for minimal more debug output (no need to be parametrized)
22 DEBUG => $ENV{KORAPXMLCONLLU_DEBUG} // 0
23};
Marc Kupietz79ba1e52021-02-12 17:26:54 +010024
Marc Kupietzaeb84a02021-10-11 17:57:29 +020025GetOptions(
26 'force-foundry|f=s' => \(my $foundry_name = ''),
27 'log|l=s' => \(my $log_level = 'warn'),
Marc Kupietz187abd72024-06-25 14:30:01 +020028 'output|o=s' => \(my $outh = '-'),
Marc Kupietz79ba1e52021-02-12 17:26:54 +010029
Marc Kupietzaeb84a02021-10-11 17:57:29 +020030 'help|h' => sub {
31 pod2usage(
32 -verbose => 99,
33 -sections => 'NAME|DESCRIPTION|SYNOPSIS|ARGUMENTS|OPTIONS|EXAMPLES',
34 -msg => $VERSION_MSG,
35 -output => '-'
36 )
37 },
38 'version|v' => sub {
39 pod2usage(
40 -verbose => 0,
41 -msg => $VERSION_MSG,
42 -output => '-'
43 );
44 }
45);
Marc Kupietz79ba1e52021-02-12 17:26:54 +010046
Marc Kupietzaeb84a02021-10-11 17:57:29 +020047# Establish logger
48binmode(STDERR, ':encoding(UTF-8)');
49Log::Any::Adapter->set('Stderr', log_level => $log_level);
50$log->notice('Debugging is activated') if DEBUG;
Marc Kupietz79ba1e52021-02-12 17:26:54 +010051
52my $docid="";
53my $zip = undef;
Marc Kupietz79ba1e52021-02-12 17:26:54 +010054my $parser_file;
55my $parse;
56my $morpho_file;
57my $morpho;
58my @spansFrom;
59my @spansTo;
60my $current;
61my ($unknown, $known) = (0, 0);
Akronf3efc9e2026-06-03 10:46:37 +020062my $sentence_text = '';
63my $doc_offset = 0;
64my $text_pos = 0;
65my $compute_offsets_mode = 0;
66# Buffer dependency arcs until all token offsets in a sentence are known
67my @dep_buffer;
Marc Kupietz79ba1e52021-02-12 17:26:54 +010068
69my ($write_morpho, $write_syntax, $base) = (1, 0, 0);
70my $filename;
Marc Kupietz79ba1e52021-02-12 17:26:54 +010071my $first=1;
72my @conllu_files = @ARGV;
73push @conllu_files, "-" if (@conllu_files == 0);
74my $fh;
Marc Kupietzdd546a82024-03-22 16:30:09 +010075
76my $dependency_foundry_name = $foundry_name;
77if ($foundry_name =~ /(.*) dependency:(.*)/) {
78 $foundry_name = $1;
79 $dependency_foundry_name = $2;
80}
81
Marc Kupietz79ba1e52021-02-12 17:26:54 +010082foreach my $conllu_file (@conllu_files) {
83 if ($conllu_file eq '-') {
84 $fh = \*STDIN;
85 } else {
86 open($fh, "<", $conllu_file) or die "Cannot open $conllu_file";
87 }
88 my $i=0; my $s=0; my $first_in_sentence=0;
89 my $lastDocSigle="";
Akron49f333b2022-09-27 17:03:49 +020090 MAIN: while (<$fh>) {
Marc Kupietzbcb55b82022-09-15 11:42:26 +020091 if(/^\s*(?:#|0\.\d)/) {
92 if(/^(?:#|0\.1)\s+filename\s*[:=]\s*(.*)/) {
93 $filename=$1;
94 if(!$first) {
95 closeDoc(0);
96 } else {
97 $first=0;
98 }
99 if($processedFilenames{$filename}) {
100 $log->warn("WARNING: $filename is already processed");
101 }
102 $processedFilenames{$filename}=1;
103 $i=0;
Akronf3efc9e2026-06-03 10:46:37 +0200104 $doc_offset = 0;
105 $sentence_text = '';
106 $compute_offsets_mode = 0;
Marc Kupietzbcb55b82022-09-15 11:42:26 +0200107 } elsif(/^#\s*foundry\s*[:=]\s*(.*)/) {
108 if(!$foundry_name) {
Marc Kupietzdd546a82024-03-22 16:30:09 +0100109 $dependency_foundry_name = $foundry_name = $1;
110 if ($foundry_name =~ /(.*) dependency:(.*)/) {
111 $foundry_name = $1;
112 $dependency_foundry_name = $2;
113 }
Marc Kupietzbcb55b82022-09-15 11:42:26 +0200114 $log->debug("Foundry: $foundry_name\n");
115 } else {
116 $log->debug("Ignored foundry name: $1\n");
117 }
118 } elsif(/^#\s*generator\s*[=]\s*udpipe/i) {
119 if(!$foundry_name) {
Marc Kupietzdd546a82024-03-22 16:30:09 +0100120 $dependency_foundry_name = $foundry_name = "ud";
Marc Kupietzbcb55b82022-09-15 11:42:26 +0200121 $log->debug("Foundry: $foundry_name\n");
122 } else {
123 $log->debug("Ignored foundry name: ud\n");
124 }
Akron49f333b2022-09-27 17:03:49 +0200125 } elsif(/^(?:#|0\.2)\s+text_id\s*[:=]\s*(.*)/) {
Marc Kupietzbcb55b82022-09-15 11:42:26 +0200126 $docid=$1;
Marc Kupietzcc391472024-06-24 10:48:34 +0200127 $docid =~ s/\s+$//;
Marc Kupietzbcb55b82022-09-15 11:42:26 +0200128 my $docSigle = $docid;
129 $docSigle =~ s/\..*//;
130 if($docSigle ne $lastDocSigle) {
131 $log->info("Analyzing $docSigle");
132 $lastDocSigle = $docSigle;
133 }
134 $known=$unknown=0;
135 $current="";
136 $parser_file = dirname($filename);
137 $parser_file =~ s@(.*)/[^/]+$@$1@;
138 $morpho_file = $parser_file;
139 $morpho_file .= "/$foundry_name/morpho.xml";
Marc Kupietzdd546a82024-03-22 16:30:09 +0100140 $parser_file .= "/$dependency_foundry_name/dependency.xml";
Marc Kupietzbcb55b82022-09-15 11:42:26 +0200141 $parse = $morpho = layer_header($docid);
142 } elsif (/^(?:#|0\.3)\s+(?:start_offsets|from)\s*[:=]\s*(.*)/) {
143 @spansFrom = split(/\s+/, $1);
144 } elsif (/^(?:#|0\.4)\s+(?:end_offsets|to)\s+[:=]\s*(.*)/) {
145 @spansTo = split(/\s+/, $1);
Akronf3efc9e2026-06-03 10:46:37 +0200146 } elsif (/^#\s*text\s*=\s*(.*)/) {
147 # Store sentence text for automatic offset computation
148 $sentence_text = decode('UTF-8', $1);
Marc Kupietz79ba1e52021-02-12 17:26:54 +0100149 }
Akron49f333b2022-09-27 17:03:49 +0200150 } elsif ( !/^\s*$/ ) {
Akronf3efc9e2026-06-03 10:46:37 +0200151 # Pre-split columns before offset computation needs the raw form
152 my @raw_cols = split('\t');
153 chomp $raw_cols[$#raw_cols] if @raw_cols;
154
155 # Enter offset computation mode when no explicit offsets given
156 if (!$compute_offsets_mode && scalar @spansFrom == 0
157 && $sentence_text && $docid) {
158 $compute_offsets_mode = 1;
159 @spansFrom = ();
160 @spansTo = ();
161 # Sentence-level span covers the full sentence text
162 $spansFrom[0] = $doc_offset;
163 $spansTo[0] = $doc_offset + length($sentence_text);
164 $text_pos = 0;
165 }
166
167 # Locate each token form in sentence text via index()
168 if ($compute_offsets_mode && @raw_cols >= 2 && $raw_cols[0] =~ /^\d+$/) {
169 my $raw_form = decode('UTF-8', $raw_cols[1]);
170 my $t_num = $raw_cols[0];
171 # Find token starting from current position (handles SpaceAfter)
172 my $pos_in_text = index($sentence_text, $raw_form, $text_pos);
173 if ($pos_in_text >= 0) {
174 $spansFrom[$t_num] = $doc_offset + $pos_in_text;
175 $spansTo[$t_num] = $spansFrom[$t_num] + length($raw_form);
176 # Advance past this token for the next search
177 $text_pos = $pos_in_text + length($raw_form);
178 } else {
179 $log->warn("WARNING: Token form not found in sentence text in $conllu_file line $.");
180 }
181 }
182
Akron49f333b2022-09-27 17:03:49 +0200183 if ( !$docid || scalar @spansTo == 0 || scalar @spansFrom == 0 ) {
184 if ( !$docid ) {
Marc Kupietz67d8c432024-06-25 14:32:16 +0200185 $log->warn("WARNING: Invalid input in $conllu_file: text_id (e.g. '# text_id = GOE_AGA.00000') missing in line $. when writing to $outh");
Akron49f333b2022-09-27 17:03:49 +0200186 }
187 if ( scalar @spansTo == 0 || scalar @spansFrom == 0 ) {
Marc Kupietz67d8c432024-06-25 14:32:16 +0200188 $log->warn("WARNING: Invalid input in $conllu_file: token offsets missing in line $. when writing to $outh");
Akron49f333b2022-09-27 17:03:49 +0200189 }
190
191 # Skip to next potentially valid document
192 while (<$fh>) {
193 next MAIN if m!^\s*$!s;
194 }
195 };
Marc Kupietzd50de7c2024-03-10 15:24:55 +0100196 my @parsed = map {
197 my $s = $_;
198 $s =~ s/&/&amp;/g;
199 $s =~ s/</&lt;/g;
200 $s =~ s/>/&gt;/g;
201 $s;
Akronf3efc9e2026-06-03 10:46:37 +0200202 } @raw_cols;
Akron49f333b2022-09-27 17:03:49 +0200203 if (@parsed != 10) {
Marc Kupietzaeb84a02021-10-11 17:57:29 +0200204 $log->warn("WARNING: skipping strange parser output line in $docid");
Marc Kupietz79ba1e52021-02-12 17:26:54 +0100205 $i++;
206 next;
207 }
208 my $t=$parsed[0];
209 if($t == 1) {
210 $s++;
211 $first_in_sentence = $i;
212 }
213 if($parsed[6] =~ /\d+/ && $parsed[7] !~ /_/) {
214 $write_syntax=1;
Akronf3efc9e2026-06-03 10:46:37 +0200215 # Buffer dep arcs; flushed at end of sentence when offsets are ready
216 push @dep_buffer, [$s, $t, $parsed[6], $parsed[7]];
Marc Kupietza591cdd2021-10-12 13:23:48 +0200217 }
Marc Kupietz5cc4df22024-03-24 13:46:42 +0100218 my $pos = $parsed[4];
219 my $upos = $parsed[3];
Marc Kupietza591cdd2021-10-12 13:23:48 +0200220 $pos =~ s/\|.*//;
221 $morpho .= qq( <span id="s${s}_n$t" from="$spansFrom[$t]" to="$spansTo[$t]">
Marc Kupietz79ba1e52021-02-12 17:26:54 +0100222 <fs type="lex" xmlns="http://www.tei-c.org/ns/1.0">
223 <f name="lex">
224 <fs>
Marc Kupietz79ba1e52021-02-12 17:26:54 +0100225);
Marc Kupietz5cc4df22024-03-24 13:46:42 +0100226 if($pos ne "_") {
227 $morpho .= qq( <f name="pos">$pos</f>\n);
228 }
229 if($upos ne "_") {
230 $morpho .= qq( <f name="upos">$upos</f>\n);
231 }
Marc Kupietz97ba2ba2021-10-11 17:55:47 +0200232 $morpho .= qq( <f name="lemma">$parsed[2]</f>\n) if($parsed[2] ne "_" || $parsed[1] eq '_');
Marc Kupietz79ba1e52021-02-12 17:26:54 +0100233 $morpho .= qq( <f name="msd">$parsed[5]</f>\n) if($parsed[5] ne "_");
234 if($parsed[9] ne "_") {
235 if ($parsed[9] =~ /[0-9.e]+/) {
236 $morpho .= qq( <f name="certainty">$parsed[9]</f>\n)
237 }
238 else {
239 $morpho .= qq( <f name="misc">$parsed[9]</f>\n)
240 }
241 }
242 $morpho .= qq( </fs>
243 </f>
244 </fs>
245 </span>
246);
247 $i++;
Akronf3efc9e2026-06-03 10:46:37 +0200248 } else {
249 # Empty line = end of sentence
250 flush_dep_buffer();
251 if ($compute_offsets_mode) {
252 # Advance doc offset past sentence + 1-char space separator
253 $doc_offset += length($sentence_text) + 1;
254 @spansFrom = ();
255 @spansTo = ();
256 $compute_offsets_mode = 0;
257 }
258 $sentence_text = '';
Marc Kupietz79ba1e52021-02-12 17:26:54 +0100259 }
260 }
261 $current .= "\n";
262 closeDoc(1);
Akron49f333b2022-09-27 17:03:49 +0200263 $zip->close() if $zip;
Marc Kupietz79ba1e52021-02-12 17:26:54 +0100264 close($fh);
265}
266exit;
267
268sub newZipStream {
269 my ($fname) = @_;
270 if (defined $zip) {
271 $zip->newStream(Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD,
Marc Kupietz447f4752024-03-22 17:35:57 +0100272 Append => 1, Name => $fname, ExtAttr => 0100666 << 16)
Marc Kupietz79ba1e52021-02-12 17:26:54 +0100273 or die "ERROR ('$fname'): zip failed: $ZipError\n";
274 } else {
275 $zip = new IO::Compress::Zip $outh, Zip64 => 1, TextFlag => 1,
Marc Kupietz447f4752024-03-22 17:35:57 +0100276 Method => $_COMPRESSION_METHOD, Append => 0, Name => "$fname", ExtAttr => 0100666 << 16
Marc Kupietz79ba1e52021-02-12 17:26:54 +0100277 or die "ERROR ('$fname'): zip failed: $ZipError\n";
278 }
279}
280
Akronf3efc9e2026-06-03 10:46:37 +0200281# Write buffered dependency arcs now that all token offsets are resolved
282sub flush_dep_buffer {
283 foreach my $dep (@dep_buffer) {
284 my ($ds, $dt, $dhead, $dlabel) = @$dep;
285 $parse .= qq@<span id="s${ds}_n$dt" from="$spansFrom[$dt]" to="$spansTo[$dt]">
286<rel label="$dlabel">
287<span from="$spansFrom[$dhead]" to="$spansTo[$dhead]"/>
288</rel>
289</span>
290@;
291 }
292 @dep_buffer = ();
293}
294
Marc Kupietz79ba1e52021-02-12 17:26:54 +0100295sub closeDoc {
Akronf3efc9e2026-06-03 10:46:37 +0200296 flush_dep_buffer();
Akron49f333b2022-09-27 17:03:49 +0200297 if ($write_morpho && $morpho_file) {
Marc Kupietz79ba1e52021-02-12 17:26:54 +0100298 newZipStream($morpho_file);
299 $zip->print($morpho, qq( </spanList>\n</layer>\n));
300 }
Akron49f333b2022-09-27 17:03:49 +0200301 if ($write_syntax && $parser_file) {
Marc Kupietz79ba1e52021-02-12 17:26:54 +0100302 $write_syntax = 0;
303 newZipStream($parser_file);
304 $zip->print($parse, qq(</spanList>\n</layer>\n));
305 }
306}
307
308sub layer_header {
309 my ($docid) = @_;
310 return(qq(<?xml version="1.0" encoding="UTF-8"?>
311<?xml-model href="span.rng" type="application/xml" schematypens="http://relaxng.org/ns/structure/1.0"?>
312<layer docid="$docid" xmlns="http://ids-mannheim.de/ns/KorAP" version="KorAP-0.4">
313<spanList>
314));
Marc Kupietzaeb84a02021-10-11 17:57:29 +0200315}
316
317=pod
318
319=encoding utf8
320
321=head1 NAME
322
323conllu2korapxml - Conversion of KorAP-XML CoNLL-U to KorAP-XML zips
324
325=head1 SYNOPSIS
326
327 conllu2korapxml < zca15.tree_tagger.conllu > zca15.tree_tagger.zip
328
329=head1 DESCRIPTION
330
331C<conllu2korapxml> converts CoNLL-U files that follow KorAP-specific comment conventions
332 and contain morphosyntactic and/or dependency annotations to
333 corresponding KorAP-XML zip files.
334
335=head1 INSTALLATION
336
337 $ cpanm https://github.com/KorAP/KorAP-XML-CoNLL-U.git
338
339=head1 OPTIONS
340
341=over 2
342
343=item B<--force-foundry|-f>
344
345Set foundry name and ignore foundry names in the input.
346
Marc Kupietzdd546a82024-03-22 16:30:09 +0100347
Marc Kupietzaeb84a02021-10-11 17:57:29 +0200348=item B<--help|-h>
349
350Print help information.
351
352=item B<--version|-v>
353
354Print version information.
355
356
357=item B<--log|-l>
358
359Loglevel for I<Log::Any>. Defaults to C<warn>.
360
Marc Kupietz187abd72024-06-25 14:30:01 +0200361=item B<--output|-o>
362
363Output file. Defaults to C<-> (stdout).
364
Marc Kupietzaeb84a02021-10-11 17:57:29 +0200365=back
366
367=head1 EXAMPLES
368
369 conllu2korapxml -f tree_tagger < t/data/wdf19.morpho.conllu > wdf19.tree_tagger.zip
370
Marc Kupietzdd546a82024-03-22 16:30:09 +0100371 conllu2korapxml -f "tree_tagger dependency:malt" < t/data/wdf19.tt-malt.conllu > wdf19.tree_tagger.zip
372
Marc Kupietzaeb84a02021-10-11 17:57:29 +0200373=head1 COPYRIGHT AND LICENSE
374
Akron249fc832024-06-04 16:36:44 +0200375Copyright (C) 2021-2024, L<IDS Mannheim|https://www.ids-mannheim.de/>
Marc Kupietzaeb84a02021-10-11 17:57:29 +0200376
377Author: Marc Kupietz
378
379Contributors: Nils Diewald
380
381L<KorAP::XML::CoNNL-U> is developed as part of the L<KorAP|https://korap.ids-mannheim.de/>
382Corpus Analysis Platform at the
383L<Leibniz Institute for the German Language (IDS)|http://ids-mannheim.de/>,
384member of the
385L<Leibniz-Gemeinschaft|http://www.leibniz-gemeinschaft.de/>.
386
387This program is free software published under the
388L<BSD-2 License|https://opensource.org/licenses/BSD-2-Clause>.