6 use Digest::SHA1 qw(sha1_base64);
9 my $conf = {}; # configuration hashref
12 my %fps = (); # records matching each fingerprint (and the lead)
13 my %recs = (); # fingerprints belonging to each record
15 open FP, '<', $ARGV[0] or die "Can't open input file: $!\n";
18 my $total = `wc -l $ARGV[0]`;
20 print "Loading and ranking fingerprints\n";
22 my @fields = split "\t", $_;
23 my $fp = populate_fingerprint(@fields);
24 rank_fingerprint($fp);
26 print "$total fingerprints processed\n";
27 print "$count records set as leads\n";
28 print "Writing matchset to disk\n";
33 sub populate_fingerprint {
35 my %fp = (); # zero fingerprint hash each time thru
37 # populate fp hash -- first the simple data
38 $fp{compact} = shift @fields;
39 $fp{json} = shift @fields;
40 $fp{id} = shift @fields;
41 # then smash everything else together, remove non-Roman characters, and
42 # generate a SHA1 hash to represent it
43 my $stripped = join('', @fields);
44 $stripped =~ s/[^A-Za-z0-9]//g;
45 $fp{sha1} = sha1_base64($stripped);
47 # populate records hash
48 $recs{ $fp{id} }{ $fp{sha1} } = {};
54 sub rank_fingerprint {
57 my $sha1 = $fp->{sha1};
59 my $islead = $recs{$id}{lead};
61 # only process records which haven't already been set as a sub
62 unless (defined $islead and $islead) {
63 unless ($fps{$sha1}) {
64 # haven't seen this fp before. create a new hashref with the current
66 $fps{$sha1} = { lead => { id => $id,
67 score => $fp->{compact} },
72 # have seen this fp. push record id onto matchlist
73 push @{ $fps{$sha1}{recs} }, $id;
74 if ($fp->{compact} > $fps{$sha1}{lead}{score}) {
75 # and set this record as lead if it scores higher than current lead
76 $recs{ $fps{$sha1}{lead}{id} }{lead} = 0; # unset current
77 $recs{ $id }{lead} = 1; # set new as lead
78 $fps{$sha1}{lead}{id} = $id;
79 $fps{$sha1}{lead}{score} = $fp->{compact};
88 Writes out a 2-column file of lead and subordinate records.
94 open OUT, '>', $conf->{output}
95 or die "Can't open ", $conf->{output}, "$!\n";
96 for my $id (keys %recs) {
97 next unless $recs{$id}{lead};
98 for my $sha1 ( keys %{$recs{$id}} ) {
99 for my $subid ( @{$fps{$sha1}{recs}} ) {
100 next if ($id == $subid);
101 next if defined $used{$subid};
103 print OUT "$id\t$subid\n";
113 # set mode on existing filehandles
114 binmode(STDIN, ':utf8');
116 my $rc = GetOptions( $c,
120 show_help() unless $rc;
121 show_help() if ($c->{help});
123 my @keys = keys %{$c};
124 show_help() unless (@ARGV and @keys);
125 for my $key ('output')
126 { push @missing, $key unless $c->{$key} }
128 print "Required option: ", join(', ', @missing), " missing!\n";
135 Usage is: compress_fingerprints -o OUTPUTFILE INPUTFILE