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
14 my %seen = (); # records we've already seen
15 my $lastscore = 0; # previous fingerprint's score
17 my %subs = (); # error-checking hashe
19 open FP, '<', $ARGV[0] or die "Can't open input file: $!\n";
21 print "Loading and ranking fingerprints\n";
23 my @fields = split "\t", $_;
24 my $fp = populate_fingerprint(@fields);
25 rank_fingerprint($fp);
27 print "Writing matchset to disk\n";
32 sub populate_fingerprint {
34 my %fp = (); # zero fingerprint hash each time thru
36 # populate fp hash -- first the simple data
37 $fp{compact} = shift @fields;
38 $fp{json} = shift @fields;
39 $fp{id} = shift @fields;
40 # then smash everything else together, remove non-Roman characters, and
41 # generate a SHA1 hash to represent it
42 my $stripped = join('', @fields);
43 $stripped =~ s/[^A-Za-z0-9]//g;
44 $fp{sha1} = sha1_base64($stripped);
46 # make sure file is sorted properly
47 if ($lastscore and ($fp{compact} > $lastscore)) {
48 print "Input file is sorted improperly or unsorted.\n";
49 die "Sort descending (sort -r) and rerun this script.\n";
51 $lastscore = $fp{compact};
57 sub rank_fingerprint {
60 my $sha1 = $fp->{sha1};
63 # only process records which haven't already been seen
64 unless (defined $seen{$id}) {
65 unless (defined $fps{$sha1}) {
66 # haven't seen this fp before. create a new listref to hold subs
67 # and stow the hash of the fingerprint that we're lead of
69 push @recs, {id => $id, sha1 => $sha1};
71 # have seen this fp. push record id onto matchlist
72 push @{ $fps{$sha1} }, $id;
81 Writes out a 2-column file of lead and subordinate records.
87 open OUT, '>', $conf->{output}
88 or die "Can't open ", $conf->{output}, "$!\n";
90 for ( @{ $fps{ $rec->{sha1} } } ) {
91 # check for dupes and die if they exist
92 die "Collision: dupe sub record $_\n" if $subs{$_};
94 die "Collision: lead in sub list ", $rec->{id}, "\n"
95 if $subs{ $rec->{id} };
98 print OUT $rec->{id}, "\t$_\n"
107 # set mode on existing filehandles
108 binmode(STDIN, ':utf8');
110 my $rc = GetOptions( $c,
114 show_help() unless $rc;
115 show_help() if ($c->{help});
117 my @keys = keys %{$c};
118 show_help() unless (@ARGV and @keys);
119 for my $key ('output')
120 { push @missing, $key unless $c->{$key} }
122 print "Required option: ", join(', ', @missing), " missing!\n";
129 Usage is: compress_fingerprints -o OUTPUTFILE INPUTFILE