/[webpac]/trunk/all2xml.pl
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Diff of /trunk/all2xml.pl

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 5 by dpavlin, Sat Jan 11 06:14:48 2003 UTC revision 678 by dpavlin, Sun Feb 27 23:07:35 2005 UTC
# Line 1  Line 1 
1  #!/usr/bin/perl -w  #!/usr/bin/perl -w
2    
3  use strict;  use strict;
4  use OpenIsis;  use Biblio::Isis;
5  use Getopt::Std;  use Getopt::Std;
6  use Data::Dumper;  use Data::Dumper;
7  use XML::Simple;  use XML::Simple;
8  use Text::Unaccent 1.02;        # 1.01 won't compile on my platform,  use Text::Iconv;
9  require Unicode::Map8;  use Config::IniFiles;
10    use Encode;
11  my $config=XMLin(undef, forcearray => [ 'isis' ], forcecontent => 1);  #use GDBM_File;
12    use Fcntl;      # for O_RDWR
13    use TDB_File;
14    use Carp;
15    
16    $|=1;
17    
18    my $config_file = $0;
19    $config_file =~ s/\.pl$/.conf/;
20    $config_file = $ARGV[0] if ($ARGV[0] && -f $ARGV[0]);
21    die "FATAL: can't find configuration file '$config_file'" if (! -e $config_file);
22    
23    my $config;
24    
25    #use index_DBI;         # default DBI module for index
26    #use index_DBI_cache;   # faster DBI module using memory cache
27    use index_DBI_filter;   # filter support for indexes
28    my $index;
29    
30  my %opts;  my %opts;
31    
32  getopts('d:m:q', \%opts);  # usage:
33    #       -d directory name
34    #       -m multiple directories
35    #       -q quiet
36    #       -s run swish
37    
38    getopts('d:m:qs', \%opts);
39    
40    my $path;       # this is name of database
41    
42    Text::Iconv->raise_error(0);     # Conversion errors don't raise exceptions
43    
44    # this is encoding of all files on disk, including import_xml/*.xml file and
45    # filter/*.pm files! It will be used to store strings in perl internally!
46    my $codepage = 'ISO-8859-2';
47    
48    my $utf2cp = Text::Iconv->new('UTF-8',$codepage);
49    # this function will convert data from XML files to local encoding
50    sub x {
51            return $utf2cp->convert($_[0]);
52    }
53    
54    # decode isis/excel or other import codepage
55    my $import2cp;
56    
57  my $db_dir = $opts{d} || "ps";  # FIX  # outgoing xml must be in UTF-8
58    my $cp2utf = Text::Iconv->new($codepage,'UTF-8');
59    
60  #die "usage: $0 -d [database_dir] -m [database1,database2] " if (! %opts);  # mapping between data type and tag which specify
61    # format in XML file
62    my %type2tag = (
63            'isis' => 'isis',
64            'excel' => 'column',
65            'marc' => 'marc',
66            'feed' => 'feed',
67            'dbf' => 'isis',        # special case, re-use isis import_xml
68    );
69    
70  #print Dumper($config->{indexer});  my $cache;      # for cacheing
 #print "-" x 70,"\n";  
