blob: df4150a3e891b51493f2295f120787c4c86fa008 [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
12use open qw(:std :utf8); # assume utf-8 encoding
Peter Harders1c5ce152020-07-22 18:02:50 +020013use Encode qw(encode decode);
Peter Hardersd892a582020-02-12 15:45:22 +010014
Peter Hardersd892a582020-02-12 15:45:22 +010015use XML::CompactTree::XS;
16use XML::LibXML::Reader;
Peter Hardersd892a582020-02-12 15:45:22 +010017
Akron4f67cd42020-07-02 12:27:58 +020018use FindBin;
19BEGIN {
20 unshift @INC, "$FindBin::Bin/../lib";
21};
22
Akron0465e9e2020-07-27 15:55:21 +020023use KorAP::XML::TEI qw!remove_xml_comments escape_xml!;
Akron8b511f92020-07-09 17:28:08 +020024use KorAP::XML::TEI::Tokenizer::External;
Akrond9627472020-07-09 16:53:09 +020025use KorAP::XML::TEI::Tokenizer::Conservative;
26use KorAP::XML::TEI::Tokenizer::Aggressive;
Akron09e0b2c2020-07-28 15:57:01 +020027use KorAP::XML::TEI::Tokenizer::Collector;
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
Peter Harders1c5ce152020-07-22 18:02:50 +020031
Akrond949e182020-02-14 12:23:57 +010032our $VERSION = '0.01';
Peter Harders6f526a32020-06-29 21:44:41 +020033
Akrond949e182020-02-14 12:23:57 +010034our $VERSION_MSG = "\ntei2korapxml - v$VERSION\n";
35
Peter Hardersd892a582020-02-12 15:45:22 +010036
Peter Harders6f526a32020-06-29 21:44:41 +020037# Parse options from the command line
Peter Hardersd892a582020-02-12 15:45:22 +010038GetOptions(
Peter Harders6f526a32020-06-29 21:44:41 +020039 "root|r=s" => \(my $_root_dir = '.'), # name of root directory inside zip file
40 "input|i=s" => \(my $input_fname = ''), # input file (yet only TEI I5 Format accepted)
Akron8b511f92020-07-09 17:28:08 +020041 'tokenizer-call|tc=s' => \(my $tokenizer_call), # Temporary argument for testing purposes
Peter Hardersf9c51242020-07-21 02:37:44 +020042 'use-intern-tokenization|ti' => \(my $tokenizer_intern), # use intern tokenization (default = no)
Akron3378dfd2020-08-01 15:01:36 +020043 'log|l=s' => \(my $log_level = 'notice'),
Akron8b511f92020-07-09 17:28:08 +020044 'help|h' => sub {
Akrond949e182020-02-14 12:23:57 +010045 pod2usage(
46 -verbose => 99,
47 -sections => 'NAME|DESCRIPTION|SYNOPSIS|ARGUMENTS|OPTIONS',
48 -msg => $VERSION_MSG,
49 -output => '-'
50 )
51 },
52 'version|v' => sub {
53 pod2usage(
54 -verbose => 0,
55 -msg => $VERSION_MSG,
56 -output => '-'
57 )
58 }
Peter Hardersd892a582020-02-12 15:45:22 +010059);
60
Akron3378dfd2020-08-01 15:01:36 +020061Log::Any::Adapter->set('Stderr', log_level => $log_level);
62
Peter Harders6f526a32020-06-29 21:44:41 +020063#
64# ~~~ parameter (mandatory) ~~~
65#
Peter Harders6f526a32020-06-29 21:44:41 +020066my $_TEXT_BODY = "text"; # tag (without attributes), which contains the primary text
67 # optional
68my $_CORP_HEADER_BEG = "idsHeader type=\"corpus\""; # just keep the correct order of the attributes and evtl. add an '.*' between them
69 # optional
70my $_DOC_HEADER_BEG = "idsHeader type=\"document\""; # analog
71 # mandatory
72my $_TEXT_HEADER_BEG = "idsHeader type=\"text\""; # analog
Akron09e0b2c2020-07-28 15:57:01 +020073
Peter Harders6f526a32020-06-29 21:44:41 +020074#
75# ~~~ constants ~~~
76#
Peter Hardersd892a582020-02-12 15:45:22 +010077
Peter Harders41c35622020-07-12 01:16:22 +020078## extern tokenization
Peter Hardersf9c51242020-07-21 02:37:44 +020079my $_GEN_TOK_EXT = $tokenizer_call ? 1 : 0;
Akron8b511f92020-07-09 17:28:08 +020080 # TODO:
81 # Read tokenizer call from configuration file.
82 # was 'java -cp '. join(":", ".", glob(&dirname(__FILE__)."/../target/*.jar")). " de.ids_mannheim.korap.tokenizer.KorAPTokenizerImpl";
83 my $ext_tok;
84 if ($tokenizer_call) {
85 $ext_tok = KorAP::XML::TEI::Tokenizer::External->new($tokenizer_call);
86 };
Peter Harders41c35622020-07-12 01:16:22 +020087 my $_tok_file_ext = "tokens.xml";
Peter Harders6f526a32020-06-29 21:44:41 +020088##
89
Akron8b511f92020-07-09 17:28:08 +020090## intern tokenization
Peter Hardersf9c51242020-07-21 02:37:44 +020091my $_GEN_TOK_INT = $tokenizer_intern; # simple tokenization (recommended for testing)
Peter Harders41c35622020-07-12 01:16:22 +020092 my $_tok_file_con = "tokens_conservative.xml";
93 my $_tok_file_agg = "tokens_aggressive.xml";
94 my $aggr_tok = KorAP::XML::TEI::Tokenizer::Aggressive->new;
95 my $cons_tok = KorAP::XML::TEI::Tokenizer::Conservative->new;
Peter Harders41c35622020-07-12 01:16:22 +020096##
97
98my $_tok_dir = "base"; # name of directory for storing tokenization files
Peter Harders6f526a32020-06-29 21:44:41 +020099
Peter Harders6f526a32020-06-29 21:44:41 +0200100my $_DEBUG = 0; # set to 1 for minimal more debug output (no need to be parametrized)
101my $_XCT_LN = 0; # only for debugging: include line numbers in elements of $tree_data
102 # (see also manpage of XML::CompactTree::XS)
103
104my $_header_file = "header.xml"; # name of files containing the text, document and corpus header
105my $_data_file = "data.xml"; # name of file containing the primary text data (tokens)
106my $_structure_dir = "struct"; # name of directory containing the $_structure_file
107my $_structure_file = "structure.xml"; # name of file containing all tags (except ${_TOKEN_TAG}'s) related information
108 # (= their names and byte offsets in $_data)
109## TODO: optional (different annotation tools can produce more zip-files for feeding into KorAP-XML-Krill)
110my $_TOKENS_PROC = 1; # on/off: processing of ${_TOKEN_TAG}'s (default: 1)
111my $_tokens_dir = "tokens"; # name of directory containing the $_tokens_file
112my $_tokens_file = "morpho.xml"; # name of file containing all ${_TOKEN_TAG}'s related information (=their byte offsets in $_data)
113 # - evtl. with additional inline annotations
114my $_TOKENS_TAG = "w"; # name of tag containing all information stored in $_tokens_file
115
116## TODO: optional
117# handling inline annotations (inside $_TOKENS_TAG)
Akrone68ec0c2020-07-28 18:06:19 +0200118my $_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 +0200119
120# TODO:
121# These parameters are now defunct and moved to Token.pm
Peter Harders6f526a32020-06-29 21:44:41 +0200122my $_INLINE_LEM_RD = "lemma"; # from which attribute to read LEMMA information
123my $_INLINE_ATT_RD = "ana"; # from which attribute to read POS information (and evtl. additional MSD - Morphosyntactic Descriptions)
124 # TODO: The format for the POS and MSD information has to suffice the regular expression ([^ ]+)( (.+))?
125 # - which means, that the POS information can be followed by an optional blank with additional
126 # MSD information; unlike the MSD part, the POS part may not contain any blanks.
127my $_INLINE_POS_WR = "pos"; # name (inside $_tokens_file) referring to POS information
128my $_INLINE_MSD_WR = "msd"; # name (inside $_tokens_file) referring to MSD information
129my $_INLINE_LEM_WR = "lemma"; # name (inside $_tokens_file) referring to LEMMA information
130##
131
132
133#
134# ~~~ variables ~~~
135#
136
Akron09e0b2c2020-07-28 15:57:01 +0200137# Initialize Token-Collector
138my $tokens = KorAP::XML::TEI::Tokenizer::Collector->new;
139
140
Akron85717512020-07-08 11:19:19 +0200141# Initialize zipper
142my $zipper = KorAP::XML::TEI::Zipper->new;
Peter Harders6f526a32020-06-29 21:44:41 +0200143my $input_fh; # input file handle (default: stdin)
144
145my $buf_in; # text body data extracted from input document ($input_fh), further processed by XML::LibXML::Reader
146my $data; # contains the primary text (created by func. 'retr_info' from $buf_in), which is written to '$data_file'
147
148my $dir; # text directory (below $_root_dir)
Peter Harders6f526a32020-06-29 21:44:41 +0200149
150my ( $text_id, $text_id_esc ); # '$text_id_esc' = escaped version of $text_id (see %ent)
151
Akronf57ed812020-07-27 10:37:52 +0200152my ( $data_fl );
Peter Harders6f526a32020-06-29 21:44:41 +0200153
Akronf57ed812020-07-27 10:37:52 +0200154my ( $data_prfx1, $data_prfx2, $data_sfx ); # $data_* are written to $_data_file
Peter Harders6f526a32020-06-29 21:44:41 +0200155
Peter Harders6f526a32020-06-29 21:44:41 +0200156
157my @structures; # list of arrays, where each array represents a TEI I5 tag (except $_TOKENS_TAG) from the input document
158 # - the input of this array is written in func. 'write_structures' into the file '$_structure_file'
159
Akron09e0b2c2020-07-28 15:57:01 +0200160my ( $ref, $idx, $att_idx ); # needed in func. 'write_structures'
Peter Harders6f526a32020-06-29 21:44:41 +0200161
162my ( $reader, # instance of 'XML::LibXML::Reader->new' (on input '$buf_in')
163 $tree_data ); # instance of 'XML::CompactTree::XS::readSubtreeToPerl' (on input '$reader')
164
165# these are only used inside recursive function 'retr_info'
166my ( $_IDX, # value is set dependent on $_XCT_LN - for extracting array of child elements from element in $tree_data
167 $e, # element from $tree_data
168 $n, # tag name of actual processed element $e
Peter Harders6f526a32020-06-29 21:44:41 +0200169 $dl, # actual length of string $data
170 @oti, # oti='open tags indizes' - a stack of indizes into @structures, where the top index in @oti
171 # represents the actual processed element from @structures
Peter Harders6f526a32020-06-29 21:44:41 +0200172 ## variables for handling ~ whitespace related issue ~ (it is sometimes necessary, to correct the from-values for some tags)
173 $add_one, # ...
174 $fval, $fval2, # ...
Peter Harders41c35622020-07-12 01:16:22 +0200175 %ws); # hash for indices of whitespace-nodes (needed to recorrect from-values)
176 # idea: when closing element, check if it's from-index minus 1 refers to a whitespace-node
Peter Harders6f526a32020-06-29 21:44:41 +0200177 # (means: 'from-index - 1' is a key in %ws).
178 # if this is _not_ the case, then the from-value is one to high => correct it by substracting 1
179
180my $output; # temporary variable needed in 'write_*'-functions for writing output to zip-stream $zip)
181
182my ( $i, $c ); # index variables used in loops
183
Peter Harders6f526a32020-06-29 21:44:41 +0200184
185#
186# ~~~ main ~~~
187#
188
189# ~ initializations ~
190
191($_XCT_LN)?($_IDX=5):($_IDX=4);
192
Akronf57ed812020-07-27 10:37:52 +0200193$data_prfx1 = $data_prfx2 = $data_sfx = "";
Peter Harders6f526a32020-06-29 21:44:41 +0200194
Peter Harders6f526a32020-06-29 21:44:41 +0200195$fval = $fval2 = 0;
196
197$_root_dir .= '/'; # base dir must always end with a slash
198$_root_dir =~ s/^\.?\///; # remove leading / (only relative paths allowed in IO::Compress::Zip) and redundant ./
199
Akronec2cef22020-07-31 10:00:15 +0200200# Normalize regex for header parsing
201for ($_CORP_HEADER_BEG,
202 $_DOC_HEADER_BEG,
203 $_TEXT_HEADER_BEG) {
204 s!^([^\s]+)(.*)$!$1\[\^>\]*$2!;
205};
Peter Hardersd892a582020-02-12 15:45:22 +0100206
207$data_prfx1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
208$data_prfx1 .= "<?xml-model href=\"text.rng\" type=\"application/xml\" schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n\n";
209$data_prfx1 .= "<raw_text docid=\"";
210$data_prfx2 .= "\" xmlns=\"http://ids-mannheim.de/ns/KorAP\">\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200211## TODO: can 'metadata.xml' change or is it constant?
Peter Hardersd892a582020-02-12 15:45:22 +0100212$data_prfx2 .= " <metadata file=\"metadata.xml\" />\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200213##
Peter Hardersd892a582020-02-12 15:45:22 +0100214$data_prfx2 .= " <text>";
215$data_sfx = "</text>\n</raw_text>";
216
Peter Hardersd892a582020-02-12 15:45:22 +0100217
Peter Harders6f526a32020-06-29 21:44:41 +0200218# ~ read input and write output (text by text) ~
Peter Harders41c35622020-07-12 01:16:22 +0200219main();
Peter Hardersd892a582020-02-12 15:45:22 +0100220
Peter Hardersd892a582020-02-12 15:45:22 +0100221
Peter Harders6f526a32020-06-29 21:44:41 +0200222#
223# ~~~ subs ~~~
224#
Peter Hardersd892a582020-02-12 15:45:22 +0100225
Peter Hardersd892a582020-02-12 15:45:22 +0100226
Peter Harders41c35622020-07-12 01:16:22 +0200227sub main {
Peter Hardersd892a582020-02-12 15:45:22 +0100228
Peter Harders6f526a32020-06-29 21:44:41 +0200229 my ( $pfx, $sfx );
Peter Hardersd892a582020-02-12 15:45:22 +0100230
Peter Harders41c35622020-07-12 01:16:22 +0200231 my $tl = 0; # text line (needed for whitespace handling)
Peter Harders6f526a32020-06-29 21:44:41 +0200232
233 $input_fh = *STDIN; # input file handle (default: stdin)
234
Akron85717512020-07-08 11:19:19 +0200235 $data_fl = 0;
Peter Harders6f526a32020-06-29 21:44:41 +0200236
Akronf57ed812020-07-27 10:37:52 +0200237 $buf_in = $data = $dir = "";
Peter Harders6f526a32020-06-29 21:44:41 +0200238
239
240 if ( $input_fname ne '' ){
241
242 open ( $input_fh, "<", "$input_fname") || die "File \'$input_fname\' could not be opened.\n";
243
244 }
245
246
Peter Harders41c35622020-07-12 01:16:22 +0200247 # prevents segfaulting of 'XML::LibXML::Reader' inside 'main()' - see notes on 'PerlIO layers' in 'man XML::LibXML')
Peter Harders90157342020-07-01 21:05:14 +0200248 # 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 +0200249 # see in perluniintro: You can switch encodings on an already opened stream by using "binmode()
250 # 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 +0200251 binmode $input_fh;
252
Akronc1124212020-07-31 08:55:38 +0200253 my $pos;
254 my $l = length('</' . $_TEXT_BODY) + 1;
Peter Harders90157342020-07-01 21:05:14 +0200255
Peter Harders6f526a32020-06-29 21:44:41 +0200256 # ~ loop (reading input document) ~
257
258 while ( <$input_fh> ){
259
Peter Harders6f526a32020-06-29 21:44:41 +0200260 # TODO: yet not tested fo big amounts of data
261 # must-have, otherwise comments in input could be fatal (e.g.: ...<!--\n<idsHeader...\n-->...)
Akron19c6c352020-08-01 13:29:00 +0200262 $_ = remove_xml_comments( $input_fh, $_ ); # remove HTML comments (<!--...-->)
Peter Harders6f526a32020-06-29 21:44:41 +0200263
Akronc1124212020-07-31 08:55:38 +0200264 if ( $data_fl && ($pos = index($_, '</' . $_TEXT_BODY)) >= 0) {
Peter Harders6f526a32020-06-29 21:44:41 +0200265
266 # ~ end of text body ~
267
268
Akron8b511f92020-07-09 17:28:08 +0200269 # 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 +0200270
Akrone19aa3e2020-07-27 11:41:27 +0200271 die "ERROR ($0): main(): input line number $.: line with closing text-body tag '${_TEXT_BODY}'"
Peter Harders6f526a32020-06-29 21:44:41 +0200272 ." contains additional information ... => Aborting\n\tline=$_"
Akronc1124212020-07-31 08:55:38 +0200273 if (substr($_, 0, $pos) . substr($_, $l + $pos)) !~ /^\s*$/;
Peter Harders6f526a32020-06-29 21:44:41 +0200274
275 if ( $dir ne "" ){
276
Peter Harders6f526a32020-06-29 21:44:41 +0200277 $reader = XML::LibXML::Reader->new( string => "<text>$buf_in</text>", huge => 1 );
Peter Harders6f526a32020-06-29 21:44:41 +0200278
Peter Harders41c35622020-07-12 01:16:22 +0200279 # ~ whitespace handling ~
280 #
281 # Every whitespace inside the processed text is 'significant' and recognized as a node of type 'XML_READER_TYPE_SIGNIFICANT_WHITESPACE'
282 # (see function 'retr_info()').
283 #
284 # Definition of significant and insignificant whitespace
285 # (source: https://www.oracle.com/technical-resources/articles/wang-whitespace.html):
286 #
287 # Significant whitespace is part of the document content and should be preserved.
288 # Insignificant whitespace is used when editing XML documents for readability.
289 # These whitespaces are typically not intended for inclusion in the delivery of the document.
290 #
Peter Harders6f526a32020-06-29 21:44:41 +0200291 if ( $_XCT_LN ){ # _XCT_LINE_NUMBERS is only for debugging
292 $tree_data = XML::CompactTree::XS::readSubtreeToPerl( $reader, XCT_DOCUMENT_ROOT | XCT_IGNORE_COMMENTS | XCT_ATTRIBUTE_ARRAY | XCT_LINE_NUMBERS );
293 } else {
294 $tree_data = XML::CompactTree::XS::readSubtreeToPerl( $reader, XCT_DOCUMENT_ROOT | XCT_IGNORE_COMMENTS | XCT_ATTRIBUTE_ARRAY );
295 }
296
297 @structures = (); @oti = ();
298
299 if ( $_TOKENS_PROC ){
Akron09e0b2c2020-07-28 15:57:01 +0200300 $tokens->reset;
Peter Harders6f526a32020-06-29 21:44:41 +0200301 }
302
Akron1c4f2202020-07-30 09:28:22 +0200303 $dl = 0;
Peter Harders6f526a32020-06-29 21:44:41 +0200304
305 # ~ whitespace related issue ~
306 $add_one = 0;
307 %ws = ();
308
309
310 # ~ recursion ~
Akron1c4f2202020-07-30 09:28:22 +0200311 retr_info(1, \$tree_data->[2] ); # parse input data
Peter Harders6f526a32020-06-29 21:44:41 +0200312
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
Akron3378dfd2020-08-01 15:01:36 +0200356 if ($_DEBUG) {
357 $log->debug("Writing (utf8-formatted) xml file $_root_dir$dir/$_data_file");
358 };
Peter Harders6f526a32020-06-29 21:44:41 +0200359
Akron85717512020-07-08 11:19:19 +0200360 $zipper->new_stream("$_root_dir$dir/$_data_file")
361 ->print("$data_prfx1$text_id_esc$data_prfx2$data$data_sfx");
Peter Harders6f526a32020-06-29 21:44:41 +0200362
363 # ~ write structures ~
364
365 write_structures() if @structures;
366
367
368 # ~ write tokens ~
369
Akron09e0b2c2020-07-28 15:57:01 +0200370 if ($_TOKENS_PROC && !$tokens->empty) {
371 $tokens->to_zip(
372 $zipper->new_stream("$_root_dir$dir/$_tokens_dir/${_tokens_file}"),
373 $text_id_esc,
374 $_INLINE_ANNOT
375 );
376 };
Peter Harders6f526a32020-06-29 21:44:41 +0200377
Peter Hardersb1227172020-07-21 02:12:10 +0200378 #print STDERR "$0: write_tokenization(): DONE\n";
379
Peter Harders6f526a32020-06-29 21:44:41 +0200380 $data_fl = 0; $buf_in = $data = $dir = ""; # reinit.
381
382 } else { # $dir eq ""
Akron3378dfd2020-08-01 15:01:36 +0200383 $log->warn("Maybe empty textSigle => skipping this text ...\ndata=$data");
Peter Hardersd892a582020-02-12 15:45:22 +0100384 }
385
Peter Harders6f526a32020-06-29 21:44:41 +0200386 } elsif ( $data_fl ){
Peter Hardersd892a582020-02-12 15:45:22 +0100387
Peter Hardersd892a582020-02-12 15:45:22 +0100388
Peter Harders6f526a32020-06-29 21:44:41 +0200389 # ~ inside text body ~
Peter Hardersd892a582020-02-12 15:45:22 +0100390
Peter Hardersd892a582020-02-12 15:45:22 +0100391
Peter Harders6f526a32020-06-29 21:44:41 +0200392 #print STDERR "inside text body (\$data_fl set)\n";
393
394 # ~ whitespace handling ~
395
Peter Harders41c35622020-07-12 01:16:22 +0200396 # The idea for the below code fragment was to fix (recreate) missing whitespace in a poorly created corpus, in which linebreaks where inserted
397 # into the text with the addition that maybe (or not) whitespace before those linebreaks was unintenionally stripped.
Peter Hardersd892a582020-02-12 15:45:22 +0100398 #
Peter Harders41c35622020-07-12 01:16:22 +0200399 # It soon turned out, that it was best to suggest considering just avoiding linebreaks and putting all primary text tokens into one line (see
400 # example further down and notes on 'Input restrictions' in the manpage).
401 #
402 # Somehow an old first very poor approach remained, which is not stringent, but also doesn't affect one-line text.
403 #
404 # 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
405 # an option on how newlines in primary text should be handled (stripped or replaced by a whitespace)).
406 #
407 # Examples (how primary text with linebreaks would be converted by below code):
408 #
409 # '...<w>end</w>\n<w>.</w>...' -> '...<w>end</w> <w>.</w>...'
410 # '...<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 +0100411
Peter Harders41c35622020-07-12 01:16:22 +0200412 s/^\s+//; s/\s+$//; # remove consecutive whitespace at beginning and end (mostly one newline)
413
414 ### NOTE: this is only relevant, if a text consists of more than one line
415 ### TODO: find a better solution, or create a warning, if a text has more than one line ($tl > 1)
416 ### 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 +0200417 if ( m/<[^>]+>[^<]/ ){ # line contains at least one tag with at least one character contents
Peter Hardersd892a582020-02-12 15:45:22 +0100418
Peter Harders41c35622020-07-12 01:16:22 +0200419 # NOTE: not stringent ('...' stands for text):
420 #
421 # beg1............................end1 => no blank before 'beg1'
422 # beg2....<pb/>...................end2 => no blank before 'beg2'
423 # beg3....<info attr1="val1"/>....end3 => no blank before 'beg3'
424 # beg4....<test>ok</test>.........end4 => blank before 'beg4'
425 #
426 # => beg1....end1beg2...<pb/>...end2beg3....<info attr1="val1"/>....end3 beg4...<test>ok</test>....end4
427 # ^
428 # |_blank between 'end3' and 'beg4'
Peter Hardersd892a582020-02-12 15:45:22 +0100429
Peter Harders41c35622020-07-12 01:16:22 +0200430 $tl++; # counter for text lines
431
432 s/^(.)/ $1/ if $tl > 1; # insert blank before 1st character (for 2nd line and consecutive lines)
Peter Hardersd892a582020-02-12 15:45:22 +0100433 }
Peter Harders41c35622020-07-12 01:16:22 +0200434 ###
Peter Hardersd892a582020-02-12 15:45:22 +0100435
Peter Harders6f526a32020-06-29 21:44:41 +0200436 # add line to buffer
437 $buf_in .= $_;
438
Akronc1124212020-07-31 08:55:38 +0200439 } elsif ( index($_, $_TEXT_BODY) >= 0 && m#^(.*)<${_TEXT_BODY}(?: [^>]*)?>(.*)$# ){
Peter Harders6f526a32020-06-29 21:44:41 +0200440
Peter Harders6f526a32020-06-29 21:44:41 +0200441 # ~ start of text body ~
442
Peter Harders6f526a32020-06-29 21:44:41 +0200443 #print STDERR "inside text body\n";
444
445 $pfx = $1; $sfx = $2;
446
447 $data_fl = 1;
448
Akrone19aa3e2020-07-27 11:41:27 +0200449 die "ERROR ($0): main(): input line number $.: line with opening text-body tag '${_TEXT_BODY}'"
Peter Harders6f526a32020-06-29 21:44:41 +0200450 ." contains additional information ... => Aborting\n\tline=$_"
451 if $pfx !~ /^\s*$/ || $sfx !~ /^\s*$/;
452
Akronf57ed812020-07-27 10:37:52 +0200453 } elsif ( m#^(.*)(<(?:${_TEXT_HEADER_BEG}|${_DOC_HEADER_BEG}|${_CORP_HEADER_BEG}).*)$# ){
Peter Harders6f526a32020-06-29 21:44:41 +0200454
Akronf57ed812020-07-27 10:37:52 +0200455 # ~ start of header ~
456 $pfx = $1;
457 my $content = "$2\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200458
Akrone19aa3e2020-07-27 11:41:27 +0200459 die "ERROR ($0): main(): input line number $.: line with opening header tag"
Peter Harders6f526a32020-06-29 21:44:41 +0200460 ." is not in expected format ... => Aborting\n\tline=$_"
461 if $pfx !~ /^\s*$/;
Peter Hardersd892a582020-02-12 15:45:22 +0100462
Akronf57ed812020-07-27 10:37:52 +0200463 # Parse header
464 my $header = KorAP::XML::TEI::Header->new($content)->parse($input_fh);
465
466 # Header was parseable
467 if ($header) {
468
469 # Write header to zip
470 my $file = $_root_dir . $header->dir . '/' . $_header_file;
471
Akron3378dfd2020-08-01 15:01:36 +0200472 $log->debug("Writing file $file") if $_DEBUG;
Akronf57ed812020-07-27 10:37:52 +0200473
474 $header->to_zip($zipper->new_stream($file));
475
476 # Header is for text level
477 if ($header->type eq 'text') {
478
479 # Remember dir and sigles
480 $dir = $header->dir;
481 $text_id = $header->id;
482 $text_id_esc = $header->id_esc;
483
484 # log output for seeing progression
Akron3378dfd2020-08-01 15:01:36 +0200485 $log->notice("$0: main(): text_id=".decode('UTF-8', $text_id ));
Akronf57ed812020-07-27 10:37:52 +0200486
487 $tl = 0; # reset (needed for ~ whitespace handling ~)
488 };
489 }
490 }
Peter Harders6f526a32020-06-29 21:44:41 +0200491 } #end: while
Peter Hardersd892a582020-02-12 15:45:22 +0100492
Akron85717512020-07-08 11:19:19 +0200493 $zipper->close;
Peter Harders6f526a32020-06-29 21:44:41 +0200494
Akron09e0b2c2020-07-28 15:57:01 +0200495 $ext_tok->close if $_GEN_TOK_EXT;
Peter Hardersd892a582020-02-12 15:45:22 +0100496
Peter Harders41c35622020-07-12 01:16:22 +0200497} # end: sub main
Peter Hardersd892a582020-02-12 15:45:22 +0100498
Peter Hardersd892a582020-02-12 15:45:22 +0100499
Peter Harders41c35622020-07-12 01:16:22 +0200500sub retr_info { # called from main()
Akron1c4f2202020-07-30 09:28:22 +0200501 # recursion level
502 # (1 = topmost level inside retr_info() = should always be level of tag $_TEXT_BODY)
503 my $rl = shift;
Peter Hardersd892a582020-02-12 15:45:22 +0100504
Peter Harders41c35622020-07-12 01:16:22 +0200505 # Notes on how 'XML::CompactTree::XS' works
Peter Harders6f526a32020-06-29 21:44:41 +0200506 #
Peter Harders41c35622020-07-12 01:16:22 +0200507 # Example: <node a="v"><node1>some <n/> text</node1><node2>more-text</node2></node>
Peter Harders6f526a32020-06-29 21:44:41 +0200508 #
Peter Harders41c35622020-07-12 01:16:22 +0200509 # Print out name of 'node2' for the above example:
510 #
511 # 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"'
512 #
513 # Exploring the structure of $data ( = reference to below array ):
Peter Harders6f526a32020-06-29 21:44:41 +0200514 #
515 # [ 0: XML_READER_TYPE_DOCUMENT,
516 # 1: ?
Peter Harders41c35622020-07-12 01:16:22 +0200517 # 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 +0200518 # 1: 'node'
519 # 2: ?
520 # 3: HASH (attributes)
521 # 4: 1 (line number)
522 # 5: [ 0: [ 0: XML_READER_TYPE_ELEMENT
523 # 1: 'node1'
524 # 2: ?
525 # 3: undefined (no attributes)
526 # 4: 1 (line number)
527 # 5: [ 0: [ 0: XML_READER_TYPE_TEXT
528 # 1: 'some '
529 # ]
530 # 1: [ 0: XML_READER_TYPE_ELEMENT
531 # 1: 'n'
532 # 2: ?
533 # 3: undefined (no attributes)
534 # 4: 1 (line number)
Peter Harders41c35622020-07-12 01:16:22 +0200535 # 5: undefined (no child-nodes)
Peter Harders6f526a32020-06-29 21:44:41 +0200536 # ]
537 # 2: [ 0: XML_READER_TYPE_TEXT
538 # 1: ' text'
539 # ]
540 # ]
541 # ]
542 # 1: [ 0: XML_READER_TYPE_ELEMENT
543 # 1: 'node2'
544 # 2: ?
545 # 3: undefined (not attributes)
546 # 4: 1 (line number)
547 # 5: [ 0: [ 0: XML_READER_TYPE_TEXT
548 # 1: 'more-text'
549 # ]
550 # ]
551 # ]
552 # ]
553 # ]
554 # ]
555 # ]
556 #
557 # $data->[0] = 9 (=> type == XML_READER_TYPE_DOCUMENT)
558 #
559 # ref($data->[2]) == ARRAY (with 1 element for 'node')
560 # ref($data->[2]->[0]) == ARRAY (with 6 elements)
561 #
562 # $data->[2]->[0]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
563 # $data->[2]->[0]->[1] == 'node'
564 # ref($data->[2]->[0]->[3]) == HASH (=> ${$data->[2]->[0]->[3]}{a} == 'v')
565 # $data->[2]->[0]->[4] == 1 (line number)
566 # ref($data->[2]->[0]->[5]) == ARRAY (with 2 elements for 'node1' and 'node2')
Peter Harders41c35622020-07-12 01:16:22 +0200567 # # child-nodes of actual node (see $_IDX)
Peter Harders6f526a32020-06-29 21:44:41 +0200568 #
569 # ref($data->[2]->[0]->[5]->[0]) == ARRAY (with 6 elements)
570 # $data->[2]->[0]->[5]->[0]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
571 # $data->[2]->[0]->[5]->[0]->[1] == 'node1'
572 # $data->[2]->[0]->[5]->[0]->[3] == undefined (=> no attribute)
573 # $data->[2]->[0]->[5]->[0]->[4] == 1 (line number)
574 # ref($data->[2]->[0]->[5]->[0]->[5]) == ARRAY (with 3 elements for 'some ', '<n/>' and ' text')
575 #
576 # ref($data->[2]->[0]->[5]->[0]->[5]->[0]) == ARRAY (with 2 elements)
577 # $data->[2]->[0]->[5]->[0]->[5]->[0]->[0] == 3 (=> type == XML_READER_TYPE_TEXT)
578 # $data->[2]->[0]->[5]->[0]->[5]->[0]->[1] == 'some '
579 #
580 # ref($data->[2]->[0]->[5]->[0]->[5]->[1]) == ARRAY (with 5 elements)
581 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[0] == 1 (=> type == XML_READER_TYPE_ELEMENT)
582 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[1] == 'n'
583 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[3] == undefined (=> no attribute)
584 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[4] == 1 (line number)
Peter Harders41c35622020-07-12 01:16:22 +0200585 # $data->[2]->[0]->[5]->[0]->[5]->[1]->[5] == undefined (=> no child-nodes)
Peter Harders6f526a32020-06-29 21:44:41 +0200586 #
587 # ref($data->[2]->[0]->[5]->[0]->[5]->[2]) == ARRAY (with 2 elements)
588 # $data->[2]->[0]->[5]->[0]->[5]->[2]->[0] == 3 (=> type == XML_READER_TYPE_TEXT)
589 # $data->[2]->[0]->[5]->[0]->[5]->[2]->[1] == ' text'
590 #
591 #
592 # retr_info() starts with the array reference ${$_[0]} (= \$tree_data->[2]), which corresponds to ${\$data->[2]} in the above example.
593 # Hence, the expression @{${$_[0]}} corresponds to @{${\$data->[2]}}, $e to ${${\$data->[2]}}[0] (= $data->[2]->[0]) and $e->[0] to
594 # ${${\$data->[2]}}[0]->[0] (= $data->[2]->[0]->[0]).
Peter Hardersd892a582020-02-12 15:45:22 +0100595
Peter Harders41c35622020-07-12 01:16:22 +0200596
Peter Harders6f526a32020-06-29 21:44:41 +0200597 foreach $e ( @{${$_[0]}} ){ # iteration through all array elements ($_[0] is a reference to an array reference)
Peter Hardersd892a582020-02-12 15:45:22 +0100598
Peter Hardersd892a582020-02-12 15:45:22 +0100599
Peter Harders41c35622020-07-12 01:16:22 +0200600 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 +0100601
Peter Hardersd892a582020-02-12 15:45:22 +0100602
Peter Harders6f526a32020-06-29 21:44:41 +0200603 #~~~~
Peter Harders41c35622020-07-12 01:16:22 +0200604 # from here: tag-node (opening)
Peter Harders6f526a32020-06-29 21:44:41 +0200605 #~~~~
Peter Hardersd892a582020-02-12 15:45:22 +0100606
Peter Hardersd892a582020-02-12 15:45:22 +0100607
Peter Harders6f526a32020-06-29 21:44:41 +0200608 # insert new array (for new tag) into @structures with tag-name and tag-attributes (if present)
609 # 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 +0100610
Peter Harders6f526a32020-06-29 21:44:41 +0200611 # ~ tag name ~
Peter Hardersd892a582020-02-12 15:45:22 +0100612
Peter Harders6f526a32020-06-29 21:44:41 +0200613 $n = $e->[1];
Peter Hardersd892a582020-02-12 15:45:22 +0100614
Peter Hardersd892a582020-02-12 15:45:22 +0100615
Peter Harders6f526a32020-06-29 21:44:41 +0200616 # ~ handle structures ~
Peter Hardersd892a582020-02-12 15:45:22 +0100617
Peter Harders6f526a32020-06-29 21:44:41 +0200618 my @array;
619 push @array, $n;
620 push @structures, \@array;
621 push @oti, $#structures; # add highest index of @structures to @oti
Peter Hardersd892a582020-02-12 15:45:22 +0100622
Peter Hardersd892a582020-02-12 15:45:22 +0100623
Peter Harders6f526a32020-06-29 21:44:41 +0200624 # ~ handle tokens ~
Peter Hardersd892a582020-02-12 15:45:22 +0100625
Akron09e0b2c2020-07-28 15:57:01 +0200626 # Wether to push entry also into tokens
Akron0eacef72020-07-30 11:51:28 +0200627 my $inside_tokens_tag = 1 if $_TOKENS_PROC && $n eq $_TOKENS_TAG;
Peter Hardersd892a582020-02-12 15:45:22 +0100628
Akron09e0b2c2020-07-28 15:57:01 +0200629 my $current_token;
630
631 # Add element to token list
Akron0eacef72020-07-30 11:51:28 +0200632 if ($inside_tokens_tag) {
Akron09e0b2c2020-07-28 15:57:01 +0200633 $current_token = $tokens->add_token($n); # TODO: adding $n is of no use (redundant)
Peter Harders6f526a32020-06-29 21:44:41 +0200634 }
Peter Hardersd892a582020-02-12 15:45:22 +0100635
Peter Hardersd892a582020-02-12 15:45:22 +0100636
Peter Harders6f526a32020-06-29 21:44:41 +0200637 # ~ handle attributes ~
Peter Hardersd892a582020-02-12 15:45:22 +0100638
Peter Harders6f526a32020-06-29 21:44:41 +0200639 if ( defined $e->[3] ){ # only if attributes exist
Peter Hardersd892a582020-02-12 15:45:22 +0100640
Peter Harders6f526a32020-06-29 21:44:41 +0200641 for ( $c = 0; $c < @{$e->[3]}; $c += 2 ){ # with 'XCT_ATTRIBUTE_ARRAY', $node->[3] is an array reference of the form
642 # [ name1, value1, name2, value2, ....] of attribute names and corresponding values.
643 # note: arrays are faster (see: http://makepp.sourceforge.net/2.0/perl_performance.html)
Peter Hardersd892a582020-02-12 15:45:22 +0100644
Peter Harders6f526a32020-06-29 21:44:41 +0200645 # '$c' references the 'key' and '$c+1' the 'value'
646 push @{$structures[$#structures]}, ${$e->[3]}[$c], ${$e->[3]}[$c+1];
Peter Hardersd892a582020-02-12 15:45:22 +0100647
Akron0eacef72020-07-30 11:51:28 +0200648 if ($inside_tokens_tag) {
Peter Hardersd892a582020-02-12 15:45:22 +0100649
Akron09e0b2c2020-07-28 15:57:01 +0200650 # Add attributes to current token
651 $current_token->add_attribute(
652 @{$e->[3]}[$c, $c + 1]
653 );
Peter Harders6f526a32020-06-29 21:44:41 +0200654 }
Peter Harders6f526a32020-06-29 21:44:41 +0200655 }
656 }
657
658
659 # ~ index 'from' ~
660
661 # this is, where a normal tag or tokens-tag ($_TOKENS_TAG) starts
662
Peter Harders41c35622020-07-12 01:16:22 +0200663 push @{$structures[$#structures]}, ( $dl + $add_one ); # see below (text- and whitespace-nodes) for explanation on '$add_one'
Peter Harders6f526a32020-06-29 21:44:41 +0200664
Akron0eacef72020-07-30 11:51:28 +0200665 if ($inside_tokens_tag) {
Peter Harders6f526a32020-06-29 21:44:41 +0200666
Akron09e0b2c2020-07-28 15:57:01 +0200667 # Set from value to tokens
668 $current_token->set_from($dl + $add_one);
669 };
Peter Harders6f526a32020-06-29 21:44:41 +0200670
671
672 #~~~~
Peter Harders41c35622020-07-12 01:16:22 +0200673 # until here: tag-node (opening)
Peter Harders6f526a32020-06-29 21:44:41 +0200674 #~~~~
675
676
677 # ~~ RECURSION ~~
678
Peter Harders41c35622020-07-12 01:16:22 +0200679 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 +0200680
Akron1c4f2202020-07-30 09:28:22 +0200681 retr_info($rl+1, \$e->[$_IDX]); # recursion with array of child-nodes
Peter Harders6f526a32020-06-29 21:44:41 +0200682 }
683
684
685 #~~~~~
Peter Harders41c35622020-07-12 01:16:22 +0200686 # from here: tag-node (closing)
Peter Harders6f526a32020-06-29 21:44:41 +0200687 #~~~~~
688
689
690 # ~ handle structures ~
691
692 {
693 my $ix = pop @oti; # index of just closed tag
694
695 my $aix = $#{$structures[$ix]}; # determine highest index from 'array referring to last closed tag' ...
696
697 $fval = ${$structures[$ix]}[ $aix ]; # ... and get it's from-value
698
699 if ( $fval > 0 && not exists $ws{ $fval - 1 } ){ # ~ whitespace related issue ~
700
Peter Harders41c35622020-07-12 01:16:22 +0200701 # ~ previous node was a text-node ~
Peter Harders6f526a32020-06-29 21:44:41 +0200702
Peter Harders41c35622020-07-12 01:16:22 +0200703 ${$structures[$ix]}[ $aix ] = $fval - 1; # recorrect from-value (see below: Notes on ~ whitespace related issue ~)
Peter Harders6f526a32020-06-29 21:44:41 +0200704 }
705
706 # in case this fails, check input
707 die "ERROR ($0, retr_info()): text_id='$text_id', processing of \@structures: from-value ($fval) is 2 or more greater"
708 ." than to-value ($dl) => please check. aborting ...\n"
709 if ( $fval - 1 ) > $dl;
710
Peter Harders41c35622020-07-12 01:16:22 +0200711 # TODO: find example for which this case applies
Peter Harders6f526a32020-06-29 21:44:41 +0200712 # maybe this is not necessary anymore, because the above recorrection of the from-value suffices
713 # 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 +0200714 # do testing with bigger corpus excerpt (wikipedia?)
Peter Harders6f526a32020-06-29 21:44:41 +0200715 ${$structures[$ix]}[ $aix ] = $dl if $fval == $dl + 1; # correct from-value (same as ... if $fval-1 == $dl)
716
717 push @{$structures[$ix]}, $dl, $rl; # to-value and recursion-level
718
719 # note: use $dl, because the offsets are _between_ the characters (e.g.: word = 'Hello' => from = 0 (before 'H'), to = 5 (after 'o'))
720 }
721
722
723 # ~ handle tokens ~
724
725
Akron0eacef72020-07-30 11:51:28 +0200726 if ($inside_tokens_tag) {
Peter Harders6f526a32020-06-29 21:44:41 +0200727
Akron09e0b2c2020-07-28 15:57:01 +0200728 # Check last added token
729 my $last_token = $tokens->last_token;
Peter Harders6f526a32020-06-29 21:44:41 +0200730
Akron09e0b2c2020-07-28 15:57:01 +0200731 # Get from-value from last added token
732 my $fval2 = $last_token->from;
Peter Harders6f526a32020-06-29 21:44:41 +0200733
734 if( $fval2 > 0 && not exists $ws{ $fval2 - 1 } ){ # ~ whitespace related issue ~
735
Peter Harders41c35622020-07-12 01:16:22 +0200736 # ~ previous node was a text-node ~
Peter Harders6f526a32020-06-29 21:44:41 +0200737
Akron09e0b2c2020-07-28 15:57:01 +0200738 # recorrect from-value
739 # (see below: Notes on ~ whitespace related issue ~)
740 $last_token->set_from($fval2 - 1);
Peter Harders6f526a32020-06-29 21:44:41 +0200741 }
742
743 # in case this fails, check input
Akron09e0b2c2020-07-28 15:57:01 +0200744 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 +0200745 ." than to-value ($dl) => please check. aborting ...\n"
746 if ( $fval2 - 1 ) > $dl;
747
Akron09e0b2c2020-07-28 15:57:01 +0200748 # TODO:
749 # find example for which this case applies
750 # maybe this is not necessary anymore, because the above recorrection of the from-value suffices
751 #
752 # TODO:
753 # 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 +0200754 # do testing with bigger corpus excerpt (wikipedia?)
Peter Harders6f526a32020-06-29 21:44:41 +0200755
Akron09e0b2c2020-07-28 15:57:01 +0200756 # Correct from-value (same as ... if $fval-1 == $dl)
757 $last_token->set_from($dl) if $fval2 == $dl + 1;
758 $last_token->set_to($dl); # Here from == to?
759 $last_token->set_level($rl);
Peter Harders6f526a32020-06-29 21:44:41 +0200760 }
761
762 # ~ whitespace related issue ~
Peter Hardersd892a582020-02-12 15:45:22 +0100763 # clean up
Peter Harders6f526a32020-06-29 21:44:41 +0200764 delete $ws{ $fval - 1 } if $fval > 0 && exists $ws{ $fval - 1 };
765 delete $ws{ $fval2 - 1 } if $_TOKENS_PROC && $fval2 > 0 && exists $ws{ $fval2 - 1 };
Peter Hardersd892a582020-02-12 15:45:22 +0100766
767
Peter Harders41c35622020-07-12 01:16:22 +0200768 #~~~~
769 # until here: tag-node (closing)
770 #~~~~
Peter Hardersd892a582020-02-12 15:45:22 +0100771
772
Peter Harders41c35622020-07-12 01:16:22 +0200773 #~~~~~
774 # from here: text- and whitespace-nodes
775 #~~~~~
776
777 # The 3rd form of nodes, besides text- (XML_READER_TYPE_TEXT) and tag-nodes (XML_READER_TYPE_ELEMENT) are nodes of the type
778 # 'XML_READER_TYPE_SIGNIFICANT_WHITESPACE'.
Peter Harders6f526a32020-06-29 21:44:41 +0200779 #
Peter Harders41c35622020-07-12 01:16:22 +0200780 # When modifiying the previous example (see: Notes on how 'XML::CompactTree::XS' works) by inserting an additional blank between
781 # '</node1>' and '<node2>', the output for '$data->[2]->[0]->[5]->[1]->[1]' is a blank (' ') and it's type is '14'
782 # (XML_READER_TYPE_SIGNIFICANT_WHITESPACE, see 'man XML::LibXML::Reader'):
Peter Harders6f526a32020-06-29 21:44:41 +0200783 #
Peter Harders41c35622020-07-12 01:16:22 +0200784 # 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 +0100785
Peter Harders6f526a32020-06-29 21:44:41 +0200786 } elsif ( $e->[0] == XML_READER_TYPE_TEXT || $e->[0] == XML_READER_TYPE_SIGNIFICANT_WHITESPACE ){
Peter Hardersd892a582020-02-12 15:45:22 +0100787
Peter Harders41c35622020-07-12 01:16:22 +0200788 # Notes on ~ whitespace related issue ~ (referred to the code fragment below)
Peter Harders6f526a32020-06-29 21:44:41 +0200789 #
Peter Harders41c35622020-07-12 01:16:22 +0200790 # Example: '... <head type="main"><s>Campagne in Frankreich</s></head><head type="sub"> <s>1792</s> ...'
Peter Harders6f526a32020-06-29 21:44:41 +0200791 #
792 # 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 +0200793 # 'Campagne in Frankreich' and '1792', which are separated by the whitespace-node ' ' (see [2]).
Peter Harders6f526a32020-06-29 21:44:41 +0200794 #
Peter Harders41c35622020-07-12 01:16:22 +0200795 # The text-node 'Campagne in Frankreich' leads to the setting of '$add_one' to 1, so that when opening the 2nd 'head'-tag,
796 # 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 +0200797 #
Peter Harders41c35622020-07-12 01:16:22 +0200798 # The assumption here is, that in most cases there _is_ a whitespace node between 2 text-nodes. The below code fragment
799 # 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 +0200800 #
Peter Harders41c35622020-07-12 01:16:22 +0200801 # 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.
802 # So when closing a tag, it can be checked, if the previous 'non-tag'-node (text or whitespace), which is the one before
803 # 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
804 # the last read 'non-tag'-node has to be corrected (see [1]),
Peter Harders6f526a32020-06-29 21:44:41 +0200805 #
Peter Harders41c35622020-07-12 01:16:22 +0200806 # For whitespace-nodes $add_one is set to 0, so when opening the next tag (in the above example the 2nd 's'-tag), no
807 # 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 +0200808 #
Peter Harders41c35622020-07-12 01:16:22 +0200809 # [1]
810 # Now, what happens, when 2 text-nodes are _not_ seperated by a whitespace-node (e.g.: <w>Augen<c>,</c></w>)?
811 # In this case, the falsely increased from-value has to be decreased again by 1 when closing the enclosing tag
812 # (see above code fragment '... not exists $ws{ $fval - 1 } ...').
Peter Harders6f526a32020-06-29 21:44:41 +0200813 #
Peter Harders41c35622020-07-12 01:16:22 +0200814 # [2]
815 # 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
816 # whitespace-node (XML_READER_TYPE_SIGNIFICANT_WHITESPACE).
Peter Harders6f526a32020-06-29 21:44:41 +0200817 #
Peter Harders41c35622020-07-12 01:16:22 +0200818 # The from-index of the 2nd w-tag in the second example refers to 'bar', which may not have been the intention
819 # (even though '<w> </w>' doesn't make a lot of sense). TODO: could this be a bug?
Peter Harders6f526a32020-06-29 21:44:41 +0200820 #
Peter Harders41c35622020-07-12 01:16:22 +0200821 # 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-
822 # 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 +0200823
824 if( $e->[0] == XML_READER_TYPE_SIGNIFICANT_WHITESPACE ){
825
Peter Harders41c35622020-07-12 01:16:22 +0200826 # ~ whitespace-node ~
827
828 # ~ whitespace related issue ~
Peter Harders6f526a32020-06-29 21:44:41 +0200829
830 $add_one = 0;
831
Peter Harders41c35622020-07-12 01:16:22 +0200832 $ws{ $dl }++; # state, that this from-index belongs to a whitespace-node
833 # ('++' doesn't mean a thing here - maybe it could be used for a consistency check)
Peter Harders6f526a32020-06-29 21:44:41 +0200834
835 }else{
836
837 # ~ text-node ~
838
839 $add_one = 1;
840 }
841
842
843 # ~ update $data and $dl ~
844
845 $data .= $e->[1];
846
847 $dl += length( $e->[1] ); # update length of $data
848
849
Peter Harders41c35622020-07-12 01:16:22 +0200850 #~~~~~
851 # until here: text- and whitespace-nodes
852 #~~~~~
853
854
855 #elsif ( $e->[0] == XML_READER_TYPE_ATTRIBUTE ) # attribute-node
Peter Harders6f526a32020-06-29 21:44:41 +0200856 # note: attributes cannot be processed like this ( => use 'XCT_ATTRIBUTE_ARRAY' - see above )
857
858
859 }else{ # not yet handled type
860
861 die "ERROR ($0): Not yet handled type (\$e->[0]=".$e->[0].") ... => Aborting\n";
862 }
863
864 } # end: foreach iteration
865
866} # end: sub retr_info
867
868
Peter Harders41c35622020-07-12 01:16:22 +0200869sub write_structures { # called from main()
Peter Harders6f526a32020-06-29 21:44:41 +0200870
871 # ~ write @structures ~
Peter Hardersd892a582020-02-12 15:45:22 +0100872
873 #print STDERR "$0: write_structures(): ...\n";
874
Peter Harders6f526a32020-06-29 21:44:41 +0200875 if ( $dir eq "" ){
Akron3378dfd2020-08-01 15:01:36 +0200876 $log->warn("write_structures(): empty textSigle => nothing to do ...");
Peter Hardersd892a582020-02-12 15:45:22 +0100877 return;
878 }
879
Peter Harders6f526a32020-06-29 21:44:41 +0200880 $output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-model href=\"span.rng\" type=\"application/xml\""
881 ." schematypens=\"http://relaxng.org/ns/structure/1.0\"?>\n\n<layer docid=\""
Peter Harders1c5ce152020-07-22 18:02:50 +0200882 .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 +0100883
884 $c = 0;
885
Peter Harders6f526a32020-06-29 21:44:41 +0200886 foreach $ref ( @structures ){
Peter Hardersd892a582020-02-12 15:45:22 +0100887
Peter Harders6f526a32020-06-29 21:44:41 +0200888 ( @{$ref} == 4 )?( $idx = 1 ):( $idx = @{$ref}-3 ); # if array '@{$ref}' doesn't contain attributes, then the number of elements in this array is 4
889 # (name, from, to, rec_level), otherwise >4
Peter Hardersd892a582020-02-12 15:45:22 +0100890
Peter Harders6f526a32020-06-29 21:44:41 +0200891 # 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 )
892
893 if( $#structures == $c && ${$ref}[ $idx ] == ${$ref}[ $idx+1 ] + 1 ){
894
895 ${$ref}[$idx] = ${$ref}[ $idx+1 ];
Peter Hardersd892a582020-02-12 15:45:22 +0100896 }
Peter Hardersd892a582020-02-12 15:45:22 +0100897
Peter Harders6f526a32020-06-29 21:44:41 +0200898 # this consistency check is already done in 'retr_info()'
899 #elsif( ${$ref}[$idx] > ${$ref}[$idx+1] ){ # consistency check: abort, if this doesn't hold
900 # die "ERROR ($0: write_structures(): \$text_id=$text_id, \$c=$c, tag-name=${$ref}[0]):"
901 # ." 'from-index=${$ref}[$idx]' > 'to-index=${$ref}[$idx+1]' => please check! aborting ...\n";
902 # die "ERROR ($0: write_structures(): \$text_id=$text_id, \$c=$c, tag-name=${$ref}[0]):"
903 # ." 'from-index=${$ref}[$idx]' > 'to-index=${$ref}[$idx+1]' => please check! aborting ...\n\n$output" }
Peter Hardersd892a582020-02-12 15:45:22 +0100904
Peter Harders6f526a32020-06-29 21:44:41 +0200905 # at least 'POS' should always be there => remove constraint '$_TOKENS_PROC'
906 #if( $_TOKENS_PROC && ${$ref}[0] ne $_TOKENS_TAG )
Peter Hardersd892a582020-02-12 15:45:22 +0100907
Peter Harders6f526a32020-06-29 21:44:41 +0200908 if( ${$ref}[0] ne $_TOKENS_TAG ){ # $_TOKENS_TAG is already written in 'write_tokens'
Peter Hardersd892a582020-02-12 15:45:22 +0100909
Peter Harders6f526a32020-06-29 21:44:41 +0200910 # l (level): insert information about depth of element in XML-tree (top element = level 1)
911 $output .= " <span id=\"s$c\" from=\"${$ref}[ $idx ]\" to=\"${$ref}[ $idx+1 ]\" l=\"${$ref}[ $idx+2 ]\">\n"
912 ." <fs type=\"struct\" xmlns=\"http://www.tei-c.org/ns/1.0\">\n"
913 ." <f name=\"name\">${$ref}[ 0 ]</f>\n";
914
915 if ( $idx > 2 ) # attributes
916 {
917 $output .= " <f name=\"attr\">\n <fs type=\"attr\">\n";
918
919 for ( $att_idx = 1; $att_idx < $idx; $att_idx += 2 ){
920
Akron0465e9e2020-07-27 15:55:21 +0200921 # see explanation in func. 'write_tokens'
922 ${$ref}[ $att_idx+1 ] = escape_xml(${$ref}[ $att_idx+1 ]);
Peter Harders6f526a32020-06-29 21:44:41 +0200923
924 # attribute (at index $att_idx) with value (at index $att_idx+1)
925 $output .= " <f name=\"${$ref}[ $att_idx ]\">${$ref}[ $att_idx+1 ]</f>\n";
926 }
927
928 $output .= " </fs>\n </f>\n";
Peter Hardersd892a582020-02-12 15:45:22 +0100929 }
930
Peter Harders6f526a32020-06-29 21:44:41 +0200931 $output .= " </fs>\n </span>\n";
Peter Hardersd892a582020-02-12 15:45:22 +0100932
Peter Harders6f526a32020-06-29 21:44:41 +0200933 } # fi: ... ne $_TOKENS_TAG
Peter Hardersd892a582020-02-12 15:45:22 +0100934
935 $c++;
936
Peter Harders6f526a32020-06-29 21:44:41 +0200937 } # end: foreach
Peter Hardersd892a582020-02-12 15:45:22 +0100938
939 $output .= " </spanList>\n</layer>";
940
Peter Harders1c5ce152020-07-22 18:02:50 +0200941 $output = encode( "UTF-8", $output ); # convert text string to binary string
Peter Hardersd892a582020-02-12 15:45:22 +0100942
Akron85717512020-07-08 11:19:19 +0200943 $zipper->new_stream("$_root_dir$dir/$_structure_dir/$_structure_file")
944 ->print($output);
Peter Hardersd892a582020-02-12 15:45:22 +0100945
946 #print STDERR "$0: write_structures(): DONE\n";
Peter Harders6f526a32020-06-29 21:44:41 +0200947
Peter Hardersd892a582020-02-12 15:45:22 +0100948} # end: sub write_structures
949
950
Akrond949e182020-02-14 12:23:57 +0100951__END__
952
953=pod
954
955=encoding utf8
956
957=head1 NAME
958
959tei2korapxml - Conversion of TEI P5 based formats to KorAP-XML
960
961=head1 SYNOPSIS
962
963 cat corpus.i5.xml | tei2korapxml > corpus.korapxml.zip
964
965=head1 DESCRIPTION
966
Akronee434b12020-07-08 12:53:01 +0200967C<tei2korapxml> is a script to convert TEI P5 and
968L<I5|https://www1.ids-mannheim.de/kl/projekte/korpora/textmodell.html>
969based documents to the
970L<KorAP-XML format|https://github.com/KorAP/KorAP-XML-Krill#about-korap-xml>.
971If no specific input is defined, data is
Akrond949e182020-02-14 12:23:57 +0100972read from C<STDIN>. If no specific output is defined, data is written
973to C<STDOUT>.
Peter Harders6f526a32020-06-29 21:44:41 +0200974
Akrond949e182020-02-14 12:23:57 +0100975This program is usually called from inside another script.
976
Akronee434b12020-07-08 12:53:01 +0200977=head1 FORMATS
978
979=head2 Input restrictions
980
981=over 2
982
983=item
984
985utf8 encoded
986
987=item
988
989TEI P5 formatted input with certain restrictions:
990
991=over 4
992
993=item
994
995B<mandatory>: text-header with integrated textsigle, text-body
996
997=item
998
999B<optional>: corp-header with integrated corpsigle,
1000doc-header with integrated docsigle
1001
1002=back
1003
1004=item
1005
1006all tokens inside the primary text (inside $data) may not be
1007newline seperated, because newlines are removed
1008(see code section C<~ inside text body ~>) and a conversion of newlines
1009into blanks between 2 tokens could lead to additional blanks,
1010where there should be none (e.g.: punctuation characters like C<,> or
1011C<.> should not be seperated from their predecessor token).
1012(see also code section C<~ whitespace handling ~>).
1013
1014=back
1015
1016=head2 Notes on the output
1017
1018=over 2
1019
1020=item
1021
1022zip file output (default on C<stdout>) with utf8 encoded entries
1023(which together form the KorAP-XML format)
1024
1025=back
1026
Akrond949e182020-02-14 12:23:57 +01001027=head1 INSTALLATION
1028
1029C<tei2korapxml> requires L<libxml2-dev> bindings to build. When
1030these bindings are available, the preferred way to install the script is
1031to use L<cpanm|App::cpanminus>.
1032
1033 $ cpanm https://github.com/KorAP/KorAP-XML-TEI.git
1034
1035In case everything went well, the C<tei2korapxml> tool will
1036be available on your command line immediately.
Peter Harders6f526a32020-06-29 21:44:41 +02001037
Akrond949e182020-02-14 12:23:57 +01001038Minimum requirement for L<KorAP::XML::TEI> is Perl 5.16.
1039
1040=head1 OPTIONS
1041
1042=over 2
1043
Akron4e603a52020-07-27 14:23:49 +02001044=item B<--root|-r>
Akrond949e182020-02-14 12:23:57 +01001045
Akron4e603a52020-07-27 14:23:49 +02001046The root directory for output. Defaults to C<.>.
Akrond949e182020-02-14 12:23:57 +01001047
1048=item B<--help|-h>
1049
1050Print help information.
1051
1052=item B<--version|-v>
1053
1054Print version information.
1055
Akron4e603a52020-07-27 14:23:49 +02001056=item B<--tokenizer-call|-tc>
1057
1058Call an external tokenizer process, that will tokenize
1059a single line from STDIN and outputs one token per line.
1060
1061=item B<--use-intern-tokenization|-ti>
1062
1063Tokenize the data using two embedded tokenizers,
1064that will take an I<Aggressive> and a I<conservative>
1065approach.
1066
Akron3378dfd2020-08-01 15:01:36 +02001067=item B<--log|-l>
1068
1069Loglevel for I<Log::Any>. Defaults to C<notice>.
1070
Akrond949e182020-02-14 12:23:57 +01001071=back
1072
1073=head1 COPYRIGHT AND LICENSE
1074
1075Copyright (C) 2020, L<IDS Mannheim|https://www.ids-mannheim.de/>
1076
1077Author: Peter Harders
1078
1079Contributors: Marc Kupietz, Carsten Schnober, Nils Diewald
1080
1081L<KorAP::XML::TEI> is developed as part of the L<KorAP|https://korap.ids-mannheim.de/>
1082Corpus Analysis Platform at the
1083L<Leibniz Institute for the German Language (IDS)|http://ids-mannheim.de/>,
1084member of the
1085L<Leibniz-Gemeinschaft|http://www.leibniz-gemeinschaft.de/>.
1086
1087This program is free software published under the
1088L<BSD-2 License|https://raw.githubusercontent.com/KorAP/KorAP-XML-TEI/master/LICENSE>.
1089
1090=cut