Codebase list findimagedupes / upstream/2.17 findimagedupes
upstream/2.17

Tree @upstream/2.17 (Download .tar.gz)

findimagedupes @upstream/2.17raw · history · blame

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
#!/usr/bin/perl -w
# $Id: findimagedupes,v 2.17 2008/12/15 21:43:25 jhnc Exp jhnc $
#
# findimagedupes - Finds visually similar or duplicate images
#
# Copyright 2006 by Jonathan H N Chin <code@jhnc.org>.
#
# This program is free software; you may redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

use strict;

require 5.006_001;

use Cwd qw(realpath);
use DB_File;
use Digest::MD5 qw(md5_hex);
use Getopt::Long qw(:config no_ignore_case require_order);
use File::MimeInfo::Magic;
use File::Temp qw(tempdir tempfile);
use Graphics::Magick;
use MIME::Base64;
use Pod::Usage;

use Inline
	C => 'DATA',
	NAME => 'findimagedupes',
	DIRECTORY => '/usr/local/lib/findimagedupes';

# ----------------------------------------------------------------------
#
# option parsing
#

use vars qw(
	$null
	$add
	$collection
	@debug %debug
	@fpdb
	$merge
	$nocompare
	$program
	$quiet
	$rescan
	$recurse
	$script
	@scriptCode
	$scriptFile
	$threshold
	@verbosity
	$prune
);

$add = 0;
$quiet = 0;
$threshold = '90%';

my %opt;
GetOptions(
	'0|null'                 => \$null,
	'a|add'                  => \$add,
	'c|collection=s'         => sub { ($collection = $_[1]) =~ s/([.]gqv)?$/.gqv/ },
	'd|debug=s'              => \@debug,
	'f|fingerprints|fp|db=s' => \@fpdb,
	'h|?|help'               => sub { pod2usage(-verbose => 1) },
	'man'                    => sub { pod2usage(-verbose => 2) },
	'M|merge=s'              => \$merge,
	'n|no-compare'           => \$nocompare,
	'P|prune'                => \$prune,
	'p|program=s'            => \$program,
	'q|quiet'                => sub { $quiet++ },
	'R|recurse'              => \$recurse,
	'r|rescan'               => \$rescan,
	's|script=s'             => \$script,
	't|threshold=s'          => \$threshold,
	'v|verbosity=s'          => \@verbosity,

	'i|include=s'            => \@scriptCode,
	'I|include-file=s'       => \$scriptFile,
) or pod2usage(-verbose => 0);

# ----------------------------------------------------------------------

my @errors = ();
my @warnings = ();

sub exitvalue {
	return(2) if @errors;
	return(1) if @warnings;
	return(0);
}

sub mkerr { push @errors, join("", @_); }
sub mkwarn { push @warnings, join("", @_); }

sub nqprint { print(@_) unless $quiet; }
sub nqwarn { warn("Warning: ", @_) unless $quiet; }
sub nqdie { nqwarn(@_); die; }
sub nqdie2 { warn("Error: ", @_) if $quiet<2; die; }
sub nqexit { warn("Error: ", @_) if $quiet<2; exit(3); }

my $inFP = 0;
$SIG{SEGV} = sub { die $inFP ? "caught segfault" : ()};

sub printScriptFile {
	print("# BEGIN USER FILE INCLUDE\n");
	open(USERSCRIPT, "< $scriptFile") or die("$!\n");
	while (<USERSCRIPT>) {
		chomp;
		print "$_\n";
	}
	close(USERSCRIPT);
	print("# END USER FILE INCLUDE\n\n");
}

# ----------------------------------------------------------------------
#
# setup
#

my ($verb_fp, $verb_md5);

my $read_input = grep(/^-$/, @ARGV);

# XXX: can we tie these to save memory without breaking hv_iterinit() ?
my (%fpcache, %filelist);

my $image = Graphics::Magick->new;

for (@debug) { $debug{$_} = 1 }

map { chomp; $_ .= "\n" } @scriptCode;

if (@scriptCode) {
	unshift(@scriptCode, "# BEGIN USER CODE INCLUDE\n" );
	   push(@scriptCode, "# END USER CODE INCLUDE\n\n" );
}

my $scriptHeader = <<'EOD';
#!/bin/sh

