blob: 3f6d7174afd62cb28d650a35d8f7c76e6d07c294 [file] [log] [blame]
Akron9cb13942020-02-14 07:39:54 +01001#!/usr/bin/env perl
Peter Hardersd892a582020-02-12 15:45:22 +01002
3## see TODOs
4
5### NOTES:
6###
7### 1. The input for this file has to be UTF8-encoded _without_ SGML-Entites (except the escaped ones -> &, <lt;, >gt;, 'apos;, "quot;
8### - XML::LibXML::Reader translates them back to their origin - e.g.: & -> & (because '&' translates to '&').
9### SGML-Entities cannot be processed, because of the first 2 missing lines in the input document (see xces2korap.sh).
10###
11### 2. Let 'data.xml' only be used/referred by 'sentences.xml', 'paragraphs.xml' and 'structure.xml', since it can contain double blanks (' ' - see comment to '<s/>' in func.
12### retr_info) and TODO: also contains not only text inside s-tags (e.g.: <label><hi rend="it bo">Ludwig Pietsch (1824-1911):</hi></label><item><s>Journalist ...)
13###
14
Peter Hardersd892a582020-02-12 15:45:22 +010015use 5.012;
16
17use strict;
18use warnings;
19use File::Basename; # dirname
20use IO::Handle qw( );
21use IO::Select;
22
23use open qw(:std :utf8); # assume utf-8 encoding
24use Encode qw(encode_utf8 decode_utf8);
25
Akrond949e182020-02-14 12:23:57 +010026use Pod::Usage;
Peter Hardersd892a582020-02-12 15:45:22 +010027use Getopt::Long;
28use XML::CompactTree::XS;
29use XML::LibXML::Reader;
30use IO::Compress::Zip qw(zip $ZipError :constants);
31use IPC::Open2; # open2
32
33my $zip; my $first_write=1;
34my $outh = *STDOUT;
35
Akrond949e182020-02-14 12:23:57 +010036our $VERSION = '0.01';
37our $VERSION_MSG = "\ntei2korapxml - v$VERSION\n";
38
Peter Hardersd892a582020-02-12 15:45:22 +010039my $_CORR_POS_FOR_EMPTY_S_TAGS = 1; # this should only be deactivated for test purposes (empty s-tags produce an additional blank (look for ' ' in data.xml)
40my $_CORR_BYTE_POS_FOR_P_TAGS = 1;
41
Peter Harders70257132020-02-13 13:47:55 +010042my $_GEN_TOK_BAS = 0;
Peter Hardersd892a582020-02-12 15:45:22 +010043my $_GEN_TOK_DUMMY = 0; # not needed for drukola or cmc
44
45my $_COMPRESSION_METHOD = ZIP_CM_DEFLATE;
46
47my $_DEBUG = 0;
48
49my $_root_dir = "."; # output base directory
50my $_header_file = "header.xml"; # filename to save text header in (in Latin1 format -> needed for ... ?) # TODO: why 'Latin1'?
51my $_data_file = "data.xml"; # filename to save text data in (in UTF-8 format -> needed for ... ?)
52my $_base_dir = "base"; # directory to store sentence and paragraph file and ...
53my $_structure_dir = "struct";
54my $_structure_file = "structure.xml";
55my ($text_id, $text_id_esc); # '$text_id_esc' = escaped version of $text_id - see %ent (needed e.g. for 'Corola-PublishingHouse/Editura "Cronica"/260_a_608')
56my $dir = ""; # text directory (on top of base)
57my $dir_crp = ""; # corpus directory (on top of base)
58my $dir_doc = ""; # document directory (on top of base)
59my $data = ""; # $data is written to '$_data_file'
60my %ent=('"', '&quot;', '&','&amp;','<','&lt;','>','&gt;'); # convert '&', '<' and '>' to their corresp. sgml-entities for compat. with KorAP
61 # NOTE: the index still refers to the above char-versions, which are counted as 1
62 # (search for '&' in data.xml and see corresp. indices in structure.xml, lemma.xml, ana.xml ...)
63my $header_crp = "";
64my $header_doc = "";
65my $header_txt = ""; # $header_* are written to '$_header_file'
66
67my ($header_fl_crp, $header_fl_doc, $header_fl_txt, $data_fl, $header_prfx, $data_prfx1, $data_prfx2, $data_sfx);
68 $header_prfx = $data_prfx1 = $data_prfx2 = $data_sfx = "";
69
70my ($i, $c);
71
72### needed for sub retr_info
73my $_XCT_LN=0; # remember line numbers (set to 1 if debugging)
74my ($reader, $tree_data, $rl, $_IDX, $n, $e, $dl, @oti);
75 # 'dl' stands for 'data length', 'oti' stands for 'open tags index'
76($_XCT_LN)?($_IDX=5):($_IDX=4);
77###
78### needed in func. write_structures
79my ($ref, $idx, $att_idx);
80
81my $buf_in = "";
82my $output;
83
84### needed for tokenization
85my $_tok_file_bas = "tokens.xml";
86
87#my @sentences; # sentence character offsets (start, end, start, end, ...)
88#my @paragraphs; # paragraph character offsets (start, end, start, end, ...)
89my @structures; # list of hashes, each hash representing an XML element
90
91## whitespace-related issue (see retr_info()): needed to correct from-offset for some tags
92my $add_one;
93my %hws; # hash for indices of whitespace nodes (needed to recorrect from-value)
94 # idea: when closing element, check if it's from-index minus 1 refers to a whitespace node (means: 'from-index - 1' is a key in %hws).
95 # if this is _not_ the case, then the from-value is one to high => correct it by substracting 1
96my ($fval, $fval2);
97$fval=$fval2=0; # init.
98##
99
100## needed if $_GEN_TOK_DUMMY is set
101my $_tok_file_con = "tokens_conservative.xml";
102my $_tok_file_agg = "tokens_aggr.xml";
103my (@tok_tokens_con, @tok_tokens_agg);
104my ($m1, $m2, $m3, $m4, $tmp, $p1, $p2, $pr, $offset, $txt);
105$offset=0;
106##
107
108# do this to prevent error message 'Global symbol "..." requires explicit package name at ...'
109my ($_ANNOT_ATT_ANNOT_NAME_RD, $_ANNOT_ATT_LEM_NAME_RD, $_ANNOT_ATT_POS_NAME_WR, $_ANNOT_ATT_MSD_NAME_WR) = ('','','','');
110
111## needed for handling some inline annotations
112my $_ANNOT_GEN = 0; # turn processing of inline annotations on/off
113#my $_ANNOT_DIR_NAME = "connexor"; # name of path/foundry to write information to
114my $_ANNOT_DIR_NAME = "drukola"; # name of path/foundry to write information to
115#my $_ANNOT_DIR_NAME = "cmc"; # name of path/foundry to write information to # cmc = computer mediated communication - needed for dck corpus
116my $_ANNOT_FILE_NAME = "morpho.xml"; # file to write annotations to
117my $_ANNOT_TAG_NAME_RD = "w"; # from which tag to fetch the below attributes
118$_ANNOT_ATT_ANNOT_NAME_RD = "ana"; # from which attribute to fetch the msd and pos information
119#$_ANNOT_ATT_ANNOT_NAME_RD = "type"; # from which attribute to fetch the msd and pos information # must be 'type' for dck corpus
120 # new: comment out, if not needed
121$_ANNOT_ATT_LEM_NAME_RD = "lemma"; # from which attribute to fetch the lemma information
122 # new: comment out, if not needed
123$_ANNOT_ATT_POS_NAME_WR = "pos"; # see e.g.: GIT/KorAP-XML-Krill/t/annotation/corpus/doc/0001/mate/morpho.xml
124 # new: comment out, if not needed
125$_ANNOT_ATT_MSD_NAME_WR = "msd"; # not needed for dck corpus
126 # new: comment out, if not needed
127my $_ANNOT_ATT_LEM_NAME_WR = "lemma"; # s.a.
128my (@annot, @oti2);
129my $inside_annot_tag = -1;
130##
131
Peter Hardersd892a582020-02-12 15:45:22 +0100132GetOptions(
Akrond949e182020-02-14 12:23:57 +0100133 'base|b=s' => \$_root_dir,
134 'help|h' => sub {
135 pod2usage(
136 -verbose => 99,
137 -sections => 'NAME|DESCRIPTION|SYNOPSIS|ARGUMENTS|OPTIONS',
138 -msg => $VERSION_MSG,
139 -output => '-'
140 )
141 },
142 'version|v' => sub {
143 pod2usage(
144 -verbose => 0,
145 -msg => $VERSION_MSG,
146 -output => '-'
147 )
148 }
Peter Hardersd892a582020-02-12 15:45:22 +0100149);
150
Peter Hardersd892a582020-02-12 15:45:22 +0100151######
152###### MAIN
153######
154$_root_dir.='/'; # must always end with a slash at this point
155$_root_dir=~s/^\.?\///; # remove leading / (only relative paths allowed in IO::Compress::Zip) and ./
156
157my $lc=0; my $tc=0; my ($pfx, $sfx);
158$header_fl_txt=0;
159
160# header_prfx
161$header_prfx = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
162$header_prfx .= "<?xml-model href=\"header.rng\" type=\"application/xml\" schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n";
163$header_prfx .= "<!DOCTYPE idsCorpus PUBLIC \"-//IDS//DTD IDS-XCES 1.0//EN\" \"http://corpora.ids-mannheim.de/idsxces1/DTD/ids.xcesdoc.dtd\">\n";
164
165$data_prfx1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
166$data_prfx1 .= "<?xml-model href=\"text.rng\" type=\"application/xml\" schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n\n";
167$data_prfx1 .= "<raw_text docid=\"";
168$data_prfx2 .= "\" xmlns=\"http://ids-mannheim.de/ns/KorAP\">\n";
169$data_prfx2 .= " <metadata file=\"metadata.xml\" />\n";
170$data_prfx2 .= " <text>";
171$data_sfx = "</text>\n</raw_text>";
172
173my($chld_out, $chld_in, $pid, $select);
174if( $_GEN_TOK_BAS ){
175 startTokenizer();
176}
177
178while(<STDIN>){
179
180 $lc++; # line counter
181
182 if( $data_fl && m/^(.+)?<\/text>(.+)?$/ ){ # end of text body
183 ###
184 ### write data.xml, sentences.xml, paragraph.xml and structure.xml
185 ###
186
187 $pfx=$1; $sfx=$2;
188 die "ERROR ($0): main(): input line number $lc: line with closing tag for 'text' contains additional information ... => Aborting\n\tline=$_"
189 if (defined $pfx && $pfx !~ /^\s*$/) || (defined $sfx && $sfx !~ /^\s*$/);
190
191 if( $dir ne "" ){
192
193### NOTE: needed for debugging (e.g. whitespace issues)
194#if( $text_id eq "GOE_AGA.00000" )
195#if( $text_id eq "GOE_AGI.04846" )
196#{
197#open H1, ">/tmp/t123";
198#print H1 "$buf_in";
199#close H1;
200#}
201####
202
203 $reader = XML::LibXML::Reader->new(string => "<text>$buf_in</text>", huge => 1);
204
205 if( $_XCT_LN ){ # _XCT_LINE_NUMBERS is only for debugging
206 #$tree_data = XML::CompactTree::XS::readSubtreeToPerl($reader, XCT_DOCUMENT_ROOT|XCT_IGNORE_WS|XCT_IGNORE_SIGNIFICANT_WS|XCT_IGNORE_COMMENTS|XCT_ATTRIBUTE_ARRAY|XCT_LINE_NUMBERS);
207 # remove 'XCT_IGNORE_WS', because whitespace (in form of one blank) between tags is needed for separation of 'text-nodes' in data.xml
208 # TODO: check out the meanings/differences of 'XCT_IGNORE_WS' and 'XCT_IGNORE_SIGNIFICANT_WS': seems like, 'XCT_IGNORE_SIGNIFICANT_WS' is the one we need
209 $tree_data = XML::CompactTree::XS::readSubtreeToPerl($reader, XCT_DOCUMENT_ROOT|XCT_IGNORE_COMMENTS|XCT_ATTRIBUTE_ARRAY|XCT_LINE_NUMBERS);
210# $tree_data = XML::CompactTree::XS::readSubtreeToPerl($reader, XCT_DOCUMENT_ROOT|XCT_IGNORE_COMMENTS|XCT_ATTRIBUTE_ARRAY|XCT_IGNORE_WS|XCT_IGNORE_SIGNIFICANT_WS|XCT_LINE_NUMBERS);
211 }else{
212 $tree_data = XML::CompactTree::XS::readSubtreeToPerl($reader, XCT_DOCUMENT_ROOT|XCT_IGNORE_COMMENTS|XCT_ATTRIBUTE_ARRAY);
213# $tree_data = XML::CompactTree::XS::readSubtreeToPerl($reader, XCT_DOCUMENT_ROOT|XCT_IGNORE_COMMENTS|XCT_ATTRIBUTE_ARRAY|XCT_IGNORE_WS|XCT_IGNORE_SIGNIFICANT_WS);
214 }
215
216 @structures=(); @oti=();
217
218 if( $_ANNOT_GEN ){
219 @annot=(); @oti2=()
220 }
221
222 $dl = 0;
223
224 $rl = 0; # recursion level
225
226 # whitespace related issue
227 $add_one = 0;
228 %hws=();
229 #
230
231###
232### recursion
233 retr_info( \$tree_data->[2] ); # parse input data
234###
235###
236 $rl--;
237
238 # write data.xml
239 $data=~tr/\n\r/ /; # NOTE: 2 blanks - otherwise offset data would become corrupt
240 $data=encode_utf8($data);
241
242 # first write it to tokenization pipe to give it some time
243 if( $_GEN_TOK_BAS ){
244 print $chld_in "$data\n\x03\n";
245 }
246
247 print STDERR "DEBUG ($0): main(): Writing (utf8-formatted) xml file $_root_dir$dir/$_data_file\n" if $_DEBUG;
248 if ($first_write){
249 $first_write=0;
250 ### 1st time: create instance
Peter Harders70257132020-02-13 13:47:55 +0100251 $zip = new IO::Compress::Zip $outh, Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 0, Name => "$_root_dir$dir/$_data_file"
Peter Hardersd892a582020-02-12 15:45:22 +0100252 or die "ERROR ('$_root_dir$dir/$_data_file'): zip failed: $ZipError\n"
253 }else{
254 ### close previous stream and open new one
255 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => "$_root_dir$dir/$_data_file" )
256 or die "ERROR ('$_root_dir$dir/$_data_file'): zip failed: $ZipError\n"
257 }
258 $data =~ s/(&|<|>)/$ent{$1}/g;
259 $zip->print("$data_prfx1$text_id_esc$data_prfx2$data$data_sfx");
260
261 # write structures
262 write_structures() if @structures;
263
264 # write annotations
265 write_annot() if $_ANNOT_GEN && @annot;
266
267 # tokenization
268 if( $_GEN_TOK_BAS || $_GEN_TOK_DUMMY )
269 {
270 write_tok();
271 if( $_GEN_TOK_DUMMY ){
272 $offset = 0; @tok_tokens_con=(); @tok_tokens_agg=();
273 }
274 }
275
276 $data_fl=0; $data = $dir = $buf_in = ""; # reinit.
277
278 }else{ # $dir eq ""
279
280 print STDERR "WARNING ($0): main(): maybe empty textSigle => skipping this text ...\n";
281 print STDERR "WARNING ($0): main(): text header=$header_txt\n";
282 print STDERR "WARNING ($0): main(): data=$data\n";
283 }
284 }elsif( $data_fl ){ # inside text body
285 #print STDERR "inside text body (\$data_fl set)\n";
286
287 ### whitespace handling
288 # remove consecutive whitespace at beginning and end (mostly one newline)
289 # to let 'XML::CompactTree::XS' recognize these blanks as 'text-nodes', the option 'XCT_IGNORE_WS' may not be used (see above).
290 s/^\s+//; s/\s+$//;
291
292 # important!: search for '>[^<][^<]*<' e.g. in 'vim goe_tagged.i5.xml.bz2' => insert a blank before every _first_ tag in a line, that contains text
293 # NOTE: the input text should avoid structures like below (which could also happen to other tags like '<pb ... />' or '<abbr>' etc.):
294 # negative example for '<w>' (see dck corpus in 'DeReKo-2016-II' - H.L. will fix this in 'DeReKo-2017-I'):
295 # <s>
296 # ...
297 # <w id="f1306078.m10.t9" lemma="zu" type="APPRART">zur</w>
298 # <w id="f1306078.m10.t10" lemma="Kenntnis" type="NN">Kenntnis</w>
299 # <w id="f1306078.m10.t11" lemma="nehmen" type="VVINF">nehmen</w>
300 # <w id="f1306078.m10.t12" lemma="," type="$,">,</w>
301 # <w id="f1306078.m10.t13" lemma="dass" type="KOUS">dass</w>
302 # ...
303 # In the above example, the whitespace/blank information between the words is lost. The below perl subst. expression does not recognize, that there may not be a blank before a comma.
304 if(m/<[^>]+>[^<]/){
305 $tc++; # text counter
306 s/^(.)/ $1/ if $tc>1; # only add a blank, if this is not the first text in the whole text
307 }
308
309 # add line to buffer
310 $buf_in .= $_;
311
312 }elsif( $header_fl_txt && m/^(.*<\/idsHeader>)(.+)?$/ ){ # end of text header
313 #print STDERR "end of text header\n";
314 ###
315 ### write header.xml
316 ###
317 $header_txt .= $1; $header_fl_txt = 0; $sfx=$2;
318 die "ERROR ($0): main(): input line number $lc: line with closing tag for 'idsHeader type=\"text\"' contains additional information ... => Aborting\n\tline=$_"
319 if defined $sfx && $sfx !~ /^\s*$/;
320 if( $dir eq "" ){
321 print STDERR "WARNING ($0): main(): input line number $lc: empty textSigle in text header => nothing to do ...\ntext header=$header_txt\n";
322 }else{
323 print STDERR "DEBUG ($0): Writing file $_root_dir$dir/$_header_file\n" if $_DEBUG;
324 # create zip buffer
325 if ($first_write){
326 $first_write=0;
Peter Harders70257132020-02-13 13:47:55 +0100327 $zip = new IO::Compress::Zip $outh, Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 0, Name => "$_root_dir$dir/$_header_file"
Peter Hardersd892a582020-02-12 15:45:22 +0100328 or die "ERROR ('$_root_dir$dir/$_header_file'): zip failed: $ZipError\n"
329 }else{
330 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => "$_root_dir$dir/$_header_file" )
331 or die "ERROR ('$_root_dir$dir/$_header_file'): zip failed: $ZipError\n"
332 }
333 $header_txt=encode_utf8($header_txt);
334 $zip->print("$header_prfx$header_txt");
335 }
336 }elsif( $header_fl_txt ){ # inside text header
337 #print STDERR "inside text header\n";
338 if( m/^(.+)?<textSigle>([^<]+)(.+)$/ ){
339 $pfx=$1; $sfx=$3; $dir=$2; $text_id = $dir; $text_id =~ tr/\//_/; $dir =~ s/("|&|<|>)/$ent{$1}/g;
340 $text_id=encode_utf8($text_id); # otherwise problems with "wide character" where $text_id is printed (see e.g.: http://ahinea.com/en/tech/perl-unicode-struggle.html)
341 # see e.g.: Drukola-Project
342 die "ERROR ($0): main(): input line number $lc: line with textSigle-tag is not in expected format ... => Aborting\n\tline=$_"
343 if (defined $pfx && $pfx !~ /^\s*$/) || $sfx !~ /^<\/textSigle>\s*$/;
344 print STDERR "$0: main(): text_id=".decode_utf8($text_id)."\n"; # some output to see progression
345 $text_id_esc = $text_id;
346 if( $text_id_esc =~ s/("|&|<|>)/$ent{$1}/g ){
347 $_ =~ s/(<textSigle>)[^<]+(<\/textSigle>)/$1$dir$2/; # do be consistent with escaping, escape also textSigle in Text-Header
348 }
349 $dir =~ tr/\./\//;
350 }
351 $header_txt .= $_;
352 }elsif( $header_fl_doc && m/^(.*<\/idsHeader>)(.+)?$/ ){ # end of document header
353 #print STDERR "end of doc header\n";
354 $header_doc .= $1; $header_fl_doc = 0; $sfx=$2;
355 die "ERROR ($0): main(): input line number $lc: line with closing tag for 'idsHeader type=\"document\"' contains additional information ... => Aborting\n\tline=$_"
356 if defined $sfx && $sfx !~ /^\s*$/;
357 if( $dir_doc eq "" ){
358 print STDERR "WARNING ($0): main(): input line number $lc: empty document sigle in document header => nothing to do ...\ndocument header=$header_doc\n";
359 }else{
360 print STDERR "DEBUG ($0): Writing file $_root_dir$dir_doc/$_header_file\n" if $_DEBUG;
361 if ($first_write){
362 $first_write=0;
Peter Harders70257132020-02-13 13:47:55 +0100363 $zip = new IO::Compress::Zip $outh, Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 0, Name => "$_root_dir$dir_doc/$_header_file"
Peter Hardersd892a582020-02-12 15:45:22 +0100364 or die "ERROR ('$_root_dir$dir_doc/$_header_file'): zip failed: $ZipError\n"
365 }else{
366 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => "$_root_dir$dir_doc/$_header_file" )
367 or die "ERROR ('$_root_dir$dir_doc/$_header_file'): zip failed: $ZipError\n"
368 }
369 $header_doc=encode_utf8($header_doc);
370 $zip->print("$header_prfx$header_doc");
371 }
372 }elsif( $header_fl_doc ){ # inside document header
373 #print STDERR "inside doc header\n";
374 if( m/^(.+)?<dokumentSigle>([^<]+)(.+)$/ ){
375 $pfx=$1; $sfx=$3; $dir_doc=$2;
376 die "ERROR ($0): main(): input line number $lc: line with dokumentSigle-tag is not in expected format ... => Aborting\n\tline=$_"
377 if (defined $pfx && $pfx !~ /^\s*$/) || $sfx !~ /^<\/dokumentSigle>\s*$/;
378 if( $dir_doc =~ s/("|&|<|>)/$ent{$1}/g ){
379 $_ =~ s/(<dokumentSigle>)[^<]+(<\/dokumentSigle>)/$1$dir_doc$2/; # do be consistent with escaping, escape also textSigle in Document-Header
380 }
381 }
382 $header_doc .= $_;
383 }elsif ( m/^.*(<idsHeader[^>]*type=\"text\".*)$/ ){ # begin of text header
384 #print STDERR "begin of text header\n";
385 $tc=0; ### reset (needed for whitespace-handling)
386 $header_txt = "$1\n"; $header_fl_txt = 1;
387 }elsif( m/^(.+)?<text(?: [^>]*)?>(.+)?$/ ){ # begin of text body
388 #print STDERR "inside text body\n";
389 $pfx=$1; $sfx=$2;
390 die "ERROR ($0): main(): input line number $lc: line with opening tag for 'text' contains additional information ... => Aborting\n\tline=$_"
391 if (defined $pfx && $pfx !~ /^\s*$/) || (defined $sfx && $sfx !~ /^\s*$/);
392 $data_fl=1;
393 }elsif ( m/^.*(<idsHeader[^>]*type=\"document\".*)$/ ){ # begin of document header
394 #print STDERR "begin of doc header\n";
395 $header_doc = "$1\n"; $header_fl_doc = 1;
396 }elsif( $header_fl_crp && m/^(.*<\/idsHeader>)(.+)?$/ ){ # end of corpus header
397 #print STDERR "end of corp header\n";
398 $header_crp .= $1; $header_fl_crp = 0; $sfx=$2;
399 die "ERROR ($0): main(): input line number $lc: line with closing tag for 'idsHeader type=\"corpus\"' contains additional information ... => Aborting\n\tline=$_"
400 if defined $sfx && $sfx !~ /^\s*$/;
401 if( $dir_crp eq "" ){
402 print STDERR "WARNING ($0): main(): input line number $lc: empty corpus sigle in corpus header => nothing to do ...\ncorpus header=$header_crp\n";
403 }else{
404 print STDERR "DEBUG ($0): Writing file $_root_dir$dir_crp/$_header_file\n" if $_DEBUG;
405 if ($first_write){
406 $first_write=0;
Peter Harders70257132020-02-13 13:47:55 +0100407 $zip = new IO::Compress::Zip $outh, Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 0, Name => "$_root_dir$dir_crp/$_header_file"
Peter Hardersd892a582020-02-12 15:45:22 +0100408 or die "ERROR ('$_root_dir$dir_crp/$_header_file'): zip failed: $ZipError\n"
409 }else{
410 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => "$_root_dir$dir_crp/$_header_file" )
411 or die "ERROR ('$_root_dir$dir_crp/$_header_file'): zip failed: $ZipError\n"
412 }
413 $header_crp=encode_utf8($header_crp);
414 $zip->print("$header_prfx$header_crp");
415 }
416 }elsif( $header_fl_crp ){ # inside corpus header
417 #print STDERR "inside corp header\n";
418 if( m/^(.+)?<korpusSigle>([^<]+)(.+)$/ ){
419 $pfx=$1; $sfx=$3; $dir_crp=$2;
420 die "ERROR ($0): main(): input line number $lc: line with korpusSigle-tag is not in expected format ... => Aborting\n\tline=$_"
421 if (defined $pfx && $pfx !~ /^\s*$/) || $sfx !~ /^<\/korpusSigle>\s*$/;
422 if( $dir_crp =~ s/("|&|<|>)/$ent{$1}/g ){
423 $_ =~ s/(<korpusSigle>)[^<]+(<\/korpusSigle>)/$1$dir_crp$2/; # do be consistent with escaping, escape also textSigle in Corpus-Header
424 }
425 }
426 $header_crp .= $_;
427 }elsif ( m/^.*(<idsHeader[^>]*type=\"corpus\".*)$/ ){ # begin of corpus header
428 #print STDERR "begin of corp header\n";
429 $header_crp = "$1\n"; $header_fl_crp = 1;
430 }
431 ###
432
433}#end: while
434
435if( $_GEN_TOK_BAS ){
436 close($chld_in);
437 close($chld_out);
438}
439$zip->close();
440
441######
442###### SUBS
443######
444#
445# $reader = XML::LibXML::Reader->new(IO => STDIN);
446# $data = XML::CompactTree::XS::readSubtreeToPerl($reader, XCT_DOCUMENT_ROOT|XCT_IGNORE_WS|XCT_IGNORE_SIGNIFICANT_WS|XCT_IGNORE_COMMENTS);
447#
448# example: <node a=\"v\"><node1>some <n/> text</node1><node2>more-text</node2></node>
449#
450# ( print out values of above example: echo "<node a=\"v\"><node1>some <n/> text</node1><node2>more-text</node2></node>"|perl -e 'use XML::CompactTree::XS; use XML::LibXML::Reader; $reader = XML::LibXML::Reader->new(IO => STDIN);$data = XML::CompactTree::XS::readSubtreeToPerl($reader,XCT_DOCUMENT_ROOT|XCT_IGNORE_WS|XCT_IGNORE_SIGNIFICANT_WS|XCT_IGNORE_COMMENTS|XCT_LINE_NUMBERS);print $data->[2]->[0]->[5]->[1]->[1]' )
451#
452# $data = reference to below array
453#
454# [ 0: XML_READER_TYPE_DOCUMENT,
455# 1: ?
456# 2: [ 0: [ 0: XML_READER_TYPE_ELEMENT
457# 1: 'node'
458# 2: ?
459# 3: HASH (attributes)
460# 4: 1 (line number)
461# 5: [ 0: [ 0: XML_READER_TYPE_ELEMENT
462# 1: 'node1'
463# 2: ?
464# 3: undefined (no attributes)
465# 4: 1 (line number)
466# 5: [ 0: [ 0: XML_READER_TYPE_TEXT
467# 1: 'some '
468# ]
469# 1: [ 0: XML_READER_TYPE_ELEMENT
470# 1: 'n'
471# 2: ?
472# 3: undefined (no attributes)
473# 4: 1 (line number)
474# 5: undefined (no child nodes)
475# ]
476# 2: [ 0: XML_READER_TYPE_TEXT
477# 1: ' text'
478# ]
479# ]
480# ]
481# 1: [ 0: XML_READER_TYPE_ELEMENT
482# 1: 'node2'
483# 2: ?
484# 3: undefined (not attributes)
485# 4: 1 (line number)
486# 5: [ 0: [ 0: XML_READER_TYPE_TEXT
487# 1: 'more-text'
488# ]
489# ]
490# ]
491# ]
492# ]
493# ]
494# ]
495#
496# $data->[0] = 9 (=> type == XML_READER_TYPE_DOCUMENT)
497#
498# ref($data->[2]) == ARRAY (with 1 element for 'node')
499# ref($data->[2]->[0]) == ARRAY (with 6 elements)
500#
501# $data->[2]->[0]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
502# $data->[2]->[0]->[1] == 'node'
503# ref($data->[2]->[0]->[3]) == HASH (=> ${$data->[2]->[0]->[3]}{a} == 'v')
504# $data->[2]->[0]->[4] == 1 (line number)
505# ref($data->[2]->[0]->[5]) == ARRAY (with 2 elements for 'node1' and 'node2') NOTE: child nodes of actual node (see $_IDX)
506#
507# ref($data->[2]->[0]->[5]->[0]) == ARRAY (with 6 elements)
508# $data->[2]->[0]->[5]->[0]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
509# $data->[2]->[0]->[5]->[0]->[1] == 'node1'
510# $data->[2]->[0]->[5]->[0]->[3] == undefined (=> no attribute)
511# $data->[2]->[0]->[5]->[0]->[4] == 1 (line number)
512# ref($data->[2]->[0]->[5]->[0]->[5]) == ARRAY (with 3 elements for 'some ', '<n/>' and ' text')
513#
514# ref($data->[2]->[0]->[5]->[0]->[5]->[0]) == ARRAY (with 2 elements)
515# $data->[2]->[0]->[5]->[0]->[5]->[0]->[0] == 3 (=> type == XML_READER_TYPE_TEXT)
516# $data->[2]->[0]->[5]->[0]->[5]->[0]->[1] == 'some '
517#
518# ref($data->[2]->[0]->[5]->[0]->[5]->[1]) == ARRAY (with 5 elements)
519# $data->[2]->[0]->[5]->[0]->[5]->[1]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
520# $data->[2]->[0]->[5]->[0]->[5]->[1]->[1] == 'n'
521# $data->[2]->[0]->[5]->[0]->[5]->[1]->[3] == undefined (=> no attribute)
522# $data->[2]->[0]->[5]->[0]->[5]->[1]->[4] == 1 (line number)
523# $data->[2]->[0]->[5]->[0]->[5]->[1]->[5] == undefined (=> no child nodes)
524#
525# ref($data->[2]->[0]->[5]->[0]->[5]->[2]) == ARRAY (with 2 elements)
526# $data->[2]->[0]->[5]->[0]->[5]->[2]->[0] == 3 (=> type == XML_READER_TYPE_TEXT)
527# $data->[2]->[0]->[5]->[0]->[5]->[2]->[1] == ' text'
528#
529#
530# NOTE: the sub 'retr_info' starts with the array reference '${$_[0]}' (= '\$tree_data->[2]'), which corresponds to '${\$data->[2]}' in the above example.
531# Hence, the expression '@{${$_[0]}}' corresponds to '@{${\$data->[2]}', '$e' to '${${\$data->[2]}}[0]' (='$data->[2]->[0]') and '$e->[0]' to '${${\$data->[2]}}[0]->[0]' (='$data->[2]->[0]->[0]'.
532
533sub retr_info{
534
535 $rl++; # rec. level (2 = topmost level inside retr_info() = level for all elements directly under <text>)
536
537 # $_[0] is a reference to an array reference
538 foreach $e( @{${$_[0]}} ){ # iteration through all array elements
539
540 ## http://search.cpan.org/~shlomif/XML-LibXML-2.0118/lib/XML/LibXML/Reader.pod#NODE_TYPES
541 if( $e->[0] == XML_READER_TYPE_ELEMENT ){ # element node
542
543 ### . insert new array (for new tag) into @structures with tag-name and (if present) tag-attributes
544 ### . update @oti (open tags indizes) with @structures highest index (=$#structures); e.g.: @a=(1,2,3) => $#a = 2
545 ###
546 $n = $e->[1]; # name of tag
547
548 $inside_annot_tag = $rl if $_ANNOT_GEN && $n eq "$_ANNOT_TAG_NAME_RD";
549
550 my @array;
551 push @array, $n; # name of tag
552 push @structures, \@array;
553
554 push @oti, $#structures; # add highest index of @structures to @oti
555
556 if( $_ANNOT_GEN && $inside_annot_tag == $rl ){
557 my @array2;
558 push @array2, $n;
559 push @annot, \@array2;
560 push @oti2, $#annot;
561 }
562
563 ### handle attributes
564 if( defined $e->[3] ){ # only go on if attributes exist
565 for( $c = 0; $c < @{$e->[3]}; $c += 2 ){ # with 'XCT_ATTRIBUTE_ARRAY', $node->[3] is an array reference of the form [ name1, value1, name2, value2, ....]
566 # of attribute names and corresponding values. NOTE: arrays are faster! (see: http://makepp.sourceforge.net/2.0/perl_performance.html)
567
568 # '$c' references the 'key' and '$c+1' the 'value' (example: perl -e '@a=(X,Y);push @b,\@a;$ref=$b[$#b];push @{$ref},Z;print @{$ref}' => XYZ)
569 push @{$structures[$#structures]}, ${$e->[3]}[$c], ${$e->[3]}[$c+1];
570
571 if( $_ANNOT_GEN && $inside_annot_tag == $rl ){
572 push @{$annot[$#annot]}, ${$e->[3]}[$c], ${$e->[3]}[$c+1];
573 }
574 }
575 }
576 ###
577
578 push @{$structures[$#structures]}, ($dl+$add_one); # from-value
579
580 if( $_ANNOT_GEN && $inside_annot_tag == $rl ){
581 push @{$annot[$#annot]}, ($dl+$add_one);
582 }
583
584 ######
585 # until here: opening tag-node
586 ######
587
588 ### RECURSION
589 if(defined $e->[$_IDX]){ # if $e->[$_IDX] is not defined (=> no array of child nodes, e.g.: <pb id="bka.00001-643-pb643" n="643" TEIform="pb"/>), do no recursion
590
591 retr_info( \$e->[$_IDX] ); # recursion with array of child nodes
592
593 $rl--; # return from recursion
594 }
595 ###
596
597 ######
598 # from here: closing tag-node
599 ######
600#print STDERR "2: dl=$dl\n" if $text_id eq "BIH_BKA.00001";
601#
602 { my $ix = pop @oti;
603 my $aix = @{$structures[$ix]};
604 $fval = ${$structures[$ix]}[$aix-1]; # from-value
605
606 # whitespace related issue
607 if( $fval>0 && not exists $hws{$fval-1} ){
608 # previous node was a text-node
609 ${$structures[$ix]}[$aix-1] = $fval-1; # recorrect from-value
610 }
611 #
612
613 die "ERROR ($0, retr_info()): text_id='$text_id', processing of \@structures: from-value ($fval) is more than 1 greater than to-value ($dl) => please check. aborting ...\n" if ($fval-1) > $dl;
614 ${$structures[$ix]}[$aix-1] = $dl if $fval == $dl+1; # correct from-value
615
616 push @{$structures[$ix]}, $dl, $rl; # to-value and recursion-level
617 ### use $dl, because the offsets are _between_ the characters (e.g.: word = 'Hallo' => from = 0 (before 'H'), to = 5 (after 'o'))
618 }
619
620 if ( $_ANNOT_GEN && $inside_annot_tag == $rl ){
621 my $ix = pop @oti2;
622 my $aix = @{$annot[$ix]};
623 $fval2 = ${$annot[$ix]}[$aix-1]; # from-value
624
625 # whitespace related issue
626 if( $fval2>0 && not exists $hws{$fval2-1} ){
627 # previous node was a text-node
628 ${$annot[$ix]}[$aix-1] = $fval2-1; # recorrect from-value
629 }
630 #
631
632 die "ERROR ($0, retr_info()): text_id='$text_id', processing of \@annot: from-value ($fval2) is more than 1 greater than to-value ($dl) => please check. aborting ...\n" if ($fval2-1) > $dl;
633 ${$annot[$ix]}[$aix-1] = $dl if $fval2 == $dl+1; # correct from-value
634
635 push @{$annot[$ix]}, $dl, $rl; # to-value and recursion-level
636 $inside_annot_tag = -1; # reset
637 }
638
639 # whitespace related issue
640 # clean up
641 delete $hws{$fval-1} if $fval>0 && exists $hws{$fval-1};
642 delete $hws{$fval2-1} if $_ANNOT_GEN && $fval2>0 && exists $hws{$fval2-1};
643 #
644
645 ######
646 # from here: text nodes
647 ######
648 }elsif( $e->[0] == XML_READER_TYPE_TEXT || $e->[0] == XML_READER_TYPE_SIGNIFICANT_WHITESPACE ){ # see 'man XML::LibXML::Reader'
649
650 # set flag, to remember to add 1 to 'from'-$dl (see above), if this text-node was _not_ a whitespace-node
651 # NOTE: this is needed to address e.g. the following situation (see first text in goe-corpus):
652 # '... <head type="main"><s>Campagne in Frankreich</s></head><head type="sub"> <s>1792</s> ...': the from-index of the 2nd head-tag
653 # should be right before '1792' (which was produced by a text-node) and not before the ' ' (which was produced by a whitespace-node)
654 # by the way: '$add_one' is not set (resp. 're'-set) for whitespace-nodes, because they always (incidentally) set '$dl' to the right
655 # from-index of the next node (e.g.: '<w>fu</w> <w>bar</w>' or '<w>fu</w><w> </w><w>bar</w>) - this is actually not the case for
656 # text-nodes (see same previous 'fubar'-example), for which '$dl' points to the from-index of ' ', _IF_ there is alway a ' ' between
657 # two text-nodes.
658 # NOTE: A new problem arises with this approach, _IF_ there is _NOT_ a ' ' between two text-nodes
659 # (see e.g. in romanian corpus 'corola-bucurenci': ... >Anului</w><w lemma="," ana="PUNCTUATION">,</w> <w ...).
660 # In this case, the from-index for the next node would be exactly 1 to high (see in approp. zip-file for above example:
661 # '... <span id="s14" from="101" to="101" l="5"> ...' - the correct span should be: '... <span id="s14" from="100" to="101" l="5"> ...').
662 # NOTE: it's not possible to solve the above problem here, because the following case would not be covered:
663 # ... <a><b><c><d/></c></b></a> ... (or see in goe-corpus 'GOE/AGI.04846': <div...><p/></div> ...)
664 # Because, no text- and whitespace-nodes are present, the from-values for 'a', 'b' and 'c' can only be corrected, when closing these tags.
665 # But this can be easily done by looking at the actual value of '$add_one' - if it's set, then there was no whitespace-node (and hence no ' ')
666 # before '<a>' and hence the from-values must be corrected.
667 # NOTE: To realize, what's stated in the above note, another information is needed, by which can be checked, if a tag contains text/ws or not
668 # (in the above 'abcd'-example, all tags are empty in the sense of that they don't contain any text/ws).
669 # By saving the recursion level, the 'text containing'-info can be simply checked, by the condition '$last_text_or_ws_node > $rl'.
670 # The condition is true, when there is text below the tag on level $rl.
671 ##$last_text_or_ws_node = $rl;
672 # NOTE: a much simpler solution, which should have the same effect, without following exactly the information-processing, is, to just set the
673 # value of the 'from'-index to the value of the 'to'-index, if "to==from-1" holds and to die with an error, if "(from-1)>to" holds.
674
675 # whitespace related issue
676 if( $e->[0] == XML_READER_TYPE_SIGNIFICANT_WHITESPACE ){
677 $add_one=0;
678 $hws{$dl}++; # '++' does not mean a thing here (could be used for consistency checking)
679 }else{ # text-node
680 $add_one=1;
681 }
682 #
683
684 $data .= $e->[1];
685 $dl += length($e->[1]);
686
687 ### needed only for dummy tokenization
688 if( $_GEN_TOK_DUMMY ){
689 $txt = $e->[1];
690 if( (substr($txt,0,1) ne ' ' || substr($txt,1,1) ne ' ') ){ # $txt has at least 2 chars, if it is not empty or equal to ' '
691
692 ### start: conservative tokenization
693 # '\p{Punct}' is equal to the character class '[-!"#%&'()*,./:;?@[\\\]_{}]'
694 while( $txt =~ /([\p{Punct}]*)([^\p{Punct} \x{9}\n]+(?:([\p{Punct}]+)[^\p{Punct} \x{9}\n]+)*)?([\p{Punct}]*)(?:[ \x{9}\n])?/g ){
695
696 $m1=$1; $m2=$2; $m3=$3; $m4=$4;
697
698#print STDERR "*** m1=$1, m2="; (defined $m2)?(print STDERR "$2"):(print STDERR "undef");print STDERR ", m3="; (defined $3)?(print STDERR "$3"):(print STDERR "undef"); print STDERR ", m4=$4\n";
699 if("$m1" ne ""){ # special chars before token
700 $p1=$-[1]; $p2=$+[1];
701 #print STDERR "A1: ".$m1." -> from $p1 to $p2\n";
702 if($p2==$p1+1){
703 if($p1!=0){$tmp=substr($txt,$p1-1,1);$pr=($tmp=~/^[^A-Za-z0-9]/)}else{$pr=0};
704 if(not $pr){$tmp=substr($txt,$p2,1);$pr=($tmp=~/^[^A-Za-z0-9]/)};
705 if($pr){push @tok_tokens_con, $p1+$offset; push @tok_tokens_con, $p2+$offset}; # from and to
706 }else{
707 for($i=0;$i<($p2-$p1);$i++){
708 #print STDERR "A2: ".substr($m1,$i,1)." -> from $p1 to $p2\n";
709 push @tok_tokens_con, $p1+$i+$offset; push @tok_tokens_con, $p1+$i+1+$offset; # from and to
710 }
711 }
712 }# "$m1" ne ""
713 #print STDERR "B: "."$m2 -> from ".($-[2]+$offset)." to ".($+[2]+$offset)."\n" if defined $m2; # token (wordform)
714
715 if(defined $m2){push @tok_tokens_con, $-[2]+$offset; push @tok_tokens_con, $+[2]+$offset}; # from and to
716
717 if(defined $m3){
718 $p1=$-[3]; $p2=$+[3];
719 #print STDERR "C: ".$m3." -> from $p1 to $p2\n";
720 if($p2==$p1+1){
721 $tmp=substr($txt,$p2,1);$pr=($tmp=~/^$/);$pr=($tmp=~/^[^A-Za-z0-9]/) if not $pr; # char after match
722 if(not $pr){$tmp=substr($txt,$p1-1,1);$pr=($tmp=~/^[^A-Za-z0-9]/)}; # char before match
723 if($pr){push @tok_tokens_con, $p1+$offset; push @tok_tokens_con, $p2+$offset}; # from and to
724 }else{ # length($m3)>1 => print all chars
725 for($i=0; $i<($p2-$p1); $i++){
726 #$tmp=substr($m3,$i,1);
727 #print STDERR "C2: $tmp -> from $p1 to $p2\n";
728 push @tok_tokens_con, $p1+$i+$offset; push @tok_tokens_con, $p1+$i+1+$offset; # from and to
729 }
730 }
731 }# defined $m3
732
733 if("$m4" ne ""){ # special chars after token
734 $p1=$-[4]; $p2=$+[4];
735 #print STDERR "D1: ".$m4." -> from ".($p1+$offset)." to ".($p2+$offset)."\n";
736 if($p2==$p1+1){
737 $tmp=substr($txt,$p2,1);$pr=($tmp=~/^$/);$pr=($tmp=~/^[^A-Za-z0-9]/) if not $pr; # char after match
738 if(not $pr){$tmp=substr($txt,$p1-1,1);$pr=($tmp=~/^[^A-Za-z0-9]/)}; # char before match
739 if($pr){push @tok_tokens_con, $p1+$offset; push @tok_tokens_con, $p2+$offset} # from and to
740 }else{
741 for($i=0;$i<($p2-$p1);$i++){
742 #print STDERR "D2: ".substr($m4,$i,1)." -> from ".($p1+$i+$offset)." to ".($p1+$i+1+$offset)."\n";
743 push @tok_tokens_con, $p1+$i+$offset; push @tok_tokens_con, $p1+$i+1+$offset; # from and to
744 }
745 }
746 }# "$m4" ne ""
747
748 }# end: while
749 ### end: conservative tokenization
750
751 ### start: aggressive tokenization
752 while( $txt =~ /([^\p{Punct} \x{9}\n]+)(?:([\p{Punct}])|(?:[ \x{9}\n])?)|([\p{Punct}])/g ){
753 if(defined $1){
754 push @tok_tokens_agg, $-[1]+$offset; push @tok_tokens_agg, $+[1]+$offset; # from and to
755 if(defined $2){push @tok_tokens_agg, $-[2]+$offset; push @tok_tokens_agg, $+[2]+$offset} # from and to
756 }else{ # defined $3
757 push @tok_tokens_agg, $-[3]+$offset; push @tok_tokens_agg, $+[3]+$offset # from and to
758 }
759 }# end: while
760 ### end: aggressive tokenization
761
762 #$offset = $dl+1;
763 $offset = $dl;
764 }
765 }
766 ###
767# }#fi
768
769#print STDERR "1: dl=$dl\n" if $text_id eq "BIH_BKA.00001";
770
771
772# elsif( $e->[0] == XML_READER_TYPE_ATTRIBUTE ) # attribute node
773# NOTE: attributes cannot be processed like this
774
775 ### from here: should not really happen
776
777 }else{ # not yet handled type
778
779 die "ERROR ($0): Not yet handled type (\$e->[0]=".$e->[0].") ... => Aborting\n";
780
781 }
782
783 }#end: foreach iteration
784
785}#end: sub retr_info
786
787
788sub write_tok { # called from MAIN
789
790 #print STDERR "$0: write_tok() ...\n";
791
792 if( $_GEN_TOK_BAS ) {
793 if( $select->can_read(3600) ){ # wait 60m for external tokenizer
794 $_ = <$chld_out>;
795 my @bounds = split;
796 write_tokenization("$_root_dir$dir/$_base_dir/$_tok_file_bas", $text_id_esc, \@bounds);
797 while($select->can_read(0)) {
798 $_ = <$chld_out>;
799 if (defined $_ && $_ ne '') {
800 print STDERR "WARNING: extra output: $_\n"
801 } else {
802 print STDERR "WARNING: tokenizer seems to have crashed, restarting.\n";
803 startTokenizer();
804 }
805 }
806 }else{
807 $zip->close();
808 die "ERROR ($0): cannot retrieve token bounds from external tokenizer for text '$text_id' => Aborting ...\n";
809 }
810 }elsif( $_GEN_TOK_DUMMY ){
811 write_tokenization("$_root_dir$dir/$_base_dir/$_tok_file_con", $text_id_esc, \@tok_tokens_con);
812 write_tokenization("$_root_dir$dir/$_base_dir/$_tok_file_agg", $text_id_esc, \@tok_tokens_agg);
813 }
814 #print STDERR "$0: write_tok(): DONE\n";
815} # end: write_tok
816
817sub write_tokenization {
818 my ($fname, $textid_esc, $bounds) = @_;
819
820 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => $fname)
821 or die "ERROR ('$fname'): zip failed: $ZipError\n";
822 $output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-model href=\"span.rng\" type=\"application/xml\" schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n\n<layer docid=\"$text_id_esc\" xmlns=\"http://ids-mannheim.de/ns/KorAP\" version=\"KorAP-0.4\">\n <spanList>\n";
823 $c=0; for( $i=0; $i < ($#$bounds + 1); $i+=2 ){
824 $output .= " <span id=\"t_$c\" from=\"".$bounds->[$i]."\" to=\"".$bounds->[$i+1]."\" />\n";
825 $c++;
826 }
827 $output .= " </spanList>\n</layer>";
828 $zip->print("$output");
829}
830
831# write structure file
832sub write_structures { # called from MAIN
833
834 #print STDERR "$0: write_structures(): ...\n";
835
836 if( $dir eq "" ){
837 print STDERR "WARNING ($0): write_structures(): empty textSigle => nothing to do ...\n";
838 return;
839 }
840
841 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => "$_root_dir$dir/$_structure_dir/$_structure_file" )
842 or die "ERROR ('$_root_dir$dir/$_structure_dir/$_structure_file'): zip failed: $ZipError\n";
843
844 $output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-model href=\"span.rng\" type=\"application/xml\" schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n\n<layer docid=\"".decode_utf8($text_id_esc)."\" xmlns=\"http://ids-mannheim.de/ns/KorAP\" version=\"KorAP-0.4\">\n <spanList>\n";
845
846 $c = 0;
847
848 foreach $ref (@structures){
849
850 (@{$ref}==4)?($idx=1):($idx=@{$ref}-3); # if array '@{$ref}' doesn't contain attributes, then the number of elements in this array is 4 (name, from, to, rec_level), otherwise >4
851
852 ### correct last from-value (if the 'second to last' from-value refers to an s-tag, then the last from-value is one to big - see retr_info)
853 if( $#structures == $c && ${$ref}[$idx] == ${$ref}[$idx+1] + 1 ){
854 ${$ref}[$idx] = ${$ref}[$idx+1];
855 }
856 ## this consistency check is already done in 'retr_info()'
857 ##elsif( ${$ref}[$idx] > ${$ref}[$idx+1] ){ # consistency check: abort, if this doesn't hold
858 ## #die "ERROR ($0: write_structures(): \$text_id=$text_id, \$c=$c, tag-name=${$ref}[0]): 'from-index=${$ref}[$idx]' > 'to-index=${$ref}[$idx+1]' => please check! aborting ...\n";
859 ## die "ERROR ($0: write_structures(): \$text_id=$text_id, \$c=$c, tag-name=${$ref}[0]): 'from-index=${$ref}[$idx]' > 'to-index=${$ref}[$idx+1]' => please check! aborting ...\n\n$output";
860 ##}
861 ###
862
863 ### at least 'POS' should always be there => remove constraint '$_ANNOT_GEN'
864 #if( $_ANNOT_GEN && ${$ref}[0] ne "$_ANNOT_TAG_NAME_RD" ){ # this is already written in 'write_annot', so don't do it twice
865 if( ${$ref}[0] ne "$_ANNOT_TAG_NAME_RD" ){ # this is already written in 'write_annot', so don't do it twice
866
867 $output .= " <span id=\"s$c\" from=\"${$ref}[$idx]\" to=\"${$ref}[$idx+1]\" l=\"${$ref}[$idx+2]\">\n"; # l (level): insert information about depth of element in XML-tree (top element = level 1)
868 $output .= " <fs type=\"struct\" xmlns=\"http://www.tei-c.org/ns/1.0\">\n";
869 $output .= " <f name=\"name\">${$ref}[0]</f>\n";
870
871 if ( $idx > 2 ) # attributes
872 {
873 $output .= " <f name=\"attr\">\n <fs type=\"attr\">\n";
874
875 for ( $att_idx=1; $att_idx < $idx; $att_idx+=2 ){
876 ${$ref}[$att_idx+1] =~ s/(&|<|>)/$ent{$1}/g; # see explanation in func. 'write_annot'
877 $output .= " <f name=\"${$ref}[$att_idx]\">${$ref}[$att_idx+1]</f>\n"; # attribute (at index $att_idx) with value (at index $att_idx+1)
878 }
879
880 $output .= " </fs>\n </f>\n";
881 }
882
883 $output .= " </fs>\n </span>\n";
884
885 }
886
887 $c++;
888
889 }# end: foreach
890
891 $output .= " </spanList>\n</layer>";
892
893 $output=encode_utf8($output);
894
895 $zip->print("$output");
896
897 #print STDERR "$0: write_structures(): DONE\n";
898} # end: sub write_structures
899
900
901sub write_annot { # called from MAIN
902 #print STDERR "$0: write_annot(): ...\n";
903
904 if( $dir eq "" ){
905 print STDERR "WARNING ($0): write_annot(): empty textSigle => nothing to do ...\n";
906 return;
907 }
908
909 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => "$_root_dir$dir/$_ANNOT_DIR_NAME/$_ANNOT_FILE_NAME" )
910 or die "ERROR ('$_root_dir$dir/$_ANNOT_DIR_NAME/$_ANNOT_FILE_NAME'): zip failed: $ZipError\n";
911
912 $output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-model href=\"span.rng\" type=\"application/xml\" schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n\n<layer docid=\"".decode_utf8($text_id_esc)."\" xmlns=\"http://ids-mannheim.de/ns/KorAP\" version=\"KorAP-0.4\">\n <spanList>\n";
913
914 $c = 0;
915
916#open H1, ">/tmp/t456" if $text_id eq "GOE_AGA.00000";
917 foreach $ref (@annot){
918
919#if($text_id eq "GOE_AGA.00000"){
920#foreach my $key(@{$ref}){print H1 " $c:$key"};
921#print H1 "\n";
922#}
923 (@{$ref}==4)?($idx=1):($idx=@{$ref}-3); # if array '@{$ref}' doesn't contain attributes, then the number of elements in this array is 4 (name, from, to, rec_level), otherwise >4
924
925 ### correct last from-value (if the 'second to last' from-value refers to a s-tag, then the last from-value is one to big - see retr_info)
926 if( $#annot == $c && ${$ref}[$idx] == ${$ref}[$idx+1] + 1 ){
927 ${$ref}[$idx] = ${$ref}[$idx+1];
928 }
929 ###
930
931 $output .= " <span id=\"s$c\" from=\"${$ref}[$idx]\" to=\"${$ref}[$idx+1]\" l=\"${$ref}[$idx+2]\">\n"; # l (level): insert information about depth of element in XML-tree (top element = level 1)
932 $output .= " <fs type=\"lex\" xmlns=\"http://www.tei-c.org/ns/1.0\">\n";
933 ##$output .= " <f name=\"${$ref}[0]\">\n";
934 $output .= " <f name=\"lex\">\n";
935
936 if ( $idx > 2 ) # attributes
937 {
938 $output .= " <fs>\n";
939
940 for ( $att_idx=1; $att_idx < $idx; $att_idx+=2 ){
941
942 ${$ref}[$att_idx+1] =~ s/(&|<|>)/$ent{$1}/g; # e.g.: look for 4th occurence of '…' in '84030_a_82705' in Drukola-Korpus 'corola-bucurenci':
943 # ... <w lemma="&gt;" ana="PUNCTUATION">&gt;</w> ...
944 # - the '&gt;' is translated to '>' and hence the result would be '<f name="lemma">></f>'
945
946 if( "$_ANNOT_ATT_ANNOT_NAME_RD" && ${$ref}[$att_idx] eq "$_ANNOT_ATT_ANNOT_NAME_RD" ){
947
948 ${$ref}[$att_idx+1] =~ /^([^ ]+)(?: (.+))?$/;
949 die "ERROR (write_annot()): unexpected format! => Aborting ... (att: ${$ref}[$att_idx+1])\n" if ($_ANNOT_ATT_POS_NAME_WR && not defined $1) || ($_ANNOT_ATT_MSD_NAME_WR && not defined $2);
950 if( "$_ANNOT_ATT_POS_NAME_WR" ){
951 $output .= " <f name=\"$_ANNOT_ATT_POS_NAME_WR\">";
952 $output .= "$1" if defined $1;
953 $output .= "</f>\n";
954 }
955 if( "$_ANNOT_ATT_MSD_NAME_WR" ){
956 $output .= " <f name=\"$_ANNOT_ATT_MSD_NAME_WR\">";
957 $output .= "$2" if defined $2;
958 $output .= "</f>\n";
959 }
960
961 }elsif( "$_ANNOT_ATT_LEM_NAME_RD" && ${$ref}[$att_idx] eq "$_ANNOT_ATT_LEM_NAME_RD" ){
962
963 $output .= " <f name=\"$_ANNOT_ATT_LEM_NAME_WR\">${$ref}[$att_idx+1]</f>\n";
964
965 }else{ # all other attributes
966
967 $output .= " <f name=\"${$ref}[$att_idx]\">${$ref}[$att_idx+1]</f>\n"; # attribute (at index $att_idx) with value (at index $att_idx+1)
968 }
969
970 } # end:for
971
972 $output .= " </fs>\n";
973 } # fi
974
975 $output .= " </f>\n </fs>\n </span>\n";
976
977 $c++;
978
979 }# end: foreach
980#close H1 if $text_id eq "GOE_AGA.00000";
981
982 $output .= " </spanList>\n</layer>";
983
984 $output=encode_utf8($output);
985
986 $zip->print("$output");
987
988 #print STDERR "$0: write_annot(): DONE\n";
989
990} # end: sub write_annot
991
Peter Hardersd892a582020-02-12 15:45:22 +0100992
993sub startTokenizer {
994 $pid = open2($chld_out, $chld_in, 'java -cp '. join(":", ".", glob(&dirname(__FILE__)."/../target/*.jar"))." de.ids_mannheim.korap.tokenizer.KorAPTokenizerImpl");
995 $select = IO::Select->new();
996 $select->add(*$chld_out);
997}
Akrond949e182020-02-14 12:23:57 +0100998
999__END__
1000
1001=pod
1002
1003=encoding utf8
1004
1005=head1 NAME
1006
1007tei2korapxml - Conversion of TEI P5 based formats to KorAP-XML
1008
1009=head1 SYNOPSIS
1010
1011 cat corpus.i5.xml | tei2korapxml > corpus.korapxml.zip
1012
1013=head1 DESCRIPTION
1014
1015C<tei2korapxml> is a script to convert TEI P5 and I5 based documents
1016to the KorAP-XML format. If no specific input is defined, data is
1017read from C<STDIN>. If no specific output is defined, data is written
1018to C<STDOUT>.
1019This program is usually called from inside another script.
1020
1021=head1 INSTALLATION
1022
1023C<tei2korapxml> requires L<libxml2-dev> bindings to build. When
1024these bindings are available, the preferred way to install the script is
1025to use L<cpanm|App::cpanminus>.
1026
1027 $ cpanm https://github.com/KorAP/KorAP-XML-TEI.git
1028
1029In case everything went well, the C<tei2korapxml> tool will
1030be available on your command line immediately.
1031Minimum requirement for L<KorAP::XML::TEI> is Perl 5.16.
1032
1033=head1 OPTIONS
1034
1035=over 2
1036
1037=item B<--base|-b>
1038
1039The base directory for output. Defaults to C<.>.
1040
1041=item B<--help|-h>
1042
1043Print help information.
1044
1045=item B<--version|-v>
1046
1047Print version information.
1048
1049=back
1050
1051=head1 COPYRIGHT AND LICENSE
1052
1053Copyright (C) 2020, L<IDS Mannheim|https://www.ids-mannheim.de/>
1054
1055Author: Peter Harders
1056
1057Contributors: Marc Kupietz, Carsten Schnober, Nils Diewald
1058
1059L<KorAP::XML::TEI> is developed as part of the L<KorAP|https://korap.ids-mannheim.de/>
1060Corpus Analysis Platform at the
1061L<Leibniz Institute for the German Language (IDS)|http://ids-mannheim.de/>,
1062member of the
1063L<Leibniz-Gemeinschaft|http://www.leibniz-gemeinschaft.de/>.
1064
1065This program is free software published under the
1066L<BSD-2 License|https://raw.githubusercontent.com/KorAP/KorAP-XML-TEI/master/LICENSE>.
1067
1068=cut