]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/extras/import/marc2bre.pl.in
install command-line MARC import tools in @prefix@/bin
[working/Evergreen.git] / Open-ILS / src / extras / import / marc2bre.pl.in
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4
5 use Error qw/:try/;
6 use OpenILS::Utils::Fieldmapper;
7 use Digest::MD5 qw/md5_hex/;
8 use OpenSRF::Utils::JSON;
9 use OpenILS::Application::AppUtils;
10 use Data::Dumper;
11 use Unicode::Normalize;
12 use Encode;
13
14 use FileHandle;
15 use Time::HiRes qw/time/;
16 use Getopt::Long;
17 use MARC::Batch;
18 use MARC::File::XML ( BinaryEncoding => 'utf-8' );
19 use MARC::Charset;
20 use DBI;
21
22 #MARC::Charset->ignore_errors(1);
23
24 my ($id_field, $id_subfield, $recid, $user, $config, $idlfile, $marctype, $tcn_offset, $tcn_mapfile, $tcn_dumpfile, $used_id_file, $used_tcn_file, $enc, @files, @trash_fields, @req_fields, $use901, $quiet, $tcn_field, $tcn_subfield) =
25         ('', 'a', 0, 1, '@sysconfdir@/opensrf_core.xml', '@sysconfdir@/fm_IDL.xml', 'USMARC', 0);
26
27 my ($db_driver, $db_host, $db_port, $db_name, $db_user, $db_pw) =
28         ('Pg', 'localhost', 5432, 'evergreen', 'postgres', 'postgres');
29
30 GetOptions(
31         'marctype=s'    => \$marctype, # format of MARC files being processed defaults to USMARC, often set to XML
32         'startid=i'     => \$recid, # id number to start with when auto-assigning id numbers, defaults to highest id in database + 1
33         'idfield=s'     => \$id_field, # field containing the record's desired internal id, NOT tcn
34         'idsubfield=s'  => \$id_subfield, # subfield of above record id field
35         'tcnfield=s'    => \$tcn_field, # field containing the record's desired tcn, NOT the internal id
36         'tcnsubfield=s' => \$tcn_subfield, # subfield of above record tcn field
37         'tcnoffset=i'   => \$tcn_offset, # optionally skip characters at beginning of supplied tcn (e.g. to remove '(Sirsi)')
38         'user=s'        => \$user, # set creator/editor values for records in database
39         'encoding=s'    => \$enc, # set assumed MARC encoding for MARC::Charset
40         'keyfile=s'     => \$tcn_mapfile, # DEPRECATED, use tcn_mapfile instead
41         'tcn_mapfile=s' => \$tcn_mapfile, # external file which allows for matching specific record tcns to specific record ids, format = one id_number|tcn_number combo per line
42         'tcnfile=s'     => \$tcn_dumpfile, # DEPRECATED, use tcn_dumpfile instead
43         'tcn_dumpfile=s'        => \$tcn_dumpfile, # allows specification of a dumpfile for all used tcn values
44         'config=s'      => \$config, # location of OpenSRF core config file, defaults to @sysconfdir@/opensrf_core.xml
45         'file=s'        => \@files, # files to process (or you can simple list the files as unnamed arguments, i.e. @ARGV)
46         'required_fields=s'     => \@req_fields, # skip any records missing these fields
47         'trash=s'       => \@trash_fields, # fields to remove from all processed records
48         'xml_idl=s'     => \$idlfile, # location of XML IDL file, defaults to @sysconfdir@/fm_IDL.xml
49         'dontuse=s'     => \$used_id_file, # DEPRECATED, use used_id_file instead
50         'used_id_file=s'        => \$used_id_file, # external file which prevents id collisions by specifying ids already in use in the database, format = one id number per line
51         'used_tcn_file=s'       => \$used_tcn_file, # external file which prevents tcn collisions by specifying tcns already in use in the database, format = one tcn number per line
52         "db_driver=s"   => \$db_driver, # database driver type, usually 'Pg'
53         "db_host=s"     => \$db_host, # database hostname
54         "db_port=i"     => \$db_port, # database port
55         "db_name=s"     => \$db_name, # database name
56         "db_user=s"     => \$db_user, # database username
57         "db_pw=s"       => \$db_pw, # database password
58         'use901'        => \$use901, # use values from previously created 901 fields and skip all other processing
59         'quiet'         => \$quiet # do not output progress count
60 );
61
62 @trash_fields = split(/,/,join(',',@trash_fields));
63 @req_fields = split(/,/,join(',',@req_fields));
64
65 if ($enc) {
66         MARC::Charset->ignore_errors(1);
67         MARC::Charset->assume_encoding($enc);
68 }
69
70 if (uc($marctype) eq 'XML') {
71         'open'->use(':utf8');
72 } else {
73         bytes->use();
74 }
75
76 @files = @ARGV if (!@files);
77
78 my @ses;
79 my @req;
80 my %processing_cache;
81
82 my $dsn = "dbi:$db_driver:host=$db_host;port=$db_port;dbname=$db_name";
83
84 if (!$recid) {
85     my $table = 'biblio_record_entry';
86     $table = 'biblio.record_entry' if ($db_driver eq 'Pg');
87
88         my $dbh = DBI->connect($dsn,$db_user,$db_pw);
89         my $sth = $dbh->prepare("SELECT MAX(id) + 1 FROM $table");
90
91         $sth->execute;
92         $sth->bind_col(1, \$recid);
93         $sth->fetch;
94         $sth->finish;
95         $dbh->disconnect;
96
97         # In a clean Evergreen schema, the maximum ID will be -1; but sequences
98         # have to start at 1, so handle the clean Evergreen schema situation
99         if ($recid == 0) {
100                 $recid = 1;
101         }
102 }
103
104 my %tcn_source_map = (
105         a  => 'Sirsi_Auto',
106         o  => 'OCLC',
107         i  => 'ISxN',
108         l  => 'LCCN',
109         s  => 'System',
110         g  => 'Gutenberg',
111         z  => 'Unknown',
112 );
113
114 Fieldmapper->import(IDL => $idlfile);
115
116 my %tcn_map;
117 if ($tcn_mapfile) {
118         open F, $tcn_mapfile or die "Couldn't open key file $tcn_mapfile";
119         while (<F>) {
120                 if ( /^(\d+)\|(\S+)/o ) {
121                         $tcn_map{$1} = $2;
122                 }
123         }
124         close(F);
125 }
126
127 my %used_recids;
128 if ($used_id_file) {
129         open F, $used_id_file or die "Couldn't open used-id file $used_id_file";
130         while (<F>) {
131                 chomp;
132                 s/^\s*//;
133                 s/\s*$//;
134                 $used_recids{$_} = 1;
135         }
136         close(F);
137 }
138
139 my %used_tcns;
140 if ($used_tcn_file) {
141         open F, $used_tcn_file or die "Couldn't open used-tcn file $used_tcn_file";
142         while (<F>) {
143                 chomp;
144                 s/^\s*//;
145                 s/\s*$//;
146                 $used_tcns{$_} = 1;
147         }
148         close(F);
149 }
150
151 select STDERR; $| = 1;
152 select STDOUT; $| = 1;
153
154 my $batch = new MARC::Batch ( $marctype, @files );
155 $batch->strict_off();
156 $batch->warnings_off();
157
158 my $starttime = time;
159 my $rec;
160 my $count = 0;
161 PROCESS: while ( try { $rec = $batch->next } otherwise { $rec = -1 } ) {
162         next if ($rec == -1);
163
164         $count++;
165
166         # Skip records that don't contain a required field (like '245', for example)
167         foreach my $req_field (@req_fields) {
168                 if (!$rec->field("$req_field")) {
169                         warn "\n!!! Record $count missing required field $req_field, skipping record.\n";
170                         next PROCESS;
171                 }
172         }
173
174         my $id;
175         my $tcn_value = '';
176         my $tcn_source = '';
177         # If $use901 is set, use it for the id, the tcn, and the tcn source without ANY further processing (i.e. no error checking)
178         if ($use901) {
179                 $rec->delete_field($_) for ($rec->field(@trash_fields));
180                 $tcn_value = $rec->subfield('901' => 'a');
181                 $tcn_source = $rec->subfield('901' => 'b');
182                 $id = $rec->subfield('901' => 'c');
183         } else {
184                 # This section of code deals with the record's 'id', which is a system-level, numeric, internal identifier
185                 # It is often convenient but not necessary to carry over the internal ids from your previous ILS, so here is where that happens
186                 if ($id_field) {
187                         my $field = $rec->field($id_field);
188                         if ($field) {
189                                 if ($field->is_control_field) {
190                                         $id = $field->data;
191                                 } else {
192                                         $id = $field->subfield($id_subfield);
193                                 }
194                                 # ensure internal record ids are numeric only
195                                 $id =~ s/\D+//gso if $id;
196                         }
197
198                         # catch problem ids
199                         if (!$id) {
200                                 warn "\n!!! Record $count has missing or invalid id field $id_field, assigning new id.\n";
201                                 $id = '';
202                         } elsif (exists $used_recids{$id}) {
203                                 warn "\n!!! Record $count has a duplicate id in field $id_field, assigning new id.\n";
204                                 $id = '';
205                         } else {
206                                 $used_recids{$id} = 1;
207                         }
208                 }
209
210                 # id field not specified or found to be invalid, assign auto id
211                 if (!$id) {
212                         while (exists $used_recids{$recid}) {
213                                 $recid++;
214                         }
215                         $used_recids{$recid} = 1;
216                         $id = $recid;
217                         $recid++;
218                 }
219
220                 # This section of code deals with the record's 'tcn', or title control number, which is a record-level, possibly alpha-numeric, sometimes user-supplied value
221                 if ($tcn_field) {
222                         if ($tcn_mapfile) {
223                                 if (my $tcn = $tcn_map{$id}) {
224                                         $rec->delete_field( $_ ) for ($rec->field($tcn_field));
225                                         $rec->append_fields( MARC::Field->new( $tcn_field, '', '', $tcn_subfield, $tcn ) );
226                                 } else {
227                                         warn "\n!!! ID $id not found in tcn_mapfile, skipping record.\n";
228                                         $count++;
229                                         next;
230                                 }
231                         }
232
233                         my $field = $rec->field($tcn_field);
234                         if ($field) {
235                                 if ($field->is_control_field) {
236                                         $tcn_value = $field->data;
237                                 } else {
238                                         $tcn_value = $field->subfield($tcn_subfield);
239                                 }
240                                 # $tcn_offset is another Sirsi influence, as it will allow you to remove '(Sirsi)'
241                                 # from exported tcns, but was added more generically to perhaps support other use cases
242                                 if ($tcn_value) { 
243                                         $tcn_value = substr($tcn_value, $tcn_offset);
244                                 } else {
245                                         $tcn_value = '';
246                                 }
247                         }
248                 }
249
250                 # turn our id and tcn into a 901 field, and also create a tcn and/or figure out the tcn source
251                 ($tcn_value, $tcn_source) = preprocess($rec, $tcn_value, $id);
252                 # delete the old identifier and trash fields
253                 $rec->delete_field($_) for ($rec->field('901', $tcn_field, $id_field, @trash_fields));
254         }
255
256         (my $xml = $rec->as_xml_record()) =~ s/\n//sog;
257         $xml =~ s/^<\?xml.+\?\s*>//go;
258         $xml =~ s/>\s+</></go;
259         $xml =~ s/\p{Cc}//go;
260         $xml = OpenILS::Application::AppUtils->entityize($xml);
261         $xml =~ s/[\x00-\x1f]//go;
262
263         my $bib = new Fieldmapper::biblio::record_entry;
264         $bib->id($id);
265         $bib->active('t');
266         $bib->deleted('f');
267         $bib->marc($xml);
268         $bib->creator($user);
269         $bib->create_date('now');
270         $bib->editor($user);
271         $bib->edit_date('now');
272         $bib->tcn_source($tcn_source);
273         $bib->tcn_value($tcn_value);
274         $bib->last_xact_id('IMPORT-'.$starttime);
275
276         print OpenSRF::Utils::JSON->perl2JSON($bib)."\n";
277         $used_tcns{$tcn_value} = 1;
278
279         if (!$quiet && !($count % 50)) {
280                 print STDERR "\r$count\t". $count / (time - $starttime);
281         }
282 }
283
284 if ($tcn_dumpfile) {
285     open TCN_DUMPFILE, '>', $tcn_dumpfile;
286     print TCN_DUMPFILE "$_\n" for (keys %used_tcns);
287 }
288
289
290 sub preprocess {
291         my $rec = shift;
292         my $tcn_value = shift;
293         my $id = shift;
294
295         my $tcn_source = '';
296         # in the following code, $tcn_number represents the portion of the tcn following the source code-letter
297         my $tcn_number = '';
298         my $warn = 0;
299         my $passed_tcn = '';
300
301         # this preprocess subroutine is optimized for Sirsi-created tcns, that is, those with a single letter
302         # followed by some digits (and maybe 'x' in older systems).  If using user supplied tcns, try to identify
303         # the source here, otherwise set to 'z' ('Unknown')
304         if ($tcn_value =~ /([a-z])([0-9xX]+)/) {
305                 $tcn_source = $1;
306                 $tcn_number = $2;
307         } else {
308                 $tcn_source = 'z';
309         }
310         
311         # save and warn if a passed in TCN is replaced  
312         if ($tcn_value && exists $used_tcns{$tcn_value}) {
313                 $passed_tcn = $tcn_value;
314                 $tcn_value = '';
315                 $tcn_number = '';
316                 $tcn_source = '';
317                 $warn = 1;
318         } 
319
320         # we didn't have a user supplied tcn, or it was a duplicate, so let's derive one from commonly unique record fields
321         if (!$tcn_value) {
322                 my $f = $rec->field('001');
323                 $tcn_value = despace($f->data) if ($f);
324         }
325
326         if (!$tcn_value || exists $used_tcns{$tcn_value}) {
327                 my $f = $rec->field('000');
328                 if ($f) {
329                         $tcn_number = despace($f->data);
330                         $tcn_source = 'g'; # only Project Gutenberg seems to use this
331                         $tcn_value = $tcn_source.$tcn_number;
332                 }
333         }
334
335     if (!$tcn_value || exists $used_tcns{$tcn_value}) {
336         my $f = $rec->field('020');
337                 if ($f) {       
338                         $tcn_number = despace($f->subfield('a'));
339                         $tcn_source = 'i';
340                         $tcn_value = $tcn_source.$tcn_number;
341                 }
342     }
343
344     if (!$tcn_value || exists $used_tcns{$tcn_value}) {
345         my $f = $rec->field('022');
346                 if ($f) {       
347                         $tcn_number = despace($f->subfield('a'));
348                         $tcn_source = 'i';
349                         $tcn_value = $tcn_source.$tcn_number;
350                 }
351     }
352
353     if (!$tcn_value || exists $used_tcns{$tcn_value}) {
354         my $f = $rec->field('010');
355                 if ($f) {       
356                         $tcn_number = despace($f->subfield('a'));
357                         $tcn_source = 'l';
358                         $tcn_value = $tcn_source.$tcn_number;
359                 }
360     }
361
362         # special case to catch possibly passed in full OCLC numbers and those derived from the 001 field
363         if ($tcn_value =~ /^oc(m|n)(\d+)$/o) {
364                 $tcn_source = 'o';
365                 $tcn_number = $2;
366                 $tcn_value = $tcn_source.$tcn_number;
367         }
368
369     if (!$tcn_value || exists $used_tcns{$tcn_value}) {
370                 $tcn_source = 's';
371                 $tcn_number = $id;
372                 $tcn_value = $tcn_source.$tcn_number;
373                 $warn = 1
374     }
375
376
377         # expand $tcn_source from code letter to full name
378         $tcn_source = do { $tcn_source_map{$tcn_source} || 'Unknown' };
379
380         if ($warn) {
381                 warn "\n!!! TCN $passed_tcn is already in use, using TCN ($tcn_value) derived from $tcn_source ID.\n";
382         }
383
384         return ($tcn_value, $tcn_source);
385 }
386
387 sub despace {
388         my $value = shift;
389
390         # remove all leading/trailing spaces and trucate at first internal space if present
391         $value =~ s/\s*$//o;
392         $value =~ s/^\s*//o;
393         $value =~ s/^(\S+).*$/$1/o;
394
395         return $value;
396 }