VIEW(){
	echo "$@"
}
END(){
	:;
}

EOD

my $collectionHeader = <<'EOD';
#GQview collection
#created with findimagedupes
# sort: manual
EOD

my $collectionFooter = <<'EOD';
#end
EOD

# ----------------------------------------------------------------------
#
# sanity checks
#

# +----------+
# | warnings |
# +----------+

if ($read_input>1) {
	mkwarn("extra occurrences of \"-\" will be ignored");
}

if ($null and !grep(/^-$/, @ARGV)) {
	mkwarn("--null has no effect in this context");
}

if ($prune and !@fpdb) {
	mkwarn("--prune has no effect in this context");
}

if ($nocompare) {
	mkwarn("--program ignored because --no-compare given") if $program;
	mkwarn("--script ignored because --no-compare given") if $script;
}

if (@warnings and !$quiet) {
	warn( join("\n", map {"Warning: $_"} @warnings), "\n" );
}

# +--------+
# | errors |
# +--------+

if ($collection and -e($collection)) {
	mkerr("Output file for --collection exists: $collection");
}

for (@fpdb) {
	mkerr("File for --fingerprints does not exist: $_")
		unless (-f($_) or (@fpdb==1 and !$merge));
}

if (@fpdb>1 and !$merge) {
	mkerr("Require --merge if using multiple fingerprint databases");
}

# XXX: not sure this is true any more
#if (@fpdb<1 and $merge) {
#	mkerr("Cannot use --merge unless --fingerprints also specified");
#}

if ($merge and -e($merge)) {
	mkerr("Output file for --merge exists: $merge");
}

if ($program) {
	if (! -e($program)) {
		mkerr("File for --program does not exist: $program");
	}
	elsif (! -x($program)) {
		mkerr("File for --program not executable: $program");
	}
}

if ($script and -e($script)) {
	mkerr("Output file for --script exists: $script");
}

if ($scriptFile and !( -f($scriptFile) and -r($scriptFile) )) {
	mkerr("File for --include-file does not exist: $scriptFile");
}

my ($thres_val, $thres_unit) = $threshold =~ m/^\s*(\d+(?:[.]\d+)?)(.*?)\s*$/o;
if ($thres_unit eq '' or $thres_unit eq '%') {
	# percentage to bits
	$threshold = int(2.56 * (100 - $thres_val));
}
elsif ($thres_unit =~ m/^b/oi) {
	# already in bits
	$threshold = int($thres_val);
}
else {
	# error
	$threshold = -1;
}
if ($threshold>256 or $threshold<0) {
	mkerr("--threshold takes values between 0.0% .. 100.0% or 0b .. 256b");
}

for (split(",", join(",", @verbosity))) {
	/^(fingerprint|fp)$/ && do { $verb_fp = 1;  next; };
	/^md5$/              && do { $verb_md5 = 1; next; };
	mkerr("unknown option to --verbosity: $_");
}

if (@errors) {
	exit(exitvalue()) unless $quiet<2;
	pod2usage(
		-verbose => 0,
		-exitval => exitvalue(),
		-msg => join("\n", map {"Error: $_"} @errors),
	);
}

# +-------------------------------------------------+
# | last chance to abort without altering any files |
# +-------------------------------------------------+

unless (@ARGV>0 or @fpdb or $merge) {
	exit(exitvalue()) unless $quiet<2;
	warn("Nothing to do!\n") unless @warnings or $quiet;
	pod2usage(
		-verbose => 0,
		-exitval => exitvalue(),
	);
}

# ----------------------------------------------------------------------
#
# load fingerprint cache
#

for my $db (@fpdb) {
	my %data;
	tie(%data, 'DB_File', $db) or nqexit("tie($db): $!\n");
	while (my ($file, $fp) = each %data) {
		next if ($prune && !-f($file));

		if (exists $fpcache{$file}) {
			# duplicate fingerprint, force regeneration
			delete $fpcache{$file};
		}
		else {
			$fpcache{$file} = $fp;
		}
	}
	untie(%data);
}

# ----------------------------------------------------------------------
#
# build file list
#

my %mergelist;
my $rw = 0;

