blob: 53c4ea87dfb266d0dd64528f91490c59f3a3dc66 [file] [log] [blame]
Akron9cb13942020-02-14 07:39:54 +01001#!/usr/bin/env perl
Peter Hardersd892a582020-02-12 15:45:22 +01002use strict;
3use warnings;
Peter Harders6f526a32020-06-29 21:44:41 +02004
Akron3378dfd2020-08-01 15:01:36 +02005use Log::Any '$log';
6use Log::Any::Adapter;
Peter Harders6f526a32020-06-29 21:44:41 +02007use Pod::Usage;
8use Getopt::Long qw(GetOptions :config no_auto_abbrev);
9
10use File::Basename qw(dirname);
Peter Hardersd892a582020-02-12 15:45:22 +010011
Akroneaa96232020-10-15 17:06:15 +020012use Encode qw(decode);
Peter Hardersd892a582020-02-12 15:45:22 +010013
Peter Hardersd892a582020-02-12 15:45:22 +010014use XML::CompactTree::XS;
15use XML::LibXML::Reader;
Peter Hardersd892a582020-02-12 15:45:22 +010016
Akron4f67cd42020-07-02 12:27:58 +020017use FindBin;
18BEGIN {
19 unshift @INC, "$FindBin::Bin/../lib";
20};
21
Marc Kupietz8a954e52021-02-16 22:03:07 +010022use KorAP::XML::TEI qw!remove_xml_comments replace_entities!;
Akron8b511f92020-07-09 17:28:08 +020023use KorAP::XML::TEI::Tokenizer::External;
Akrond9627472020-07-09 16:53:09 +020024use KorAP::XML::TEI::Tokenizer::Conservative;
25use KorAP::XML::TEI::Tokenizer::Aggressive;
Akron7501ca02020-08-01 21:05:25 +020026use KorAP::XML::TEI::Annotations::Collector;
Akrona10ad592020-08-03 11:20:23 +020027use KorAP::XML::TEI::Data;
Akron85717512020-07-08 11:19:19 +020028use KorAP::XML::TEI::Zipper;
Akronf57ed812020-07-27 10:37:52 +020029use KorAP::XML::TEI::Header;
Peter Hardersd892a582020-02-12 15:45:22 +010030
Marc Kupietz1e882fb2020-09-09 00:05:46 +020031eval {
32 require KorAP::XML::TEI::Tokenizer::KorAP;
33 1;
34};
Peter Harders1c5ce152020-07-22 18:02:50 +020035
Marc Kupietza1421f02021-02-18 15:32:38 +010036our $VERSION = '1.00';
Peter Harders6f526a32020-06-29 21:44:41 +020037
Akrond949e182020-02-14 12:23:57 +010038our $VERSION_MSG = "\ntei2korapxml - v$VERSION\n";
39
Akronb3649472020-09-29 08:24:46 +020040# Set to 1 for minimal more debug output (no need to be parametrized)
41use constant DEBUG => $ENV{KORAPXMLTEI_DEBUG} // 0;
Peter Hardersd892a582020-02-12 15:45:22 +010042
Peter Harders6f526a32020-06-29 21:44:41 +020043# Parse options from the command line
Peter Hardersd892a582020-02-12 15:45:22 +010044GetOptions(
Akron75d63142021-02-23 18:40:56 +010045 "root|r=s" => \(my $_root_dir = '.'),
46 "input|i=s" => \(my $input_fname = ''),
47 'tokenizer-call|tc=s' => \(my $tokenizer_call),
48 'tokenizer-korap|tk' => \(my $tokenizer_korap),
49 'tokenizer-internal|ti' => \(my $_GEN_TOK_INT),
50 'use-tokenizer-sentence-splits|s' => \(my $use_tokenizer_sentence_splits),
51 'inline-tokens=s' => \(my $inline_tokens = 'tokens#morpho'),
52 'inline-structures=s' => \(my $inline_structures = 'struct#structure'),
53 'skip-inline-tokens' => \(my $skip_inline_tokens = 0),
54 'base-foundry=s' => \(my $_tok_dir = 'base'),
55 'data-file=s' => \(my $_data_file = 'data'),
56 'header-file=s' => \(my $_header_file = 'header'),
57 'tokens-file=s' => \(my $_tok_file_ext = 'tokens'),
58 'log|l=s' => \(my $log_level = 'notice'),
59 'help|h' => sub {
Akrond949e182020-02-14 12:23:57 +010060 pod2usage(
61 -verbose => 99,
62 -sections => 'NAME|DESCRIPTION|SYNOPSIS|ARGUMENTS|OPTIONS',
63 -msg => $VERSION_MSG,
64 -output => '-'
65 )
66 },
67 'version|v' => sub {
68 pod2usage(
69 -verbose => 0,
70 -msg => $VERSION_MSG,
71 -output => '-'
72 )
73 }
Peter Hardersd892a582020-02-12 15:45:22 +010074);
75
Akronb87c58d2021-02-23 17:23:30 +010076# Establish logger
Marc Kupietz44b1f252020-11-26 16:31:40 +010077binmode(STDERR, ":encoding(UTF-8)");
Akron3378dfd2020-08-01 15:01:36 +020078Log::Any::Adapter->set('Stderr', log_level => $log_level);
79
Akronb3649472020-09-29 08:24:46 +020080$log->notice('Debugging is activated') if DEBUG;
81
Akron0529e512021-02-22 09:55:35 +010082# tag (without attributes), which contains the primary text
83my $_TEXT_BODY = 'text';
Akron0c41ab32020-09-29 07:33:33 +020084# optional
Akron09e0b2c2020-07-28 15:57:01 +020085
Akron0529e512021-02-22 09:55:35 +010086# TODO: IDS-specific (and redundant)
87my $_HEADER_TAG = 'idsHeader';
Akron0c41ab32020-09-29 07:33:33 +020088
Marc Kupietz985da0c2021-02-15 19:29:50 +010089if ($use_tokenizer_sentence_splits && !$tokenizer_korap) {
90 die $log->fatal("Sentence splitting is currently only supported by KorAP tokenizer (use -tk to activate it");
Akronb87c58d2021-02-23 17:23:30 +010091};
Marc Kupietz985da0c2021-02-15 19:29:50 +010092
Akron0c41ab32020-09-29 07:33:33 +020093my $ext_tok;
94if ($tokenizer_call) {
95 $ext_tok = KorAP::XML::TEI::Tokenizer::External->new($tokenizer_call);
96}
Marc Kupietz1e882fb2020-09-09 00:05:46 +020097
Akron0c41ab32020-09-29 07:33:33 +020098elsif ($tokenizer_korap) {
Marc Kupietz985da0c2021-02-15 19:29:50 +010099 $ext_tok = KorAP::XML::TEI::Tokenizer::KorAP->new($use_tokenizer_sentence_splits);
Akron0c41ab32020-09-29 07:33:33 +0200100};
Peter Harders6f526a32020-06-29 21:44:41 +0200101##
102
Akron0c41ab32020-09-29 07:33:33 +0200103
Akron4e3c7e32021-02-18 15:19:53 +0100104#
105# ~~~ constants ~~~
106#
107
108
Akron8b511f92020-07-09 17:28:08 +0200109## intern tokenization
Akronb87c58d2021-02-23 17:23:30 +0100110my $aggr_tok = KorAP::XML::TEI::Tokenizer::Aggressive->new;
111my $cons_tok = KorAP::XML::TEI::Tokenizer::Conservative->new;
Peter Harders41c35622020-07-12 01:16:22 +0200112##
113
Akrondd0be8f2021-02-18 19:29:41 +0100114# Name of the directory and the file containing all inline structure informations
115# except for $_TOKEN_TAG information
116my ($_structure_dir, $_structure_file) = split '#', $inline_structures . '#structure';
Akrondd0be8f2021-02-18 19:29:41 +0100117
Akron1a5271a2021-02-18 13:18:15 +0100118# Name of the directory and the file containing all inline token informations
119# i.e. tokens of the $_TOKENS_TAG, if $_TOKENS_PROC is set
120my ($_tokens_dir, $_tokens_file) = split '#', $inline_tokens . '#morpho';
Akron1a5271a2021-02-18 13:18:15 +0100121
Akronb87c58d2021-02-23 17:23:30 +0100122# name of the tag containing all information stored in $_tokens_file
123my $_TOKENS_TAG = "w";
Peter Harders6f526a32020-06-29 21:44:41 +0200124
Akron4e3c7e32021-02-18 15:19:53 +0100125# Handling inline annotations (inside $_TOKENS_TAG)
Akronb87c58d2021-02-23 17:23:30 +0100126my $_INLINE_ANNOT = $ENV{KORAPXMLTEI_INLINE} ? 1 : 0;
127
128# Initialize Token- and Structure-Collector
129my $tokens = KorAP::XML::TEI::Annotations::Collector->new;
130my $structures = KorAP::XML::TEI::Annotations::Collector->new;
131
132# Initialize Data-Collector
133my $data = KorAP::XML::TEI::Data->new;
134
135# Initialize zipper
136my $zipper = KorAP::XML::TEI::Zipper->new($_root_dir);
Akron09e0b2c2020-07-28 15:57:01 +0200137
Peter Harders6f526a32020-06-29 21:44:41 +0200138
139#
140# ~~~ variables ~~~
141#
142
Akron09e0b2c2020-07-28 15:57:01 +0200143
Peter Harders6f526a32020-06-29 21:44:41 +0200144my $input_fh; # input file handle (default: stdin)
145
Peter Harders6f526a32020-06-29 21:44:41 +0200146my $dir; # text directory (below $_root_dir)
Peter Harders6f526a32020-06-29 21:44:41 +0200147
Akron0c41ab32020-09-29 07:33:33 +0200148my ( $text_id,
149 $text_id_esc ); # '$text_id_esc' = escaped version of $text_id
Peter Harders6f526a32020-06-29 21:44:41 +0200150
Peter Harders6f526a32020-06-29 21:44:41 +0200151# these are only used inside recursive function 'retr_info'
Akron4e3c7e32021-02-18 15:19:53 +0100152my ( $_IDX, # value is set dependent on DEBUG - for extracting array of child elements from element in $tree_data
Peter Harders6f526a32020-06-29 21:44:41 +0200153 $e, # element from $tree_data
Peter Harders6f526a32020-06-29 21:44:41 +0200154 ## variables for handling ~ whitespace related issue ~ (it is sometimes necessary, to correct the from-values for some tags)
155 $add_one, # ...
Akron7501ca02020-08-01 21:05:25 +0200156 $fval, # ...
Peter Harders41c35622020-07-12 01:16:22 +0200157 %ws); # hash for indices of whitespace-nodes (needed to recorrect from-values)
158 # idea: when closing element, check if it's from-index minus 1 refers to a whitespace-node
Peter Harders6f526a32020-06-29 21:44:41 +0200159 # (means: 'from-index - 1' is a key in %ws).
160 # if this is _not_ the case, then the from-value is one to high => correct it by substracting 1
161
Peter Harders6f526a32020-06-29 21:44:41 +0200162
163#
164# ~~~ main ~~~
165#
166
167# ~ initializations ~
168
Akron4e3c7e32021-02-18 15:19:53 +0100169# Include line numbers in elements of $tree_data for debugging
170DEBUG ? ($_IDX = 5) : ($_IDX = 4);
Peter Harders6f526a32020-06-29 21:44:41 +0200171
Akron7501ca02020-08-01 21:05:25 +0200172$fval = 0;
Peter Harders6f526a32020-06-29 21:44:41 +0200173
Peter Harders6f526a32020-06-29 21:44:41 +0200174# ~ read input and write output (text by text) ~
Peter Hardersd892a582020-02-12 15:45:22 +0100175
Akron347be812020-09-29 07:52:52 +0200176my $tl = 0; # text line (needed for whitespace handling)
Peter Hardersd892a582020-02-12 15:45:22 +0100177
Akron347be812020-09-29 07:52:52 +0200178$input_fh = *STDIN; # input file handle (default: stdin)
Peter Hardersd892a582020-02-12 15:45:22 +0100179
Akron347be812020-09-29 07:52:52 +0200180# Maybe not necessary
181$data->reset;
Peter Hardersd892a582020-02-12 15:45:22 +0100182
Akrondafaa7a2021-02-19 15:17:58 +0100183$dir = '';
Peter Hardersd892a582020-02-12 15:45:22 +0100184
Akron347be812020-09-29 07:52:52 +0200185if ( $input_fname ne '' ){
186 unless (open($input_fh, '<', $input_fname)) {
187 die $log->fatal("File '$input_fname' could not be opened.");
188 };
189}
Peter Harders6f526a32020-06-29 21:44:41 +0200190
Akronf8088e62021-02-18 16:18:59 +0100191# Prevents segfaulting (see notes on segfault prevention)
Akron347be812020-09-29 07:52:52 +0200192binmode $input_fh;
Peter Harders6f526a32020-06-29 21:44:41 +0200193
Akrond20898f2021-02-19 15:52:17 +0100194my $sfx;
Akron347be812020-09-29 07:52:52 +0200195my $pos;
Akroneaa96232020-10-15 17:06:15 +0200196my $input_enc = 'UTF-8';
Akron347be812020-09-29 07:52:52 +0200197my $l = length('</' . $_TEXT_BODY) + 1;
Peter Harders6f526a32020-06-29 21:44:41 +0200198
Akron347be812020-09-29 07:52:52 +0200199# ~ loop (reading input document) ~
Peter Harders6f526a32020-06-29 21:44:41 +0200200
Akron347be812020-09-29 07:52:52 +0200201MAIN: while ( <$input_fh> ){
202
203 $_ = remove_xml_comments( $input_fh, $_ ); # remove HTML (multi-line) comments (<!--...-->)
204
Akroneaa96232020-10-15 17:06:15 +0200205 # Set input encoding
206 if ( index($_, '<?xml') == 0 && $_ =~ /\sencoding=(['"])([^\1]+?)\1/) {
207 $input_enc = $2;
208 next;
209 };
210
211 $_ = decode($input_enc, $_);
Marc Kupietz8a954e52021-02-16 22:03:07 +0100212 $_ = replace_entities($_);
Akroneaa96232020-10-15 17:06:15 +0200213
Akron347be812020-09-29 07:52:52 +0200214 if ( index($_, $_TEXT_BODY) >= 0 && m#^(.*)<${_TEXT_BODY}(?: [^>]*)?>(.*)$# ){
215
216 # ~ start of text body ~
217
Akron347be812020-09-29 07:52:52 +0200218 $sfx = $2;
219
Akrond20898f2021-02-19 15:52:17 +0100220 if ($1 !~ /^\s*$/ || $sfx !~ /^\s*$/) {
Akron347be812020-09-29 07:52:52 +0200221 die $log->fatal("input line number $.: " .
222 "line with opening text-body tag '${_TEXT_BODY}' " .
223 "contains additional information ... => Aborting (line=$_)");
Akron0bb7e722020-09-29 07:48:33 +0200224 };
Peter Harders6f526a32020-06-29 21:44:41 +0200225
Akron347be812020-09-29 07:52:52 +0200226 # text body data extracted from input document ($input_fh), further processed by XML::LibXML::Reader
227 my $buf_in = '';
Peter Harders90157342020-07-01 21:05:14 +0200228
Akron347be812020-09-29 07:52:52 +0200229 # Iterate over all lines in the text body
230 while (<$input_fh>) {
Peter Harders90157342020-07-01 21:05:14 +0200231
Akron347be812020-09-29 07:52:52 +0200232 $_ = remove_xml_comments( $input_fh, $_ );
Akroneaa96232020-10-15 17:06:15 +0200233 $_ = decode($input_enc, $_);
Marc Kupietz8a954e52021-02-16 22:03:07 +0100234 $_ = replace_entities($_);
Peter Harders6f526a32020-06-29 21:44:41 +0200235
Akron347be812020-09-29 07:52:52 +0200236 # ~ end of text body ~
237 if (($pos = index($_, '</' . $_TEXT_BODY)) >= 0) {
Peter Harders6f526a32020-06-29 21:44:41 +0200238
Akron91705d72021-02-19 10:59:45 +0100239 # write data.xml, structure.xml and evtl. morpho.xml and/or tokenization files
Peter Harders6f526a32020-06-29 21:44:41 +0200240
Akron347be812020-09-29 07:52:52 +0200241 if ((substr($_, 0, $pos) . substr($_, $l + $pos)) !~ /^\s*$/) {
242 die $log->fatal("input line number $.: " .
243 "line with closing text-body tag '${_TEXT_BODY}'".
244 " contains additional information ... => Aborting (line=$_)");
245 };
Peter Harders6f526a32020-06-29 21:44:41 +0200246
Akrondafaa7a2021-02-19 15:17:58 +0100247 if ($dir eq '') {
248 $log->warn("Maybe empty textSigle => skipping this text ...\ndata=" . substr($data->data, 0, 200));
249 next MAIN;
250 };
Peter Harders6f526a32020-06-29 21:44:41 +0200251
Akrondafaa7a2021-02-19 15:17:58 +0100252 my $reader = XML::LibXML::Reader->new(
253 string => "<text>$buf_in</text>",
254 huge => 1
255 );
256
257 # See notes on whitespace handling
258 my $param = XCT_DOCUMENT_ROOT | XCT_IGNORE_COMMENTS | XCT_ATTRIBUTE_ARRAY;
259
260 # XCT_LINE_NUMBERS is only needed for debugging
261 # (see XML::CompactTree::XS)
262 $param |= XCT_LINE_NUMBERS if DEBUG;
263 my $tree_data = XML::CompactTree::XS::readSubtreeToPerl($reader, $param);
264
265 $structures->reset;
266
Akron75d63142021-02-23 18:40:56 +0100267 $tokens->reset unless $skip_inline_tokens;
Akrondafaa7a2021-02-19 15:17:58 +0100268
269 # ~ whitespace related issue ~
270 $add_one = 0;
271 %ws = ();
272
273 # ~ recursion ~
274 retr_info(1, \$tree_data->[2] ); # parse input data
275
276 if (DEBUG) {
277 $log->debug("Writing (utf8-formatted) xml file $dir/${_data_file}.xml");
278 };
279
280 # ~ write data.xml ~
281 $data->to_zip(
282 $zipper->new_stream("$dir/${_data_file}.xml"),
283 $text_id_esc
284 );
285
286 # ~ tokenization ~
Akron9df4a242021-02-19 15:31:16 +0100287 if ($ext_tok) {
Akrondafaa7a2021-02-19 15:17:58 +0100288
289 # Tokenize and output
290 $ext_tok->tokenize($data->data)->to_zip(
291 $zipper->new_stream("$dir/$_tok_dir/${_tok_file_ext}.xml"),
292 $text_id_esc
Akrond20898f2021-02-19 15:52:17 +0100293 );
Akrondafaa7a2021-02-19 15:17:58 +0100294 };
Peter Harders6f526a32020-06-29 21:44:41 +0200295
Akrondafaa7a2021-02-19 15:17:58 +0100296 if ($_GEN_TOK_INT) {
Peter Harders6f526a32020-06-29 21:44:41 +0200297
Akrondafaa7a2021-02-19 15:17:58 +0100298 # Tokenize and output
299 $cons_tok->tokenize($data->data)->to_zip(
300 $zipper->new_stream("$dir/$_tok_dir/" . $cons_tok->name . '.xml'),
Akron347be812020-09-29 07:52:52 +0200301 $text_id_esc
302 );
Akron598d1a72020-08-02 17:33:31 +0200303
Akrondafaa7a2021-02-19 15:17:58 +0100304 $aggr_tok->tokenize($data->data)->to_zip(
305 $zipper->new_stream("$dir/$_tok_dir/" . $aggr_tok->name . '.xml'),
306 $text_id_esc
307 );
Akron598d1a72020-08-02 17:33:31 +0200308
Akrondafaa7a2021-02-19 15:17:58 +0100309 $aggr_tok->reset;
310 $cons_tok->reset;
311 };
Akrona10ad592020-08-03 11:20:23 +0200312
Akrondafaa7a2021-02-19 15:17:58 +0100313 if ($use_tokenizer_sentence_splits) {
314 $ext_tok->sentencize_from_previous_input($structures);
Akron9df4a242021-02-19 15:31:16 +0100315 };
Akron598d1a72020-08-02 17:33:31 +0200316
Akrondafaa7a2021-02-19 15:17:58 +0100317 # ~ write structures ~
318 if (!$structures->empty) {
319 $structures->to_zip(
Akronb87c58d2021-02-23 17:23:30 +0100320 $zipper->new_stream("$dir/$_structure_dir/${_structure_file}.xml"),
Akrondafaa7a2021-02-19 15:17:58 +0100321 $text_id_esc,
322 2 # = structure serialization
323 );
324 };
325
326 # ~ write tokens ~
Akron75d63142021-02-23 18:40:56 +0100327 unless ($skip_inline_tokens || $tokens->empty) {
Akrondafaa7a2021-02-19 15:17:58 +0100328 $tokens->to_zip(
Akronb87c58d2021-02-23 17:23:30 +0100329 $zipper->new_stream("$dir/$_tokens_dir/${_tokens_file}.xml"),
Akrondafaa7a2021-02-19 15:17:58 +0100330 $text_id_esc,
331 $_INLINE_ANNOT # Either 0 = tokens without inline or 1 = tokens with inline
332 );
333 };
334
335 # reinit.
336 $dir = '';
337
338 # Maybe not necessary
339 $data->reset;
340
Akron347be812020-09-29 07:52:52 +0200341 next MAIN;
Akron598d1a72020-08-02 17:33:31 +0200342 };
343
Akron347be812020-09-29 07:52:52 +0200344 # ~ inside text body ~
Peter Harders6f526a32020-06-29 21:44:41 +0200345
Akron347be812020-09-29 07:52:52 +0200346 # ~ whitespace handling ~
Peter Harders6f526a32020-06-29 21:44:41 +0200347
Akronf8088e62021-02-18 16:18:59 +0100348 # Fix whitespaces (see notes on whitespace fixing)
Peter Hardersd892a582020-02-12 15:45:22 +0100349
Akronf8088e62021-02-18 16:18:59 +0100350 # TODO: Maybe it's best, to keep the stripping of whitespace and to just remove the if-clause and to insert a blank by default (with possibly
351 # an option on how newlines in primary text should be handled (stripped or replaced by a whitespace)).
352
353 # Remove consecutive whitespace at beginning and end (mostly one newline)
354 s/^\s+//; s/\s+$//;
Akronf57ed812020-07-27 10:37:52 +0200355
Akron347be812020-09-29 07:52:52 +0200356 ### NOTE: this is only relevant, if a text consists of more than one line
357 ### TODO: find a better solution, or create a warning, if a text has more than one line ($tl > 1)
358 ### do testing with 2 different corpora (one with only one-line texts, the other with several lines per text)
359 if (m/<[^>]+>[^<]/) { # line contains at least one tag with at least one character contents
Akronf57ed812020-07-27 10:37:52 +0200360
Akron347be812020-09-29 07:52:52 +0200361 $tl++; # counter for text lines
Akronf57ed812020-07-27 10:37:52 +0200362
Akron347be812020-09-29 07:52:52 +0200363 s/^(.)/ $1/ if $tl > 1; # insert blank before 1st character (for 2nd line and consecutive lines)
364 }
365 ###
Akronf57ed812020-07-27 10:37:52 +0200366
Akron347be812020-09-29 07:52:52 +0200367 # add line to buffer
368 $buf_in .= $_;
369 };
Akronf57ed812020-07-27 10:37:52 +0200370
Akron0529e512021-02-22 09:55:35 +0100371 } elsif (m#^(.*)(\<${_HEADER_TAG}[^>]*?type=["'].*)$#) {
Akronf57ed812020-07-27 10:37:52 +0200372
Akron347be812020-09-29 07:52:52 +0200373 # ~ start of header ~
Akron347be812020-09-29 07:52:52 +0200374 my $content = "$2\n";
Akronf57ed812020-07-27 10:37:52 +0200375
Akrond20898f2021-02-19 15:52:17 +0100376 if ($1 !~ /^\s*$/) {
Akron347be812020-09-29 07:52:52 +0200377 die $log->fatal("input line number $.: " .
378 "line with opening header tag" .
379 " is not in expected format ... => Aborting (line=$_)");
380 };
381
382 # Parse header
Akroneaa96232020-10-15 17:06:15 +0200383 my $header = KorAP::XML::TEI::Header->new($content, $input_enc)->parse($input_fh);
Akron347be812020-09-29 07:52:52 +0200384
385 # Header was parseable
386 if ($header) {
387
388 # Write header to zip
Akron26a71522021-02-19 10:27:37 +0100389 my $file = $header->dir . '/' . $_header_file . '.xml';
Akron347be812020-09-29 07:52:52 +0200390
Akronb3649472020-09-29 08:24:46 +0200391 $log->debug("Writing file $file") if DEBUG;
Akron347be812020-09-29 07:52:52 +0200392
393 $header->to_zip($zipper->new_stream($file));
394
395 # Header is for text level
396 if ($header->type eq 'text') {
397
398 # Remember dir and sigles
399 $dir = $header->dir;
400 $text_id = $header->id;
401 $text_id_esc = $header->id_esc;
402
403 # log output for seeing progression
Akron91577922021-02-19 10:32:54 +0100404 $log->notice("$0: text_id=$text_id");
Akron347be812020-09-29 07:52:52 +0200405
406 $tl = 0; # reset (needed for ~ whitespace handling ~)
Akronf57ed812020-07-27 10:37:52 +0200407 }
408 }
Akron347be812020-09-29 07:52:52 +0200409 }
410} #end: while
Peter Hardersd892a582020-02-12 15:45:22 +0100411
Akron347be812020-09-29 07:52:52 +0200412$zipper->close;
Peter Harders6f526a32020-06-29 21:44:41 +0200413
Akron9df4a242021-02-19 15:31:16 +0100414$ext_tok->close if $ext_tok;
Peter Hardersd892a582020-02-12 15:45:22 +0100415
Akron347be812020-09-29 07:52:52 +0200416exit(0);
Peter Hardersd892a582020-02-12 15:45:22 +0100417
Peter Hardersd892a582020-02-12 15:45:22 +0100418
Akrond658df72021-02-18 18:58:56 +0100419# Recursively called function to handle XML tree data
420sub retr_info {
Akron1c4f2202020-07-30 09:28:22 +0200421 # recursion level
422 # (1 = topmost level inside retr_info() = should always be level of tag $_TEXT_BODY)
423 my $rl = shift;
Peter Hardersd892a582020-02-12 15:45:22 +0100424
Akrond658df72021-02-18 18:58:56 +0100425 # Iteration through all array elements
426 # ($_[0] is a reference to an array reference)
427 # See notes on how 'XML::CompactTree::XS' works and
428 # see 'NODE TYPES' in manpage of XML::LibXML::Reader
429 foreach $e (@{${$_[0]}}) {
Peter Hardersd892a582020-02-12 15:45:22 +0100430
Akrond658df72021-02-18 18:58:56 +0100431 # Element node
432 if ($e->[0] == XML_READER_TYPE_ELEMENT) {
Peter Hardersd892a582020-02-12 15:45:22 +0100433
Peter Harders6f526a32020-06-29 21:44:41 +0200434 #~~~~
Peter Harders41c35622020-07-12 01:16:22 +0200435 # from here: tag-node (opening)
Peter Harders6f526a32020-06-29 21:44:41 +0200436 #~~~~
Peter Hardersd892a582020-02-12 15:45:22 +0100437
Akron7501ca02020-08-01 21:05:25 +0200438 # $e->[1] represents the tag name
Akronace12772021-02-19 13:16:26 +0100439 # Skip sentences
Marc Kupietz985da0c2021-02-15 19:29:50 +0100440 if ($use_tokenizer_sentence_splits && $e->[1] eq "s") {
Akronace12772021-02-19 13:16:26 +0100441 if (defined $e->[$_IDX]) {
442 retr_info($rl+1, \$e->[$_IDX]);
443 }
444 next;
Marc Kupietz985da0c2021-02-15 19:29:50 +0100445 }
Peter Hardersd892a582020-02-12 15:45:22 +0100446
Akronace12772021-02-19 13:16:26 +0100447 my $anno = $structures->add_new_annotation($e->[1]);
Peter Hardersd892a582020-02-12 15:45:22 +0100448
Akron7501ca02020-08-01 21:05:25 +0200449 # Add element also to token list
Akron75d63142021-02-23 18:40:56 +0100450 if (!$skip_inline_tokens && $e->[1] eq $_TOKENS_TAG) {
Akron7501ca02020-08-01 21:05:25 +0200451 $tokens->add_annotation($anno);
452 };
Peter Hardersd892a582020-02-12 15:45:22 +0100453
Akrond658df72021-02-18 18:58:56 +0100454 # Handle attributes (if attributes exist)
455 if (defined $e->[3]) {
Peter Hardersd892a582020-02-12 15:45:22 +0100456
Akrond658df72021-02-18 18:58:56 +0100457 # with 'XCT_ATTRIBUTE_ARRAY', $node->[3] is an array reference of the form
458 # [ name1, value1, name2, value2, ....] of attribute names and corresponding values.
459 # note: arrays are faster (see: http://makepp.sourceforge.net/2.0/perl_performance.html)
Akrondac5d932021-02-23 21:12:02 +0100460 for (local $_ = 0; $_ < @{$e->[3]}; $_ += 2) {
Peter Hardersd892a582020-02-12 15:45:22 +0100461
Akrondac5d932021-02-23 21:12:02 +0100462 # '$_' references the 'key' and '$_+1' the 'value'
Akron7501ca02020-08-01 21:05:25 +0200463 $anno->add_attribute(
Akrondac5d932021-02-23 21:12:02 +0100464 @{$e->[3]}[$_, $_ + 1]
Akron7501ca02020-08-01 21:05:25 +0200465 );
Akrond658df72021-02-18 18:58:56 +0100466 };
467 };
Peter Harders6f526a32020-06-29 21:44:41 +0200468
469 # this is, where a normal tag or tokens-tag ($_TOKENS_TAG) starts
Akrona10ad592020-08-03 11:20:23 +0200470 $anno->set_from($data->position + $add_one);
Peter Harders6f526a32020-06-29 21:44:41 +0200471
Akrond658df72021-02-18 18:58:56 +0100472
Peter Harders6f526a32020-06-29 21:44:41 +0200473 #~~~~
Peter Harders41c35622020-07-12 01:16:22 +0200474 # until here: tag-node (opening)
Peter Harders6f526a32020-06-29 21:44:41 +0200475 #~~~~
476
477
Akrond658df72021-02-18 18:58:56 +0100478 # Call function recursively
479 # do no recursion, if $e->[$_IDX] is not defined
480 # (because we have no array of child-nodes, e.g.: <back/>)
481 if (defined $e->[$_IDX]) {
Peter Harders6f526a32020-06-29 21:44:41 +0200482
Akrond658df72021-02-18 18:58:56 +0100483 # Recursion with array of child-nodes
484 retr_info($rl+1, \$e->[$_IDX]);
Peter Harders6f526a32020-06-29 21:44:41 +0200485 }
486
487
488 #~~~~~
Peter Harders41c35622020-07-12 01:16:22 +0200489 # from here: tag-node (closing)
Peter Harders6f526a32020-06-29 21:44:41 +0200490 #~~~~~
491
Akrond658df72021-02-18 18:58:56 +0100492 # NOTE: use $pos, because the offsets are _between_ the characters
493 # (e.g.: word = 'Hello' => from = 0 (before 'H'), to = 5 (after 'o'))
Akrona10ad592020-08-03 11:20:23 +0200494 my $pos = $data->position;
Peter Harders6f526a32020-06-29 21:44:41 +0200495
Akrond658df72021-02-18 18:58:56 +0100496 # Handle structures and tokens
Peter Harders6f526a32020-06-29 21:44:41 +0200497
Akrond658df72021-02-18 18:58:56 +0100498 $fval = $anno->from;
Peter Harders6f526a32020-06-29 21:44:41 +0200499
Peter Harders6f526a32020-06-29 21:44:41 +0200500 # ~ whitespace related issue ~
Akrond658df72021-02-18 18:58:56 +0100501 if ($fval > 0 && not exists $ws{$fval - 1}) {
502
503 # ~ previous node was a text-node ~
504 $anno->set_from($fval - 1);
505 }
506
507 # in case this fails, check input
508 if (($fval - 1) > $pos) {
509 die $log->fatal("text_id='$text_id', " .
510 "processing of structures: " .
511 "from-value ($fval) is 2 or more greater " .
512 "than to-value ($pos) => please check. Aborting");
513 };
514
515 # TODO: find example for which this case applies
516 # maybe this is not necessary anymore, because the above recorrection of the from-value suffices
517 #
518 # TODO: check, if it's better to remove this line and change above check to 'if ($fval - 1) >= $pos;
519 # do testing with bigger corpus excerpt (wikipedia?)
520 $anno->set_from($pos) if $fval == $pos + 1;
521 $anno->set_to($pos);
522 $anno->set_level($rl);
523
524 # Clean up whitespace
Akron0c41ab32020-09-29 07:33:33 +0200525 delete $ws{$fval - 1} if $fval > 0 && exists $ws{$fval - 1};
Peter Hardersd892a582020-02-12 15:45:22 +0100526
527
Peter Harders41c35622020-07-12 01:16:22 +0200528 #~~~~
529 # until here: tag-node (closing)
530 #~~~~
Peter Harders6f526a32020-06-29 21:44:41 +0200531 }
532
Akrond658df72021-02-18 18:58:56 +0100533 # Text node
534 elsif ($e->[0] == XML_READER_TYPE_TEXT){
Peter Harders6f526a32020-06-29 21:44:41 +0200535
Akrond658df72021-02-18 18:58:56 +0100536 $add_one = 1;
537 $data->append($e->[1]);
538 }
539
540 # Whitespace node
541 # (See notes on whitespace handling - regarding XML_READER_TYPE_SIGNIFICANT_WHITESPACE)
542 elsif ($e->[0] == XML_READER_TYPE_SIGNIFICANT_WHITESPACE) {
543
544 # state, that this from-index belongs to a whitespace-node
545 # ('++' doesn't mean a thing here - maybe it could be used for a consistency check)
546 $ws{$data->position}++;
547
548 $add_one = 0;
549 $data->append($e->[1]);
550 }
551
552 # not yet handled type
553 else {
554
555 die $log->fatal('Not yet handled type ($e->[0]=' . $e->[0] . ') ... => Aborting');
556 };
557 };
558};
559
Peter Harders6f526a32020-06-29 21:44:41 +0200560
Akrond949e182020-02-14 12:23:57 +0100561__END__
562
563=pod
564
565=encoding utf8
566
567=head1 NAME
568
569tei2korapxml - Conversion of TEI P5 based formats to KorAP-XML
570
571=head1 SYNOPSIS
572
573 cat corpus.i5.xml | tei2korapxml > corpus.korapxml.zip
574
575=head1 DESCRIPTION
576
Akronee434b12020-07-08 12:53:01 +0200577C<tei2korapxml> is a script to convert TEI P5 and
578L<I5|https://www1.ids-mannheim.de/kl/projekte/korpora/textmodell.html>
579based documents to the
580L<KorAP-XML format|https://github.com/KorAP/KorAP-XML-Krill#about-korap-xml>.
581If no specific input is defined, data is
Akrond949e182020-02-14 12:23:57 +0100582read from C<STDIN>. If no specific output is defined, data is written
583to C<STDOUT>.
Peter Harders6f526a32020-06-29 21:44:41 +0200584
Akrond949e182020-02-14 12:23:57 +0100585This program is usually called from inside another script.
586
Akronee434b12020-07-08 12:53:01 +0200587=head1 FORMATS
588
589=head2 Input restrictions
590
591=over 2
592
593=item
594
Akronee434b12020-07-08 12:53:01 +0200595TEI P5 formatted input with certain restrictions:
596
597=over 4
598
599=item
600
601B<mandatory>: text-header with integrated textsigle, text-body
602
603=item
604
605B<optional>: corp-header with integrated corpsigle,
606doc-header with integrated docsigle
607
608=back
609
610=item
611
Akron0c41ab32020-09-29 07:33:33 +0200612All tokens inside the primary text may not be
Akronee434b12020-07-08 12:53:01 +0200613newline seperated, because newlines are removed
Akron0c41ab32020-09-29 07:33:33 +0200614(see L<KorAP::XML::TEI::Data>) and a conversion of newlines
Akronee434b12020-07-08 12:53:01 +0200615into blanks between 2 tokens could lead to additional blanks,
616where there should be none (e.g.: punctuation characters like C<,> or
617C<.> should not be seperated from their predecessor token).
618(see also code section C<~ whitespace handling ~>).
619
620=back
621
622=head2 Notes on the output
623
624=over 2
625
626=item
627
628zip file output (default on C<stdout>) with utf8 encoded entries
629(which together form the KorAP-XML format)
630
631=back
632
Akrond949e182020-02-14 12:23:57 +0100633=head1 INSTALLATION
634
635C<tei2korapxml> requires L<libxml2-dev> bindings to build. When
636these bindings are available, the preferred way to install the script is
637to use L<cpanm|App::cpanminus>.
638
639 $ cpanm https://github.com/KorAP/KorAP-XML-TEI.git
640
641In case everything went well, the C<tei2korapxml> tool will
642be available on your command line immediately.
Peter Harders6f526a32020-06-29 21:44:41 +0200643
Akrond949e182020-02-14 12:23:57 +0100644Minimum requirement for L<KorAP::XML::TEI> is Perl 5.16.
645
646=head1 OPTIONS
647
648=over 2
649
Akron4e603a52020-07-27 14:23:49 +0200650=item B<--root|-r>
Akrond949e182020-02-14 12:23:57 +0100651
Akron4e603a52020-07-27 14:23:49 +0200652The root directory for output. Defaults to C<.>.
Akrond949e182020-02-14 12:23:57 +0100653
654=item B<--help|-h>
655
656Print help information.
657
658=item B<--version|-v>
659
660Print version information.
661
Akron4e603a52020-07-27 14:23:49 +0200662=item B<--tokenizer-call|-tc>
663
664Call an external tokenizer process, that will tokenize
665a single line from STDIN and outputs one token per line.
666
Marc Kupietz1e882fb2020-09-09 00:05:46 +0200667=item B<--tokenizer-korap|-tk>
668
669Use the standard KorAP/DeReKo tokenizer.
670
Akron6d7b8e42020-09-29 07:37:41 +0200671=item B<--tokenizer-internal|-ti>
Akron4e603a52020-07-27 14:23:49 +0200672
673Tokenize the data using two embedded tokenizers,
674that will take an I<Aggressive> and a I<conservative>
675approach.
676
Akron75d63142021-02-23 18:40:56 +0100677=item B<--skip-inline-tokens>
678
679Boolean flag indicating that inline tokens should not
680be processed. Defaults to false (meaning inline tokens will be processed).
681
Akron1a5271a2021-02-18 13:18:15 +0100682=item B<--inline-tokens> <foundry>#[<file>]
683
684Define the foundry and file (without extension)
685to store inline token information in.
686If L</KORAPXMLTEI_INLINE> is set, this will contain
687annotations as well.
688Defaults to C<tokens> and C<morpho>.
689
Akrondd0be8f2021-02-18 19:29:41 +0100690=item B<--inline-structures> <foundry>#[<file>]
691
692Define the foundry and file (without extension)
693to store inline structure information in.
694Defaults to C<struct> and C<structures>.
695
Akron26a71522021-02-19 10:27:37 +0100696=item B<--base-foundry> <foundry>
697
698Define the base foundry to store newly generated
699token information in.
700Defaults to C<base>.
701
702=item B<--data-file> <file>
703
704Define the file (without extension)
705to store primary data information in.
706Defaults to C<data>.
707
708=item B<--header-file> <file>
709
710Define the file name (without extension)
711to store header information on
712the corpus, document, and text level in.
713Defaults to C<header>.
714
Marc Kupietz985da0c2021-02-15 19:29:50 +0100715=item B<--use-tokenizer-sentence-splits|-s>
716
717Replace existing with, or add new, sentence boundary information
718provided by the KorAP tokenizer (currently supported only).
719
Akron91705d72021-02-19 10:59:45 +0100720=item B<--tokens-file> <file>
721
722Define the file (without extension)
723to store generated token information in
724(either from the KorAP tokenizer or an externally called tokenizer).
725Defaults to C<tokens>.
726
Akron3378dfd2020-08-01 15:01:36 +0200727=item B<--log|-l>
728
729Loglevel for I<Log::Any>. Defaults to C<notice>.
730
Akrond949e182020-02-14 12:23:57 +0100731=back
732
Akronb3649472020-09-29 08:24:46 +0200733=head1 ENVIRONMENT VARIABLES
734
735=over 2
736
737=item B<KORAPXMLTEI_DEBUG>
738
739Activate minimal debugging.
740Defaults to C<false>.
741
742=item B<KORAPXMLTEI_INLINE>
743
744Process inline annotations, if present.
745Defaults to C<false>.
746
747=back
748
Akrond949e182020-02-14 12:23:57 +0100749=head1 COPYRIGHT AND LICENSE
750
Marc Kupietze955ecc2021-02-17 17:42:01 +0100751Copyright (C) 2021, L<IDS Mannheim|https://www.ids-mannheim.de/>
Akrond949e182020-02-14 12:23:57 +0100752
753Author: Peter Harders
754
Akronaabd0952020-09-29 07:35:08 +0200755Contributors: Nils Diewald, Marc Kupietz, Carsten Schnober
Akrond949e182020-02-14 12:23:57 +0100756
757L<KorAP::XML::TEI> is developed as part of the L<KorAP|https://korap.ids-mannheim.de/>
758Corpus Analysis Platform at the
759L<Leibniz Institute for the German Language (IDS)|http://ids-mannheim.de/>,
760member of the
761L<Leibniz-Gemeinschaft|http://www.leibniz-gemeinschaft.de/>.
762
763This program is free software published under the
Marc Kupietze955ecc2021-02-17 17:42:01 +0100764L<BSD-2 License|https://opensource.org/licenses/BSD-2-Clause>.
Akrond949e182020-02-14 12:23:57 +0100765
766=cut
Akronf8088e62021-02-18 16:18:59 +0100767
768# NOTES
769
770## Notes on how 'XML::CompactTree::XS' works
771
772Example: <node a="v"><node1>some <n/> text</node1><node2>more-text</node2></node>
773
774Print out name of 'node2' for the above example:
775
776echo '<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 "\x27".$data->[2]->[0]->[5]->[1]->[1]."\x27\n"'
777
778Exploring the structure of $data ( = reference to below array ):
779
780[ 0: XML_READER_TYPE_DOCUMENT,
781 1: ?
Akron91577922021-02-19 10:32:54 +0100782 2: [ 0: [ 0: XML_READER_TYPE_ELEMENT <- start recursion with array '$data->[2]' (see retr_info( \$tree_data->[2] ))
Akronf8088e62021-02-18 16:18:59 +0100783 1: 'node'
784 2: ?
785 3: HASH (attributes)
786 4: 1 (line number)
787 5: [ 0: [ 0: XML_READER_TYPE_ELEMENT
788 1: 'node1'
789 2: ?
790 3: undefined (no attributes)
791 4: 1 (line number)
792 5: [ 0: [ 0: XML_READER_TYPE_TEXT
793 1: 'some '
794 ]
795 1: [ 0: XML_READER_TYPE_ELEMENT
796 1: 'n'
797 2: ?
798 3: undefined (no attributes)
799 4: 1 (line number)
800 5: undefined (no child-nodes)
801 ]
802 2: [ 0: XML_READER_TYPE_TEXT
803 1: ' text'
804 ]
805 ]
806 ]
807 1: [ 0: XML_READER_TYPE_ELEMENT
808 1: 'node2'
809 2: ?
810 3: undefined (not attributes)
811 4: 1 (line number)
812 5: [ 0: [ 0: XML_READER_TYPE_TEXT
813 1: 'more-text'
814 ]
815 ]
816 ]
817 ]
818 ]
819 ]
820]
821
822$data->[0] = 9 (=> type == XML_READER_TYPE_DOCUMENT)
823
824ref($data->[2]) == ARRAY (with 1 element for 'node')
825ref($data->[2]->[0]) == ARRAY (with 6 elements)
826
827$data->[2]->[0]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
828$data->[2]->[0]->[1] == 'node'
829ref($data->[2]->[0]->[3]) == HASH (=> ${$data->[2]->[0]->[3]}{a} == 'v')
830$data->[2]->[0]->[4] == 1 (line number)
831ref($data->[2]->[0]->[5]) == ARRAY (with 2 elements for 'node1' and 'node2')
832 # child-nodes of actual node (see $_IDX)
833
834ref($data->[2]->[0]->[5]->[0]) == ARRAY (with 6 elements)
835$data->[2]->[0]->[5]->[0]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
836$data->[2]->[0]->[5]->[0]->[1] == 'node1'
837$data->[2]->[0]->[5]->[0]->[3] == undefined (=> no attribute)
838$data->[2]->[0]->[5]->[0]->[4] == 1 (line number)
839ref($data->[2]->[0]->[5]->[0]->[5]) == ARRAY (with 3 elements for 'some ', '<n/>' and ' text')
840
841ref($data->[2]->[0]->[5]->[0]->[5]->[0]) == ARRAY (with 2 elements)
842$data->[2]->[0]->[5]->[0]->[5]->[0]->[0] == 3 (=> type == XML_READER_TYPE_TEXT)
843$data->[2]->[0]->[5]->[0]->[5]->[0]->[1] == 'some '
844
845ref($data->[2]->[0]->[5]->[0]->[5]->[1]) == ARRAY (with 5 elements)
846$data->[2]->[0]->[5]->[0]->[5]->[1]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
847$data->[2]->[0]->[5]->[0]->[5]->[1]->[1] == 'n'
848$data->[2]->[0]->[5]->[0]->[5]->[1]->[3] == undefined (=> no attribute)
849$data->[2]->[0]->[5]->[0]->[5]->[1]->[4] == 1 (line number)
850$data->[2]->[0]->[5]->[0]->[5]->[1]->[5] == undefined (=> no child-nodes)
851
852ref($data->[2]->[0]->[5]->[0]->[5]->[2]) == ARRAY (with 2 elements)
853$data->[2]->[0]->[5]->[0]->[5]->[2]->[0] == 3 (=> type == XML_READER_TYPE_TEXT)
854$data->[2]->[0]->[5]->[0]->[5]->[2]->[1] == ' text'
855
856
857retr_info() starts with the array reference ${$_[0]} (= \$tree_data->[2]), which corresponds to ${\$data->[2]} in the above example.
858Hence, the expression @{${$_[0]}} corresponds to @{${\$data->[2]}}, $e to ${${\$data->[2]}}[0] (= $data->[2]->[0]) and $e->[0] to
859${${\$data->[2]}}[0]->[0] (= $data->[2]->[0]->[0]).
860
861
862## Notes on whitespace handling
863
864Every whitespace inside the processed text is 'significant' and recognized as a node of type 'XML_READER_TYPE_SIGNIFICANT_WHITESPACE'
865(see function 'retr_info()').
866
867Definition of significant and insignificant whitespace
868(source: https://www.oracle.com/technical-resources/articles/wang-whitespace.html):
869
870Significant whitespace is part of the document content and should be preserved.
871Insignificant whitespace is used when editing XML documents for readability.
872These whitespaces are typically not intended for inclusion in the delivery of the document.
873
874### Regarding XML_READER_TYPE_SIGNIFICANT_WHITESPACE
875
876The 3rd form of nodes, besides text- (XML_READER_TYPE_TEXT) and tag-nodes (XML_READER_TYPE_ELEMENT) are nodes of the type
877 'XML_READER_TYPE_SIGNIFICANT_WHITESPACE'.
878
879When modifiying the previous example (see: Notes on how 'XML::CompactTree::XS' works) by inserting an additional blank between
880 '</node1>' and '<node2>', the output for '$data->[2]->[0]->[5]->[1]->[1]' is a blank (' ') and it's type is '14'
881 (XML_READER_TYPE_SIGNIFICANT_WHITESPACE, see 'man XML::LibXML::Reader'):
882
883echo '<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=\x27".$data->[2]->[0]->[5]->[1]->[1]."\x27, type=".$data->[2]->[0]->[5]->[1]->[0]."\n"'
884
885
886Example: '... <head type="main"><s>Campagne in Frankreich</s></head><head type="sub"> <s>1792</s> ...'
887
888Two text-nodes should normally be separated by a blank. In the above example, that would be the 2 text-nodes
889 'Campagne in Frankreich' and '1792', which are separated by the whitespace-node ' ' (see [2]).
890
891The text-node 'Campagne in Frankreich' leads to the setting of '$add_one' to 1, so that when opening the 2nd 'head'-tag,
892 it's from-index gets set to the correct start-index of '1792' (and not to the start-index of the whitespace-node ' ').
893
894The assumption here is, that in most cases there _is_ a whitespace node between 2 text-nodes. The below code fragment
895 enables a way, to check, if this really _was_ the case for the last 2 'non-tag'-nodes, when closing a tag:
896
897When a whitespace-node is read, its from-index is stored as a hash-key (in %ws), to state that it belongs to a ws-node.
898 So when closing a tag, it can be checked, if the previous 'non-tag'-node (text or whitespace), which is the one before
899 the last read 'non-tag'-node, was a actually _not_ a ws-node, but instead a text-node. In that case, the from-value of
900 the last read 'non-tag'-node has to be corrected (see [1]),
901
902For whitespace-nodes $add_one is set to 0, so when opening the next tag (in the above example the 2nd 's'-tag), no
903 additional 1 is added (because this was already done by the whitespace-node itself when incrementing the variable $pos).
904
905[1]
906Now, what happens, when 2 text-nodes are _not_ seperated by a whitespace-node (e.g.: <w>Augen<c>,</c></w>)?
907 In this case, the falsely increased from-value has to be decreased again by 1 when closing the enclosing tag
908 (see above code fragment '... not exists $ws{ $fval - 1 } ...').
909
910[2]
911Comparing the 2 examples '<w>fu</w> <w>bar</w>' and '<w>fu</w><w> </w><w>bar</w>', is ' ' in both cases handled as a
912 whitespace-node (XML_READER_TYPE_SIGNIFICANT_WHITESPACE).
913
914The from-index of the 2nd w-tag in the second example refers to 'bar', which may not have been the intention
915 (even though '<w> </w>' doesn't make a lot of sense). TODO: could this be a bug?
916
917Empty tags also cling to the next text-token - e.g. in '<w>tok1</w> <w>tok2</w><a><b/></a> <w>tok3</w>' are the from-
918 and to-indizes for the tags 'a' and 'b' both 12, which is the start-index of the token 'tok3'.
919
920
921## Notes on whitespace fixing
922
923The idea for the below code fragment was to fix (recreate) missing whitespace in a poorly created corpus, in which linebreaks where inserted
924 into the text with the addition that maybe (or not) whitespace before those linebreaks was unintenionally stripped.
925
926It soon turned out, that it was best to suggest considering just avoiding linebreaks and putting all primary text tokens into one line (see
927 example further down and notes on 'Input restrictions' in the manpage).
928
929Somehow an old first very poor approach remained, which is not stringent, but also doesn't affect one-line text.
930
931Examples (how primary text with linebreaks would be converted by below code):
932
933 '...<w>end</w>\n<w>.</w>...' -> '...<w>end</w> <w>.</w>...'
934 '...<w>,</w>\n<w>this</w>\n<w>is</w>\n<w>it</w>\n<w>!</w>...' -> '<w>,<w> <w>this</w> <w>is</w> <w>it</w> <w>!</w>'.
935
936Blanks are inserted before the 1st character:
937
938 NOTE: not stringent ('...' stands for text):
939
940 beg1............................end1 => no blank before 'beg1'
941 beg2....<pb/>...................end2 => no blank before 'beg2'
942 beg3....<info attr1="val1"/>....end3 => no blank before 'beg3'
943 beg4....<test>ok</test>.........end4 => blank before 'beg4'
944
945 => beg1....end1beg2...<pb/>...end2beg3....<info attr1="val1"/>....end3 beg4...<test>ok</test>....end4
946 ^
947 |_blank between 'end3' and 'beg4'
948
949
950## Notes on segfault prevention
951
Akron91577922021-02-19 10:32:54 +0100952binmode on the input handler prevents segfaulting of 'XML::LibXML::Reader' inside the main loop
Akronf8088e62021-02-18 16:18:59 +0100953(see notes on 'PerlIO layers' in 'man XML::LibXML'),
954removing 'use open qw(:std :utf8)' would fix this problem too, but using binmode on input is more granular
955see in perluniintro: You can switch encodings on an already opened stream by using "binmode()
956see in perlfunc: If LAYER is omitted or specified as ":raw" the filehandle is made suitable for passing binary data.