71    
72  # how to convert isis code page to UTF8?  # lookup hash (tied to file)
73  my $isis_map = Unicode::Map8->new($config->{isis_codepage}) || die;  my %lhash;
74    # this option will cache all lookup entries in memory.
75    # if you are tight on memory, turn this off
76    my $use_lhash_cache = 1;
77    
78  sub isis2xml {  my $last_field_name;    # cache to prevent repeated fields
79    
80    sub data2xml {
81    
82            use xmlify;
83    
84            my $type = shift @_;
85          my $row = shift @_;          my $row = shift @_;
86            my $add_xml = shift @_;
87            # needed to read values from configuration file
88            my $cfg = shift @_;
89            my $database = shift @_;
90    
91          my $xml;          my $xml;
92    
93          sub isis_sf {          use parse_format;
94                  my $row = shift @_;  
95                  my $isis_id = shift @_;          my $html = "";          # html formatted display output
96                  my $subfield = shift @_;  
97                  if ($row->{$isis_id}->[0]) {          my %field_usage;        # counter for usage of each field
98                          my $sf = OpenIsis::subfields($row->{$isis_id}->[0]);  
99                          if (! defined $subfield || length($subfield) == 0) {          # sort subrouting using order="" attribute
100                                  # subfield list undef, empty or no defined subfields for this record          sub by_order {
101                                  my $all_sf = $row->{$isis_id}->[0];                  my $va = $config->{indexer}->{$a}->{order} ||
102                                  $all_sf =~ s/\^./ /g;   nuke definirions                          $config->{indexer}->{$a};
103                                  return $all_sf;                  my $vb = $config->{indexer}->{$b}->{order} ||
104                          } elsif ($sf->{$subfield}) {                          $config->{indexer}->{$b};
105                                  return $sf->{$subfield};  
106                    return $va <=> $vb;
107            }
108    
109            my @sorted_tags;
110            if ($cache->{tags_by_order}) {
111                    @sorted_tags = @{$cache->{tags_by_order}};
112            } else {
113                    @sorted_tags = sort by_order keys %{$config->{indexer}};
114                    $cache->{tags_by_order} = \@sorted_tags;
115            }
116    
117            if (! @sorted_tags) {
118                    print STDERR "WARNING: no tags for this type found in import_xml file!\n";
119            }
120    
121            # lookup key
122            my $lookup_key;
123    
124            # cache for field in pages
125            delete $cache->{display_data};
126            delete $cache->{swish_data};
127            delete $cache->{swish_exact_data};
128            delete $cache->{index_data};
129            delete $cache->{index_delimiter};
130            my @page_fields;        # names of fields
131    
132    
133            # subs used to produce output
134    
135            sub get_field_name($$$) {
136                    my ($config,$field,$field_usage) = @_;
137    
138                    # find field name (signular, plural)
139                    my $field_name = "";
140                    if ($config->{indexer}->{$field}->{name_singular} && $field_usage == 1) {
141                            $field_name = $config->{indexer}->{$field}->{name_singular};
142                    } elsif ($config->{indexer}->{$field}->{name_plural}) {
143                            $field_name = $config->{indexer}->{$field}->{name_plural};
144                    } elsif ($config->{indexer}->{$field}->{name}) {
145                            $field_name = $config->{indexer}->{$field}->{name};
146                    } else {
147                            print STDERR "WARNING: field '$field' doesn't have 'name' attribute!";
148                    }
149    
150                    if ($field_name) {
151                            $field_name = x($field_name);
152                            if (! $last_field_name) {
153                                    $last_field_name = $field_name;
154                                    return $last_field_name;
155                            } elsif ($field_name ne $last_field_name) {
156                                    $last_field_name = $field_name;
157                                    return $last_field_name;
158                          }                          }
159                  }                  }
160          }          }
161    
         foreach my $field (keys %{$config->{indexer}}) {  
162    
163            # init variables for different types
164            sub init_visible_type($) {
165                    my $type = shift;
166    
167                    # swish, swish_exact, display, index, index_lookup
168                    # swish and display defaults
169                    my ($s,$se,$d,$i,$il) = (1,0,1,0,0);
170                    if (lc($type) eq "display") {
171                            $s = 0;
172                    } elsif (lc($type) eq "swish") {
173                            $d = 0;
174                    } elsif (lc($type) eq "index") {
175                            ($s,$se,$d,$i) = (0,1,0,1);
176                    } elsif (lc($type) eq "swish_exact") {
177                            ($s,$se,$d,$i) = (0,1,0,0);
178                    } elsif (lc($type) =~ /^lookup/) {
179                            ($s,$se,$d,$i,$il) = (0,1,0,0,1);
180                    } elsif ($type) {
181                            print STDERR "WARNING: unknown type: $type\n";
182                    }
183                    return ($s,$se,$d,$i,$il);
184            }
185    
186    
187            # convert
188            #
189            # <tag>
190            #  <delimiter>, </delimiter>
191            #  <value>200a</value>
192            # </tag>
193            #
194            # to
195            #
196            # <tag delimiter=", ">200a</tag>
197            #
198            # but without loosing spaces in delimiter (becasue
199            # new XML::Simple strips spaces in attribute values
200            # as defined in XML specification)
201            #
202            sub unroll_x($) {
203                    my $x = shift;
204    
205                    if (defined $x->{value}) {
206                            my ($v,$d) = ($x->{value}->{content}, $x->{delimiter}->{content});
207                            delete $x->{value};
208                            delete $x->{delimiter};
209                            $x->{content} = $v;
210                            $x->{delimiter} = $d;
211                    }
212                    return $x;
213            }
214    
215            # begin real work: go field by field
216            foreach my $field (@sorted_tags) {
217    
218                    $field=x($field);
219                    $field_usage{$field}++;
220    
221                    my $swish_data = "";
222                    my $swish_exact_data = "";
223                  my $display_data = "";                  my $display_data = "";
224                  my $index_data = "";                  my @index_data;
225                    my $line_delimiter;
226    
227                    my ($swish,$display);
228    
229                    my $tag = $type2tag{$type} || die "can't find which tag to use for type $type";
230    
231                    # is this field page-by-page?
232                    my $iterate_by_page = $config->{indexer}->{$field}->{iterate_by_page};
233                    push @page_fields,$field if ($iterate_by_page);
234                    my %page_max = ();
235                    # default line_delimiter if using
236                    my $page_line_delimiter = $config->{indexer}->{$field}->{page_line_delimiter} || '<br/>';
237                    $cache->{index_delimiter}->{$field} = $config->{indexer}->{$field}->{index_delimiter};
238    
239                    my $format_name = $config->{indexer}->{$field}->{format_name};
240                    my $format_delimiter = $config->{indexer}->{$field}->{format_delimiter};
241                    if ($format_name && $format_delimiter) {
242                            $cache->{format}->{$field}->{format_name} = $format_name;
243                            $cache->{format}->{$field}->{format_delimiter} = $format_delimiter;
244                    }
245    
246                    foreach my $x (@{$config->{indexer}->{$field}->{$tag}}) {
247    
248                  foreach my $x (@{$config->{indexer}->{$field}->{isis}}) {                          $x = unroll_x($x);
249    
250                          my $display_tmp = "";                          my $format = x($x->{content});
251                          my $index_tmp = "";                          my $delimiter = x($x->{delimiter}) || ' ';
252    
253                          my $format = $x->{content};                          my $repeat_off = 0;     # init repeatable offset
254                          my $i = 1;      # index only  
255                          my $d = 1;      # display only                          my ($s,$se,$d,$i,$il) = init_visible_type($x->{type});
256                          $i = 0 if (lc($x->{type}) eq "display");  
257                          $d = 0 if (lc($x->{type}) eq "index");                          # what will separate last line from this one?
258  #print "## i: $i d: $d ## $format ##";                            if ($display_data && $x->{append}) {
259                          # parse format                                  $line_delimiter = $delimiter;
260                          my $prefix = "";                          } elsif ($display_data) {
261                          if ($format =~ s/^([^\d]+)//) {                                  $line_delimiter = '<br/>';
262                                  $prefix = $1;                          }
263                          }  
264                          while ($format) {                          # init vars so that we go into while...
265                                  if ($format =~ s/^(\d\d\d)(\w?)//) {                          ($swish,$display) = (1,1);
266                                          my $isis_tmp = isis_sf($row,$1,$2);  
267                                          if ($isis_tmp) {                          sub mkformat($$) {
268  #                                               $display_tmp .= $prefix . "/$1/$2/".$isis_tmp if ($d);                                  my $x = shift || die "mkformat needs tag reference";
269                                                  $display_tmp .= $prefix . $isis_tmp if ($d);                                  my $data = shift || return;
270                                                  $index_tmp .= $isis_tmp." " if ($i);                                  my $format_name = x($x->{format_name}) || return $data;
271  #print " $isis_tmp <--\n";                                  my $fmt = x($config->{format}->{$format_name}->{content}) || die "<format name=\"$format_name\"> is not defined!";
272                                          }                                  my $format_delimiter = x($x->{format_delimiter});
273                                          $prefix = "";                                  my @data;
274                                  } elsif ($format =~ s/^([^\d]+)//) {                                  if ($format_delimiter) {
275                                          $prefix = $1;                                          @data = split(/$format_delimiter/,$data);
276                                  } else {                                  } else {
277                                          print STDERR "WARNING: unparsed format '$format'\n";                                          push @data,$data;
278                                    }
279    
280                                    if ($fmt) {
281                                            my $nr = scalar $fmt =~ s/%s/%s/g;
282                                            if (($#data+1) == $nr) {
283                                                    return sprintf($fmt,@data);
284                                            } else {
285                                                    #print STDERR "mkformat: [$data] can't be split on [$format_delimiter] to $nr fields!\n";
286                                                    return $data;
287                                            }
288                                    } else {
289                                            print STDERR "usage of link '$format_name' without defined format (<link> tag)\n";
290                                    }
291                            }
292    
293                            # while because of repeatable fields
294                            while ($swish || $display) {
295                                    my $page = $repeat_off;
296                                    $page_max{$field} = $page if ($iterate_by_page && $page > ($page_max{$field} || 0));
297                                    ($swish,$display) = parse_format($type, $format,$row,$repeat_off++,$import2cp);
298                                    if ($repeat_off > 1000) {
299                                            print STDERR "loop (more than 1000 repeatable fields) deteced in $row, $format\n";
300                                          last;                                          last;
301                                  };                                  }
302    
303                                    # is this field is lookup?
304                                    if ($display && $x->{lookup}) {
305                                            my $null = "<!-- null -->";
306                                            if ($use_lhash_cache) {
307                                                    if (!defined($cache->{lhash}->{$display})) {
308                                                            my $new_display = $lhash{$display};
309                                                            if (defined($new_display)) {
310    #print STDERR "lookup cache store '$display' = '$new_display'\n";
311                                                                    $display = $new_display;
312                                                                    $cache->{lhash}->{$display} = $new_display;
313                                                            } else {
314    #                                                               print STDERR "WARNING: lookup for '$display' didn't find anything.\n";
315                                                                    $display = "";
316                                                                    $cache->{lhash}->{$display} = $null;
317                                                            }
318                                                    } else {
319                                                            $display = $cache->{lhash}->{$display};
320                                                    }
321                                            } else {
322                                                    $display = $lhash{$display} || $null;
323                                            }
324                                    }
325    
326                                    # filter="name" ; filter this field through
327                                    # filter/[name].pm
328                                    my $filter = $x->{filter};
329                                    if ($filter && !$cache->{filter_loaded}->{$filter}) {
330                                            require "filter/".$filter.".pm";
331                                            $cache->{filter_loaded}->{$filter}++;
332                                    }
333                                    # type="swish" ; field for swish
334                                    if ($swish) {
335                                            my $tmp = $swish;
336                                            if ($filter && ($s || $se)) {
337                                                    no strict 'refs';
338                                                    $tmp = join(" ",&$filter($tmp)) if ($s || $se);
339                                            }
340    
341                                            $swish_data .= $tmp if ($s && $tmp);
342                                            $swish_exact_data .= "xxbxx $tmp xxexx " if ($tmp && $tmp ne "" && $se);
343                                    }
344    
345                                    # type="display" ; field for display
346                                    if ($d && $display) {
347                                            my $ldel = $delimiter;
348                                            if ($line_delimiter && $display_data) {
349                                                    $ldel = $line_delimiter;
350                                            }
351                                            if ($filter) {
352                                                    no strict 'refs';
353                                                    my @arr;
354                                                    foreach my $tmp (&$filter($display)) {
355                                                            my $tmp2 = mkformat($x,$tmp);
356                                                            push @arr,$tmp2 if ($tmp2);
357                                                    }
358                                                    $display_data .= $ldel if ($display_data && @arr);
359                                                    $display_data .= join($delimiter,@arr);
360                                            } else {
361                                                    $display_data .= $ldel if ($display_data);
362                                                    my $tmp = mkformat($x,$display);
363                                                    $display_data .= $tmp if ($tmp);
364                                            }
365                                    }
366                                                    
367                                    # type="index" ; insert into index
368                                    my $idisplay;
369                                    if ($i && $display) {
370                                            $idisplay = $display;
371                                            if ($filter) {
372                                                    no strict 'refs';
373                                                    $idisplay = &$filter($idisplay);
374                                            }
375                                            push @index_data, $idisplay if ($idisplay && !$iterate_by_page);
376                                    }
377    
378                                    # store fields in lookup
379                                    if ($il && $display) {
380                                            if (lc($x->{type}) eq "lookup_key") {
381                                                    if ($lookup_key) {
382                                                            print STDERR "WARNING: try to redefine lookup_key (keys shouldn't be repeatable fields!)";
383                                                    } else {
384                                                            if ($filter) {
385                                                                    no strict 'refs';
386                                                                    $lookup_key = &$filter($display);
387                                                            } else {
388                                                                    $lookup_key = $display;
389                                                            }
390                                                    }
391                                            } elsif (lc($x->{type}) eq "lookup_val") {
392                                                    if ($lookup_key) {
393                                                            if ($filter) {
394                                                                    no strict 'refs';
395                                                                    $lhash{$lookup_key} = &$filter($display);
396                                                            } else {
397                                                                    $lhash{$lookup_key} = $display;
398                                                            }
399                                                    } else {
400                                                            print STDERR "WARNING: no lookup_key defined for  '$display'?";
401                                                    }
402                                            }
403    
404                                    }
405    
406                                    # store data for page-by-page repeatable fields
407                                    if ($iterate_by_page) {
408                                            sub iterate_fld($$$$$$) {
409                                                    my ($cache,$what,$field,$page,$data,$append) = @_;
410                                                    return if (!$data);
411    
412                                                    my $ldel = $page_line_delimiter;
413                                                    $ldel = " " if ($append);
414    #print STDERR "line delimiter: ",Dumper($ldel) if ($ldel);
415                                                    if (! $cache->{$what}->{$field}->[$page]) {
416                                                            $cache->{$what}->{$field}->[$page] = $data;
417                                                    } else {
418                                                            $cache->{$what}->{$field}->[$page] .= $ldel.$data;
419                                                    }
420                                            }
421    
422                                            if ($display_data) {
423                                                    iterate_fld($cache,'display_data',$field,$page,$display_data,$x->{append});
424                                            }
425                                                    $display_data = "";
426                                            if ($swish_data) {
427                                                    iterate_fld($cache,'swish_data',$field,$page,$swish_data,$x->{append});
428                                                    $swish_data = "";
429                                            }
430                                            if ($swish_exact_data) {
431                                                    iterate_fld($cache,'swish_exact_data',$field,$page,$swish_exact_data,$x->{append});
432                                                    $swish_exact_data = "";
433                                            }
434    
435                                            if ($idisplay) {
436                                                    my $ldel=$page_line_delimiter;
437                                                    my @index_data;
438                                                    if ($cache->{index_data}->{$field}->[$page]) {
439    
440                                                            @index_data = @{$cache->{index_data}->{$field}->[$page]};
441                                                    }
442                                                    if ($x->{append}) {
443                                                            if (@index_data) {
444                                                                    $index_data[$#index_data] .= $idisplay;
445                                                            } else {
446                                                                    push @index_data, $idisplay;
447                                                            }
448                                                    } else {
449                                                            push @index_data, $idisplay;
450                                                    }
451                                                    $idisplay = "";
452                                                    @{$cache->{index_data}->{$field}->[$page]} = @index_data;
453                                            }
454                                    }
455                          }                          }
                         # add suffix  
                         $display_tmp .= $prefix if ($display_tmp);  
456    
457  #                       $display_data .= $display_tmp if ($display_tmp ne "");                          if (! $iterate_by_page) {
458  #                       $index_data .= $index_tmp if ($index_tmp ne "");                                  my $idel = $x->{index_delimiter};
459                          $display_data .= $display_tmp;                                  # fill data in index
460                          $index_data .= $index_tmp;                                  foreach my $tmp (@index_data) {
461                                            my $i = $d = $tmp;
462                                            if ($idel && $tmp =~ m/$idel/) {
463                                                    ($i,$d) = split(/$idel/,$tmp);
464                                            }
465                                            $index->insert($field, $i, $d, $path);
466                                    }
467                                    @index_data = ();
468                            }
469                    }
470    
471                    # now try to parse variables from configuration file
472                    foreach my $x (@{$config->{indexer}->{$field}->{'config'}}) {
473    
474                            $x = unroll_x($x);
475    
476                            my $delimiter = x($x->{delimiter}) || ' ';
477                            my $val = $cfg->val($database, x($x->{content}));
478    
479                            # FIXME index_lookup is not supported!
480                            my ($s,$se,$d,$i,$il) = init_visible_type($x->{type});
481    
482                            if ($val) {
483                                    $display_data .= $delimiter.$val if ($d);
484                                    $swish_data .= " ".$val if ($s);
485                                    $index->insert($field, $val, $path) if ($i);
486                            }
487    
488                            if ($iterate_by_page) {
489                                    # FIXME data from config tag will appear just
490                                    # on first page!!!
491                                    my $page = 0;
492                                    if ($display_data) {
493                                            $cache->{display_data}->{$field}->[$page] = $display_data;
494                                            $display_data = "";
495                                    }
496                                    if ($swish_data) {
497                                            $cache->{swish_data}->{$field}->[$page] = $swish_data;
498                                            $swish_data = "";
499                                    }
500                                    if ($swish_exact_data) {
501                                            $cache->{swish_exact_data}->{$field}->[$page] = $swish_exact_data;
502                                            $swish_exact_data = "";
503                                    }
504                            }
505                  }                  }
506  #print "--display:$display_data\n--index:$index_data\n";  
507                  $xml->{$field}->{display} .= $isis_map->tou($display_data)->utf8 if ($display_data);                  # save data page-by-page
508                  $xml->{$field}->{index} .= unac_string($config->{isis_codepage},$index_data) if ($index_data);                  foreach my $field (@page_fields) {
509                            my $nr_pages = $page_max{$field} || next;
510    #print STDERR "field '$field' iterate over ",($nr_pages || 0)," pages...\n";
511    #print STDERR Dumper($cache->{display_data});
512                            for (my $page=0; $page <= $nr_pages; $page++) {
513                                    my $display_data;
514                                    if ($cache->{format}->{$field}) {
515                                            my $tmp = mkformat($cache->{format}->{$field},$cache->{display_data}->{$field}->[$page]);
516                                            $display_data=$tmp if ($tmp);
517                                    } else {
518                                            $display_data = $cache->{display_data}->{$field}->[$page];
519                                    }
520                                    if ($display_data) { # default
521                                            if ($field eq "headline") {
522                                                    $xml .= xmlify("headline", $display_data);
523                                            } else {
524    
525                                                    # fallback to empty field name if needed
526                                                    $html .= get_field_name($config,$field,$field_usage{$field}) || '';
527                                                    $html .= "#-#".$display_data."###\n";
528                                            }
529                                    }
530                                    
531                                    my $swish_data = $cache->{swish_data}->{$field}->[$page];
532                                    if ($swish_data) {
533                                            # remove extra spaces
534                                            $swish_data =~ s/ +/ /g;
535                                            $swish_data =~ s/ +$//g;
536    
537                                            $xml .= xmlify($field."_swish", my_unac_string($codepage,$swish_data));
538                                    }
539    
540                                    my $swish_exact_data = $cache->{swish_exact_data}->{$field}->[$page];
541                                    if ($swish_exact_data) {
542                                            $swish_exact_data =~ s/ +/ /g;
543                                            $swish_exact_data =~ s/ +$//g;
544    
545                                            # add delimiters before and after word.
546                                            # That is required to produce exact match
547                                            $xml .= xmlify($field."_swish_exact", my_unac_string($codepage,$swish_exact_data));
548                                    }
549                                    
550                                    my $idel = $cache->{index_delimiter}->{$field};
551                                    foreach my $tmp (@{$cache->{index_data}->{$field}->[$page]}) {
552                                            my $i = $tmp;
553                                            my $d = $tmp;
554                                            if ($idel && $tmp =~ m/$idel/) {
555                                                    ($i,$d) = split(/$idel/,$tmp);
556                                            }
557                                            $index->insert($field, $i, $d, $path);
558    #print STDERR "index [$idel] $field: $i --> $d [$path]\n";
559                                    }
560                            }
561                    
562                    }
563                    
564                    if (! $iterate_by_page) {
565                            if ($display_data) {
566                                    if ($field eq "headline") {
567                                            $xml .= xmlify("headline", $display_data);
568                                    } else {
569    
570                                            # fallback to empty field name if needed
571                                            $html .= get_field_name($config,$field,$field_usage{$field}) || '';
572                                            $html .= "#-#".$display_data."###\n";
573                                    }
574                            }
575                            if ($swish_data) {
576                                    # remove extra spaces
577                                    $swish_data =~ s/ +/ /g;
578                                    $swish_data =~ s/ +$//g;
579    
580                                    $xml .= xmlify($field."_swish", my_unac_string($codepage,$swish_data));
581                            }
582    
583                            if ($swish_exact_data) {
584                                    $swish_exact_data =~ s/ +/ /g;
585                                    $swish_exact_data =~ s/ +$//g;
586    
587                                    # add delimiters before and after word.
588                                    # That is required to produce exact match
589                                    $xml .= xmlify($field."_swish_exact", my_unac_string($codepage,$swish_exact_data));
590                            }
591                    }
592          }          }
593    
594            # dump formatted output in <html>
595            if ($html) {
596                    #$xml .= xmlify("html",$html);
597                    $xml .= "<html><![CDATA[ $html ]]></html>";
598            }
599            
600          if ($xml) {          if ($xml) {
601                  return XMLout($xml, rootname => 'xml', noattr => 1 );                  $xml .= $add_xml if ($add_xml);
602                    return "<xml>\n$xml</xml>\n";
603          } else {          } else {
604                  return;                  return;
605          }          }
# Line 108  sub isis2xml { Line 607  sub isis2xml {
607    
608  ##########################################################################  ##########################################################################
609    
610  my $last_tell=0;  # read configuration for this script
611    my $cfg = new Config::IniFiles( -file => $config_file );
612    
613  my @isis_dirs = ( '.' );        # use dirname as database name  # read global.conf configuration
614    my $cfg_global = new Config::IniFiles( -file => 'global.conf' );
615    
616  if ($opts{m}) {  # open index
617          @isis_dirs = split(/,/,$opts{m});  $index = new index_DBI(
618                    $cfg_global->val('global', 'dbi_dbd'),
619                    $cfg_global->val('global', 'dbi_dsn'),
620                    $cfg_global->val('global', 'dbi_user'),
621                    $cfg_global->val('global', 'dbi_passwd') || '',
622            );
623    
624    my $show_progress = $cfg_global->val('global', 'show_progress');
625    
626    my $my_unac_filter = $cfg_global->val('global', 'my_unac_filter');
627    if ($my_unac_filter) {
628            print STDERR "using $my_unac_filter to filter characters for search\n";
629            require $my_unac_filter;
630    } else {
631            print STDERR "### fallback to default my_unac_string!\n";
632            eval q{
633            sub main::my_unac_string($$) {
634                    my ($charset, $string) = (@_);
635                    return $string;
636            }
637            };
638  }  }
639    
640  my @isis_dbs;  foreach my $database ($cfg->Sections) {
641    
642  foreach (@isis_dirs) {          # save database name in global variable path for later
643          if (-e $config->{isis_data}."/$db_dir/$_/LIBRI") {          # (need for index filter creation)
644                  push @isis_dbs,$config->{isis_data}."/$db_dir/$_/LIBRI/LIBRI";          $path = $database;
645          }  
646          if (-e $config->{isis_data}."/$db_dir/$_/PERI") {          my $type = lc($cfg -> val($database, 'type')) || die "$database doesn't have 'type' defined";
647                  push @isis_dbs,$config->{isis_data}."/$db_dir/$_/PERI/PERI";          my $add_xml = $cfg -> val($database, 'xml');    # optional
648    
649            # create new lookup file
650            my $lookup_file = $cfg -> val($database, 'lookup_newfile'); # optional
651            if ($lookup_file) {
652                    #tie %lhash, 'GDBM_File', $lookup_file, &GDBM_NEWDB, 0644;
653                    if (! -e $lookup_file) {
654                            open(LOOKUP, "> $lookup_file") || die "can't create $lookup_file': $!";
655                            close(LOOKUP);
656                    }
657                    tie %lhash, 'TDB_File', $lookup_file, TDB_CLEAR_IF_FIRST, O_RDWR, 0644;
658                    print STDERR "creating lookup file '$lookup_file'\n";
659                    # delete memory cache for lookup file
660                    delete $cache->{lhash};
661          }          }
662          if (-e $config->{isis_data}."/$db_dir/$_/AMS") {  
663                  push @isis_dbs,$config->{isis_data}."/$db_dir/$_/AMS/AMS";          # open existing lookup file
664            $lookup_file = $cfg -> val($database, 'lookup_open'); # optional
665            if ($lookup_file) {
666                    #tie %lhash, 'GDBM_File', $lookup_file, &GDBM_READER, 0644;
667                    tie %lhash, 'TDB_File', $lookup_file, TDB_DEFAULT, O_RDWR, 0644;
668                    print STDERR "opening lookup file '$lookup_file'\n";
669          }          }
670          if (-e $config->{isis_data}."/$db_dir/$_/ARTI") {  
671  #               push @isis_dbs,$config->{isis_data}."/$db_dir/$_/ARTI/ARTI";          my $import_xml_file = "./import_xml/$type.xml";
672    
673            if (! -r $import_xml_file) {
674                    print STDERR "ERROR: file $import_xml_file not readable skipping!\n";
675                    next;
676          }          }
 }  
677    
678  print STDERR "FATAL: Can't find isis database.\nPerhaps isis_data (".$config->{isis_data}.") has wrong value?\n" if (! @isis_dbs);          print STDERR "reading $import_xml_file\n";
679    
680            # extract just type basic
681            my $type_base = $type;
682            $type_base =~ s/_.+$//g;
683    
684            $config=XMLin($import_xml_file, ForceArray => [ $type2tag{$type_base}, 'config', 'format' ], ForceContent => 1 );
685    
686            # helper for progress bar
687            sub fmt_time {
688                    my $t = shift || 0;
689                    my $out = "";
690    
691                    my ($ss,$mm,$hh) = gmtime($t);
692                    $out .= "${hh}h" if ($hh);
693                    $out .= sprintf("%02d:%02d", $mm,$ss);
694                    $out .= "  " if ($hh == 0);
695                    return $out;
696            }
697    
698  my $db;          # output current progress indicator
699            my $last_p = 0;
700            my $start_t = time();
701            sub progress {
702                    return if (! $show_progress);
703                    my $current = shift;
704                    my $total = shift || 1;
705                    my $p = int($current * 100 / $total);
706                    if ($p < $last_p || $current == 1) {
707                            $start_t = time();
708                            $last_p = 0;
709                    } elsif ($p != $last_p) {
710                            my $rate = ($current / (time() - $start_t || 1));
711                            my $eta = ($total-$current) / ($rate || 1);
712                            printf STDERR ("%5d [%-38s] %-5d %0.1f/s %s\r",$current,"=" x ($p/3)."$p%>", $total, $rate, fmt_time($eta));
713                            $last_p = $p;
714                    }
715            }
716    
717  foreach my $isis_db (@isis_dbs) {          my $fake_dir = 1;
718            my $fake_pos = 0;
719            my $last_fake_t = time();
720            sub fakeprogress {
721                    return if (! $show_progress);
722                    my $current = shift @_;
723    
724                    my @ind = ('-','\\','|','/','-','\\','|','/');
725    
726                    if ($current < $fake_pos) {
727                            $start_t = time();
728                            $last_fake_t = 0;
729                            $fake_dir = 1;
730                            $fake_pos = 0;
731                    }
732    
733                    if (time()-$last_fake_t >= 1) {
734                            $last_fake_t = time();
735                            $fake_pos += $fake_dir;
736                            $fake_dir = -$fake_dir if ($fake_pos > 38);
737                    }
738    
739          my $db = OpenIsis::open( $isis_db );                  if ($current % 10 == 0) {
740          if (0) {                          my $rate = ($current / (time() - $start_t || 1));
741  #       # FIX                          printf STDERR ("%5d [%-38s] %0.1f/s\r",$current, " " x $fake_pos .$ind[($current / 10) % 8], $rate);
742  #       if (! $db ) {                  }
                 print STDERR "WARNING: can't open '$isis_db'\n";  
                 next ;  
743          }          }
744    
745          my $max_rowid = OpenIsis::maxRowid( $db );          # now read database
746    print STDERR "using: $type...\n";
747    
748          print STDERR "Reading database: $isis_db [$max_rowid rows]\n";          # erase cache for tags by order in this database
749            delete $cache->{tags_by_order};
750    
751          my $last_p = 0;          if ($type_base eq "isis") {
752    
753                    my $isis_db = $cfg -> val($database, 'isis_db') || die "$database doesn't have 'isis_db' defined!";
754    
755                    $import2cp = Text::Iconv->new($config->{isis_codepage},$codepage);
756                    my $db = new Biblio::Isis( isisdb => $isis_db );
757    
758                    if (! $db) {
759                            print STDERR "FATAL: can't read ISIS database: $isis_db, skipping...\n";
760                            next;
761                    }
762    
763                    my $max_rowid = $db->count if ($db);
764    
765                    print STDERR "Reading database: $isis_db [$max_rowid rows]\n";
766    
767                    for (my $row_id = 1; $row_id <= $max_rowid; $row_id++ ) {
768                            my $row = $db->to_hash( $row_id );
769                            if ($row) {
770    
771                                    $row->{mfn} = $row_id;
772                                    $row->{record} = $db->{record};
773    
774                                    progress($row->{mfn}, $max_rowid);
775    
776                                    my $swishpath = $path."#".int($row->{mfn});
777    
778                                    if (my $xml = data2xml($type_base,$row,$add_xml,$cfg,$database)) {
779                                            $xml = $cp2utf->convert($xml);
780                                            use bytes;      # as opposed to chars
781                                            print "Path-Name: $swishpath\n";
782                                            print "Content-Length: ".(length($xml)+1)."\n";
783                                            print "Document-Type: XML\n\n$xml\n";
784                                    }
785                            }
786                    }
787                    print STDERR "\n";
788    
789            } elsif ($type_base eq "excel") {
790                    require Spreadsheet::ParseExcel;
791                    require Spreadsheet::ParseExcel::Utility;
792                    import Spreadsheet::ParseExcel::Utility qw(int2col);
793                    
794                    $import2cp = Text::Iconv->new($config->{excel_codepage},$codepage);
795                    my $excel_file = $cfg -> val($database, 'excel_file') || die "$database doesn't have 'excel_file' defined!";
796    
797                    my $sheet = x($config->{sheet}) || die "no sheet in $type.xml";
798                    my $start_row = x($config->{start_row}) - 1 || die "no start_row in $type.xml";
799    
800                    my $oBook = Spreadsheet::ParseExcel::Workbook->Parse($excel_file) || die "can't open Excel file '$excel_file'";
801    
802                    my $sheet_nr = 0;
803                    foreach my $oWks (@{$oBook->{Worksheet}}) {
804                            #print STDERR "-- SHEET $sheet_nr:", $oWks->{Name}, "\n";
805                            last if ($oWks->{Name} eq $sheet);
806                            $sheet_nr++;
807                    }
808    
809                    my $oWorksheet = $oBook->{Worksheet}[$sheet_nr];
810            
811                    print STDERR "using sheet: ",$oWorksheet->{Name},"\n";
812                    defined ($oWorksheet) || die "can't find sheet '$sheet' in $excel_file";
813                    my $end_row = x($config->{end_row}) || $oWorksheet->{MaxRow};
814    
815                    for(my $iR = $start_row ; defined $end_row && $iR <= $end_row ; $iR++) {
816                            my $row;
817                            for(my $iC = $oWorksheet->{MinCol} ; defined $oWorksheet->{MaxCol} && $iC <= $oWorksheet->{MaxCol} ; $iC++) {
818                                    my $cell = $oWorksheet->{Cells}[$iR][$iC];
819                                    if ($cell) {
820                                            # this conversion is a cludge.
821                                            # Files from Excell could have
822                                            # characters which don't fit into
823                                            # destination encoding.
824                                            $row->{int2col($iC)} = $utf2cp->convert($cell->Value) || $cell->Value;
825                                    }
826                            }
827    
828                            progress($iR, $end_row);
829    
830    #                       print "row[$iR/$end_row] ";
831    #                       foreach (keys %{$row}) {
832    #                               print "$_: ",$row->{$_},"\t";
833    #                       }
834    #                       print "\n";
835    
836                            my $swishpath = $database."#".$iR;
837    
838                            next if (! $row);
839    
840                            if (my $xml = data2xml($type_base,$row,$add_xml,$cfg,$database)) {
841                                    $xml = $cp2utf->convert($xml);
842                                    use bytes;      # as opposed to chars
843                                    print "Path-Name: $swishpath\n";
844                                    print "Content-Length: ".(length($xml)+1)."\n";
845                                    print "Document-Type: XML\n\n$xml\n";
846                            }
847                    }
848    
849  #       { my $row_id = 1;                  print STDERR "\n";
850  # FIX  
851          for (my $row_id = 1; $row_id <= $max_rowid; $row_id++ ) {          } elsif ($type_base eq "marc") {
852                  my $row = OpenIsis::read( $db, $row_id );  
853                  if ($row && $row->{mfn}) {                  require MARC::File::USMARC;
854                    
855                          # output current process indicator                  $import2cp = Text::Iconv->new($config->{marc_codepage},$codepage);
856                          my $p = int($row->{mfn} * 100 / $max_rowid);                  my $marc_file = $cfg -> val($database, 'marc_file') || die "$database doesn't have 'marc_file' defined!";
857                          if ($p != $last_p) {  
858                                  printf STDERR ("%5d / %5d [%-51s] %-2d %% \r",$row->{mfn},$max_rowid,"=" x ($p/2).">", $p ) if (! $opts{q});                  # optional argument is format
859                                  $last_p = $p;                  warn "marc_format is no longer used!" if ($config->{marc_format});
860                    print STDERR "Reading MARC file '$marc_file'\n";
861    
862                    my $marc = MARC::File::USMARC->in( $marc_file );
863    
864                    if (! $marc) {
865                            print STDERR "FATAL: can't read MARC file: $marc_file, skipping...\n";
866                            next;
867                    }
868    
869                    # count records in MARC file
870                    sub marc_count {
871                            my $filename = shift || die;
872                            my $file = MARC::File::USMARC->in($filename) || return;
873                            my $count = 0;
874                            while ($file->skip()) {
875                                    $count++;
876                          }                          }
877                            return $count;
878                    }
879    
880                    my $count = marc_count($marc_file) || warn "no records in '$marc_file'?";
881    
882                    my $i = 1;
883    
884                    while( my $rec = $marc->next() ) {
885    
886                          if (my $xml = isis2xml($row)) {                          progress($i,$count);
887                                  print "Path-Name: $isis_db#".$row->{mfn}."\n";  
888                            my $swishpath = $database."#".$i;
889    
890                            if (my $xml = data2xml($type_base,$rec,$add_xml,$cfg,$database)) {
891                                    $xml = $cp2utf->convert($xml);
892                                    use bytes;      # as opposed to chars
893                                    print "Path-Name: $swishpath\n";
894                                  print "Content-Length: ".(length($xml)+1)."\n";                                  print "Content-Length: ".(length($xml)+1)."\n";
895                                  print "Document-Type: XML\n\n$xml\n";                                  print "Document-Type: XML\n\n$xml\n";
896                          }                          }
897    
898                            $i++;
899                  }                  }
900    
901                    print STDERR "\n";
902    
903            } elsif ($type_base eq "feed") {
904    
905                    $import2cp = Text::Iconv->new($config->{feed_codepage},$codepage);
906                    my $prog = x($config->{prog}) || die "$database doesn't have 'prog' defined!";
907    
908                    print STDERR "Reading feed from program '$prog'\n";
909    
910                    open(FEED,"feeds/$prog |") || die "can't start $prog: $!";
911    
912                    my $i=1;        # record nr.
913    
914                    my $data;
915                    my $line=1;
916    
917                    while (<FEED>) {
918                            chomp;
919    
920                            if (/^$/) {
921                                    my $swishpath = $database."#".$i++;
922    
923                                    if (my $xml = data2xml($type_base,$data,$add_xml,$cfg,$database)) {
924                                            $xml = $cp2utf->convert($xml);
925                                            use bytes;      # as opposed to chars
926                                            print "Path-Name: $swishpath\n";
927                                            print "Content-Length: ".(length($xml)+1)."\n";
928                                            print "Document-Type: XML\n\n$xml\n";
929                                    }
930                                    $line = 1;
931                                    $data = {};
932                                    next;
933                            }
934    
935                            $line = $1 if (s/^(\d+):\s*//);
936                            $data->{$line++} = $_;
937    
938                            fakeprogress($i);
939    
940                    }
941                    # close lookup
942                    untie %lhash if (%lhash);
943    
944            } elsif ($type_base eq "dbf") {
945    
946                    my $dbf_file = $cfg -> val($database, 'dbf_file') || die "$database doesn't have 'dbf_file' defined!";
947                    my $dbf_codepage = $cfg -> val($database, 'dbf_codepage') || die "$database doesn't have 'dbf_codepage' defined!";
948                    my $dbf_mapping = $cfg -> val($database, 'dbf_mapping') || die "$database doesn't have 'dbf_mapping' defined!";
949    
950                    $import2cp = Text::Iconv->new($dbf_codepage,$codepage);
951                    require XBase;
952                    my $db = new XBase $dbf_file;
953    
954                    if (! $db) {
955                            print STDERR "ERROR: can't read DBF database: $dbf_file, skipping...\n";
956                            next;
957                    }
958    
959                    my $max_rowid = $db->last_record;
960    
961                    print STDERR "Reading database: $dbf_file [$max_rowid rows]\n";
962    
963                    my %dbf2iso;
964                    foreach my $m (split(/[\n\r]+/,$dbf_mapping)) {
965                            my ($col,$fld) = split(/\s+/,$m,2);
966                            $dbf2iso{$col} = $fld;
967                    }
968    
969    #print STDERR "## dbf2iso: ",Dumper(\%dbf2iso),"\n## /dbf2iso\n";
970    
971                    # bad, bad...
972                    require "to_hash.pm";
973    
974                    foreach my $row_id (0 .. $max_rowid) {
975                            my $dbf_row = $db->get_record_as_hash($row_id);
976                            if ($dbf_row) {
977    
978    #print STDERR "## dbf_row: ",Dumper($dbf_row),"\n## /dbf_row\n";
979                                    # apply mapping from config file
980                                    # all unspecified records will get _ in
981                                    # front of them - _DELETE will be __DELETE
982                                    my $rec;
983                                    map {
984                                            my $new_fld = $dbf2iso{$_} || '_'.$_;
985                                            my $data = $dbf_row->{$_};
986                                            push @{ $rec->{$new_fld} }, $data if ($data && $data !~ /^(?:\s+|\$a\.|)$/);
987                                    } keys %{$dbf_row};
988    #print STDERR "## rec: ",Dumper($rec),"\n## /rec\n";
989                                    my $row = to_hash($row_id+1, $rec);
990    
991                                    $row->{mfn} = $row_id+1;
992                                    $row->{record} = $rec;
993    
994    #print STDERR "## row: ",Dumper($row),"\n## /row\n";
995                                    progress($row->{mfn}, $max_rowid);
996    
997                                    my $swishpath = $path."#".int($row->{mfn});
998    
999                                    if (my $xml = data2xml($type_base,$row,$add_xml,$cfg,$database)) {
1000                                            $xml = $cp2utf->convert($xml);
1001                                            use bytes;      # as opposed to chars
1002                                            print "Path-Name: $swishpath\n";
1003                                            print "Content-Length: ".(length($xml)+1)."\n";
1004                                            print "Document-Type: XML\n\n$xml\n";
1005                                    }
1006                            }
1007                    }
1008                    print STDERR "\n";
1009          }          }
         print STDERR "\n";  
1010  }  }
1011    
1012    # call this to commit index
1013    $index->close;
1014    
1015  1;  1;
1016  __END__  __END__
# Line 184  __END__ Line 1018  __END__
1018    
1019  =head1 NAME  =head1 NAME
1020    
1021  isis2xml.pl - read isis file and dump XML  all2xml.pl - read various file formats and dump XML for SWISH-E
1022    
1023    =head1 SYNOPSYS
1024    
1025     $ all2xml.pl [test.conf]
1026    
1027  =head1 DESCRIPTION  =head1 DESCRIPTION
1028    
1029  This command will read ISIS data file using OpenIsis perl module and  This command will read ISIS data file using Biblio::Isis perl module, MARC
1030  create XML file for usage with I<SWISH-E>  records using MARC::File module and optionally Micro$oft Excel files to
1031  indexer. Dispite it's name, this script B<isn't general xml generator>  create one XML file for usage with I<SWISH-E> indexer. Dispite it's name,
1032  from isis files (isis allready has something like that). Output of this  this script B<isn't general xml generator> from isis files (isis allready
1033  script is tailor-made for SWISH-E.  has something like that). Output of this script is tailor-made for SWISH-E.
1034    
1035    If no configuration file is specified, it will use default one called
1036    C<all2xml.conf>.
1037    
1038    =head1 BUGS
1039    
1040    Documentation is really lacking. However, in true Open Source spirit, source
1041    is best documentation. I even made considerable effort to comment parts
1042    which are not intuitively clear, so...
1043    
1044  =head1 AUTHOR  =head1 AUTHOR
1045    

Legend:
Removed from v.5  
changed lines
  Added in v.678

  ViewVC Help
Powered by ViewVC 1.1.26