if ($merge) {
	tie(%mergelist, 'DB_File', $merge) or nqexit("tie($merge): $!\n");
	%mergelist = %fpcache;
	$rw = 1;
}
elsif (@fpdb==1) {
	tie(%mergelist, 'DB_File', $fpdb[0]) or nqexit("tie($fpdb[0]): $!\n");
	%mergelist = %fpcache if $prune;
	$rw = 1;
}

$| = 1;
$/ = "\0" if $null;

for (@ARGV) {
	classify($_);
}

untie(%mergelist);

finddupes() unless $nocompare;

exit 0;

# ----------------------------------------------------------------------

sub process_file {
	my ($path) = @_;
	my $file = realpath($path); # normalize to absolute canonical path
	if (!$file) {
		nqwarn("skipping bogus file: $path\n");
	}
	else {
		my $fp;
		if ($rescan or !exists $fpcache{$file}) {
			$fp = fingerprint($file);
		}
		elsif ($add and exists $fpcache{$file}) {
			$fp = $fpcache{$file};
		}
		if ($fp) {
			$filelist{$file} = $fp;
			delete $fpcache{$file};
			$mergelist{$file} = $filelist{$file} if $rw;
		}

		if ($verb_fp) {
			my $fp = ( $filelist{$file} || $fpcache{$file} );
			if ($fp) {
				print(encode_base64($fp, ""), "  $file\n");
			}
			else {
				nqwarn("can't get fingerprint: $file\n");
			}
		}
		if ($verb_md5) {
			open(FILE, $file) or nqdie2("open($file): $!\n");
			binmode(FILE);
			my $digest = Digest::MD5->new->addfile(*FILE)->hexdigest;
			if ($digest) {
				print("$digest  $file\n");
			}
			else {
				nqwarn("can't get md5sum: $file\n");
			}
			close(FILE);
		}
	}
}

# XXX: This function is complicated by two things:
#	- Historically we didn't recurse and it would be nice to
#		retain nonrecursion as an option.
#	- We need to process "." and ".." when they are given
#		explicitly on the command line.
#	Perhaps we could cleanup the code by rewriting using
#		something like the "-" code?
sub classify {
	my ($file) = @_;

	if ($file eq "-") {
		if ($read_input) {
			$read_input = 0;
			while (<>) {
				chomp;
				classify($_);
			}
		}
		else {
			# silently ignore any extra occurrences of "-"
			# (we already reported them at startup)
		}
	}
	elsif (-d($file) and !-l($file)) {
		# don't follow directory symlinks, to prevent looping
		if (opendir(DIR, $file)) {
			for (readdir(DIR)) {
				my $path = "$file/$_";
				if (-d($path) and !-l($path)) {
					next if m/^\.\.?$/o;	# skip . and ..
					classify($path) if $recurse;
				}
				elsif (-f($path)) {
					process_file($path);
				}
			}
		}
		else {
			nqwarn("can't process directory $file: $@\n");
		}
	}
	elsif (-f($file)) {
		# symlinks are okay for normal files
		process_file($file);
	}
	else {
		# skip anything else (devices, etc)
		nqwarn("skipping file: $file\n");
	}
}

# ----------------------------------------------------------------------

sub try {
	my ($err) = @_;
	if ($err and $err !~ /Warning (315|330):/) {
		die("imagemagick problem: $err\n");
	}
}

sub fingerprint {
	my ($file) = @_;
	my $blob;

	# imagemagick doesn't always catch output from the programs
	# it spawns, so we have to clean up for it...
	open(SAVED_OUT, ">&", \*STDOUT) or nqdie2("open(/dev/null): $!");
	open(SAVED_ERR, ">&", \*STDERR) or nqdie2("open(/dev/null): $!");
	open(STDOUT, ">/dev/null");
	open(STDERR, ">/dev/null");

	$inFP = 1;
	my $result = eval {
		if ((mimetype($file)||'') =~ /^(audio|video)/) {
			die("not fingerprinting A/V file: $file\n");
		}

		if (!$image->Ping($file)) {
			die("not fingerprinting unknown-type file: $file\n");
		}

		try $image->Read($file);

		if ($#$image<0) {
			die("fingerprint: not enough image data for $file");
		}
		else {
			$#$image = 0;
		}
		try $image->Sample("160x160!");
		try $image->Modulate(saturation=>-100);
		try $image->Blur(radius=>3,sigma=>99);
		try $image->Normalize();
		try $image->Equalize();
		try $image->Sample("16x16");
		try $image->Threshold();
		try $image->Set(magick=>'mono');

		($blob) = $image->ImageToBlob();
		if (!defined($blob)) {
			die("This can't happen! undefined blob for: $file\n");
		}
	};

	$inFP = 0;
	@$image = ();

	open(STDOUT, ">&", \*SAVED_OUT) or nqdie2("open(/dev/null): $!");
	open(STDERR, ">&", \*SAVED_ERR) or nqdie2("open(/dev/null): $!");
	close(SAVED_OUT);
	close(SAVED_ERR);

	if (defined $result) {
		return $blob;
	}
	else {
		nqwarn($@);
		return undef;
	}
}

