blob: 590daad5edf69804b145d03b1acfd4df5aab62c1 [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
5use Pod::Usage;
6use Getopt::Long qw(GetOptions :config no_auto_abbrev);
7
8use File::Basename qw(dirname);
Peter Hardersd892a582020-02-12 15:45:22 +01009
10use open qw(:std :utf8); # assume utf-8 encoding
Peter Harders1c5ce152020-07-22 18:02:50 +020011use Encode qw(encode decode);
Peter Hardersd892a582020-02-12 15:45:22 +010012
Peter Hardersd892a582020-02-12 15:45:22 +010013use XML::CompactTree::XS;
14use XML::LibXML::Reader;
Peter Hardersd892a582020-02-12 15:45:22 +010015
Akron4f67cd42020-07-02 12:27:58 +020016use FindBin;
17BEGIN {
18 unshift @INC, "$FindBin::Bin/../lib";
19};
20
Akron0465e9e2020-07-27 15:55:21 +020021use KorAP::XML::TEI qw!remove_xml_comments escape_xml!;
Akron8b511f92020-07-09 17:28:08 +020022use KorAP::XML::TEI::Tokenizer::External;
Akrond9627472020-07-09 16:53:09 +020023use KorAP::XML::TEI::Tokenizer::Conservative;
24use KorAP::XML::TEI::Tokenizer::Aggressive;
Akron09e0b2c2020-07-28 15:57:01 +020025use KorAP::XML::TEI::Tokenizer::Collector;
Akron85717512020-07-08 11:19:19 +020026use KorAP::XML::TEI::Zipper;
Akronf57ed812020-07-27 10:37:52 +020027use KorAP::XML::TEI::Header;
Peter Hardersd892a582020-02-12 15:45:22 +010028
Peter Harders1c5ce152020-07-22 18:02:50 +020029
Akrond949e182020-02-14 12:23:57 +010030our $VERSION = '0.01';
Peter Harders6f526a32020-06-29 21:44:41 +020031
Akrond949e182020-02-14 12:23:57 +010032our $VERSION_MSG = "\ntei2korapxml - v$VERSION\n";
33
Peter Hardersd892a582020-02-12 15:45:22 +010034
Peter Harders6f526a32020-06-29 21:44:41 +020035# Parse options from the command line
Peter Hardersd892a582020-02-12 15:45:22 +010036GetOptions(
Peter Harders6f526a32020-06-29 21:44:41 +020037 "root|r=s" => \(my $_root_dir = '.'), # name of root directory inside zip file
38 "input|i=s" => \(my $input_fname = ''), # input file (yet only TEI I5 Format accepted)
Akron8b511f92020-07-09 17:28:08 +020039 'tokenizer-call|tc=s' => \(my $tokenizer_call), # Temporary argument for testing purposes
Peter Hardersf9c51242020-07-21 02:37:44 +020040 'use-intern-tokenization|ti' => \(my $tokenizer_intern), # use intern tokenization (default = no)
Akron8b511f92020-07-09 17:28:08 +020041 'help|h' => sub {
Akrond949e182020-02-14 12:23:57 +010042 pod2usage(
43 -verbose => 99,
44 -sections => 'NAME|DESCRIPTION|SYNOPSIS|ARGUMENTS|OPTIONS',
45 -msg => $VERSION_MSG,
46 -output => '-'
47 )
48 },
49 'version|v' => sub {
50 pod2usage(
51 -verbose => 0,
52 -msg => $VERSION_MSG,
53 -output => '-'
54 )
55 }
Peter Hardersd892a582020-02-12 15:45:22 +010056);
57
Peter Harders6f526a32020-06-29 21:44:41 +020058#
59# ~~~ parameter (mandatory) ~~~
60#
Peter Harders6f526a32020-06-29 21:44:41 +020061my $_TEXT_BODY = "text"; # tag (without attributes), which contains the primary text
62 # optional
63my $_CORP_HEADER_BEG = "idsHeader type=\"corpus\""; # just keep the correct order of the attributes and evtl. add an '.*' between them
64 # optional
65my $_DOC_HEADER_BEG = "idsHeader type=\"document\""; # analog
66 # mandatory
67my $_TEXT_HEADER_BEG = "idsHeader type=\"text\""; # analog
Akron09e0b2c2020-07-28 15:57:01 +020068
Peter Harders6f526a32020-06-29 21:44:41 +020069#
70# ~~~ constants ~~~
71#
Peter Hardersd892a582020-02-12 15:45:22 +010072
Peter Harders41c35622020-07-12 01:16:22 +020073## extern tokenization
Peter Hardersf9c51242020-07-21 02:37:44 +020074my $_GEN_TOK_EXT = $tokenizer_call ? 1 : 0;
Akron8b511f92020-07-09 17:28:08 +020075 # TODO:
76 # Read tokenizer call from configuration file.
77 # was 'java -cp '. join(":", ".", glob(&dirname(__FILE__)."/../target/*.jar")). " de.ids_mannheim.korap.tokenizer.KorAPTokenizerImpl";
78 my $ext_tok;
79 if ($tokenizer_call) {
80 $ext_tok = KorAP::XML::TEI::Tokenizer::External->new($tokenizer_call);
81 };
Peter Harders41c35622020-07-12 01:16:22 +020082 my $_tok_file_ext = "tokens.xml";
Peter Harders6f526a32020-06-29 21:44:41 +020083##
84
Akron8b511f92020-07-09 17:28:08 +020085## intern tokenization
Peter Hardersf9c51242020-07-21 02:37:44 +020086my $_GEN_TOK_INT = $tokenizer_intern; # simple tokenization (recommended for testing)
Peter Harders41c35622020-07-12 01:16:22 +020087 my $_tok_file_con = "tokens_conservative.xml";
88 my $_tok_file_agg = "tokens_aggressive.xml";
89 my $aggr_tok = KorAP::XML::TEI::Tokenizer::Aggressive->new;
90 my $cons_tok = KorAP::XML::TEI::Tokenizer::Conservative->new;
Peter Harders41c35622020-07-12 01:16:22 +020091##
92
93my $_tok_dir = "base"; # name of directory for storing tokenization files
Peter Harders6f526a32020-06-29 21:44:41 +020094
Peter Harders6f526a32020-06-29 21:44:41 +020095my $_DEBUG = 0; # set to 1 for minimal more debug output (no need to be parametrized)
96my $_XCT_LN = 0; # only for debugging: include line numbers in elements of $tree_data
97 # (see also manpage of XML::CompactTree::XS)
98
99my $_header_file = "header.xml"; # name of files containing the text, document and corpus header
100my $_data_file = "data.xml"; # name of file containing the primary text data (tokens)
101my $_structure_dir = "struct"; # name of directory containing the $_structure_file
102my $_structure_file = "structure.xml"; # name of file containing all tags (except ${_TOKEN_TAG}'s) related information
103 # (= their names and byte offsets in $_data)
104## TODO: optional (different annotation tools can produce more zip-files for feeding into KorAP-XML-Krill)
105my $_TOKENS_PROC = 1; # on/off: processing of ${_TOKEN_TAG}'s (default: 1)
106my $_tokens_dir = "tokens"; # name of directory containing the $_tokens_file
107my $_tokens_file = "morpho.xml"; # name of file containing all ${_TOKEN_TAG}'s related information (=their byte offsets in $_data)
108 # - evtl. with additional inline annotations
109my $_TOKENS_TAG = "w"; # name of tag containing all information stored in $_tokens_file
110
111## TODO: optional
112# handling inline annotations (inside $_TOKENS_TAG)
Akrone68ec0c2020-07-28 18:06:19 +0200113my $_INLINE_ANNOT = $ENV{KORAPXMLTEI_INLINE}?1:0; # on/off: set to 1 if inline annotations are present and should be processed (default: 0)
Akron09e0b2c2020-07-28 15:57:01 +0200114
115# TODO:
116# These parameters are now defunct and moved to Token.pm
Peter Harders6f526a32020-06-29 21:44:41 +0200117my $_INLINE_LEM_RD = "lemma"; # from which attribute to read LEMMA information
118my $_INLINE_ATT_RD = "ana"; # from which attribute to read POS information (and evtl. additional MSD - Morphosyntactic Descriptions)
119 # TODO: The format for the POS and MSD information has to suffice the regular expression ([^ ]+)( (.+))?
120 # - which means, that the POS information can be followed by an optional blank with additional
121 # MSD information; unlike the MSD part, the POS part may not contain any blanks.
122my $_INLINE_POS_WR = "pos"; # name (inside $_tokens_file) referring to POS information
123my $_INLINE_MSD_WR = "msd"; # name (inside $_tokens_file) referring to MSD information
124my $_INLINE_LEM_WR = "lemma"; # name (inside $_tokens_file) referring to LEMMA information
125##
126
127
128#
129# ~~~ variables ~~~
130#
131
Akron09e0b2c2020-07-28 15:57:01 +0200132# Initialize Token-Collector
133my $tokens = KorAP::XML::TEI::Tokenizer::Collector->new;
134
135
Akron85717512020-07-08 11:19:19 +0200136# Initialize zipper
137my $zipper = KorAP::XML::TEI::Zipper->new;
Peter Harders6f526a32020-06-29 21:44:41 +0200138my $input_fh; # input file handle (default: stdin)
139
140my $buf_in; # text body data extracted from input document ($input_fh), further processed by XML::LibXML::Reader
141my $data; # contains the primary text (created by func. 'retr_info' from $buf_in), which is written to '$data_file'
142
143my $dir; # text directory (below $_root_dir)
Peter Harders6f526a32020-06-29 21:44:41 +0200144
145my ( $text_id, $text_id_esc ); # '$text_id_esc' = escaped version of $text_id (see %ent)
146
Akronf57ed812020-07-27 10:37:52 +0200147my ( $data_fl );
Peter Harders6f526a32020-06-29 21:44:41 +0200148
Akronf57ed812020-07-27 10:37:52 +0200149my ( $data_prfx1, $data_prfx2, $data_sfx ); # $data_* are written to $_data_file
Peter Harders6f526a32020-06-29 21:44:41 +0200150
Peter Harders6f526a32020-06-29 21:44:41 +0200151
152my @structures; # list of arrays, where each array represents a TEI I5 tag (except $_TOKENS_TAG) from the input document
153 # - the input of this array is written in func. 'write_structures' into the file '$_structure_file'
154
Akron09e0b2c2020-07-28 15:57:01 +0200155my ( $ref, $idx, $att_idx ); # needed in func. 'write_structures'
Peter Harders6f526a32020-06-29 21:44:41 +0200156
157my ( $reader, # instance of 'XML::LibXML::Reader->new' (on input '$buf_in')
158 $tree_data ); # instance of 'XML::CompactTree::XS::readSubtreeToPerl' (on input '$reader')
159
160# these are only used inside recursive function 'retr_info'
161my ( $_IDX, # value is set dependent on $_XCT_LN - for extracting array of child elements from element in $tree_data
162 $e, # element from $tree_data
163 $n, # tag name of actual processed element $e
164 $rl, # recursion level
165 $dl, # actual length of string $data
166 @oti, # oti='open tags indizes' - a stack of indizes into @structures, where the top index in @oti
167 # represents the actual processed element from @structures
Peter Harders6f526a32020-06-29 21:44:41 +0200168 $inside_tokens_tag, # flag is set, when inside $_TOKENS_TAG
169 ## variables for handling ~ whitespace related issue ~ (it is sometimes necessary, to correct the from-values for some tags)
170 $add_one, # ...
171 $fval, $fval2, # ...
Peter Harders41c35622020-07-12 01:16:22 +0200172 %ws); # hash for indices of whitespace-nodes (needed to recorrect from-values)
173 # idea: when closing element, check if it's from-index minus 1 refers to a whitespace-node
Peter Harders6f526a32020-06-29 21:44:41 +0200174 # (means: 'from-index - 1' is a key in %ws).
175 # if this is _not_ the case, then the from-value is one to high => correct it by substracting 1
176
177my $output; # temporary variable needed in 'write_*'-functions for writing output to zip-stream $zip)
178
179my ( $i, $c ); # index variables used in loops
180
Peter Harders6f526a32020-06-29 21:44:41 +0200181
182#
183# ~~~ main ~~~
184#
185
186# ~ initializations ~
187
188($_XCT_LN)?($_IDX=5):($_IDX=4);
189
Akronf57ed812020-07-27 10:37:52 +0200190$data_prfx1 = $data_prfx2 = $data_sfx = "";
Peter Harders6f526a32020-06-29 21:44:41 +0200191
192$inside_tokens_tag = -1;
193
194$fval = $fval2 = 0;
195
196$_root_dir .= '/'; # base dir must always end with a slash
197$_root_dir =~ s/^\.?\///; # remove leading / (only relative paths allowed in IO::Compress::Zip) and redundant ./
198
Akronf57ed812020-07-27 10:37:52 +0200199$_CORP_HEADER_BEG =~ s#^([^\s]+)(.*)$#$1\[\^>\]*$2#;
200$_DOC_HEADER_BEG =~ s#^([^\s]+)(.*)$#$1\[\^>\]*$2#;
201$_TEXT_HEADER_BEG =~ s#^([^\s]+)(.*)$#$1\[\^>\]*$2#;
Peter Hardersd892a582020-02-12 15:45:22 +0100202
203$data_prfx1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
204$data_prfx1 .= "<?xml-model href=\"text.rng\" type=\"application/xml\" schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n\n";
205$data_prfx1 .= "<raw_text docid=\"";
206$data_prfx2 .= "\" xmlns=\"http://ids-mannheim.de/ns/KorAP\">\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200207## TODO: can 'metadata.xml' change or is it constant?
Peter Hardersd892a582020-02-12 15:45:22 +0100208$data_prfx2 .= " <metadata file=\"metadata.xml\" />\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200209##
Peter Hardersd892a582020-02-12 15:45:22 +0100210$data_prfx2 .= " <text>";
211$data_sfx = "</text>\n</raw_text>";
212
Peter Hardersd892a582020-02-12 15:45:22 +0100213
Peter Harders6f526a32020-06-29 21:44:41 +0200214# ~ read input and write output (text by text) ~
Peter Harders41c35622020-07-12 01:16:22 +0200215main();
Peter Hardersd892a582020-02-12 15:45:22 +0100216
Peter Hardersd892a582020-02-12 15:45:22 +0100217
Peter Harders6f526a32020-06-29 21:44:41 +0200218#
219# ~~~ subs ~~~
220#
Peter Hardersd892a582020-02-12 15:45:22 +0100221
Peter Hardersd892a582020-02-12 15:45:22 +0100222
Peter Harders41c35622020-07-12 01:16:22 +0200223sub main {
Peter Hardersd892a582020-02-12 15:45:22 +0100224
Peter Harders6f526a32020-06-29 21:44:41 +0200225 my ( $pfx, $sfx );
Peter Hardersd892a582020-02-12 15:45:22 +0100226
Peter Harders41c35622020-07-12 01:16:22 +0200227 my $tl = 0; # text line (needed for whitespace handling)
Peter Harders6f526a32020-06-29 21:44:41 +0200228
229 $input_fh = *STDIN; # input file handle (default: stdin)
230
Akron85717512020-07-08 11:19:19 +0200231 $data_fl = 0;
Peter Harders6f526a32020-06-29 21:44:41 +0200232
Akronf57ed812020-07-27 10:37:52 +0200233 $buf_in = $data = $dir = "";
Peter Harders6f526a32020-06-29 21:44:41 +0200234
235
236 if ( $input_fname ne '' ){
237
238 open ( $input_fh, "<", "$input_fname") || die "File \'$input_fname\' could not be opened.\n";
239
240 }
241
242
Peter Harders41c35622020-07-12 01:16:22 +0200243 # prevents segfaulting of 'XML::LibXML::Reader' inside 'main()' - see notes on 'PerlIO layers' in 'man XML::LibXML')
Peter Harders90157342020-07-01 21:05:14 +0200244 # removing 'use open qw(:std :utf8)' would fix this problem too, but using binmode on input is more granular
Peter Harders1c5ce152020-07-22 18:02:50 +0200245 # see in perluniintro: You can switch encodings on an already opened stream by using "binmode()
246 # see in perlfunc: If LAYER is omitted or specified as ":raw" the filehandle is made suitable for passing binary data.
Peter Harders90157342020-07-01 21:05:14 +0200247 binmode $input_fh;
248
249
Peter Harders6f526a32020-06-29 21:44:41 +0200250 # ~ loop (reading input document) ~
251
252 while ( <$input_fh> ){
253
Peter Harders6f526a32020-06-29 21:44:41 +0200254 # TODO: yet not tested fo big amounts of data
255 # must-have, otherwise comments in input could be fatal (e.g.: ...<!--\n<idsHeader...\n-->...)
Akron95bc98a2020-07-11 12:00:12 +0200256 remove_xml_comments( $input_fh, $_ ); # remove HTML comments (<!--...-->)
Peter Harders6f526a32020-06-29 21:44:41 +0200257
258 if ( $data_fl && m#^(.*)</${_TEXT_BODY}>(.*)$# ){
259
260
261 # ~ end of text body ~
262
263
Akron8b511f92020-07-09 17:28:08 +0200264 # write data.xml, structure.xml and evtl. morpho.xml and/or tokenization files (s.a.: $_tok_file_ext, $_tok_file_con, $_tok_file_agg)
Peter Harders6f526a32020-06-29 21:44:41 +0200265
266 $pfx = $1; $sfx = $2;
267
Akrone19aa3e2020-07-27 11:41:27 +0200268 die "ERROR ($0): main(): input line number $.: line with closing text-body tag '${_TEXT_BODY}'"
Peter Harders6f526a32020-06-29 21:44:41 +0200269 ." contains additional information ... => Aborting\n\tline=$_"
270 if $pfx !~ /^\s*$/ || $sfx !~ /^\s*$/;
271
272 if ( $dir ne "" ){
273
Peter Harders6f526a32020-06-29 21:44:41 +0200274 $reader = XML::LibXML::Reader->new( string => "<text>$buf_in</text>", huge => 1 );
Peter Harders6f526a32020-06-29 21:44:41 +0200275
Peter Harders41c35622020-07-12 01:16:22 +0200276 # ~ whitespace handling ~
277 #
278 # Every whitespace inside the processed text is 'significant' and recognized as a node of type 'XML_READER_TYPE_SIGNIFICANT_WHITESPACE'
279 # (see function 'retr_info()').
280 #
281 # Definition of significant and insignificant whitespace
282 # (source: https://www.oracle.com/technical-resources/articles/wang-whitespace.html):
283 #
284 # Significant whitespace is part of the document content and should be preserved.
285 # Insignificant whitespace is used when editing XML documents for readability.
286 # These whitespaces are typically not intended for inclusion in the delivery of the document.
287 #
Peter Harders6f526a32020-06-29 21:44:41 +0200288 if ( $_XCT_LN ){ # _XCT_LINE_NUMBERS is only for debugging
289 $tree_data = XML::CompactTree::XS::readSubtreeToPerl( $reader, XCT_DOCUMENT_ROOT | XCT_IGNORE_COMMENTS | XCT_ATTRIBUTE_ARRAY | XCT_LINE_NUMBERS );
290 } else {
291 $tree_data = XML::CompactTree::XS::readSubtreeToPerl( $reader, XCT_DOCUMENT_ROOT | XCT_IGNORE_COMMENTS | XCT_ATTRIBUTE_ARRAY );
292 }
293
294 @structures = (); @oti = ();
295
296 if ( $_TOKENS_PROC ){
Akron09e0b2c2020-07-28 15:57:01 +0200297 $tokens->reset;
Peter Harders6f526a32020-06-29 21:44:41 +0200298 }
299
300 $dl = $rl = 0;
301
302 # ~ whitespace related issue ~
303 $add_one = 0;
304 %ws = ();
305
306
307 # ~ recursion ~
308
309 retr_info( \$tree_data->[2] ); # parse input data
310
311 $rl--;
312
313
314 # ~ write data.xml ~
315
Peter Harders41c35622020-07-12 01:16:22 +0200316 # TODO: should not be necessary, because whitespace at the end of every input line is removed: see 'whitespace handling' inside text body
317 # (...elsif ( $data_fl )....)
Peter Harders6f526a32020-06-29 21:44:41 +0200318 $data =~ tr/\n\r/ /; # note: 2 blanks - otherwise offset data would become corrupt
Peter Harders41c35622020-07-12 01:16:22 +0200319 #
Peter Harders6f526a32020-06-29 21:44:41 +0200320
Peter Harders6f526a32020-06-29 21:44:41 +0200321
Akronedee6e52020-07-27 14:15:11 +0200322 # ~ tokenization ~
323
Akron8b511f92020-07-09 17:28:08 +0200324 if ( $_GEN_TOK_EXT ){
Peter Hardersb1227172020-07-21 02:12:10 +0200325
Akron09e0b2c2020-07-28 15:57:01 +0200326 # Tokenize and output
Akronedee6e52020-07-27 14:15:11 +0200327 $ext_tok->tokenize($data)->to_zip(
328 $zipper->new_stream("$_root_dir$dir/$_tok_dir/$_tok_file_ext"),
329 $text_id_esc
330 );
Akron09e0b2c2020-07-28 15:57:01 +0200331 };
Peter Harders42e18a62020-07-21 02:43:26 +0200332
333 if ( $_GEN_TOK_INT ){
Peter Hardersb1227172020-07-21 02:12:10 +0200334
Akronedee6e52020-07-27 14:15:11 +0200335 # Tokenize and output
336 $cons_tok->tokenize($data)->to_zip(
337 $zipper->new_stream("$_root_dir$dir/$_tok_dir/$_tok_file_con"),
338 $text_id_esc
339 );
340
341 $aggr_tok->tokenize($data)->to_zip(
342 $zipper->new_stream("$_root_dir$dir/$_tok_dir/$_tok_file_agg"),
343 $text_id_esc
344 );
345
346 $aggr_tok->reset;
347 $cons_tok->reset;
Akron09e0b2c2020-07-28 15:57:01 +0200348 };
Akron8b511f92020-07-09 17:28:08 +0200349
Akron0465e9e2020-07-27 15:55:21 +0200350 # Encode and escape data
351 $data = escape_xml(encode( "UTF-8", $data ));
352 # note: the index still refers to the 'single character'-versions,
353 # which are counted as 1 (search for '&amp;' in data.xml and see
354 # corresponding indices in $_tokens_file)
355
Peter Harders6f526a32020-06-29 21:44:41 +0200356 print STDERR "DEBUG ($0): main(): Writing (utf8-formatted) xml file $_root_dir$dir/$_data_file\n" if $_DEBUG;
357
Akron85717512020-07-08 11:19:19 +0200358 $zipper->new_stream("$_root_dir$dir/$_data_file")
359 ->print("$data_prfx1$text_id_esc$data_prfx2$data$data_sfx");
Peter Harders6f526a32020-06-29 21:44:41 +0200360
361 # ~ write structures ~
362
363 write_structures() if @structures;
364
365
366 # ~ write tokens ~
367
Akron09e0b2c2020-07-28 15:57:01 +0200368 if ($_TOKENS_PROC && !$tokens->empty) {
369 $tokens->to_zip(
370 $zipper->new_stream("$_root_dir$dir/$_tokens_dir/${_tokens_file}"),
371 $text_id_esc,
372 $_INLINE_ANNOT
373 );
374 };
Peter Harders6f526a32020-06-29 21:44:41 +0200375
Peter Hardersb1227172020-07-21 02:12:10 +0200376 #print STDERR "$0: write_tokenization(): DONE\n";
377
Peter Harders6f526a32020-06-29 21:44:41 +0200378 $data_fl = 0; $buf_in = $data = $dir = ""; # reinit.
379
380 } else { # $dir eq ""
381
382 print STDERR "WARNING ($0): main(): maybe empty textSigle => skipping this text ...\n";
Akronf57ed812020-07-27 10:37:52 +0200383 # print STDERR "WARNING ($0): main(): text header=$header_txt\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200384 print STDERR "WARNING ($0): main(): data=$data\n";
Peter Hardersd892a582020-02-12 15:45:22 +0100385 }
386
Peter Harders6f526a32020-06-29 21:44:41 +0200387 } elsif ( $data_fl ){
Peter Hardersd892a582020-02-12 15:45:22 +0100388
Peter Hardersd892a582020-02-12 15:45:22 +0100389
Peter Harders6f526a32020-06-29 21:44:41 +0200390 # ~ inside text body ~
Peter Hardersd892a582020-02-12 15:45:22 +0100391
Peter Hardersd892a582020-02-12 15:45:22 +0100392
Peter Harders6f526a32020-06-29 21:44:41 +0200393 #print STDERR "inside text body (\$data_fl set)\n";
394
395 # ~ whitespace handling ~
396
Peter Harders41c35622020-07-12 01:16:22 +0200397 # The idea for the below code fragment was to fix (recreate) missing whitespace in a poorly created corpus, in which linebreaks where inserted
398 # into the text with the addition that maybe (or not) whitespace before those linebreaks was unintenionally stripped.
Peter Hardersd892a582020-02-12 15:45:22 +0100399 #
Peter Harders41c35622020-07-12 01:16:22 +0200400 # It soon turned out, that it was best to suggest considering just avoiding linebreaks and putting all primary text tokens into one line (see
401 # example further down and notes on 'Input restrictions' in the manpage).
402 #
403 # Somehow an old first very poor approach remained, which is not stringent, but also doesn't affect one-line text.
404 #
405 # 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
406 # an option on how newlines in primary text should be handled (stripped or replaced by a whitespace)).
407 #
408 # Examples (how primary text with linebreaks would be converted by below code):
409 #
410 # '...<w>end</w>\n<w>.</w>...' -> '...<w>end</w> <w>.</w>...'
411 # '...<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>'.
Peter Hardersd892a582020-02-12 15:45:22 +0100412
Peter Harders41c35622020-07-12 01:16:22 +0200413 s/^\s+//; s/\s+$//; # remove consecutive whitespace at beginning and end (mostly one newline)
414
415 ### NOTE: this is only relevant, if a text consists of more than one line
416 ### TODO: find a better solution, or create a warning, if a text has more than one line ($tl > 1)
417 ### do testing with 2 different corpora (one with only one-line texts, the other with several lines per text)
Peter Harders6f526a32020-06-29 21:44:41 +0200418 if ( m/<[^>]+>[^<]/ ){ # line contains at least one tag with at least one character contents
Peter Hardersd892a582020-02-12 15:45:22 +0100419
Peter Harders41c35622020-07-12 01:16:22 +0200420 # NOTE: not stringent ('...' stands for text):
421 #
422 # beg1............................end1 => no blank before 'beg1'
423 # beg2....<pb/>...................end2 => no blank before 'beg2'
424 # beg3....<info attr1="val1"/>....end3 => no blank before 'beg3'
425 # beg4....<test>ok</test>.........end4 => blank before 'beg4'
426 #
427 # => beg1....end1beg2...<pb/>...end2beg3....<info attr1="val1"/>....end3 beg4...<test>ok</test>....end4
428 # ^
429 # |_blank between 'end3' and 'beg4'
Peter Hardersd892a582020-02-12 15:45:22 +0100430
Peter Harders41c35622020-07-12 01:16:22 +0200431 $tl++; # counter for text lines
432
433 s/^(.)/ $1/ if $tl > 1; # insert blank before 1st character (for 2nd line and consecutive lines)
Peter Hardersd892a582020-02-12 15:45:22 +0100434 }
Peter Harders41c35622020-07-12 01:16:22 +0200435 ###
Peter Hardersd892a582020-02-12 15:45:22 +0100436
Peter Harders6f526a32020-06-29 21:44:41 +0200437 # add line to buffer
438 $buf_in .= $_;
439
Peter Harders6f526a32020-06-29 21:44:41 +0200440 } elsif ( m#^(.*)<${_TEXT_BODY}(?: [^>]*)?>(.*)$# ){
441
Peter Harders6f526a32020-06-29 21:44:41 +0200442 # ~ start of text body ~
443
Peter Harders6f526a32020-06-29 21:44:41 +0200444 #print STDERR "inside text body\n";
445
446 $pfx = $1; $sfx = $2;
447
448 $data_fl = 1;
449
Akrone19aa3e2020-07-27 11:41:27 +0200450 die "ERROR ($0): main(): input line number $.: line with opening text-body tag '${_TEXT_BODY}'"
Peter Harders6f526a32020-06-29 21:44:41 +0200451 ." contains additional information ... => Aborting\n\tline=$_"
452 if $pfx !~ /^\s*$/ || $sfx !~ /^\s*$/;
453
Akronf57ed812020-07-27 10:37:52 +0200454 } elsif ( m#^(.*)(<(?:${_TEXT_HEADER_BEG}|${_DOC_HEADER_BEG}|${_CORP_HEADER_BEG}).*)$# ){
Peter Harders6f526a32020-06-29 21:44:41 +0200455
Akronf57ed812020-07-27 10:37:52 +0200456 # ~ start of header ~
457 $pfx = $1;
458 my $content = "$2\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200459
Akrone19aa3e2020-07-27 11:41:27 +0200460 die "ERROR ($0): main(): input line number $.: line with opening header tag"
Peter Harders6f526a32020-06-29 21:44:41 +0200461 ." is not in expected format ... => Aborting\n\tline=$_"
462 if $pfx !~ /^\s*$/;
Peter Hardersd892a582020-02-12 15:45:22 +0100463
Akronf57ed812020-07-27 10:37:52 +0200464 # Parse header
465 my $header = KorAP::XML::TEI::Header->new($content)->parse($input_fh);
466
467 # Header was parseable
468 if ($header) {
469
470 # Write header to zip
471 my $file = $_root_dir . $header->dir . '/' . $_header_file;
472
473 print STDERR "DEBUG ($0): Writing file $file\n" if $_DEBUG;
474
475 $header->to_zip($zipper->new_stream($file));
476
477 # Header is for text level
478 if ($header->type eq 'text') {
479
480 # Remember dir and sigles
481 $dir = $header->dir;
482 $text_id = $header->id;
483 $text_id_esc = $header->id_esc;
484
485 # log output for seeing progression
Peter Harders1c5ce152020-07-22 18:02:50 +0200486 print STDERR "$0: main(): text_id=".decode("UTF-8", $text_id )."\n";
Akronf57ed812020-07-27 10:37:52 +0200487
488 $tl = 0; # reset (needed for ~ whitespace handling ~)
489 };
490 }
491 }
Peter Harders6f526a32020-06-29 21:44:41 +0200492 } #end: while
Peter Hardersd892a582020-02-12 15:45:22 +0100493
Akron85717512020-07-08 11:19:19 +0200494 $zipper->close;
Peter Harders6f526a32020-06-29 21:44:41 +0200495
Akron09e0b2c2020-07-28 15:57:01 +0200496 $ext_tok->close if $_GEN_TOK_EXT;
Peter Hardersd892a582020-02-12 15:45:22 +0100497
Peter Harders41c35622020-07-12 01:16:22 +0200498} # end: sub main
Peter Hardersd892a582020-02-12 15:45:22 +0100499
Peter Hardersd892a582020-02-12 15:45:22 +0100500
Peter Harders41c35622020-07-12 01:16:22 +0200501sub retr_info { # called from main()
Peter Hardersd892a582020-02-12 15:45:22 +0100502
Peter Harders41c35622020-07-12 01:16:22 +0200503 # Notes on how 'XML::CompactTree::XS' works
Peter Harders6f526a32020-06-29 21:44:41 +0200504 #
Peter Harders41c35622020-07-12 01:16:22 +0200505 # Example: <node a="v"><node1>some <n/> text</node1><node2>more-text</node2></node>
Peter Harders6f526a32020-06-29 21:44:41 +0200506 #
Peter Harders41c35622020-07-12 01:16:22 +0200507 # Print out name of 'node2' for the above example:
508 #
509 # 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 "\x27".$data->[2]->[0]->[5]->[1]->[1]."\x27\n"'
510 #
511 # Exploring the structure of $data ( = reference to below array ):
Peter Harders6f526a32020-06-29 21:44:41 +0200512 #
513 # [ 0: XML_READER_TYPE_DOCUMENT,
514 # 1: ?
Peter Harders41c35622020-07-12 01:16:22 +0200515 # 2: [ 0: [ 0: XML_READER_TYPE_ELEMENT <- start recursion with array '$data->[2]' (see main(): retr_info( \$tree_data->[2] ))
Peter Harders6f526a32020-06-29 21:44:41 +0200516 # 1: 'node'
517 # 2: ?
518 # 3: HASH (attributes)
519 # 4: 1 (line number)
520 # 5: [ 0: [ 0: XML_READER_TYPE_ELEMENT
521 # 1: 'node1'
522 # 2: ?
523 # 3: undefined (no attributes)
524 # 4: 1 (line number)
525 # 5: [ 0: [ 0: XML_READER_TYPE_TEXT
526 # 1: 'some '
527 # ]
528 # 1: [ 0: XML_READER_TYPE_ELEMENT
529 # 1: 'n'
530 # 2: ?
531 # 3: undefined (no attributes)
532 # 4: 1 (line number)
Peter Harders41c35622020-07-12 01:16:22 +0200533 # 5: undefined (no child-nodes)
Peter Harders6f526a32020-06-29 21:44:41 +0200534 # ]
535 # 2: [ 0: XML_READER_TYPE_TEXT
536 # 1: ' text'
537 # ]
538 # ]
539 # ]
540 # 1: [ 0: XML_READER_TYPE_ELEMENT
541 # 1: 'node2'
542 # 2: ?
543 # 3: undefined (not attributes)
544 # 4: 1 (line number)
545 # 5: [ 0: [ 0: XML_READER_TYPE_TEXT
546 # 1: 'more-text'
547 # ]
548 # ]
549 # ]
550 # ]
551 # ]
552 # ]
553 # ]
554 #
555 # $data->[0] = 9 (=> type == XML_READER_TYPE_DOCUMENT)
556 #
557 # ref($data->[2]) == ARRAY (with 1 element for 'node')
558 # ref($data->[2]->[0]) == ARRAY (with 6 elements)
559 #
560 # $data->[2]->[0]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
561 # $data->[2]->[0]->[1] == 'node'
562 # ref($data->[2]->[0]->[3]) == HASH (=> ${$data->[2]->[0]->[3]}{a} == 'v')
563 # $data->[2]->[0]->[4] == 1 (line number)
564 # ref($data->[2]->[0]->[5]) == ARRAY (with 2 elements for 'node1' and 'node2')
Peter Harders41c35622020-07-12 01:16:22 +0200565 # # child-nodes of actual node (see $_IDX)
Peter Harders6f526a32020-06-29 21:44:41 +0200566 #
567 # ref($data->[2]->[0]->[5]->[0]) == ARRAY (with 6 elements)
568 # $data->[2]->[0]->[5]->[0]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
569 # $data->[2]->[0]->[5]->[0]->[1] == 'node1'
570 # $data->[2]->[0]->[5]->[0]->[3] == undefined (=> no attribute)
571 # $data->[2]->[0]->[5]->[0]->[4] == 1 (line number)
572 # ref($data->[2]->[0]->[5]->[0]->[5]) == ARRAY (with 3 elements for 'some ', '<n/>' and ' text')
573 #
574 # ref($data->[2]->[0]->[5]->[0]->[5]->[0]) == ARRAY (with 2 elements)
575 # $data->[2]->[0]->[5]->[0]->[5]->[0]->[0] == 3 (=> type == XML_READER_TYPE_TEXT)
576 # $data->[2]->[0]->[5]->[0]->[5]->[0]->[1] == 'some '
577 #
578 # ref($data->[2]->[0]->[5]->[0]->[5]->[1]) == ARRAY (with 5 elements)
579 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
580 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[1] == 'n'
581 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[3] == undefined (=> no attribute)
582 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[4] == 1 (line number)
Peter Harders41c35622020-07-12 01:16:22 +0200583 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[5] == undefined (=> no child-nodes)
Peter Harders6f526a32020-06-29 21:44:41 +0200584 #
585 # ref($data->[2]->[0]->[5]->[0]->[5]->[2]) == ARRAY (with 2 elements)
586 # $data->[2]->[0]->[5]->[0]->[5]->[2]->[0] == 3 (=> type == XML_READER_TYPE_TEXT)
587 # $data->[2]->[0]->[5]->[0]->[5]->[2]->[1] == ' text'
588 #
589 #
590 # retr_info() starts with the array reference ${$_[0]} (= \$tree_data->[2]), which corresponds to ${\$data->[2]} in the above example.
591 # Hence, the expression @{${$_[0]}} corresponds to @{${\$data->[2]}}, $e to ${${\$data->[2]}}[0] (= $data->[2]->[0]) and $e->[0] to
592 # ${${\$data->[2]}}[0]->[0] (= $data->[2]->[0]->[0]).
Peter Hardersd892a582020-02-12 15:45:22 +0100593
Peter Harders41c35622020-07-12 01:16:22 +0200594
Peter Harders6f526a32020-06-29 21:44:41 +0200595 $rl++; # recursion level (1 = topmost level inside retr_info() = should always be level of tag $_TEXT_BODY)
Peter Hardersd892a582020-02-12 15:45:22 +0100596
Peter Hardersd892a582020-02-12 15:45:22 +0100597
Peter Harders6f526a32020-06-29 21:44:41 +0200598 foreach $e ( @{${$_[0]}} ){ # iteration through all array elements ($_[0] is a reference to an array reference)
Peter Hardersd892a582020-02-12 15:45:22 +0100599
Peter Hardersd892a582020-02-12 15:45:22 +0100600
Peter Harders41c35622020-07-12 01:16:22 +0200601 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 +0100602
Peter Hardersd892a582020-02-12 15:45:22 +0100603
Peter Harders6f526a32020-06-29 21:44:41 +0200604 #~~~~
Peter Harders41c35622020-07-12 01:16:22 +0200605 # from here: tag-node (opening)
Peter Harders6f526a32020-06-29 21:44:41 +0200606 #~~~~
Peter Hardersd892a582020-02-12 15:45:22 +0100607
Peter Hardersd892a582020-02-12 15:45:22 +0100608
Peter Harders6f526a32020-06-29 21:44:41 +0200609 # insert new array (for new tag) into @structures with tag-name and tag-attributes (if present)
610 # 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 +0100611
Peter Harders6f526a32020-06-29 21:44:41 +0200612 # ~ tag name ~
Peter Hardersd892a582020-02-12 15:45:22 +0100613
Peter Harders6f526a32020-06-29 21:44:41 +0200614 $n = $e->[1];
Peter Hardersd892a582020-02-12 15:45:22 +0100615
Peter Hardersd892a582020-02-12 15:45:22 +0100616
Peter Harders6f526a32020-06-29 21:44:41 +0200617 # ~ handle structures ~
Peter Hardersd892a582020-02-12 15:45:22 +0100618
Peter Harders6f526a32020-06-29 21:44:41 +0200619 my @array;
620 push @array, $n;
621 push @structures, \@array;
622 push @oti, $#structures; # add highest index of @structures to @oti
Peter Hardersd892a582020-02-12 15:45:22 +0100623
Peter Hardersd892a582020-02-12 15:45:22 +0100624
Peter Harders6f526a32020-06-29 21:44:41 +0200625 # ~ handle tokens ~
Peter Hardersd892a582020-02-12 15:45:22 +0100626
Akron09e0b2c2020-07-28 15:57:01 +0200627 # Wether to push entry also into tokens
628 $inside_tokens_tag = $rl if $_TOKENS_PROC && $n eq $_TOKENS_TAG;
Peter Hardersd892a582020-02-12 15:45:22 +0100629
Akron09e0b2c2020-07-28 15:57:01 +0200630 my $current_token;
631
632 # Add element to token list
Peter Harders6f526a32020-06-29 21:44:41 +0200633 if ( $_TOKENS_PROC && $inside_tokens_tag == $rl ){
Akron09e0b2c2020-07-28 15:57:01 +0200634 $current_token = $tokens->add_token($n); # TODO: adding $n is of no use (redundant)
Peter Harders6f526a32020-06-29 21:44:41 +0200635 }
Peter Hardersd892a582020-02-12 15:45:22 +0100636
Peter Hardersd892a582020-02-12 15:45:22 +0100637
Peter Harders6f526a32020-06-29 21:44:41 +0200638 # ~ handle attributes ~
Peter Hardersd892a582020-02-12 15:45:22 +0100639
Peter Harders6f526a32020-06-29 21:44:41 +0200640 if ( defined $e->[3] ){ # only if attributes exist
Peter Hardersd892a582020-02-12 15:45:22 +0100641
Peter Harders6f526a32020-06-29 21:44:41 +0200642 for ( $c = 0; $c < @{$e->[3]}; $c += 2 ){ # with 'XCT_ATTRIBUTE_ARRAY', $node->[3] is an array reference of the form
643 # [ name1, value1, name2, value2, ....] of attribute names and corresponding values.
644 # note: arrays are faster (see: http://makepp.sourceforge.net/2.0/perl_performance.html)
Peter Hardersd892a582020-02-12 15:45:22 +0100645
Peter Harders6f526a32020-06-29 21:44:41 +0200646 # '$c' references the 'key' and '$c+1' the 'value'
647 push @{$structures[$#structures]}, ${$e->[3]}[$c], ${$e->[3]}[$c+1];
Peter Hardersd892a582020-02-12 15:45:22 +0100648
Peter Harders6f526a32020-06-29 21:44:41 +0200649 if ( $_TOKENS_PROC && $inside_tokens_tag == $rl ){
Peter Hardersd892a582020-02-12 15:45:22 +0100650
Akron09e0b2c2020-07-28 15:57:01 +0200651 # Add attributes to current token
652 $current_token->add_attribute(
653 @{$e->[3]}[$c, $c + 1]
654 );
Peter Harders6f526a32020-06-29 21:44:41 +0200655 }
Peter Harders6f526a32020-06-29 21:44:41 +0200656 }
657 }
658
659
660 # ~ index 'from' ~
661
662 # this is, where a normal tag or tokens-tag ($_TOKENS_TAG) starts
663
Peter Harders41c35622020-07-12 01:16:22 +0200664 push @{$structures[$#structures]}, ( $dl + $add_one ); # see below (text- and whitespace-nodes) for explanation on '$add_one'
Peter Harders6f526a32020-06-29 21:44:41 +0200665
666 if ( $_TOKENS_PROC && $inside_tokens_tag == $rl ){
667
Akron09e0b2c2020-07-28 15:57:01 +0200668 # Set from value to tokens
669 $current_token->set_from($dl + $add_one);
670 };
Peter Harders6f526a32020-06-29 21:44:41 +0200671
672
673 #~~~~
Peter Harders41c35622020-07-12 01:16:22 +0200674 # until here: tag-node (opening)
Peter Harders6f526a32020-06-29 21:44:41 +0200675 #~~~~
676
677
678 # ~~ RECURSION ~~
679
Peter Harders41c35622020-07-12 01:16:22 +0200680 if ( defined $e->[$_IDX] ){ # do no recursion, if $e->[$_IDX] is not defined (because we have no array of child-nodes, e.g.: <back/>)
Peter Harders6f526a32020-06-29 21:44:41 +0200681
Peter Harders41c35622020-07-12 01:16:22 +0200682 retr_info( \$e->[$_IDX] ); # recursion with array of child-nodes
Peter Harders6f526a32020-06-29 21:44:41 +0200683
684 $rl--; # return from recursion
685 }
686
687
688 #~~~~~
Peter Harders41c35622020-07-12 01:16:22 +0200689 # from here: tag-node (closing)
Peter Harders6f526a32020-06-29 21:44:41 +0200690 #~~~~~
691
692
693 # ~ handle structures ~
694
695 {
696 my $ix = pop @oti; # index of just closed tag
697
698 my $aix = $#{$structures[$ix]}; # determine highest index from 'array referring to last closed tag' ...
699
700 $fval = ${$structures[$ix]}[ $aix ]; # ... and get it's from-value
701
702 if ( $fval > 0 && not exists $ws{ $fval - 1 } ){ # ~ whitespace related issue ~
703
Peter Harders41c35622020-07-12 01:16:22 +0200704 # ~ previous node was a text-node ~
Peter Harders6f526a32020-06-29 21:44:41 +0200705
Peter Harders41c35622020-07-12 01:16:22 +0200706 ${$structures[$ix]}[ $aix ] = $fval - 1; # recorrect from-value (see below: Notes on ~ whitespace related issue ~)
Peter Harders6f526a32020-06-29 21:44:41 +0200707 }
708
709 # in case this fails, check input
710 die "ERROR ($0, retr_info()): text_id='$text_id', processing of \@structures: from-value ($fval) is 2 or more greater"
711 ." than to-value ($dl) => please check. aborting ...\n"
712 if ( $fval - 1 ) > $dl;
713
Peter Harders41c35622020-07-12 01:16:22 +0200714 # TODO: find example for which this case applies
Peter Harders6f526a32020-06-29 21:44:41 +0200715 # maybe this is not necessary anymore, because the above recorrection of the from-value suffices
716 # TODO: check, if it's better to remove this line and change above check to 'if ( $fval - 1) >= $dl;
Peter Harders41c35622020-07-12 01:16:22 +0200717 # do testing with bigger corpus excerpt (wikipedia?)
Peter Harders6f526a32020-06-29 21:44:41 +0200718 ${$structures[$ix]}[ $aix ] = $dl if $fval == $dl + 1; # correct from-value (same as ... if $fval-1 == $dl)
719
720 push @{$structures[$ix]}, $dl, $rl; # to-value and recursion-level
721
722 # note: use $dl, because the offsets are _between_ the characters (e.g.: word = 'Hello' => from = 0 (before 'H'), to = 5 (after 'o'))
723 }
724
725
726 # ~ handle tokens ~
727
728
729 if ( $_TOKENS_PROC && $inside_tokens_tag == $rl ){
730
Akron09e0b2c2020-07-28 15:57:01 +0200731 # Check last added token
732 my $last_token = $tokens->last_token;
Peter Harders6f526a32020-06-29 21:44:41 +0200733
Akron09e0b2c2020-07-28 15:57:01 +0200734 # Get from-value from last added token
735 my $fval2 = $last_token->from;
Peter Harders6f526a32020-06-29 21:44:41 +0200736
737 if( $fval2 > 0 && not exists $ws{ $fval2 - 1 } ){ # ~ whitespace related issue ~
738
Peter Harders41c35622020-07-12 01:16:22 +0200739 # ~ previous node was a text-node ~
Peter Harders6f526a32020-06-29 21:44:41 +0200740
Akron09e0b2c2020-07-28 15:57:01 +0200741 # recorrect from-value
742 # (see below: Notes on ~ whitespace related issue ~)
743 $last_token->set_from($fval2 - 1);
Peter Harders6f526a32020-06-29 21:44:41 +0200744 }
745
746 # in case this fails, check input
Akron09e0b2c2020-07-28 15:57:01 +0200747 die "ERROR ($0, retr_info()): text_id='$text_id', processing of tokens: from-value ($fval2) is 2 or more greater"
Peter Harders6f526a32020-06-29 21:44:41 +0200748 ." than to-value ($dl) => please check. aborting ...\n"
749 if ( $fval2 - 1 ) > $dl;
750
Akron09e0b2c2020-07-28 15:57:01 +0200751 # TODO:
752 # find example for which this case applies
753 # maybe this is not necessary anymore, because the above recorrection of the from-value suffices
754 #
755 # TODO:
756 # check, if it's better to remove this line and change above check to 'if ( $fval2 - 1) >= $dl;
Peter Harders41c35622020-07-12 01:16:22 +0200757 # do testing with bigger corpus excerpt (wikipedia?)
Peter Harders6f526a32020-06-29 21:44:41 +0200758
Akron09e0b2c2020-07-28 15:57:01 +0200759 # Correct from-value (same as ... if $fval-1 == $dl)
760 $last_token->set_from($dl) if $fval2 == $dl + 1;
761 $last_token->set_to($dl); # Here from == to?
762 $last_token->set_level($rl);
Peter Harders6f526a32020-06-29 21:44:41 +0200763
764 $inside_tokens_tag = -1; # reset
765 }
766
767 # ~ whitespace related issue ~
Peter Hardersd892a582020-02-12 15:45:22 +0100768 # clean up
Peter Harders6f526a32020-06-29 21:44:41 +0200769 delete $ws{ $fval - 1 } if $fval > 0 && exists $ws{ $fval - 1 };
770 delete $ws{ $fval2 - 1 } if $_TOKENS_PROC && $fval2 > 0 && exists $ws{ $fval2 - 1 };
Peter Hardersd892a582020-02-12 15:45:22 +0100771
772
Peter Harders41c35622020-07-12 01:16:22 +0200773 #~~~~
774 # until here: tag-node (closing)
775 #~~~~
Peter Hardersd892a582020-02-12 15:45:22 +0100776
777
Peter Harders41c35622020-07-12 01:16:22 +0200778 #~~~~~
779 # from here: text- and whitespace-nodes
780 #~~~~~
781
782 # The 3rd form of nodes, besides text- (XML_READER_TYPE_TEXT) and tag-nodes (XML_READER_TYPE_ELEMENT) are nodes of the type
783 # 'XML_READER_TYPE_SIGNIFICANT_WHITESPACE'.
Peter Harders6f526a32020-06-29 21:44:41 +0200784 #
Peter Harders41c35622020-07-12 01:16:22 +0200785 # When modifiying the previous example (see: Notes on how 'XML::CompactTree::XS' works) by inserting an additional blank between
786 # '</node1>' and '<node2>', the output for '$data->[2]->[0]->[5]->[1]->[1]' is a blank (' ') and it's type is '14'
787 # (XML_READER_TYPE_SIGNIFICANT_WHITESPACE, see 'man XML::LibXML::Reader'):
Peter Harders6f526a32020-06-29 21:44:41 +0200788 #
Peter Harders41c35622020-07-12 01:16:22 +0200789 # 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=\x27".$data->[2]->[0]->[5]->[1]->[1]."\x27, type=".$data->[2]->[0]->[5]->[1]->[0]."\n"'
Peter Hardersd892a582020-02-12 15:45:22 +0100790
Peter Harders6f526a32020-06-29 21:44:41 +0200791 } elsif ( $e->[0] == XML_READER_TYPE_TEXT || $e->[0] == XML_READER_TYPE_SIGNIFICANT_WHITESPACE ){
Peter Hardersd892a582020-02-12 15:45:22 +0100792
Peter Harders41c35622020-07-12 01:16:22 +0200793 # Notes on ~ whitespace related issue ~ (referred to the code fragment below)
Peter Harders6f526a32020-06-29 21:44:41 +0200794 #
Peter Harders41c35622020-07-12 01:16:22 +0200795 # Example: '... <head type="main"><s>Campagne in Frankreich</s></head><head type="sub"> <s>1792</s> ...'
Peter Harders6f526a32020-06-29 21:44:41 +0200796 #
797 # Two text-nodes should normally be separated by a blank. In the above example, that would be the 2 text-nodes
Peter Harders41c35622020-07-12 01:16:22 +0200798 # 'Campagne in Frankreich' and '1792', which are separated by the whitespace-node ' ' (see [2]).
Peter Harders6f526a32020-06-29 21:44:41 +0200799 #
Peter Harders41c35622020-07-12 01:16:22 +0200800 # The text-node 'Campagne in Frankreich' leads to the setting of '$add_one' to 1, so that when opening the 2nd 'head'-tag,
801 # it's from-index gets set to the correct start-index of '1792' (and not to the start-index of the whitespace-node ' ').
Peter Harders6f526a32020-06-29 21:44:41 +0200802 #
Peter Harders41c35622020-07-12 01:16:22 +0200803 # The assumption here is, that in most cases there _is_ a whitespace node between 2 text-nodes. The below code fragment
804 # enables a way, to check, if this really _was_ the case for the last 2 'non-tag'-nodes, when closing a tag:
Peter Harders6f526a32020-06-29 21:44:41 +0200805 #
Peter Harders41c35622020-07-12 01:16:22 +0200806 # When 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.
807 # So when closing a tag, it can be checked, if the previous 'non-tag'-node (text or whitespace), which is the one before
808 # 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
809 # the last read 'non-tag'-node has to be corrected (see [1]),
Peter Harders6f526a32020-06-29 21:44:41 +0200810 #
Peter Harders41c35622020-07-12 01:16:22 +0200811 # For whitespace-nodes $add_one is set to 0, so when opening the next tag (in the above example the 2nd 's'-tag), no
812 # additional 1 is added (because this was already done by the whitespace-node itself when incrementing the variable $dl).
Peter Harders6f526a32020-06-29 21:44:41 +0200813 #
Peter Harders41c35622020-07-12 01:16:22 +0200814 # [1]
815 # Now, what happens, when 2 text-nodes are _not_ seperated by a whitespace-node (e.g.: <w>Augen<c>,</c></w>)?
816 # In this case, the falsely increased from-value has to be decreased again by 1 when closing the enclosing tag
817 # (see above code fragment '... not exists $ws{ $fval - 1 } ...').
Peter Harders6f526a32020-06-29 21:44:41 +0200818 #
Peter Harders41c35622020-07-12 01:16:22 +0200819 # [2]
820 # Comparing 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
821 # whitespace-node (XML_READER_TYPE_SIGNIFICANT_WHITESPACE).
Peter Harders6f526a32020-06-29 21:44:41 +0200822 #
Peter Harders41c35622020-07-12 01:16:22 +0200823 # The from-index of the 2nd w-tag in the second example refers to 'bar', which may not have been the intention
824 # (even though '<w> </w>' doesn't make a lot of sense). TODO: could this be a bug?
Peter Harders6f526a32020-06-29 21:44:41 +0200825 #
Peter Harders41c35622020-07-12 01:16:22 +0200826 # Empty 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-
827 # and to-indizes for the tags 'a' and 'b' both 12, which is the start-index of the token 'tok3'.
Peter Harders6f526a32020-06-29 21:44:41 +0200828
829 if( $e->[0] == XML_READER_TYPE_SIGNIFICANT_WHITESPACE ){
830
Peter Harders41c35622020-07-12 01:16:22 +0200831 # ~ whitespace-node ~
832
833 # ~ whitespace related issue ~
Peter Harders6f526a32020-06-29 21:44:41 +0200834
835 $add_one = 0;
836
Peter Harders41c35622020-07-12 01:16:22 +0200837 $ws{ $dl }++; # state, that this from-index belongs to a whitespace-node
838 # ('++' doesn't mean a thing here - maybe it could be used for a consistency check)
Peter Harders6f526a32020-06-29 21:44:41 +0200839
840 }else{
841
842 # ~ text-node ~
843
844 $add_one = 1;
845 }
846
847
848 # ~ update $data and $dl ~
849
850 $data .= $e->[1];
851
852 $dl += length( $e->[1] ); # update length of $data
853
854
Peter Harders41c35622020-07-12 01:16:22 +0200855 #~~~~~
856 # until here: text- and whitespace-nodes
857 #~~~~~
858
859
860 #elsif ( $e->[0] == XML_READER_TYPE_ATTRIBUTE ) # attribute-node
Peter Harders6f526a32020-06-29 21:44:41 +0200861 # note: attributes cannot be processed like this ( => use 'XCT_ATTRIBUTE_ARRAY' - see above )
862
863
864 }else{ # not yet handled type
865
866 die "ERROR ($0): Not yet handled type (\$e->[0]=".$e->[0].") ... => Aborting\n";
867 }
868
869 } # end: foreach iteration
870
871} # end: sub retr_info
872
873
Peter Harders41c35622020-07-12 01:16:22 +0200874sub write_structures { # called from main()
Peter Harders6f526a32020-06-29 21:44:41 +0200875
876 # ~ write @structures ~
Peter Hardersd892a582020-02-12 15:45:22 +0100877
878 #print STDERR "$0: write_structures(): ...\n";
879
Peter Harders6f526a32020-06-29 21:44:41 +0200880 if ( $dir eq "" ){
881
882 print STDERR "WARNING ($0): write_structures(): empty textSigle => nothing to do ...\n";
Peter Hardersd892a582020-02-12 15:45:22 +0100883 return;
884 }
885
Peter Harders6f526a32020-06-29 21:44:41 +0200886 $output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-model href=\"span.rng\" type=\"application/xml\""
887 ." schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n\n<layer docid=\""
Peter Harders1c5ce152020-07-22 18:02:50 +0200888 .decode( "UTF-8", $text_id_esc )."\" xmlns=\"http://ids-mannheim.de/ns/KorAP\" version=\"KorAP-0.4\">\n <spanList>\n"; # convert binary string to text string
Peter Hardersd892a582020-02-12 15:45:22 +0100889
890 $c = 0;
891
Peter Harders6f526a32020-06-29 21:44:41 +0200892 foreach $ref ( @structures ){
Peter Hardersd892a582020-02-12 15:45:22 +0100893
Peter Harders6f526a32020-06-29 21:44:41 +0200894 ( @{$ref} == 4 )?( $idx = 1 ):( $idx = @{$ref}-3 ); # if array '@{$ref}' doesn't contain attributes, then the number of elements in this array is 4
895 # (name, from, to, rec_level), otherwise >4
Peter Hardersd892a582020-02-12 15:45:22 +0100896
Peter Harders6f526a32020-06-29 21:44:41 +0200897 # 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 )
898
899 if( $#structures == $c && ${$ref}[ $idx ] == ${$ref}[ $idx+1 ] + 1 ){
900
901 ${$ref}[$idx] = ${$ref}[ $idx+1 ];
Peter Hardersd892a582020-02-12 15:45:22 +0100902 }
Peter Hardersd892a582020-02-12 15:45:22 +0100903
Peter Harders6f526a32020-06-29 21:44:41 +0200904 # this consistency check is already done in 'retr_info()'
905 #elsif( ${$ref}[$idx] > ${$ref}[$idx+1] ){ # consistency check: abort, if this doesn't hold
906 # die "ERROR ($0: write_structures(): \$text_id=$text_id, \$c=$c, tag-name=${$ref}[0]):"
907 # ." 'from-index=${$ref}[$idx]' > 'to-index=${$ref}[$idx+1]' => please check! aborting ...\n";
908 # die "ERROR ($0: write_structures(): \$text_id=$text_id, \$c=$c, tag-name=${$ref}[0]):"
909 # ." 'from-index=${$ref}[$idx]' > 'to-index=${$ref}[$idx+1]' => please check! aborting ...\n\n$output" }
Peter Hardersd892a582020-02-12 15:45:22 +0100910
Peter Harders6f526a32020-06-29 21:44:41 +0200911 # at least 'POS' should always be there => remove constraint '$_TOKENS_PROC'
912 #if( $_TOKENS_PROC && ${$ref}[0] ne $_TOKENS_TAG )
Peter Hardersd892a582020-02-12 15:45:22 +0100913
Peter Harders6f526a32020-06-29 21:44:41 +0200914 if( ${$ref}[0] ne $_TOKENS_TAG ){ # $_TOKENS_TAG is already written in 'write_tokens'
Peter Hardersd892a582020-02-12 15:45:22 +0100915
Peter Harders6f526a32020-06-29 21:44:41 +0200916 # l (level): insert information about depth of element in XML-tree (top element = level 1)
917 $output .= " <span id=\"s$c\" from=\"${$ref}[ $idx ]\" to=\"${$ref}[ $idx+1 ]\" l=\"${$ref}[ $idx+2 ]\">\n"
918 ." <fs type=\"struct\" xmlns=\"http://www.tei-c.org/ns/1.0\">\n"
919 ." <f name=\"name\">${$ref}[ 0 ]</f>\n";
920
921 if ( $idx > 2 ) # attributes
922 {
923 $output .= " <f name=\"attr\">\n <fs type=\"attr\">\n";
924
925 for ( $att_idx = 1; $att_idx < $idx; $att_idx += 2 ){
926
Akron0465e9e2020-07-27 15:55:21 +0200927 # see explanation in func. 'write_tokens'
928 ${$ref}[ $att_idx+1 ] = escape_xml(${$ref}[ $att_idx+1 ]);
Peter Harders6f526a32020-06-29 21:44:41 +0200929
930 # attribute (at index $att_idx) with value (at index $att_idx+1)
931 $output .= " <f name=\"${$ref}[ $att_idx ]\">${$ref}[ $att_idx+1 ]</f>\n";
932 }
933
934 $output .= " </fs>\n </f>\n";
Peter Hardersd892a582020-02-12 15:45:22 +0100935 }
936
Peter Harders6f526a32020-06-29 21:44:41 +0200937 $output .= " </fs>\n </span>\n";
Peter Hardersd892a582020-02-12 15:45:22 +0100938
Peter Harders6f526a32020-06-29 21:44:41 +0200939 } # fi: ... ne $_TOKENS_TAG
Peter Hardersd892a582020-02-12 15:45:22 +0100940
941 $c++;
942
Peter Harders6f526a32020-06-29 21:44:41 +0200943 } # end: foreach
Peter Hardersd892a582020-02-12 15:45:22 +0100944
945 $output .= " </spanList>\n</layer>";
946
Peter Harders1c5ce152020-07-22 18:02:50 +0200947 $output = encode( "UTF-8", $output ); # convert text string to binary string
Peter Hardersd892a582020-02-12 15:45:22 +0100948
Akron85717512020-07-08 11:19:19 +0200949 $zipper->new_stream("$_root_dir$dir/$_structure_dir/$_structure_file")
950 ->print($output);
Peter Hardersd892a582020-02-12 15:45:22 +0100951
952 #print STDERR "$0: write_structures(): DONE\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200953
Peter Hardersd892a582020-02-12 15:45:22 +0100954} # end: sub write_structures
955
956
Akrond949e182020-02-14 12:23:57 +0100957__END__
958
959=pod
960
961=encoding utf8
962
963=head1 NAME
964
965tei2korapxml - Conversion of TEI P5 based formats to KorAP-XML
966
967=head1 SYNOPSIS
968
969 cat corpus.i5.xml | tei2korapxml > corpus.korapxml.zip
970
971=head1 DESCRIPTION
972
Akronee434b12020-07-08 12:53:01 +0200973C<tei2korapxml> is a script to convert TEI P5 and
974L<I5|https://www1.ids-mannheim.de/kl/projekte/korpora/textmodell.html>
975based documents to the
976L<KorAP-XML format|https://github.com/KorAP/KorAP-XML-Krill#about-korap-xml>.
977If no specific input is defined, data is
Akrond949e182020-02-14 12:23:57 +0100978read from C<STDIN>. If no specific output is defined, data is written
979to C<STDOUT>.
Peter Harders6f526a32020-06-29 21:44:41 +0200980
Akrond949e182020-02-14 12:23:57 +0100981This program is usually called from inside another script.
982
Akronee434b12020-07-08 12:53:01 +0200983=head1 FORMATS
984
985=head2 Input restrictions
986
987=over 2
988
989=item
990
991utf8 encoded
992
993=item
994
995TEI P5 formatted input with certain restrictions:
996
997=over 4
998
999=item
1000
1001B<mandatory>: text-header with integrated textsigle, text-body
1002
1003=item
1004
1005B<optional>: corp-header with integrated corpsigle,
1006doc-header with integrated docsigle
1007
1008=back
1009
1010=item
1011
1012all tokens inside the primary text (inside $data) may not be
1013newline seperated, because newlines are removed
1014(see code section C<~ inside text body ~>) and a conversion of newlines
1015into blanks between 2 tokens could lead to additional blanks,
1016where there should be none (e.g.: punctuation characters like C<,> or
1017C<.> should not be seperated from their predecessor token).
1018(see also code section C<~ whitespace handling ~>).
1019
1020=back
1021
1022=head2 Notes on the output
1023
1024=over 2
1025
1026=item
1027
1028zip file output (default on C<stdout>) with utf8 encoded entries
1029(which together form the KorAP-XML format)
1030
1031=back
1032
Akrond949e182020-02-14 12:23:57 +01001033=head1 INSTALLATION
1034
1035C<tei2korapxml> requires L<libxml2-dev> bindings to build. When
1036these bindings are available, the preferred way to install the script is
1037to use L<cpanm|App::cpanminus>.
1038
1039 $ cpanm https://github.com/KorAP/KorAP-XML-TEI.git
1040
1041In case everything went well, the C<tei2korapxml> tool will
1042be available on your command line immediately.
Peter Harders6f526a32020-06-29 21:44:41 +02001043
Akrond949e182020-02-14 12:23:57 +01001044Minimum requirement for L<KorAP::XML::TEI> is Perl 5.16.
1045
1046=head1 OPTIONS
1047
1048=over 2
1049
Akron4e603a52020-07-27 14:23:49 +02001050=item B<--root|-r>
Akrond949e182020-02-14 12:23:57 +01001051
Akron4e603a52020-07-27 14:23:49 +02001052The root directory for output. Defaults to C<.>.
Akrond949e182020-02-14 12:23:57 +01001053
1054=item B<--help|-h>
1055
1056Print help information.
1057
1058=item B<--version|-v>
1059
1060Print version information.
1061
Akron4e603a52020-07-27 14:23:49 +02001062=item B<--tokenizer-call|-tc>
1063
1064Call an external tokenizer process, that will tokenize
1065a single line from STDIN and outputs one token per line.
1066
1067=item B<--use-intern-tokenization|-ti>
1068
1069Tokenize the data using two embedded tokenizers,
1070that will take an I<Aggressive> and a I<conservative>
1071approach.
1072
Akrond949e182020-02-14 12:23:57 +01001073=back
1074
1075=head1 COPYRIGHT AND LICENSE
1076
1077Copyright (C) 2020, L<IDS Mannheim|https://www.ids-mannheim.de/>
1078
1079Author: Peter Harders
1080
1081Contributors: Marc Kupietz, Carsten Schnober, Nils Diewald
1082
1083L<KorAP::XML::TEI> is developed as part of the L<KorAP|https://korap.ids-mannheim.de/>
1084Corpus Analysis Platform at the
1085L<Leibniz Institute for the German Language (IDS)|http://ids-mannheim.de/>,
1086member of the
1087L<Leibniz-Gemeinschaft|http://www.leibniz-gemeinschaft.de/>.
1088
1089This program is free software published under the
1090L<BSD-2 License|https://raw.githubusercontent.com/KorAP/KorAP-XML-TEI/master/LICENSE>.
1091
1092=cut