blob: fe8c37d58528eaa548c8c8b5fd4b841a8f4be0e8 [file] [log] [blame]
Akron9cb13942020-02-14 07:39:54 +01001#!/usr/bin/env perl
Peter Hardersd892a582020-02-12 15:45:22 +01002
Peter Hardersd892a582020-02-12 15:45:22 +01003###
Peter Harders6f526a32020-06-29 21:44:41 +02004### converts input in TEI P5 format (https://www1.ids-mannheim.de/kl/projekte/korpora/textmodell.html)
5### into output in KorAP-XML format (https://github.com/KorAP/KorAP-XML-Krill -> 'KorAP-XML document')
Peter Hardersd892a582020-02-12 15:45:22 +01006###
Peter Harders6f526a32020-06-29 21:44:41 +02007### input restrictions:
Peter Hardersd892a582020-02-12 15:45:22 +01008###
Peter Harders6f526a32020-06-29 21:44:41 +02009### . utf8 encoded
10### . TEI P5 formatted input with certain restrictions:
11### . mandatory: text-header with integrated textsigle, text-body
12### . optional: corp-header with integrated corpsigle, doc-header with integrated docsigle
13###
14### . all tokens inside the primary text (inside $data) may not be newline seperated, because newlines
15### are removed (see below: 'inside text body') and a conversion of newlines into blanks between 2 tokens
16### could lead to additional blanks, where there should be none (e.g.: punctuation characters like ',' or
17### '.' should not be seperated from their predecessor token).
18### - see also '~ whitespace handling ~'
19###
20### . POS and MSD inline annotations handling (see below: expected format)
21### ...
22###
23### notes on the output:
24###
25### . zip file output (default on stdout) with utf8 encoded entries (which together form the KorAP-XML format)
26### ...
27###
Peter Hardersd892a582020-02-12 15:45:22 +010028
29use strict;
30use warnings;
Peter Harders6f526a32020-06-29 21:44:41 +020031
32use Pod::Usage;
33use Getopt::Long qw(GetOptions :config no_auto_abbrev);
34
35use File::Basename qw(dirname);
36use IO::Handle;
Peter Hardersd892a582020-02-12 15:45:22 +010037use IO::Select;
38
39use open qw(:std :utf8); # assume utf-8 encoding
40use Encode qw(encode_utf8 decode_utf8);
41
Peter Hardersd892a582020-02-12 15:45:22 +010042use XML::CompactTree::XS;
43use XML::LibXML::Reader;
44use IO::Compress::Zip qw(zip $ZipError :constants);
Peter Harders6f526a32020-06-29 21:44:41 +020045use IPC::Open2 qw(open2);
Peter Hardersd892a582020-02-12 15:45:22 +010046
Peter Hardersd892a582020-02-12 15:45:22 +010047
Akrond949e182020-02-14 12:23:57 +010048our $VERSION = '0.01';
Peter Harders6f526a32020-06-29 21:44:41 +020049
Akrond949e182020-02-14 12:23:57 +010050our $VERSION_MSG = "\ntei2korapxml - v$VERSION\n";
51
Peter Hardersd892a582020-02-12 15:45:22 +010052
Peter Harders6f526a32020-06-29 21:44:41 +020053# Parse options from the command line
Peter Hardersd892a582020-02-12 15:45:22 +010054GetOptions(
Peter Harders6f526a32020-06-29 21:44:41 +020055 "root|r=s" => \(my $_root_dir = '.'), # name of root directory inside zip file
56 "input|i=s" => \(my $input_fname = ''), # input file (yet only TEI I5 Format accepted)
Akrond949e182020-02-14 12:23:57 +010057 'help|h' => sub {
58 pod2usage(
59 -verbose => 99,
60 -sections => 'NAME|DESCRIPTION|SYNOPSIS|ARGUMENTS|OPTIONS',
61 -msg => $VERSION_MSG,
62 -output => '-'
63 )
64 },
65 'version|v' => sub {
66 pod2usage(
67 -verbose => 0,
68 -msg => $VERSION_MSG,
69 -output => '-'
70 )
71 }
Peter Hardersd892a582020-02-12 15:45:22 +010072);
73
Peter Harders6f526a32020-06-29 21:44:41 +020074#
75# ~~~ parameter (mandatory) ~~~
76#
Peter Hardersd892a582020-02-12 15:45:22 +010077
Peter Harders6f526a32020-06-29 21:44:41 +020078 # optional
79my $_CORP_SIGLE = "korpusSigle"; # opening and closing tags (without attributes) have to be in one line
80 # (e.g.: <korpusSigle>GOE</korpusSigle>)
81 # optional
82my $_DOC_SIGLE = "dokumentSigle"; # analog
83 # mandatory
84my $_TEXT_SIGLE = "textSigle"; # analog
85 # mandatory
86my $_TEXT_BODY = "text"; # tag (without attributes), which contains the primary text
87 # optional
88my $_CORP_HEADER_BEG = "idsHeader type=\"corpus\""; # just keep the correct order of the attributes and evtl. add an '.*' between them
89 # optional
90my $_DOC_HEADER_BEG = "idsHeader type=\"document\""; # analog
91 # mandatory
92my $_TEXT_HEADER_BEG = "idsHeader type=\"text\""; # analog
93
94#
95# ~~~ constants ~~~
96#
Peter Hardersd892a582020-02-12 15:45:22 +010097
Peter Harders6f526a32020-06-29 21:44:41 +020098## DEPRECATED (only IDS-intern - the tokenization is normally done by external tools)
99my $_GEN_TOK_BAS = 0; # IDS internal tokenization
100 my( $chld_out, $chld_in, $pid, $select );
101##
102
103## dummy tokenization (only for testing)
104my $_GEN_TOK_DUMMY = 0; # use dummy base tokenization for testing (base tokenization is normally done by external tools)
105 my $_tok_file_con = "tokens_conservative.xml";
106 my $_tok_file_agg = "tokens_aggressive.xml";
107 my ( @tok_tokens_con, @tok_tokens_agg, $m1, $m2, $m3, $m4, $tmp, $p1, $p2, $pr, $txt, $offset );
108my $_base_tokenization_dir = "base"; # name of directory for storing files of dummy tokenization (only used in func. select_tokenization)
109
110# man IO::Compress::Zip
111# At present three compression methods are supported by IO::Compress::Zip, namely
112# Store (no compression at all), Deflate, Bzip2 and LZMA.
113# Note that to create Bzip2 content, the module "IO::Compress::Bzip2" must be installed.
114# Note that to create LZMA content, the module "IO::Compress::Lzma" must be installed.
115my $_COMPRESSION_METHOD = ZIP_CM_DEFLATE; # The symbols, ZIP_CM_STORE, ZIP_CM_DEFLATE, ZIP_CM_BZIP2 and ZIP_CM_LZMA are used to select the compression method.
116
117my $_DEBUG = 0; # set to 1 for minimal more debug output (no need to be parametrized)
118my $_XCT_LN = 0; # only for debugging: include line numbers in elements of $tree_data
119 # (see also manpage of XML::CompactTree::XS)
120
121my $_header_file = "header.xml"; # name of files containing the text, document and corpus header
122my $_data_file = "data.xml"; # name of file containing the primary text data (tokens)
123my $_structure_dir = "struct"; # name of directory containing the $_structure_file
124my $_structure_file = "structure.xml"; # name of file containing all tags (except ${_TOKEN_TAG}'s) related information
125 # (= their names and byte offsets in $_data)
126## TODO: optional (different annotation tools can produce more zip-files for feeding into KorAP-XML-Krill)
127my $_TOKENS_PROC = 1; # on/off: processing of ${_TOKEN_TAG}'s (default: 1)
128my $_tokens_dir = "tokens"; # name of directory containing the $_tokens_file
129my $_tokens_file = "morpho.xml"; # name of file containing all ${_TOKEN_TAG}'s related information (=their byte offsets in $_data)
130 # - evtl. with additional inline annotations
131my $_TOKENS_TAG = "w"; # name of tag containing all information stored in $_tokens_file
132
133## TODO: optional
134# handling inline annotations (inside $_TOKENS_TAG)
135my $_INLINE_ANNOT = 0; # on/off: set to 1 if inline annotations are present and should be processed (default: 0)
136my $_INLINE_LEM_RD = "lemma"; # from which attribute to read LEMMA information
137my $_INLINE_ATT_RD = "ana"; # from which attribute to read POS information (and evtl. additional MSD - Morphosyntactic Descriptions)
138 # TODO: The format for the POS and MSD information has to suffice the regular expression ([^ ]+)( (.+))?
139 # - which means, that the POS information can be followed by an optional blank with additional
140 # MSD information; unlike the MSD part, the POS part may not contain any blanks.
141my $_INLINE_POS_WR = "pos"; # name (inside $_tokens_file) referring to POS information
142my $_INLINE_MSD_WR = "msd"; # name (inside $_tokens_file) referring to MSD information
143my $_INLINE_LEM_WR = "lemma"; # name (inside $_tokens_file) referring to LEMMA information
144##
145
146
147#
148# ~~~ variables ~~~
149#
150
151my $zip; # IO::Compress::Zip object
152my $zip_outh; # handle for zip file output (stdout)
153my $first_write; # needed to decide wether to call '$zip->newStream' (for appending to zip file)
154my $input_fh; # input file handle (default: stdin)
155
156my $buf_in; # text body data extracted from input document ($input_fh), further processed by XML::LibXML::Reader
157my $data; # contains the primary text (created by func. 'retr_info' from $buf_in), which is written to '$data_file'
158
159my $dir; # text directory (below $_root_dir)
160my $dir_crp; # corpus directory (below $_root_dir)
161my $dir_doc; # document directory (below $_root_dir)
162
163my ( $text_id, $text_id_esc ); # '$text_id_esc' = escaped version of $text_id (see %ent)
164
165my %ent = ('"', '&quot;', '&','&amp;', # convert '&', '<' and '>' into their corresponding sgml-entities
166 '<','&lt;','>','&gt;');
167 # note: the index still refers to the 'single character'-versions, which are counted as 1
168 # (search for '&amp;' in data.xml and see corresponding indices in $_tokens_file)
169
170my $header_txt; # raw text header (written to '$_root_dir$dir/$_header_file')
171my $header_doc; # raw document header (written to '$_root_dir$dir_doc/$_header_file')
172my $header_crp; # raw corpus header (written to '$_root_dir$dir_crp/$_header_file')
173
174my ( $header_fl_crp, $header_fl_doc, # flags for tracking where we are in the input document
175 $header_fl_txt, $data_fl );
176
177my ( $header_prfx, $data_prfx1, # $header_prfx is written to $_header_file, $data_* are written to $_data_file
178 $data_prfx2, $data_sfx );
179
180my @structures; # list of arrays, where each array represents a TEI I5 tag (except $_TOKENS_TAG) from the input document
181 # - the input of this array is written in func. 'write_structures' into the file '$_structure_file'
182
183my @tokens; # list of arrays, where each array represents a $_TOKENS_TAG from the input document
184 # - the input of this array is written in func. 'write_tokens' into the file '$_tokens_file'
185
186my ( $ref, $idx, $att_idx ); # needed in func. 'write_structures' and 'write_tokens'
187
188my ( $reader, # instance of 'XML::LibXML::Reader->new' (on input '$buf_in')
189 $tree_data ); # instance of 'XML::CompactTree::XS::readSubtreeToPerl' (on input '$reader')
190
191# these are only used inside recursive function 'retr_info'
192my ( $_IDX, # value is set dependent on $_XCT_LN - for extracting array of child elements from element in $tree_data
193 $e, # element from $tree_data
194 $n, # tag name of actual processed element $e
195 $rl, # recursion level
196 $dl, # actual length of string $data
197 @oti, # oti='open tags indizes' - a stack of indizes into @structures, where the top index in @oti
198 # represents the actual processed element from @structures
199 @oti2, # analogously to @oti, but with reference to array @tokens
200 $inside_tokens_tag, # flag is set, when inside $_TOKENS_TAG
201 ## variables for handling ~ whitespace related issue ~ (it is sometimes necessary, to correct the from-values for some tags)
202 $add_one, # ...
203 $fval, $fval2, # ...
204 %ws); # hash for indices of whitespace nodes (needed to recorrect from-values)
205 # idea: when closing element, check if it's from-index minus 1 refers to a whitespace node
206 # (means: 'from-index - 1' is a key in %ws).
207 # if this is _not_ the case, then the from-value is one to high => correct it by substracting 1
208
209my $output; # temporary variable needed in 'write_*'-functions for writing output to zip-stream $zip)
210
211my ( $i, $c ); # index variables used in loops
212
213## DEPRECATED (only IDS-intern)
214my $_tok_file_bas = "tokens.xml";
215##
216
217my ( $_CORP_HEADER_END, $_DOC_HEADER_END, $_TEXT_HEADER_END );
218
219
220#
221# ~~~ main ~~~
222#
223
224# ~ initializations ~
225
226($_XCT_LN)?($_IDX=5):($_IDX=4);
227
228$header_prfx = $data_prfx1 = $data_prfx2 = $data_sfx = "";
229
230$header_fl_txt = $header_fl_doc = $header_fl_crp = 0;
231
232$inside_tokens_tag = -1;
233
234$fval = $fval2 = 0;
235
236$_root_dir .= '/'; # base dir must always end with a slash
237$_root_dir =~ s/^\.?\///; # remove leading / (only relative paths allowed in IO::Compress::Zip) and redundant ./
238
239$_CORP_HEADER_BEG =~ s#^([^\s]+)(.*)$#$1\[\^>\]*$2#; $_CORP_HEADER_END = $1;
240$_DOC_HEADER_BEG =~ s#^([^\s]+)(.*)$#$1\[\^>\]*$2#; $_DOC_HEADER_END = $1;
241$_TEXT_HEADER_BEG =~ s#^([^\s]+)(.*)$#$1\[\^>\]*$2#; $_TEXT_HEADER_END = $1;
242
243## TODO: remove this, because it's IDS-specific
Peter Hardersd892a582020-02-12 15:45:22 +0100244$header_prfx = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
245$header_prfx .= "<?xml-model href=\"header.rng\" type=\"application/xml\" schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n";
246$header_prfx .= "<!DOCTYPE idsCorpus PUBLIC \"-//IDS//DTD IDS-XCES 1.0//EN\" \"http://corpora.ids-mannheim.de/idsxces1/DTD/ids.xcesdoc.dtd\">\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200247##
Peter Hardersd892a582020-02-12 15:45:22 +0100248
249$data_prfx1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
250$data_prfx1 .= "<?xml-model href=\"text.rng\" type=\"application/xml\" schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n\n";
251$data_prfx1 .= "<raw_text docid=\"";
252$data_prfx2 .= "\" xmlns=\"http://ids-mannheim.de/ns/KorAP\">\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200253## TODO: can 'metadata.xml' change or is it constant?
Peter Hardersd892a582020-02-12 15:45:22 +0100254$data_prfx2 .= " <metadata file=\"metadata.xml\" />\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200255##
Peter Hardersd892a582020-02-12 15:45:22 +0100256$data_prfx2 .= " <text>";
257$data_sfx = "</text>\n</raw_text>";
258
Peter Hardersd892a582020-02-12 15:45:22 +0100259
Peter Harders6f526a32020-06-29 21:44:41 +0200260## DEPRECATED (only IDS-intern)
261startTokenizer() if $_GEN_TOK_BAS;
262##
Peter Hardersd892a582020-02-12 15:45:22 +0100263
Peter Harders6f526a32020-06-29 21:44:41 +0200264# ~ read input and write output (text by text) ~
Peter Harders90157342020-07-01 21:05:14 +0200265process();
Peter Hardersd892a582020-02-12 15:45:22 +0100266
Peter Hardersd892a582020-02-12 15:45:22 +0100267
Peter Harders6f526a32020-06-29 21:44:41 +0200268#
269# ~~~ subs ~~~
270#
Peter Hardersd892a582020-02-12 15:45:22 +0100271
Peter Hardersd892a582020-02-12 15:45:22 +0100272
Peter Harders90157342020-07-01 21:05:14 +0200273sub process {
Peter Hardersd892a582020-02-12 15:45:22 +0100274
Peter Harders6f526a32020-06-29 21:44:41 +0200275 my ( $pfx, $sfx );
Peter Hardersd892a582020-02-12 15:45:22 +0100276
Peter Harders6f526a32020-06-29 21:44:41 +0200277 my $lc = 0; # line counter
278
279 my $tc = 0; # text counter
280
281 $input_fh = *STDIN; # input file handle (default: stdin)
282
283 $zip_outh = *STDOUT; # output file handle (default: stdout)
284
285 $data_fl = 0; $first_write = 1;
286
287 $buf_in = $data = $dir = $dir_doc = $dir_crp = "";
288 $header_txt = $header_doc = $header_crp = "";
289
290
291 if ( $input_fname ne '' ){
292
293 open ( $input_fh, "<", "$input_fname") || die "File \'$input_fname\' could not be opened.\n";
294
295 }
296
297
Peter Harders90157342020-07-01 21:05:14 +0200298 # prevents segfaulting of 'XML::LibXML::Reader' inside 'process()' - see notes on 'PerlIO layers' in 'man XML::LibXML')
299 # removing 'use open qw(:std :utf8)' would fix this problem too, but using binmode on input is more granular
300 binmode $input_fh;
301
302
Peter Harders6f526a32020-06-29 21:44:41 +0200303 # ~ loop (reading input document) ~
304
305 while ( <$input_fh> ){
306
307 $lc++; # line counter
308
309 # TODO: yet not tested fo big amounts of data
310 # must-have, otherwise comments in input could be fatal (e.g.: ...<!--\n<idsHeader...\n-->...)
311 delHTMLcom ( $_ ); # remove HTML comments (<!--...-->)
312
313 if ( $data_fl && m#^(.*)</${_TEXT_BODY}>(.*)$# ){
314
315
316 # ~ end of text body ~
317
318
319 # write data.xml, structure.xml and evtl. morpho.xml and/or the dummy tokenization files (s.a.: $_tok_file_con and $_tok_file_agg)
320
321 $pfx = $1; $sfx = $2;
322
323 die "ERROR ($0): main(): input line number $lc: line with closing text-body tag '${_TEXT_BODY}'"
324 ." contains additional information ... => Aborting\n\tline=$_"
325 if $pfx !~ /^\s*$/ || $sfx !~ /^\s*$/;
326
327 if ( $dir ne "" ){
328
Peter Harders6f526a32020-06-29 21:44:41 +0200329 $reader = XML::LibXML::Reader->new( string => "<text>$buf_in</text>", huge => 1 );
Peter Harders6f526a32020-06-29 21:44:41 +0200330
331 if ( $_XCT_LN ){ # _XCT_LINE_NUMBERS is only for debugging
332 $tree_data = XML::CompactTree::XS::readSubtreeToPerl( $reader, XCT_DOCUMENT_ROOT | XCT_IGNORE_COMMENTS | XCT_ATTRIBUTE_ARRAY | XCT_LINE_NUMBERS );
333 } else {
334 $tree_data = XML::CompactTree::XS::readSubtreeToPerl( $reader, XCT_DOCUMENT_ROOT | XCT_IGNORE_COMMENTS | XCT_ATTRIBUTE_ARRAY );
335 }
336
337 @structures = (); @oti = ();
338
339 if ( $_TOKENS_PROC ){
340 @tokens = (); @oti2 = ()
341 }
342
343 $dl = $rl = 0;
344
345 # ~ whitespace related issue ~
346 $add_one = 0;
347 %ws = ();
348
349
350 # ~ recursion ~
351
352 retr_info( \$tree_data->[2] ); # parse input data
353
354 $rl--;
355
356
357 # ~ write data.xml ~
358
359 $data =~ tr/\n\r/ /; # note: 2 blanks - otherwise offset data would become corrupt
360
361 $data = encode_utf8( $data );
362
363 ## DEPRECATED (only IDS-intern)
364 # first write it to tokenization pipe to give it some time
365 if ( $_GEN_TOK_BAS ){
366 print $chld_in "$data\n\x03\n";
367 }
368 ##
369
370 print STDERR "DEBUG ($0): main(): Writing (utf8-formatted) xml file $_root_dir$dir/$_data_file\n" if $_DEBUG;
371
372 if ( $first_write ){
373
374 $first_write = 0;
375
376 # 1st time: create instance
377 $zip = new IO::Compress::Zip $zip_outh, Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 0, Name => "$_root_dir$dir/$_data_file"
378 or die "ERROR ('$_root_dir$dir/$_data_file'): zip failed: $ZipError\n"
379
380 } else {
381
382 # closes the current compressed data stream and starts a new one.
383 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => "$_root_dir$dir/$_data_file" )
384 or die "ERROR ('$_root_dir$dir/$_data_file'): zip failed: $ZipError\n"
385 }
386
387 $data =~ s/(&|<|>)/$ent{$1}/g;
388
389 $zip->print( "$data_prfx1$text_id_esc$data_prfx2$data$data_sfx" );
390
391
392 # ~ write structures ~
393
394 write_structures() if @structures;
395
396
397 # ~ write tokens ~
398
399 write_tokens() if $_TOKENS_PROC && @tokens;
400
401
402 # ~ dummy tokenization ~
403
404 if ( $_GEN_TOK_BAS || $_GEN_TOK_DUMMY ){ ## DEPRECATED ($_GEN_TOK_BAS: only IDS-intern)
405
406 select_tokenization();
407
408 if ( $_GEN_TOK_DUMMY ){
409 $offset = 0; @tok_tokens_con=(); @tok_tokens_agg=();
410 }
411 }
412
413 $data_fl = 0; $buf_in = $data = $dir = ""; # reinit.
414
415 } else { # $dir eq ""
416
417 print STDERR "WARNING ($0): main(): maybe empty textSigle => skipping this text ...\n";
418 print STDERR "WARNING ($0): main(): text header=$header_txt\n";
419 print STDERR "WARNING ($0): main(): data=$data\n";
Peter Hardersd892a582020-02-12 15:45:22 +0100420 }
421
Peter Harders6f526a32020-06-29 21:44:41 +0200422 } elsif ( $data_fl ){
Peter Hardersd892a582020-02-12 15:45:22 +0100423
Peter Hardersd892a582020-02-12 15:45:22 +0100424
Peter Harders6f526a32020-06-29 21:44:41 +0200425 # ~ inside text body ~
Peter Hardersd892a582020-02-12 15:45:22 +0100426
Peter Hardersd892a582020-02-12 15:45:22 +0100427
Peter Harders6f526a32020-06-29 21:44:41 +0200428 #print STDERR "inside text body (\$data_fl set)\n";
429
430 # ~ whitespace handling ~
431
432 # remove consecutive whitespace at beginning and end (mostly one newline)
433 # to let 'XML::CompactTree::XS' recognize these blanks as 'text-nodes', the option 'XCT_IGNORE_WS' may not be used (see above).
434 s/^\s+//; s/\s+$//;
435
436 # There's nothing wrong with inserting an additional blank at the start of the 2nd and all consecutive lines (which contain at least one tag),
437 # because it helps for better readability of the text in the '$_data_file' (e.g.: assure blanks between sentences).
438 # Furthermore, the input lines should avoid primary text tokens, which span across several lines, unless the line breaks doesn't lead
439 # to a situation which produces unwanted blanks - e.g.: '...<w>end</w>\n<w>.</w>...' would lead to '...<w>end</w> <w>.</w>...', or
440 # '...<w>,</w>\n<w>this</w>\n<w>is</w>\n<w>it</w>\n<w>!</w>...' to '<w>,<w> <w>this</w> <w>is</w> <w>it</w> <w>!</w>'. Even when considering
441 # to correct those unwanted effects, there would be lots of examples aside punctuation, where there would not exist an easy way or unarbitrary
442 # solution regarding the elimination of the false blanks.
Peter Hardersd892a582020-02-12 15:45:22 +0100443 #
Peter Harders6f526a32020-06-29 21:44:41 +0200444 # So, the best way to avoid having false blanks in the output, is to assure that linebreaks between word-tags doesn't occur in the input
445 # (see also comments on 'input restrictions' at the top of this script).
Peter Hardersd892a582020-02-12 15:45:22 +0100446
Peter Harders6f526a32020-06-29 21:44:41 +0200447 if ( m/<[^>]+>[^<]/ ){ # line contains at least one tag with at least one character contents
Peter Hardersd892a582020-02-12 15:45:22 +0100448
Peter Harders6f526a32020-06-29 21:44:41 +0200449 $tc++; # text counter
Peter Hardersd892a582020-02-12 15:45:22 +0100450
Peter Harders6f526a32020-06-29 21:44:41 +0200451 s/^(.)/ $1/ if $tc > 1; # add blank before 1st character for 2nd line and consecutive lines (which contain at least one tag)
Peter Hardersd892a582020-02-12 15:45:22 +0100452 }
453
Peter Harders6f526a32020-06-29 21:44:41 +0200454 # add line to buffer
455 $buf_in .= $_;
456
457 } elsif ( $header_fl_txt && m#^(.*</${_TEXT_HEADER_END}>)(.*)$# ){
458
459
460 # ~ end of text header ~
461
462
463 #print STDERR "end of text header\n";
464
465 # write it to header.xml
466
467 $sfx = $2;
468
469 $header_txt .= $1; $header_fl_txt = 0;
470
471
472 die "ERROR ($0): main(): input line number $lc: line with closing text-header tag '${_TEXT_HEADER_END}'"
473 ." contains additional information ... => Aborting\n\tline=$_"
474 if $sfx !~ /^\s*$/;
475
476 if ( $dir eq "" ){
477
478 print STDERR "WARNING ($0): main(): input line number $lc: empty textSigle in text header => nothing to do ...\ntext header=$header_txt\n";
479
480 } else {
481
482 print STDERR "DEBUG ($0): Writing file $_root_dir$dir/$_header_file\n" if $_DEBUG;
483
484 if ( $first_write ){
485
486 $first_write = 0;
487
488 $zip = new IO::Compress::Zip $zip_outh, Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD,
489 Append => 0, Name => "$_root_dir$dir/$_header_file"
490 or die "ERROR ('$_root_dir$dir/$_header_file'): zip failed: $ZipError\n"
491
492 } else {
493
494 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => "$_root_dir$dir/$_header_file" )
495 or die "ERROR ('$_root_dir$dir/$_header_file'): zip failed: $ZipError\n"
496 }
497
498 $header_txt = encode_utf8( $header_txt );
499
500 $zip->print( "$header_prfx$header_txt" );
501
502 $header_txt = "";
Peter Hardersd892a582020-02-12 15:45:22 +0100503 }
Peter Hardersd892a582020-02-12 15:45:22 +0100504
Peter Harders6f526a32020-06-29 21:44:41 +0200505 } elsif ( $header_fl_txt ){
Peter Hardersd892a582020-02-12 15:45:22 +0100506
Peter Harders6f526a32020-06-29 21:44:41 +0200507 # ~ inside text header ~
Peter Hardersd892a582020-02-12 15:45:22 +0100508
Peter Harders6f526a32020-06-29 21:44:41 +0200509
510 #print STDERR "inside text header\n";
511
512 if( m#^(.*)<${_TEXT_SIGLE}(?: [^>]*)?>([^<]*)(.*)$# ){
513
514 $pfx = $1; $sfx = $3;
515
516 $dir = $2; $text_id = $dir;
517
518 $text_id =~ tr/\//_/; $dir =~ s/("|&|<|>)/$ent{$1}/g;
519
520 $text_id = encode_utf8( $text_id );
521
522 die "ERROR ($0): main(): input line number $lc: line with text-sigle tag '$_TEXT_SIGLE' is not in expected format ... => Aborting\n\tline=$_"
523 if $pfx !~ /^\s*$/ || $sfx !~ m#^</${_TEXT_SIGLE}>\s*$# || $dir =~ /^\s*$/;
524
525 # log output for seeing progression
526 print STDERR "$0: main(): text_id=".decode_utf8( $text_id )."\n";
527
528 $text_id_esc = $text_id;
529
530 s#(<${_TEXT_SIGLE}(?: [^>]*)?>)[^<]+(</${_TEXT_SIGLE}>)#$1$dir$2# # to be consistent with escaping, escape also textSigle in text-header
531 if $text_id_esc =~ s/("|&|<|>)/$ent{$1}/g;
532
533 $dir =~ tr/\./\//;
534 }
535
536 $header_txt .= $_;
537
538 } elsif ( $header_fl_doc && m#^(.*</${_DOC_HEADER_END}>)(.*)$# ){
539
540
541 # ~ end of document header ~
542
543
544 #print STDERR "end of doc header\n";
545
546 # write it to header.xml
547
548 $sfx = $2;
549
550 $header_doc .= $1; $header_fl_doc = 0;
551
552 die "ERROR ($0): main(): input line number $lc: line with closing document-header tag '${_DOC_HEADER_END}'"
553 ." contains additional information ... => Aborting\n\tline=$_"
554 if $sfx !~ /^\s*$/;
555
556 if( $dir_doc eq "" ){
557
558 print STDERR "WARNING ($0): main(): input line number $lc: empty document sigle in document header"
559 ." => nothing to do ...\ndocument header=$header_doc\n";
560
561 } else {
562
563 print STDERR "DEBUG ($0): Writing file $_root_dir$dir_doc/$_header_file\n" if $_DEBUG;
564
565 if ( $first_write ){
566
567 $first_write = 0;
568
569 $zip = new IO::Compress::Zip $zip_outh, Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 0,
570 Name => "$_root_dir$dir_doc/$_header_file"
571 or die "ERROR ('$_root_dir$dir_doc/$_header_file'): zip failed: $ZipError\n"
572
573 } else {
574
575 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => "$_root_dir$dir_doc/$_header_file" )
576 or die "ERROR ('$_root_dir$dir_doc/$_header_file'): zip failed: $ZipError\n"
577 }
578
579 $header_doc = encode_utf8( $header_doc );
580
581 $zip->print( "$header_prfx$header_doc" );
582
583 $header_doc = $dir_doc = "";
584 }
585
586 } elsif ( $header_fl_doc ){
587
588
589 # ~ inside document header ~
590
591
592 #print STDERR "inside doc header\n";
593
594 if ( m#^(.*)<${_DOC_SIGLE}(?: [^>]*)?>([^<]*)(.*)$# ){
595
596 $pfx = $1; $sfx = $3;
597
598 $dir_doc = $2;
599
600 die "ERROR ($0): main(): input line number $lc: line with document-sigle tag '$_DOC_SIGLE' is not in expected format ... => Aborting\n\tline=$_"
601 if $pfx !~ /^\s*$/ || $sfx !~ m#^</${_DOC_SIGLE}>\s*$# || $dir_doc =~ /^\s*$/;
602
603 s#(<${_DOC_SIGLE}(?: [^>]*)?>)[^<]+(</${_DOC_SIGLE}>)#$1$dir_doc$2# # to be consistent with escaping, escape also textSigle in Document-Header
604 if $dir_doc =~ s/("|&|<|>)/$ent{$1}/g;
605 }
606
607 $header_doc .= $_;
608
609 } elsif ( m#^(.*)(<${_TEXT_HEADER_BEG}.*)$# ){
610
611 # ~ start of text header ~
612
613
614 #print STDERR "begin of text header\n";
615
616 $header_txt = $_; $header_fl_txt = 1; $pfx = $1;
617
618 $tc = 0; # reset (needed for ~ whitespace handling ~)
619
620 die "ERROR ($0): main(): input line number $lc: line with opening text-header tag '${_TEXT_HEADER_BEG}'"
621 ." is not in expected format ... => Aborting\n\tline=$_"
622 if $pfx !~ /^\s*$/;
623
624 } elsif ( m#^(.*)<${_TEXT_BODY}(?: [^>]*)?>(.*)$# ){
625
626
627 # ~ start of text body ~
628
629
630 #print STDERR "inside text body\n";
631
632 $pfx = $1; $sfx = $2;
633
634 $data_fl = 1;
635
636 die "ERROR ($0): main(): input line number $lc: line with opening text-body tag '${_TEXT_BODY}'"
637 ." contains additional information ... => Aborting\n\tline=$_"
638 if $pfx !~ /^\s*$/ || $sfx !~ /^\s*$/;
639
640 } elsif ( m#^(.*)(<${_DOC_HEADER_BEG}.*)$# ){
641
642
643 # ~ start of document header ~
644
645
646 #print STDERR "begin of doc header\n";
647
648 $header_doc = "$2\n"; $header_fl_doc = 1; $pfx = $1;
649
650 die "ERROR ($0): main(): input line number $lc: line with opening document-header tag '${_DOC_HEADER_BEG}'"
651 ."is not in expected format ... => Aborting\n\tline=$_"
652 if $pfx !~ /^\s*$/;
653
654 } elsif ( $header_fl_crp && m#^(.*</${_CORP_HEADER_END}>)(.*)$# ){
655
656
657 # ~ end of corpus header ~
658
659
660 #print STDERR "end of corp header\n";
661
662 $sfx = $2;
663
664 $header_crp .= $1; $header_fl_crp = 0;
665
666 die "ERROR ($0): main(): input line number $lc: line with closing corpus-header tag '${_CORP_HEADER_END}'"
667 ." contains additional information ... => Aborting\n\tline=$_"
668 if $sfx !~ /^\s*$/;
669
670 if ( $dir_crp eq "" ){
671
672 print STDERR "WARNING ($0): main(): input line number $lc: empty corpus sigle in corpus header => nothing to do ...\ncorpus header=$header_crp\n";
673
674 } else {
675
676 print STDERR "DEBUG ($0): Writing file $_root_dir$dir_crp/$_header_file\n" if $_DEBUG;
677
678 if ( $first_write ){
679
680 $first_write = 0;
681
Peter Harders6f526a32020-06-29 21:44:41 +0200682 $zip = new IO::Compress::Zip $zip_outh, Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD,
683 Append => 0, Name => "$_root_dir$dir_crp/$_header_file"
684 or die "ERROR ('$_root_dir$dir_crp/$_header_file'): zip failed: $ZipError\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200685
686 } else {
687
688 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => "$_root_dir$dir_crp/$_header_file" )
689 or die "ERROR ('$_root_dir$dir_crp/$_header_file'): zip failed: $ZipError\n"
690 }
691
692 $header_crp = encode_utf8( $header_crp );
693
694 $zip->print( "$header_prfx$header_crp" );
695
696 $header_crp = $dir_crp = "";
697 }
698
699 } elsif ( $header_fl_crp ){
700
701
702 # ~ inside corpus header ~
703
704
705 #print STDERR "inside corp header\n";
706
707 if ( m#^(.*)<${_CORP_SIGLE}(?: [^>]*)?>([^<]*)(.*)$# ){
708
709 $pfx = $1; $sfx = $3;
710
711 $dir_crp = $2;
712
713 die "ERROR ($0): main(): input line number $lc: line with korpusSigle-tag is not in expected format ... => Aborting\n\tline=$_"
714 if $pfx !~ /^\s*$/ || $sfx !~ m#^</${_CORP_SIGLE}>\s*$# || $dir_crp =~ /^\s*$/;
715
716 if ( $dir_crp =~ s/("|&|<|>)/$ent{$1}/g ){
717
718 s#(<${_CORP_SIGLE}(?: [^>]*)?>)[^<]+(</${_CORP_SIGLE}>)#$1$dir_crp$2# # to be consistent with escaping, escape also textSigle in Corpus-Header
Peter Hardersd892a582020-02-12 15:45:22 +0100719 }
720 }
721
Peter Harders6f526a32020-06-29 21:44:41 +0200722 $header_crp .= $_;
Peter Hardersd892a582020-02-12 15:45:22 +0100723
Peter Harders6f526a32020-06-29 21:44:41 +0200724 } elsif ( m#^(.*)(<${_CORP_HEADER_BEG}.*)$# ){
Peter Hardersd892a582020-02-12 15:45:22 +0100725
Peter Hardersd892a582020-02-12 15:45:22 +0100726
Peter Harders6f526a32020-06-29 21:44:41 +0200727 # ~ start of corpus header ~
Peter Hardersd892a582020-02-12 15:45:22 +0100728
Peter Harders6f526a32020-06-29 21:44:41 +0200729
730 #print STDERR "begin of corp header\n";
731
732 $header_crp = $2; $header_fl_crp = 1; $pfx = $1;
733
734 die "ERROR ($0): main(): input line number $lc: line with opening corpus-header tag '${_CORP_HEADER_BEG}'"
735 ." is not in expected format ... => Aborting\n\tline=$_"
736 if $pfx !~ /^\s*$/;
Peter Hardersd892a582020-02-12 15:45:22 +0100737 }
738
Peter Harders6f526a32020-06-29 21:44:41 +0200739 } #end: while
Peter Hardersd892a582020-02-12 15:45:22 +0100740
Peter Harders6f526a32020-06-29 21:44:41 +0200741 $zip->close();
742
743 ## DEPRECATED (only IDS-intern)
744 if( $_GEN_TOK_BAS ){
745 close($chld_in);
746 close($chld_out);
Peter Hardersd892a582020-02-12 15:45:22 +0100747 }
Peter Harders6f526a32020-06-29 21:44:41 +0200748 ##
Peter Hardersd892a582020-02-12 15:45:22 +0100749
Peter Harders90157342020-07-01 21:05:14 +0200750} # end: sub process
Peter Hardersd892a582020-02-12 15:45:22 +0100751
Peter Hardersd892a582020-02-12 15:45:22 +0100752
Peter Harders6f526a32020-06-29 21:44:41 +0200753sub retr_info { # called from process()
Peter Hardersd892a582020-02-12 15:45:22 +0100754
Peter Harders6f526a32020-06-29 21:44:41 +0200755 # EXAMPLE: <node a="v"><node1>some <n/> text</node1><node2>more-text</node2></node>
756 #
757 # print out values of above example:
758 # 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_COMMENTS | XCT_LINE_NUMBERS ); print $data->[2]->[0]->[5]->[1]->[1]'
759 #
760 # $data = reference to below array
761 #
762 # [ 0: XML_READER_TYPE_DOCUMENT,
763 # 1: ?
764 # 2: [ 0: [ 0: XML_READER_TYPE_ELEMENT <- start recursion with array '$data->[2]' (see process(): retr_info( \$tree_data->[2] ))
765 # 1: 'node'
766 # 2: ?
767 # 3: HASH (attributes)
768 # 4: 1 (line number)
769 # 5: [ 0: [ 0: XML_READER_TYPE_ELEMENT
770 # 1: 'node1'
771 # 2: ?
772 # 3: undefined (no attributes)
773 # 4: 1 (line number)
774 # 5: [ 0: [ 0: XML_READER_TYPE_TEXT
775 # 1: 'some '
776 # ]
777 # 1: [ 0: XML_READER_TYPE_ELEMENT
778 # 1: 'n'
779 # 2: ?
780 # 3: undefined (no attributes)
781 # 4: 1 (line number)
782 # 5: undefined (no child nodes)
783 # ]
784 # 2: [ 0: XML_READER_TYPE_TEXT
785 # 1: ' text'
786 # ]
787 # ]
788 # ]
789 # 1: [ 0: XML_READER_TYPE_ELEMENT
790 # 1: 'node2'
791 # 2: ?
792 # 3: undefined (not attributes)
793 # 4: 1 (line number)
794 # 5: [ 0: [ 0: XML_READER_TYPE_TEXT
795 # 1: 'more-text'
796 # ]
797 # ]
798 # ]
799 # ]
800 # ]
801 # ]
802 # ]
803 #
804 # $data->[0] = 9 (=> type == XML_READER_TYPE_DOCUMENT)
805 #
806 # ref($data->[2]) == ARRAY (with 1 element for 'node')
807 # ref($data->[2]->[0]) == ARRAY (with 6 elements)
808 #
809 # $data->[2]->[0]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
810 # $data->[2]->[0]->[1] == 'node'
811 # ref($data->[2]->[0]->[3]) == HASH (=> ${$data->[2]->[0]->[3]}{a} == 'v')
812 # $data->[2]->[0]->[4] == 1 (line number)
813 # ref($data->[2]->[0]->[5]) == ARRAY (with 2 elements for 'node1' and 'node2')
814 # # child nodes of actual node (see $_IDX)
815 #
816 # ref($data->[2]->[0]->[5]->[0]) == ARRAY (with 6 elements)
817 # $data->[2]->[0]->[5]->[0]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
818 # $data->[2]->[0]->[5]->[0]->[1] == 'node1'
819 # $data->[2]->[0]->[5]->[0]->[3] == undefined (=> no attribute)
820 # $data->[2]->[0]->[5]->[0]->[4] == 1 (line number)
821 # ref($data->[2]->[0]->[5]->[0]->[5]) == ARRAY (with 3 elements for 'some ', '<n/>' and ' text')
822 #
823 # ref($data->[2]->[0]->[5]->[0]->[5]->[0]) == ARRAY (with 2 elements)
824 # $data->[2]->[0]->[5]->[0]->[5]->[0]->[0] == 3 (=> type == XML_READER_TYPE_TEXT)
825 # $data->[2]->[0]->[5]->[0]->[5]->[0]->[1] == 'some '
826 #
827 # ref($data->[2]->[0]->[5]->[0]->[5]->[1]) == ARRAY (with 5 elements)
828 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
829 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[1] == 'n'
830 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[3] == undefined (=> no attribute)
831 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[4] == 1 (line number)
832 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[5] == undefined (=> no child nodes)
833 #
834 # ref($data->[2]->[0]->[5]->[0]->[5]->[2]) == ARRAY (with 2 elements)
835 # $data->[2]->[0]->[5]->[0]->[5]->[2]->[0] == 3 (=> type == XML_READER_TYPE_TEXT)
836 # $data->[2]->[0]->[5]->[0]->[5]->[2]->[1] == ' text'
837 #
838 #
839 # retr_info() starts with the array reference ${$_[0]} (= \$tree_data->[2]), which corresponds to ${\$data->[2]} in the above example.
840 # Hence, the expression @{${$_[0]}} corresponds to @{${\$data->[2]}}, $e to ${${\$data->[2]}}[0] (= $data->[2]->[0]) and $e->[0] to
841 # ${${\$data->[2]}}[0]->[0] (= $data->[2]->[0]->[0]).
Peter Hardersd892a582020-02-12 15:45:22 +0100842
Peter Harders6f526a32020-06-29 21:44:41 +0200843 $rl++; # recursion level (1 = topmost level inside retr_info() = should always be level of tag $_TEXT_BODY)
Peter Hardersd892a582020-02-12 15:45:22 +0100844
Peter Hardersd892a582020-02-12 15:45:22 +0100845
Peter Harders6f526a32020-06-29 21:44:41 +0200846 foreach $e ( @{${$_[0]}} ){ # iteration through all array elements ($_[0] is a reference to an array reference)
Peter Hardersd892a582020-02-12 15:45:22 +0100847
Peter Hardersd892a582020-02-12 15:45:22 +0100848
Peter Harders6f526a32020-06-29 21:44:41 +0200849 if ( $e->[0] == XML_READER_TYPE_ELEMENT ){ # element node (see 'NODE TYPES' in manpage of XML::LibXML::Reader)
Peter Hardersd892a582020-02-12 15:45:22 +0100850
Peter Hardersd892a582020-02-12 15:45:22 +0100851
Peter Harders6f526a32020-06-29 21:44:41 +0200852 #~~~~
853 # from here: opening tag
854 #~~~~
Peter Hardersd892a582020-02-12 15:45:22 +0100855
Peter Hardersd892a582020-02-12 15:45:22 +0100856
Peter Harders6f526a32020-06-29 21:44:41 +0200857 # insert new array (for new tag) into @structures with tag-name and tag-attributes (if present)
858 # update @oti (open tags indizes) with @structures highest index (= $#structures); e.g.: @a=(1,2,3) => $#a = 2
Peter Hardersd892a582020-02-12 15:45:22 +0100859
Peter Harders6f526a32020-06-29 21:44:41 +0200860 # ~ tag name ~
Peter Hardersd892a582020-02-12 15:45:22 +0100861
Peter Harders6f526a32020-06-29 21:44:41 +0200862 $n = $e->[1];
Peter Hardersd892a582020-02-12 15:45:22 +0100863
Peter Hardersd892a582020-02-12 15:45:22 +0100864
Peter Harders6f526a32020-06-29 21:44:41 +0200865 # ~ handle structures ~
Peter Hardersd892a582020-02-12 15:45:22 +0100866
Peter Harders6f526a32020-06-29 21:44:41 +0200867 my @array;
868 push @array, $n;
869 push @structures, \@array;
870 push @oti, $#structures; # add highest index of @structures to @oti
Peter Hardersd892a582020-02-12 15:45:22 +0100871
Peter Hardersd892a582020-02-12 15:45:22 +0100872
Peter Harders6f526a32020-06-29 21:44:41 +0200873 # ~ handle tokens ~
Peter Hardersd892a582020-02-12 15:45:22 +0100874
Peter Harders6f526a32020-06-29 21:44:41 +0200875 $inside_tokens_tag = $rl if $_TOKENS_PROC && $n eq $_TOKENS_TAG; # wether to push entry also into @tokens array
Peter Hardersd892a582020-02-12 15:45:22 +0100876
Peter Harders6f526a32020-06-29 21:44:41 +0200877 if ( $_TOKENS_PROC && $inside_tokens_tag == $rl ){
Peter Hardersd892a582020-02-12 15:45:22 +0100878
Peter Harders6f526a32020-06-29 21:44:41 +0200879 my @array2;
880 push @array2, $n;
881 push @tokens, \@array2;
882 push @oti2, $#tokens;
883 }
Peter Hardersd892a582020-02-12 15:45:22 +0100884
Peter Hardersd892a582020-02-12 15:45:22 +0100885
Peter Harders6f526a32020-06-29 21:44:41 +0200886 # ~ handle attributes ~
Peter Hardersd892a582020-02-12 15:45:22 +0100887
Peter Harders6f526a32020-06-29 21:44:41 +0200888 if ( defined $e->[3] ){ # only if attributes exist
Peter Hardersd892a582020-02-12 15:45:22 +0100889
Peter Harders6f526a32020-06-29 21:44:41 +0200890 for ( $c = 0; $c < @{$e->[3]}; $c += 2 ){ # with 'XCT_ATTRIBUTE_ARRAY', $node->[3] is an array reference of the form
891 # [ name1, value1, name2, value2, ....] of attribute names and corresponding values.
892 # note: arrays are faster (see: http://makepp.sourceforge.net/2.0/perl_performance.html)
Peter Hardersd892a582020-02-12 15:45:22 +0100893
Peter Harders6f526a32020-06-29 21:44:41 +0200894 # '$c' references the 'key' and '$c+1' the 'value'
895 push @{$structures[$#structures]}, ${$e->[3]}[$c], ${$e->[3]}[$c+1];
Peter Hardersd892a582020-02-12 15:45:22 +0100896
Peter Harders6f526a32020-06-29 21:44:41 +0200897 if ( $_TOKENS_PROC && $inside_tokens_tag == $rl ){
Peter Hardersd892a582020-02-12 15:45:22 +0100898
Peter Harders6f526a32020-06-29 21:44:41 +0200899 push @{$tokens[$#tokens]}, ${$e->[3]}[$c], ${$e->[3]}[$c+1];
900 }
901
902 }
903 }
904
905
906 # ~ index 'from' ~
907
908 # this is, where a normal tag or tokens-tag ($_TOKENS_TAG) starts
909
910 push @{$structures[$#structures]}, ( $dl + $add_one ); # see below (text and whitespace nodes) for explanation on '$add_one'
911
912 if ( $_TOKENS_PROC && $inside_tokens_tag == $rl ){
913
914 push @{$tokens[$#tokens]}, ( $dl + $add_one );
915 }
916
917
918 #~~~~
919 # until here: opening tag
920 #~~~~
921
922
923 # ~~ RECURSION ~~
924
925 if ( defined $e->[$_IDX] ){ # do no recursion, if $e->[$_IDX] is not defined (because we have no array of child nodes, e.g.: <back/>)
926
927 retr_info( \$e->[$_IDX] ); # recursion with array of child nodes
928
929 $rl--; # return from recursion
930 }
931
932
933 #~~~~~
934 # from here: closing tag
935 #~~~~~
936
937
938 # ~ handle structures ~
939
940 {
941 my $ix = pop @oti; # index of just closed tag
942
943 my $aix = $#{$structures[$ix]}; # determine highest index from 'array referring to last closed tag' ...
944
945 $fval = ${$structures[$ix]}[ $aix ]; # ... and get it's from-value
946
947 if ( $fval > 0 && not exists $ws{ $fval - 1 } ){ # ~ whitespace related issue ~
948
949 # previous node was a text-node
950
951 ${$structures[$ix]}[ $aix ] = $fval - 1; # recorrect from-value (see below: notes on ~ whitespace related issue ~)
952 }
953
954 # in case this fails, check input
955 die "ERROR ($0, retr_info()): text_id='$text_id', processing of \@structures: from-value ($fval) is 2 or more greater"
956 ." than to-value ($dl) => please check. aborting ...\n"
957 if ( $fval - 1 ) > $dl;
958
959 # TODO: construct example for which this case applies
960 # maybe this is not necessary anymore, because the above recorrection of the from-value suffices
961 # TODO: check, if it's better to remove this line and change above check to 'if ( $fval - 1) >= $dl;
962 ${$structures[$ix]}[ $aix ] = $dl if $fval == $dl + 1; # correct from-value (same as ... if $fval-1 == $dl)
963
964 push @{$structures[$ix]}, $dl, $rl; # to-value and recursion-level
965
966 # note: use $dl, because the offsets are _between_ the characters (e.g.: word = 'Hello' => from = 0 (before 'H'), to = 5 (after 'o'))
967 }
968
969
970 # ~ handle tokens ~
971
972
973 if ( $_TOKENS_PROC && $inside_tokens_tag == $rl ){
974
975 my $ix = pop @oti2;
976
977 my $aix = $#{$tokens[$ix]};
978
979 $fval2 = ${$tokens[$ix]}[ $aix ]; # from-value
980
981 if( $fval2 > 0 && not exists $ws{ $fval2 - 1 } ){ # ~ whitespace related issue ~
982
983 # previous node was a text-node
984
985 ${$tokens[$ix]}[ $aix ] = $fval2 - 1; # recorrect from-value
986 }
987
988 # in case this fails, check input
989 die "ERROR ($0, retr_info()): text_id='$text_id', processing of \@tokens: from-value ($fval2) is 2 or more greater"
990 ." than to-value ($dl) => please check. aborting ...\n"
991 if ( $fval2 - 1 ) > $dl;
992
993 # TODO: construct example for which this case applies
994 # maybe this is not necessary anymore, because the above recorrection of the from-value suffices
995 # TODO: check, if it's better to remove this line and change above check to 'if ( $fval2 - 1) >= $dl;
996 ${$tokens[$ix]}[ $aix ] = $dl if $fval2 == $dl + 1; # correct from-value (same as ... if $fval-1 == $dl)
997
998 push @{$tokens[$ix]}, $dl, $rl; # to-value and recursion-level
999
1000 $inside_tokens_tag = -1; # reset
1001 }
1002
1003 # ~ whitespace related issue ~
Peter Hardersd892a582020-02-12 15:45:22 +01001004 # clean up
Peter Harders6f526a32020-06-29 21:44:41 +02001005 delete $ws{ $fval - 1 } if $fval > 0 && exists $ws{ $fval - 1 };
1006 delete $ws{ $fval2 - 1 } if $_TOKENS_PROC && $fval2 > 0 && exists $ws{ $fval2 - 1 };
Peter Hardersd892a582020-02-12 15:45:22 +01001007
1008
Peter Harders6f526a32020-06-29 21:44:41 +02001009 #~~~~~
1010 # from here: text (and whitespace) nodes
1011 #~~~~~
Peter Hardersd892a582020-02-12 15:45:22 +01001012
1013
Peter Harders6f526a32020-06-29 21:44:41 +02001014 # the 3rd form of nodes, next to text-nodes (XML_READER_TYPE_TEXT) and tag-nodes (XML_READER_TYPE_ELEMENT) are nodes
1015 # of the type 'XML_READER_TYPE_SIGNIFICANT_WHITESPACE'
1016 #
1017 # when modifiying the above example (at the top of this sub) by inserting an additional blank between '</node1>' and '<node2>',
1018 # the output for '$data->[2]->[0]->[5]->[1]->[1]' becomes a blank (' ') and it's type is '14' (see manpage of XML::LibXML::Reader):
1019 #
1020 # 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_COMMENTS | XCT_LINE_NUMBERS ); print "node=".$data->[2]->[0]->[5]->[1]->[1].", type=".$data->[2]->[0]->[5]->[1]->[0]."\n"'
Peter Hardersd892a582020-02-12 15:45:22 +01001021
Peter Harders6f526a32020-06-29 21:44:41 +02001022 } elsif ( $e->[0] == XML_READER_TYPE_TEXT || $e->[0] == XML_READER_TYPE_SIGNIFICANT_WHITESPACE ){
Peter Hardersd892a582020-02-12 15:45:22 +01001023
Peter Harders6f526a32020-06-29 21:44:41 +02001024 # notes on ~ whitespace related issue ~ (see below source code)
1025 #
1026 # example: '... <head type="main"><s>Campagne in Frankreich</s></head><head type="sub"> <s>1792</s> ...'
1027 #
1028 # Two text-nodes should normally be separated by a blank. In the above example, that would be the 2 text-nodes
1029 # 'Campagne in Frankreich' and '1792', which are separated by the whitespace-node ' '.
1030 #
1031 # Assumed, that the above example marks the general case, then the text-node 'Campagne in Frankreich' leads to the
1032 # setting of '$add_one' to 1, so that when opening the 2nd 'head'-tag and setting it's from-index, it gets the right
1033 # offset, which is the start-index of '1792'.
1034 #
1035 # To check, that the above consideration holds, we save the from-index of a read whitespace-node into the hash %ws.
1036 # By this, it can be checked when closing a tag, if the 'non-tag'-node (text or whitespace) before the last 'non-tag'-
1037 # node was actually a whitespace-node ($ws{ $fval - 1 }).
1038 #
1039 # For whitespace-nodes, also $add_one has to be set to 0, so when opening the next tag (in the above example the 2nd
1040 # 's'-tag), no additional 1 is added, because this was already done by the whitespace-node itself (by incrementing the
1041 # variable $dl).
1042 #
1043 # Now, what happens, when 2 text-nodes are not seperated by a whitespace-node (blank)? (e.g.: <w>Augen<c>,</c></w>)
1044 #
1045 # In this case, the falsely increased from-value has to be decreased again by 1 when closing the referring tag
1046 # (...$fval - 1; # recorrect).
1047 #
1048 # Comparing the 2 examples '<w>fu</w> <w>bar</w>' and '<w>fu</w><w> </w><w>bar</w>' (even though, the 2nd one makes less
1049 # sense, because of '<w> </w>'), in both the ' ' is handled as a whitespace-node (XML_READER_TYPE_SIGNIFICANT_WHITESPACE).
1050 #
1051 # So the from-index of the 2nd w-tag (in the second example) would refer to 'bar', which may not have been the intention
1052 # (even, if '<w> </w>' doesn't make a lot of sense). TODO: could this be a bug, which needs to be fixed?
1053 #
1054 # Empty tags also cling to the next text-token - e.g. in '...<w>tok1</w> <w>tok2</w><a><b/></a><w>tok3</w>...' the from-
1055 # and to-indizes for the tags 'a' and 'b' are both 9, which is the start-index of the token 'tok3'.
1056
1057 if( $e->[0] == XML_READER_TYPE_SIGNIFICANT_WHITESPACE ){
1058
1059 # ~ whitespace related issue ~
1060
1061 $add_one = 0;
1062
1063 $ws{ $dl }++; # '++' does not mean a thing here (could be used for consistency checking)
1064
1065 }else{
1066
1067 # ~ text-node ~
1068
1069 $add_one = 1;
1070 }
1071
1072
1073 # ~ update $data and $dl ~
1074
1075 $data .= $e->[1];
1076
1077 $dl += length( $e->[1] ); # update length of $data
1078
1079
1080
1081 #~~~~~
1082 # from here (until end): dummy tokenization
1083 #~~~~~
1084
1085 if ( $_GEN_TOK_DUMMY ){
1086
1087 $txt = $e->[1];
1088
1089 if ( substr( $txt, 0, 1 ) ne ' ' || substr( $txt, 1, 1) ne ' ' ){ # $txt has at least 2 chars, if it's not empty or equal to ' '
1090
1091
1092 # ~ start: conservative tokenization ~
1093
1094
1095 # '\p{Punct}' is equal to the character class '[-!"#%&'()*,./:;?@[\\\]_{}]'
1096 while ( $txt =~ /([\p{Punct}]*)([^\p{Punct} \x{9}\n]+(?:([\p{Punct}]+)[^\p{Punct} \x{9}\n]+)*)?([\p{Punct}]*)(?:[ \x{9}\n])?/g ){
1097
1098 $m1 = $1; $m2 = $2; $m3 = $3; $m4 = $4;
1099
1100 if ( "$m1" ne "" ){ # special chars before token
1101
1102 $p1 = $-[1]; $p2 = $+[1];
1103
1104 #print STDERR "A1: ".$m1." -> from $p1 to $p2\n";
1105
1106 if ( $p2 == $p1+1 ){
1107
1108 if ( $p1 != 0 ){ $tmp = substr( $txt, $p1-1, 1 ); $pr = ( $tmp =~ /^[^A-Za-z0-9]/ ) } else { $pr = 0 };
1109
1110 if ( not $pr ){ $tmp = substr( $txt, $p2, 1 ); $pr = ( $tmp =~ /^[^A-Za-z0-9]/ ) };
1111
1112 if ( $pr ){ push @tok_tokens_con, $p1+$offset; push @tok_tokens_con, $p2+$offset }; # from and to
1113
1114 } else {
1115
1116 for ( $i = 0; $i < ( $p2-$p1 ); $i++ ){
1117
1118 #print STDERR "A2: ".substr($m1,$i,1)." -> from $p1 to $p2\n";
1119
1120 push @tok_tokens_con, $p1+$i+$offset; push @tok_tokens_con, $p1+$i+1+$offset; # from and to
1121 }
1122 }
1123
1124 } # fi: "$m1" ne ""
1125
1126 #print STDERR "B: "."$m2 -> from ".($-[2]+$offset)." to ".($+[2]+$offset)."\n" if defined $m2; # token (wordform)
1127
1128 if ( defined $m2 ){ push @tok_tokens_con, $-[2]+$offset; push @tok_tokens_con, $+[2]+$offset }; # from and to
1129
1130 if ( defined $m3 ){
1131
1132 $p1 = $-[3]; $p2 = $+[3];
1133
1134 #print STDERR "C: ".$m3." -> from $p1 to $p2\n";
1135
1136 if ( $p2 == $p1+1 ){
1137
1138 $tmp = substr( $txt, $p2, 1); $pr = ( $tmp =~ /^$/ ); $pr = ( $tmp =~ /^[^A-Za-z0-9]/ ) if not $pr; # char after match
1139
1140 if ( not $pr ){ $tmp = substr( $txt, $p1-1, 1 ); $pr = ( $tmp =~ /^[^A-Za-z0-9]/ ) }; # char before match
1141
1142 if ( $pr ){ push @tok_tokens_con, $p1+$offset; push @tok_tokens_con, $p2+$offset }; # from and to
1143
1144 } else { # length($m3)>1 => print all chars
1145
1146 for ( $i = 0; $i < ( $p2-$p1 ); $i++ ){
1147
1148 #$tmp=substr($m3,$i,1);
1149 #print STDERR "C2: $tmp -> from $p1 to $p2\n";
1150
1151 push @tok_tokens_con, $p1+$i+$offset; push @tok_tokens_con, $p1+$i+1+$offset; # from and to
1152 }
1153
1154 }
1155
1156 } # fi: defined $m3
1157
1158 if ( "$m4" ne "" ){ # special chars after token
1159
1160 $p1 = $-[4]; $p2 = $+[4];
1161
1162 #print STDERR "D1: ".$m4." -> from ".($p1+$offset)." to ".($p2+$offset)."\n";
1163
1164 if ( $p2 == $p1+1 ){
1165
1166 $tmp = substr( $txt, $p2, 1 ); $pr = ( $tmp =~ /^$/ ); $pr = ( $tmp =~ /^[^A-Za-z0-9]/ ) if not $pr; # char after match
1167
1168 if ( not $pr ){ $tmp = substr ( $txt, $p1-1, 1 ); $pr = ( $tmp =~ /^[^A-Za-z0-9]/ ) }; # char before match
1169
1170 if ( $pr ){ push @tok_tokens_con, $p1+$offset; push @tok_tokens_con, $p2+$offset } # from and to
1171
1172 }else{
1173
1174 for ( $i = 0; $i < ( $p2-$p1 ); $i++ ){
1175
1176 #print STDERR "D2: ".substr($m4,$i,1)." -> from ".($p1+$i+$offset)." to ".($p1+$i+1+$offset)."\n";
1177
1178 push @tok_tokens_con, $p1+$i+$offset; push @tok_tokens_con, $p1+$i+1+$offset; # from and to
1179 }
1180 }
1181
1182 }# fi: "$m4" ne ""
1183
1184 }# end: while
1185
1186
1187 # ~ end: conservative tokenization ~
1188
1189
1190 # ~ start: aggressive tokenization ~
1191
1192
1193 while ( $txt =~ /([^\p{Punct} \x{9}\n]+)(?:([\p{Punct}])|(?:[ \x{9}\n])?)|([\p{Punct}])/g ){
1194
1195 if ( defined $1 ){
1196
1197 push @tok_tokens_agg, $-[1]+$offset; push @tok_tokens_agg, $+[1]+$offset; # from and to
1198
1199 if ( defined $2 ){ push @tok_tokens_agg, $-[2]+$offset; push @tok_tokens_agg, $+[2]+$offset } # from and to
1200
1201 }else{ # defined $3
1202
1203 push @tok_tokens_agg, $-[3]+$offset; push @tok_tokens_agg, $+[3]+$offset # from and to
1204 }
1205
1206 } # end: while
1207
1208 # ~ end: aggressive tokenization ~
1209
1210 ##$offset = $dl+1;
1211
1212 $offset = $dl;
1213
1214 } # fi
1215
1216 } # fi: $_GEN_TOK_DUMMY
1217
1218
1219 #elsif ( $e->[0] == XML_READER_TYPE_ATTRIBUTE ) # attribute node
1220 # note: attributes cannot be processed like this ( => use 'XCT_ATTRIBUTE_ARRAY' - see above )
1221
1222
1223 }else{ # not yet handled type
1224
1225 die "ERROR ($0): Not yet handled type (\$e->[0]=".$e->[0].") ... => Aborting\n";
1226 }
1227
1228 } # end: foreach iteration
1229
1230} # end: sub retr_info
1231
1232
1233sub select_tokenization { # called from process()
1234
1235 #print STDERR "$0: select_tokenization() ...\n";
1236
1237 ## DEPRECATED (only IDS-intern)
Peter Hardersd892a582020-02-12 15:45:22 +01001238 if( $_GEN_TOK_BAS ) {
1239 if( $select->can_read(3600) ){ # wait 60m for external tokenizer
1240 $_ = <$chld_out>;
1241 my @bounds = split;
Peter Harders6f526a32020-06-29 21:44:41 +02001242 write_tokenization("$_root_dir$dir/$_base_tokenization_dir/$_tok_file_bas", $text_id_esc, \@bounds);
Peter Hardersd892a582020-02-12 15:45:22 +01001243 while($select->can_read(0)) {
1244 $_ = <$chld_out>;
1245 if (defined $_ && $_ ne '') {
1246 print STDERR "WARNING: extra output: $_\n"
1247 } else {
1248 print STDERR "WARNING: tokenizer seems to have crashed, restarting.\n";
1249 startTokenizer();
1250 }
1251 }
1252 }else{
1253 $zip->close();
1254 die "ERROR ($0): cannot retrieve token bounds from external tokenizer for text '$text_id' => Aborting ...\n";
1255 }
Peter Harders6f526a32020-06-29 21:44:41 +02001256 ##
Peter Hardersd892a582020-02-12 15:45:22 +01001257 }elsif( $_GEN_TOK_DUMMY ){
Peter Harders6f526a32020-06-29 21:44:41 +02001258 write_tokenization("$_root_dir$dir/$_base_tokenization_dir/$_tok_file_con", $text_id_esc, \@tok_tokens_con);
1259 write_tokenization("$_root_dir$dir/$_base_tokenization_dir/$_tok_file_agg", $text_id_esc, \@tok_tokens_agg);
Peter Hardersd892a582020-02-12 15:45:22 +01001260 }
Peter Hardersd892a582020-02-12 15:45:22 +01001261
Peter Harders6f526a32020-06-29 21:44:41 +02001262 #print STDERR "$0: write_tokenization(): DONE\n";
1263
1264} # end: select_tokenization
1265
1266sub write_tokenization { # called from select_tokenization()
1267
1268 my ( $fname, $textid_esc, $bounds ) = @_;
Peter Hardersd892a582020-02-12 15:45:22 +01001269
1270 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => $fname)
1271 or die "ERROR ('$fname'): zip failed: $ZipError\n";
Peter Harders6f526a32020-06-29 21:44:41 +02001272
1273 $output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-model href=\"span.rng\" type=\"application/xml\""
1274 ." schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n\n<layer docid=\"$text_id_esc\" xmlns=\"http://ids-mannheim.de/ns/KorAP\""
1275 ." version=\"KorAP-0.4\">\n <spanList>\n";
1276
1277 $c = 0;
1278
1279 for( $i = 0; $i < ($#$bounds + 1); $i += 2 ){
1280
Peter Hardersd892a582020-02-12 15:45:22 +01001281 $output .= " <span id=\"t_$c\" from=\"".$bounds->[$i]."\" to=\"".$bounds->[$i+1]."\" />\n";
Peter Harders6f526a32020-06-29 21:44:41 +02001282
Peter Hardersd892a582020-02-12 15:45:22 +01001283 $c++;
1284 }
Peter Hardersd892a582020-02-12 15:45:22 +01001285
Peter Harders6f526a32020-06-29 21:44:41 +02001286 $output .= " </spanList>\n</layer>";
1287
1288 $zip->print ( "$output" );
1289
1290} # end: sub write_tokenization
1291
1292
1293sub write_structures { # called from process()
1294
1295 # ~ write @structures ~
Peter Hardersd892a582020-02-12 15:45:22 +01001296
1297 #print STDERR "$0: write_structures(): ...\n";
1298
Peter Harders6f526a32020-06-29 21:44:41 +02001299 if ( $dir eq "" ){
1300
1301 print STDERR "WARNING ($0): write_structures(): empty textSigle => nothing to do ...\n";
Peter Hardersd892a582020-02-12 15:45:22 +01001302 return;
1303 }
1304
1305 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => "$_root_dir$dir/$_structure_dir/$_structure_file" )
1306 or die "ERROR ('$_root_dir$dir/$_structure_dir/$_structure_file'): zip failed: $ZipError\n";
1307
Peter Harders6f526a32020-06-29 21:44:41 +02001308 $output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-model href=\"span.rng\" type=\"application/xml\""
1309 ." schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n\n<layer docid=\""
1310 .decode_utf8($text_id_esc)."\" xmlns=\"http://ids-mannheim.de/ns/KorAP\" version=\"KorAP-0.4\">\n <spanList>\n";
Peter Hardersd892a582020-02-12 15:45:22 +01001311
1312 $c = 0;
1313
Peter Harders6f526a32020-06-29 21:44:41 +02001314 foreach $ref ( @structures ){
Peter Hardersd892a582020-02-12 15:45:22 +01001315
Peter Harders6f526a32020-06-29 21:44:41 +02001316 ( @{$ref} == 4 )?( $idx = 1 ):( $idx = @{$ref}-3 ); # if array '@{$ref}' doesn't contain attributes, then the number of elements in this array is 4
1317 # (name, from, to, rec_level), otherwise >4
Peter Hardersd892a582020-02-12 15:45:22 +01001318
Peter Harders6f526a32020-06-29 21:44:41 +02001319 # 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 )
1320
1321 if( $#structures == $c && ${$ref}[ $idx ] == ${$ref}[ $idx+1 ] + 1 ){
1322
1323 ${$ref}[$idx] = ${$ref}[ $idx+1 ];
Peter Hardersd892a582020-02-12 15:45:22 +01001324 }
Peter Hardersd892a582020-02-12 15:45:22 +01001325
Peter Harders6f526a32020-06-29 21:44:41 +02001326 # this consistency check is already done in 'retr_info()'
1327 #elsif( ${$ref}[$idx] > ${$ref}[$idx+1] ){ # consistency check: abort, if this doesn't hold
1328 # die "ERROR ($0: write_structures(): \$text_id=$text_id, \$c=$c, tag-name=${$ref}[0]):"
1329 # ." 'from-index=${$ref}[$idx]' > 'to-index=${$ref}[$idx+1]' => please check! aborting ...\n";
1330 # die "ERROR ($0: write_structures(): \$text_id=$text_id, \$c=$c, tag-name=${$ref}[0]):"
1331 # ." 'from-index=${$ref}[$idx]' > 'to-index=${$ref}[$idx+1]' => please check! aborting ...\n\n$output" }
Peter Hardersd892a582020-02-12 15:45:22 +01001332
Peter Harders6f526a32020-06-29 21:44:41 +02001333 # at least 'POS' should always be there => remove constraint '$_TOKENS_PROC'
1334 #if( $_TOKENS_PROC && ${$ref}[0] ne $_TOKENS_TAG )
Peter Hardersd892a582020-02-12 15:45:22 +01001335
Peter Harders6f526a32020-06-29 21:44:41 +02001336 if( ${$ref}[0] ne $_TOKENS_TAG ){ # $_TOKENS_TAG is already written in 'write_tokens'
Peter Hardersd892a582020-02-12 15:45:22 +01001337
Peter Harders6f526a32020-06-29 21:44:41 +02001338 # l (level): insert information about depth of element in XML-tree (top element = level 1)
1339 $output .= " <span id=\"s$c\" from=\"${$ref}[ $idx ]\" to=\"${$ref}[ $idx+1 ]\" l=\"${$ref}[ $idx+2 ]\">\n"
1340 ." <fs type=\"struct\" xmlns=\"http://www.tei-c.org/ns/1.0\">\n"
1341 ." <f name=\"name\">${$ref}[ 0 ]</f>\n";
1342
1343 if ( $idx > 2 ) # attributes
1344 {
1345 $output .= " <f name=\"attr\">\n <fs type=\"attr\">\n";
1346
1347 for ( $att_idx = 1; $att_idx < $idx; $att_idx += 2 ){
1348
1349 ${$ref}[ $att_idx+1 ] =~ s/(&|<|>)/$ent{$1}/g; # see explanation in func. 'write_tokens'
1350
1351 # attribute (at index $att_idx) with value (at index $att_idx+1)
1352 $output .= " <f name=\"${$ref}[ $att_idx ]\">${$ref}[ $att_idx+1 ]</f>\n";
1353 }
1354
1355 $output .= " </fs>\n </f>\n";
Peter Hardersd892a582020-02-12 15:45:22 +01001356 }
1357
Peter Harders6f526a32020-06-29 21:44:41 +02001358 $output .= " </fs>\n </span>\n";
Peter Hardersd892a582020-02-12 15:45:22 +01001359
Peter Harders6f526a32020-06-29 21:44:41 +02001360 } # fi: ... ne $_TOKENS_TAG
Peter Hardersd892a582020-02-12 15:45:22 +01001361
1362 $c++;
1363
Peter Harders6f526a32020-06-29 21:44:41 +02001364 } # end: foreach
Peter Hardersd892a582020-02-12 15:45:22 +01001365
1366 $output .= " </spanList>\n</layer>";
1367
Peter Harders6f526a32020-06-29 21:44:41 +02001368 $output = encode_utf8( $output );
Peter Hardersd892a582020-02-12 15:45:22 +01001369
Peter Harders6f526a32020-06-29 21:44:41 +02001370 $zip->print( "$output" );
Peter Hardersd892a582020-02-12 15:45:22 +01001371
1372 #print STDERR "$0: write_structures(): DONE\n";
Peter Harders6f526a32020-06-29 21:44:41 +02001373
Peter Hardersd892a582020-02-12 15:45:22 +01001374} # end: sub write_structures
1375
1376
Peter Harders6f526a32020-06-29 21:44:41 +02001377sub write_tokens { # called from process()
1378
1379 # ~ write @tokens ~
1380
1381 #print STDERR "$0: write_tokens(): ...\n";
Peter Hardersd892a582020-02-12 15:45:22 +01001382
1383 if( $dir eq "" ){
Peter Harders6f526a32020-06-29 21:44:41 +02001384
1385 print STDERR "WARNING ($0): write_tokens(): empty textSigle => nothing to do ...\n";
Peter Hardersd892a582020-02-12 15:45:22 +01001386 return;
1387 }
1388
Peter Harders6f526a32020-06-29 21:44:41 +02001389 $zip->newStream( Zip64 => 1, TextFlag => 1, Method => $_COMPRESSION_METHOD, Append => 1, Name => "$_root_dir$dir/$_tokens_dir/$_tokens_file" )
1390 or die "ERROR ('$_root_dir$dir/$_tokens_dir/$_tokens_file'): zip failed: $ZipError\n";
Peter Hardersd892a582020-02-12 15:45:22 +01001391
Peter Harders6f526a32020-06-29 21:44:41 +02001392 $output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-model href=\"span.rng\" type=\"application/xml\""
1393 ." schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n\n<layer docid=\""
1394 .decode_utf8($text_id_esc)."\" xmlns=\"http://ids-mannheim.de/ns/KorAP\" version=\"KorAP-0.4\">\n <spanList>\n";
Peter Hardersd892a582020-02-12 15:45:22 +01001395
1396 $c = 0;
1397
Peter Harders6f526a32020-06-29 21:44:41 +02001398 foreach $ref ( @tokens ){
Peter Hardersd892a582020-02-12 15:45:22 +01001399
Peter Harders6f526a32020-06-29 21:44:41 +02001400 # if array '@{$ref}' doesn't contain attributes, then the number of elements in this array is 4 (name, from, to, rec_level), otherwise >4
1401 ( @{$ref} == 4 )?( $idx = 1 ):( $idx = @{$ref}-3 );
Peter Hardersd892a582020-02-12 15:45:22 +01001402
Peter Harders6f526a32020-06-29 21:44:41 +02001403 # 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())
1404 if ( $#tokens == $c && ${$ref}[ $idx ] == ${$ref}[ $idx+1 ] + 1 ){
1405
1406 ${$ref}[ $idx ] = ${$ref}[ $idx+1 ]; # TODO: check
Peter Hardersd892a582020-02-12 15:45:22 +01001407 }
Peter Hardersd892a582020-02-12 15:45:22 +01001408
Peter Harders6f526a32020-06-29 21:44:41 +02001409 # l (level): insert information about depth of element in XML-tree (top element = level 1)
1410 $output .= " <span id=\"s$c\" from=\"${$ref}[ $idx ]\" to=\"${$ref}[ $idx+1 ]\" l=\"${$ref}[ $idx+2 ]\">\n"
1411 ." <fs type=\"lex\" xmlns=\"http://www.tei-c.org/ns/1.0\">\n"
1412 ." <f name=\"lex\">\n";
Peter Hardersd892a582020-02-12 15:45:22 +01001413
Peter Harders6f526a32020-06-29 21:44:41 +02001414 if ( $idx > 2 ){ # attributes
1415
Peter Hardersd892a582020-02-12 15:45:22 +01001416 $output .= " <fs>\n";
1417
Peter Harders6f526a32020-06-29 21:44:41 +02001418 for ( $att_idx = 1; $att_idx < $idx; $att_idx += 2 ){
Peter Hardersd892a582020-02-12 15:45:22 +01001419
Peter Harders6f526a32020-06-29 21:44:41 +02001420 ${$ref}[ $att_idx+1 ] =~ s/(&|<|>)/$ent{$1}/g; # ... <w lemma="&gt;" ana="PUNCTUATION">&gt;</w> ...
1421 # the '&gt;' is translated to '>' and hence the result would be '<f name="lemma">></f>'
Peter Hardersd892a582020-02-12 15:45:22 +01001422
Peter Harders6f526a32020-06-29 21:44:41 +02001423 if ( $_INLINE_ANNOT && ${$ref}[ $att_idx ] eq "$_INLINE_ATT_RD" ){
Peter Hardersd892a582020-02-12 15:45:22 +01001424
Peter Harders6f526a32020-06-29 21:44:41 +02001425 ${$ref}[ $att_idx+1 ] =~ /^([^ ]+)(?: (.+))?$/;
1426
1427 die "ERROR (write_tokens()): unexpected format! => Aborting ... (att: ${$ref}[ $att_idx+1 ])\n"
1428 if ( $_INLINE_POS_WR && not defined $1 ) || ( $_INLINE_MSD_WR && not defined $2 );
1429
1430 if ( "$_INLINE_POS_WR" ){
1431
1432 $output .= " <f name=\"$_INLINE_POS_WR\">";
Peter Hardersd892a582020-02-12 15:45:22 +01001433 $output .= "$1" if defined $1;
1434 $output .= "</f>\n";
1435 }
Peter Harders6f526a32020-06-29 21:44:41 +02001436
1437 if ( "$_INLINE_MSD_WR" ){
1438
1439 $output .= " <f name=\"$_INLINE_MSD_WR\">";
Peter Hardersd892a582020-02-12 15:45:22 +01001440 $output .= "$2" if defined $2;
1441 $output .= "</f>\n";
1442 }
1443
Peter Harders6f526a32020-06-29 21:44:41 +02001444 } elsif ( $_INLINE_ANNOT && "$_INLINE_LEM_RD" && ${$ref}[ $att_idx ] eq "$_INLINE_LEM_RD" ){
Peter Hardersd892a582020-02-12 15:45:22 +01001445
Peter Harders6f526a32020-06-29 21:44:41 +02001446 $output .= " <f name=\"$_INLINE_LEM_WR\">${$ref}[ $att_idx+1 ]</f>\n";
Peter Hardersd892a582020-02-12 15:45:22 +01001447
Peter Harders6f526a32020-06-29 21:44:41 +02001448 } else { # all other attributes
Peter Hardersd892a582020-02-12 15:45:22 +01001449
Peter Harders6f526a32020-06-29 21:44:41 +02001450 $output .= " <f name=\"${$ref}[$att_idx]\">${$ref}[ $att_idx+1 ]</f>\n"; # attribute (at index $att_idx) with value (at index $att_idx+1)
Peter Hardersd892a582020-02-12 15:45:22 +01001451 }
1452
Peter Harders6f526a32020-06-29 21:44:41 +02001453 } # end: for
Peter Hardersd892a582020-02-12 15:45:22 +01001454
1455 $output .= " </fs>\n";
Peter Harders6f526a32020-06-29 21:44:41 +02001456
1457 } # fi: attributes
Peter Hardersd892a582020-02-12 15:45:22 +01001458
1459 $output .= " </f>\n </fs>\n </span>\n";
1460
1461 $c++;
1462
Peter Harders6f526a32020-06-29 21:44:41 +02001463 } # end: foreach
Peter Hardersd892a582020-02-12 15:45:22 +01001464
1465 $output .= " </spanList>\n</layer>";
1466
Peter Harders6f526a32020-06-29 21:44:41 +02001467 $output = encode_utf8( $output );
Peter Hardersd892a582020-02-12 15:45:22 +01001468
Peter Harders6f526a32020-06-29 21:44:41 +02001469 $zip->print( "$output" );
Peter Hardersd892a582020-02-12 15:45:22 +01001470
Peter Harders6f526a32020-06-29 21:44:41 +02001471 #print STDERR "$0: write_tokens(): DONE\n";
Peter Hardersd892a582020-02-12 15:45:22 +01001472
Peter Harders6f526a32020-06-29 21:44:41 +02001473} # end: sub write_tokens
Peter Hardersd892a582020-02-12 15:45:22 +01001474
Peter Hardersd892a582020-02-12 15:45:22 +01001475
Peter Harders6f526a32020-06-29 21:44:41 +02001476sub delHTMLcom { # remove HTML comments
1477
1478 # the source code part where $tc is used, leads to the situation, that comments can produce an additional blank, which
1479 # sometimes is not desirable (e.g.: '...<!-- comment -->\n<w>token</w>...' would lead to '... <w>token</w>...' in $buf_in).
1480 # removing comments before processing the line, prevents this situation.
1481
1482 my ( $pfx, $sfx );
1483
1484 while ( $_[0] =~ s/<!--.*?-->//g ){}; # remove all comments in actual line
1485
1486 if ( $_[0] =~ /^(.*)<!--/ && $_[0] !~ /-->/ ){ # remove comment spanning over several lines
1487
1488 $pfx = $1;
1489
1490 while ( $_[0] = <> ){
1491
1492 if ( $_[0] =~ /-->(.*)$/ ){
1493 $sfx = $1; last
1494 }
1495
1496 }
1497
1498 $_[0] = "$pfx$sfx";
1499
1500 }
1501
1502 if ( $_[0] =~ s/^\s*$// ){ # get next line and feed it also to this sub, if actual line is empty or only contains whitespace
1503
1504 $_[0] = <>; delHTMLcom ( $_[0] );
1505 }
1506}
1507
1508
1509## DEPRECATED ($_GEN_TOK_BAS: only IDS-intern)
Peter Hardersd892a582020-02-12 15:45:22 +01001510sub startTokenizer {
1511 $pid = open2($chld_out, $chld_in, 'java -cp '. join(":", ".", glob(&dirname(__FILE__)."/../target/*.jar"))." de.ids_mannheim.korap.tokenizer.KorAPTokenizerImpl");
1512 $select = IO::Select->new();
1513 $select->add(*$chld_out);
1514}
Peter Harders6f526a32020-06-29 21:44:41 +02001515##
Akrond949e182020-02-14 12:23:57 +01001516
1517__END__
1518
1519=pod
1520
1521=encoding utf8
1522
1523=head1 NAME
1524
1525tei2korapxml - Conversion of TEI P5 based formats to KorAP-XML
1526
1527=head1 SYNOPSIS
1528
1529 cat corpus.i5.xml | tei2korapxml > corpus.korapxml.zip
1530
1531=head1 DESCRIPTION
1532
1533C<tei2korapxml> is a script to convert TEI P5 and I5 based documents
Peter Harders6f526a32020-06-29 21:44:41 +02001534
Akrond949e182020-02-14 12:23:57 +01001535to the KorAP-XML format. If no specific input is defined, data is
Peter Harders6f526a32020-06-29 21:44:41 +02001536
Akrond949e182020-02-14 12:23:57 +01001537read from C<STDIN>. If no specific output is defined, data is written
Peter Harders6f526a32020-06-29 21:44:41 +02001538
Akrond949e182020-02-14 12:23:57 +01001539to C<STDOUT>.
Peter Harders6f526a32020-06-29 21:44:41 +02001540
Akrond949e182020-02-14 12:23:57 +01001541This program is usually called from inside another script.
1542
1543=head1 INSTALLATION
1544
1545C<tei2korapxml> requires L<libxml2-dev> bindings to build. When
Peter Harders6f526a32020-06-29 21:44:41 +02001546
Akrond949e182020-02-14 12:23:57 +01001547these bindings are available, the preferred way to install the script is
Peter Harders6f526a32020-06-29 21:44:41 +02001548
Akrond949e182020-02-14 12:23:57 +01001549to use L<cpanm|App::cpanminus>.
1550
1551 $ cpanm https://github.com/KorAP/KorAP-XML-TEI.git
1552
1553In case everything went well, the C<tei2korapxml> tool will
Peter Harders6f526a32020-06-29 21:44:41 +02001554
Akrond949e182020-02-14 12:23:57 +01001555be available on your command line immediately.
Peter Harders6f526a32020-06-29 21:44:41 +02001556
Akrond949e182020-02-14 12:23:57 +01001557Minimum requirement for L<KorAP::XML::TEI> is Perl 5.16.
1558
1559=head1 OPTIONS
1560
1561=over 2
1562
1563=item B<--base|-b>
1564
1565The base directory for output. Defaults to C<.>.
1566
1567=item B<--help|-h>
1568
1569Print help information.
1570
1571=item B<--version|-v>
1572
1573Print version information.
1574
1575=back
1576
1577=head1 COPYRIGHT AND LICENSE
1578
1579Copyright (C) 2020, L<IDS Mannheim|https://www.ids-mannheim.de/>
1580
1581Author: Peter Harders
1582
1583Contributors: Marc Kupietz, Carsten Schnober, Nils Diewald
1584
1585L<KorAP::XML::TEI> is developed as part of the L<KorAP|https://korap.ids-mannheim.de/>
Peter Harders6f526a32020-06-29 21:44:41 +02001586
Akrond949e182020-02-14 12:23:57 +01001587Corpus Analysis Platform at the
Peter Harders6f526a32020-06-29 21:44:41 +02001588
Akrond949e182020-02-14 12:23:57 +01001589L<Leibniz Institute for the German Language (IDS)|http://ids-mannheim.de/>,
Peter Harders6f526a32020-06-29 21:44:41 +02001590
Akrond949e182020-02-14 12:23:57 +01001591member of the
Peter Harders6f526a32020-06-29 21:44:41 +02001592
Akrond949e182020-02-14 12:23:57 +01001593L<Leibniz-Gemeinschaft|http://www.leibniz-gemeinschaft.de/>.
1594
1595This program is free software published under the
Peter Harders6f526a32020-06-29 21:44:41 +02001596
Akrond949e182020-02-14 12:23:57 +01001597L<BSD-2 License|https://raw.githubusercontent.com/KorAP/KorAP-XML-TEI/master/LICENSE>.
1598
1599=cut