sub finddupes {
	my @matches = diffbits(\%fpcache, \%filelist, $threshold, $add);

	my (%set, %ptr, %val);

	while (@matches) {
		my $a = shift(@matches);
		my $b = shift(@matches);
		my $c = shift(@matches);
		$set{$a} = 1;
		$set{$b} = 1;

		# cf. debian bug #87013

		if (!defined($ptr{$a}) and !defined($ptr{$b})) {
			$ptr{$a} = $a;
			push @{$val{$a}}, $a, $b;
			$ptr{$b} = $a;
			$#{$val{$b}} = 0;
		}
		elsif (defined($ptr{$a}) and !defined($ptr{$b})) {
			push @{$val{$ptr{$a}}}, $b;
			$ptr{$b} = $ptr{$a};
			$#{$val{$b}} = 0;
		}
		elsif (!defined($ptr{$a}) and defined($ptr{$b})) {
			push @{$val{$ptr{$b}}}, $a;
			$ptr{$a} = $ptr{$b};
			$#{$val{$a}} = 0;
		}
		elsif ($ptr{$a} ne $ptr{$b}) {
			my $valptrb = $val{$ptr{$b}};
			push @{$val{$ptr{$a}}}, @{$valptrb};
			for my $bkey (@{$valptrb}) {
				$ptr{$bkey} = $ptr{$a};
			}
			$#$valptrb = 0;
			# else $val{$a} is $val{$b} already
		}
	}

	my $cnt = 0;
	for my $k (keys %filelist, keys %fpcache) {
		$set{$cnt} = $k if defined $set{$cnt};
		$cnt++;
	}

	# FIXME: What is the proper format of collection files?
	#	It seems to be poorly defined, and gthumb parses them
	#	differently from gqview itself. In particular, gthumb
	#	seems to misparse comment lines, and the sort pragma
	#	it defines seems to be fragile wrt whitespace.
	if ($collection) {
		open(COLLECTION, "> $collection") or nqdie2("open(> $collection): $!\n");
		select(COLLECTION);

		print $collectionHeader;
		for my $k (keys %ptr) {
			next unless $ptr{$k} eq $k;
			for ( @{$val{$ptr{$k}}} ) {
				my $name = $set{$_};

				if ( $name =~ /[\n"]/s ) {
					nqwarn("excluded from $collection: $name\n");
				}
				else {
					print qq{"$name"\n};
				}
			}
		}
		print $collectionFooter;
		close(COLLECTION);
	}

	if ($script) {
		open(COMMANDS, "> $script") or nqdie2("open(> $script): $!\n");
	}
	else {
		open(COMMANDS, "| /bin/sh") or nqdie2("open(| /bin/sh): $!\n");
	}
	select(COMMANDS);

	if ($script or $program or !$collection) {
		$program = 'VIEW' unless $program;
		print $scriptHeader;
		printScriptFile if $scriptFile;
		print @scriptCode if @scriptCode;
		for my $k (keys %ptr) {
			next unless $ptr{$k} eq $k;
			print join(" \\\n\t",
				$program,
				( map { quotemeta $set{$_} } @{$val{$ptr{$k}}} ),
				";\n"
			);
		}
		print "\nEND;\n\n";
	}
	close(COMMANDS);
}

# ======================================================================

__DATA__

=head1 NAME

findimagedupes - Finds visually similar or duplicate images

=head1 SYNOPSIS

findimagedupes [option ...] [--] [ - | [file ...] ]

   Options:
      -f, --fingerprints=FILE    -c, --collection=FILE
      -M, --merge=FILE           -p, --program=PROGRAM
      -P, --prune                -s, --script=FILE
      -a, --add                  -i, --include=TEXT
      -r, --rescan               -I, --include-file=FILE
      -n, --no-compare
                                 -q, --quiet
      -t, --threshold=AMOUNT     -v, --verbosity=LIST

      -0, --null                 -h, --help
      -R, --recurse                  --man

With no options, compares the specified files and does not use nor
update any fingerprint database.

Directories of images may be specified instead of individual files;
Sub-directories of these are not searched unless --recurse is used.

=head1 INSTALLATION

If you use linux, your distribution may include a prepackaged version.
For example, Debian and Ubuntu do.

Otherwise, at a minimum you'll need Perl with the modules listed at the
top of the findimagedupes script. Also the GraphicksMagick package.

You may need to change Inline's C<DIRECTORY> to point somewhere else.
Read the Inline module documentation for details.

=head1 OPTIONS

=over 8

=item B<-0>, B<--null>

If a file C<-> is given, a list of files is read from stdin.

Without B<-0>, the list is specified one file per line, such as
produced by find(1) with its C<-print> option.

With B<-0>, the list is expected to be null-delimited, such as
produced by find(1) with its C<-print0> option.

=item B<-a>, B<--add>

Only look for duplicates of files specified on the commandline.

Matches are also sought in any fingerprint databases specified.

=item B<-c>, B<--collection>=I<FILE>

Create GQView collection I<FILE>.gqv of duplicates.

The program attempts to produce well-formed collections.
In particular, it will print a warning and exclude any file
whose name contains newline or doublequote. (In this situation,
gqview(1) seems to create a .gqv collection file that it
silently fails to read back in properly.)

=item B<-d>, B<--debug>=I<OPTS>

Enable debugging output. Options I<OPTS> are subject to change.
See the program source for details.

=item B<-f>, B<--fingerprints>=I<FILE>

Use I<FILE> as fingerprint database.

May be abbreviated as B<--fp> or B<--db>.

This option may be given multiple times when B<--merge> is used.
(Note: I<FILE> could contain commas, so multiple databases may
not be specified as a single comma-delimited list.)

=item B<-h>, B<--help>

Print usage and option sections of this manual.

=item B<-i>, B<--include>=I<TEXT>

I<TEXT> is Bourne-shell code to customise B<--script>.

It is executed after any code included using B<--include-file>.

May be given multiple times. Code will be concatenated.

=item B<-I>, B<--include-file>=I<FILE>

I<FILE> is a file containing Bourne-shell code to customise 
B<--script>. 

It is executed before any code included using B<--include>.

=item B<--man>

Display the full documentation, using default pager.

=item B<--merge>=I<FILE>

Takes any databases specified with B<--fingerprints>
and merges them into a new database called I<FILE>.
Conflicting fingerprints for an image will cause one of two actions to occur:

=over 4

=item 1.

If the image does not exist, then the entry is elided.

=item 2.

If the image does exist, then the old information is ignored
and a new fingerprint is generated from scratch.

=back

By default, image existence is not checked unless there is a conflict.
To force removal of defunct data, use B<--prune> as well.

A list of image files is not required if this option is used.
However, if a list is provided, fingerprint data for the files
will be copied or (re)generated as appropriate.

When B<--merge> is used, the original fingerprint databases are not modified,
even if B<--prune> is used.

See also: B<--rescan>

=item B<-n>, B<--no-compare>

Don't look for duplicates.

=item B<-p>, B<--program>=I<PROGRAM>

Launch I<PROGRAM> (in foreground) to view each set of dupes.

I<PROGRAM> must be the full path to an existing executable file.
For more flexibility, see the B<--include> and B<--include-file>
options.

See also: B<--script>

=item B<--prune>

Remove fingerprint data for images that do not exist any more.
Has no effect unless B<--fingerprints> or B<--merge> is also used.

Databases specified by B<--fingerprints> are only modified if
B<--merge> is not used.

=item B<-q>, B<--quiet>

This option may be given multiple times.

Usually, progress, warning and error messages are printed on stderr.
If this option is given, warnings are not displayed.
If it is given twice or more, errors are not displayed either.

Information requested with B<--verbosity> is still displayed.

=item B<-R>, B<--recurse>

Use B<--recurse> to search recursively for images inside
subdirectories. For historical reasons, the default is to not do so.
To avoid looping, symbolic links to directories are never followed.

=item B<-r>, B<--rescan>

(Re)generate all fingerprints, not just any that are unknown.

If used with B<--add>, only the fingerprints of files specified
on the commandline are (re)generated.

Implies B<--prune>.

=item B<-s>, B<--script>=I<FILE>

When used with B<--program>, I<PROGRAM> is not launched immediately.
Instead sh(1)-style commands are saved to I<FILE>.
This script may be edited (if desired) and then executed manually.

When used without B<--program>, two skeletal shell functions
are generated: C<VIEW> simply echo(1)s its arguments; 
the empty function C<END> runs after files-processing is finished.

To display to terminal (or feed into a pipe), use C<-> as I<FILE>.

If B<--script> is not given, the script is still created in memory and
is executed immediately. So, with the default VIEW and END functions,
lines containing sets of duplicates are displayed. See: B<EXAMPLES>

See also: B<--include>, B<--include-file>

=item B<-t>, B<--threshold>=I<AMOUNT>

Use I<AMOUNT> as threshold of similarity.
Append C<%> to give a percentage or C<b> for bits.
For backwards compatibility, a number with no unit is treated as
a percentage. Percentage is the minimum required for a match;
bits is the maximum that may differ: bits=floor(2.56(100-percent))

A fractional part may be given but it is only accurate to 100/256
(0.390625) for percentage and it is meaningless for C<bits>.
Default is C<90%> (C<25b>) if not specified.

=item B<-v>, B<--verbosity>=I<LIST>

Enable display of informational messages to stdout,
where I<LIST> is a comma-delimited list of:

=over 8

=item B<md5>

Display the checksum for each file, as per md5sum(1).

=item B<fingerprint> | B<fp>

Display the base64-encoded fingerprint of each file.

=back

Alternatively, B<--verbosity> may be given multiple times, and accumulates.
Note that this may not be sensible. For example, to be useful,
B<md5> output probably should not be merged with B<fingerprint> data.

=back

=head1 DESCRIPTION

B<findimagedupes> compares a list of files for visual similarity.

=over 1

=item To calculate an image fingerprint:

 1) Read image.
 2) Resample to 160x160 to standardize size.
 3) Grayscale by reducing saturation.
 4) Blur a lot to get rid of noise.
 5) Normalize to spread out intensity as much as possible.
 6) Equalize to make image as contrasty as possible.
 7) Resample again down to 16x16.
 8) Reduce to 1bpp.
 9) The fingerprint is this raw image data.

