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";
19 my $total = `wc -l $ARGV[0]`;
22 print "Loading and ranking fingerprints\n";
24 my @fields = split "\t", $_;
25 my $fp = populate_fingerprint(@fields);
26 rank_fingerprint($fp);
28 print "\r", ( int($i / $total) ), "% complete" unless ($i % 1000);
30 print "$total fingerprints processed\n";
31 print "$count records set as leads\n";
32 print "Writing matchset to disk\n";
37 sub populate_fingerprint {
39 my %fp = (); # zero fingerprint hash each time thru
41 # populate fp hash -- first the simple data
42 $fp{compact} = shift @fields;
43 $fp{json} = shift @fields;
44 $fp{id} = shift @fields;
45 # then smash everything else together, remove non-Roman characters, and
46 # generate a SHA1 hash to represent it
47 my $stripped = join('', @fields);
48 $stripped =~ s/[^A-Za-z0-9]//g;
49 $fp{sha1} = sha1_base64($stripped);
51 # populate records hash
52 $recs{ $fp{id} }{ $fp{sha1} } = {};
58 sub rank_fingerprint {
61 my $sha1 = $fp->{sha1};
63 my $islead = $recs{$id}{lead};
65 # only process records which haven't already been set as a sub
66 unless (defined $islead and $islead) {
67 unless ($fps{$sha1}) {
68 # haven't seen this fp before. create a new hashref with the current
70 $fps{$sha1} = { lead => { id => $id,
71 score => $fp->{compact} },
76 # have seen this fp. push record id onto matchlist
77 push @{ $fps{$sha1}{recs} }, $id;
78 if ($fp->{compact} > $fps{$sha1}{lead}{score}) {
79 # and set this record as lead if it scores higher than current lead
80 $recs{ $fps{$sha1}{lead}{id} }{lead} = 0; # unset current
81 $recs{ $id }{lead} = 1; # set new as lead
82 $fps{$sha1}{lead}{id} = $id;
83 $fps{$sha1}{lead}{score} = $fp->{compact};
92 Writes out a 2-column file of lead and subordinate records.
98 open OUT, '>', $conf->{output}
99 or die "Can't open ", $conf->{output}, "$!\n";
100 for my $id (keys %recs) {
101 next unless $recs{$id}{lead};
102 for my $sha1 ( keys %{$recs{$id}} ) {
103 for my $subid ( @{$fps{$sha1}{recs}} ) {
104 next if ($id == $subid);
105 next if defined $used{$subid};
107 print OUT "$id\t$subid\n";
117 # set mode on existing filehandles
118 binmode(STDIN, ':utf8');
120 my $rc = GetOptions( $c,
124 show_help() unless $rc;
125 show_help() if ($c->{help});
127 my @keys = keys %{$c};
128 show_help() unless (@ARGV and @keys);
129 for my $key ('output')
130 { push @missing, $key unless $c->{$key} }
132 print "Required option: ", join(', ', @missing), " missing!\n";
139 Usage is: compress_fingerprints -o OUTPUTFILE INPUTFILE