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 "Writing results ($count lead records) to disk\n";
31 sub populate_fingerprint {
33 my %fp = (); # zero fingerprint hash each time thru
35 # populate fp hash -- first the simple data
36 $fp{compact} = shift @fields;
37 $fp{json} = shift @fields;
38 $fp{id} = shift @fields;
39 # then smash everything else together, remove non-Roman characters, and
40 # generate a SHA1 hash to represent it
41 my $stripped = join('', @fields);
42 $stripped =~ s/[^A-Za-z0-9]//g;
43 $fp{sha1} = sha1_base64($stripped);
45 # populate records hash
46 $recs{ $fp{id} }{ $fp{sha1} } = {};
52 sub rank_fingerprint {
55 my $sha1 = $fp->{sha1};
57 my $islead = $recs{$id}{lead};
59 # only process records which haven't already been set as a sub
60 unless (defined $islead and $islead) {
61 unless ($fps{$sha1}) {
62 # haven't seen this fp before. create a new hashref with the current
64 $fps{$sha1} = { lead => { id => $id,
65 score => $fp->{compact} },
67 $recs{$id}{$sha1}{lead} = 1;
70 # have seen this fp. push record id onto matchlist
71 push @{ $fps{$sha1}{recs} }, $id;
72 if ($fp->{compact} > $fps{$sha1}{lead}{score}) {
73 # and set this record as lead if it scores higher than current lead
74 $recs{ $fps{$sha1}{lead}{id} }{lead} = 0; # unset current
75 $recs{ $id }{lead} = 1; # set new as lead
76 $fps{$sha1}{lead}{id} = $id;
77 $fps{$sha1}{lead}{score} = $fp->{compact};
86 Writes out a 2-column file of lead and subordinate records.
92 open OUT, '>', $conf->{output}
93 or die "Can't open ", $conf->{output}, "$!\n";
94 for my $id (keys %recs) {
95 next unless $recs{$id}{lead};
96 for my $sha1 ( keys %{$recs{$id}} ) {
97 for my $subid ( @{$fps{$sha1}{recs}} ) {
98 next if ($id == $subid);
99 next if defined $used{$subid};
101 print OUT "$id\t$subid\n";
111 # set mode on existing filehandles
112 binmode(STDIN, ':utf8');
114 my $rc = GetOptions( $c,
118 show_help() unless $rc;
119 show_help() if ($c->{help});
121 my @keys = keys %{$c};
122 show_help() unless (@ARGV and @keys);
123 for my $key ('output')
124 { push @missing, $key unless $c->{$key} }
126 print "Required option: ", join(', ', @missing), " missing!\n";
133 Usage is: compress_fingerprints -o OUTPUTFILE INPUTFILE