=item To compare two images for similarity:

 1) Take fingerprint pairs and xor them.
 2) Compute the percentage of 1 bits in the result.
 3) If percentage exceeds threshold, declare files to be similar.

=back


=head1 RETURN VALUE

=over 4

=item 0

Success.

=item 1

Usage information was requested (B<--help> or B<--man>), or there
were warnings.

=item 2

Invalid options or arguments were provided.

=item 3

Runtime error.

=back

Any other return values indicate an internal error of some sort.

=head1 DIAGNOSTICS

To be written.

=head1 EXAMPLES

=over 4

=item findimagedupes -R -- .

Look for and compare images in all subdirectories of the current directory.

=item find -type f . -print0 | findimagedupes -0 -- -

Same as above.

=item findimagedupes -i 'echo "# sort: manual"' -i 'VIEW(){ for f in "$@";do echo \"file://$f\";done }' -- *.jpg > dupes.gqv

Use script hooks to produce collection-style output
suitable for use with gthumb(1).

=back

=head1 FILES

To be written.

=head1 BUGS

There is a memory leak somewhere.

Killing the programme may corrupt the fingerprint database(s).

Changing version of GraphicsMagick invalidates fingerprint databases.

=head1 NOTES

Directory recursion is deliberately not implemented:
Composing a file-list and using it with C<-> is a more flexible approach.

