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