Repetitions are culled before comparisons take place, so a commandline
like C<findimagedupes a.jpg a.jpg> will not produce a match.

The program needs a lot of memory. Probably not an issue, unless your
machine has less than 128MB of free RAM and you try to compare more than
a hundred-thousand files at once (and the program will run quite slowly
with that many files anyway---about eight hours initially to generate
fingerprints and another ten minutes to do the actual comparing).

=head1 SEE ALSO

find(1), md5sum(1)

B<gqview> - GTK based multiformat image viewer

B<gthumb> - an image viewer and browser for GNOME

=head1 AUTHOR

Jonathan H N Chin <code@jhnc.org>

=head1 COPYRIGHT AND LICENSE

 Copyright 2006 by Jonathan H N Chin <code@jhnc.org>.

 This program is free software; you may redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

=head1 HISTORY

This code has been written from scratch. However it owes its existence
to B<findimagedupes> by Rob Kudla and uses the same duplicate-detection
algorithm.

=cut

__C__

/* efficient bit-comparison */

#include <stdint.h>
#include <string.h>

#define LOOKUP_SIZE 65536
#define FP_CHUNKS 16

typedef uint16_t FP[FP_CHUNKS];

unsigned int simplecountbits (unsigned int i) {
	unsigned int val = i, res = 0;

	while (val) {
		res += (val&1);
		val >>= 1;
	}
	return(res);
}

void diffbits (SV* oldfiles, SV* newfiles, unsigned int threshold, unsigned limit) {
	FP *the_data, *a, *b;
	unsigned int lookup[LOOKUP_SIZE];
	unsigned int i, j, k, m, bits, old, new;
	HV *oldhash;
	HE *oldhash_entry;
	HV *newhash;
	HE *newhash_entry;
	unsigned int numkeys = 0;
	SV *sv_val;
	Inline_Stack_Vars;

	if ((threshold<0) || (threshold>256)) {
		croak("ridiculous threshold specified");
	}

	/* pack fingerprints into C array */
	/* partly lifted from Inline::C-Cookbook */

	if (! SvROK(newfiles)) {
		croak("newfiles is not a reference");
	}
	newhash = (HV *)SvRV(newfiles);
	new = hv_iterinit(newhash);

	if (! SvROK(oldfiles)) {
		croak("oldfiles is not a reference");
	}
	oldhash = (HV *)SvRV(oldfiles);
	old = hv_iterinit(oldhash);

	numkeys = new+old;
	if (numkeys<2) {
		/* minor optimization: return without doing anything */
		/* malloc(0) could be bad... */
		Inline_Stack_Void;
	}
	the_data = (FP *)malloc(numkeys*sizeof(FP));
	if (!the_data) {
		croak("malloc failed");
	}

	for (i = 0; i<new; i++) {
		newhash_entry = hv_iternext(newhash);
		sv_val = hv_iterval(newhash, newhash_entry);
		memcpy(the_data+i, SvPV(sv_val, PL_na), sizeof(FP));
	}
	for (i = new; i<numkeys; i++) {
		oldhash_entry = hv_iternext(oldhash);
		sv_val = hv_iterval(oldhash, oldhash_entry);
		memcpy(the_data+i, SvPV(sv_val, PL_na), sizeof(FP));
	}

	/* initialise lookup table */
	/* XXX: fast enough? could optimise more or compile-in a static table */
	for (i=0; i<LOOKUP_SIZE; i++) {
		lookup[i] = simplecountbits(i);
	}

	/* look for matches */
	Inline_Stack_Reset;
	for (a=the_data, i=0, m=(limit>0 ? new : numkeys-1); i<m; a++, i++) {
		for (b=a+1, j=i+1; j<numkeys; b++, j++) {
			for (bits=0, k=0; k<FP_CHUNKS; k++) {
				bits += lookup[(*a)[k]^(*b)[k]];
				if (bits > threshold) goto abortmatch;
			}
			/* if (bits <= threshold) */ {
				Inline_Stack_Push(sv_2mortal(newSViv(i)));
				Inline_Stack_Push(sv_2mortal(newSViv(j)));
				Inline_Stack_Push(sv_2mortal(newSViv(bits)));
			}
abortmatch:;
		}
	}
	Inline_Stack_Done;

	/* clean up */
	free(the_data);
}