lib/Image/Kimdaba.pm untested

filter: Statementstmt 0.0% 0 / 183 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 18 totaltotal 0.0% 0 / 283 CC 21 SCAR 28.1
CC
21
Cov
0%
matchOptions
56.0
member
30.0
getRootFolder
12.0
CRAP 16.5
1 # Copyright 2005 Jean-Michel Fayard jmfayard_at_gmail.com
2 # Put into the public domain.
3 #
4  
5 package Image::Kimdaba;
6 use strict;
7 use warnings;
8 use XML::Parser;
9 use Carp;
10  
11 =head1 NAME
12  
13 Image::Kimdaba - Parser for the KDE Image Database
14  
15 See here : http://ktown.kde.org/kimdaba
16  
17 =head1 SYNOPSIS
18  
19 use Image::Kimdaba;
20 use English qw( -no_match_vars ) ;
21
22 my @ListOfPictures;
23
24 my $folder=getRootFolder();
25 parseDB( "$folder" );
26
27 print "Your actual Kimdaba settings are :\n";
28 while( my ($attr, $value) = each %kimdabaconfig)
29 {
30 print "\t$attr => $value\n";
31 }
32 print "\n";
33
34 my $nb1= scalar keys %imageattributes;
35 my $nb2= scalar keys %imageoptions;
36 print "Following options were present in your $nb1 pictures :\n";
37 while( my ($option,$r_values) = each %alloptions )
38 {
39 my $nb = scalar @$r_values;
40 print "\t$nb $option\n";
41 }
42 print "\n";
43
44 local $, = "\n" ; # print bla,bla prints "bla\nbla"
45
46 print "\n\n== NO Keywords (ten first) ==\n";
47 @ListOfPictures=matchAnyOption( "Keywords" => [] );
48 print sort(@ListOfPictures[0..9]);
49
50 print "\n\n== Holiday ==\n";
51 @ListOfPictures=matchAnyOption( "Keywords" => [ "holiday" ] );
52 print sort(@ListOfPictures);
53
54 print "\n\n== ANNE HELENE ==\n";
55 @ListOfPictures=matchAnyOption( "Persons" => [ "Anne Helene" ] );
56 print sort(@ListOfPictures);
57
58 print "\n\n== ANY OF (JESPER, ANNE HELEN) ==\n";
59  
60 @ListOfPictures=matchAnyOption( "Persons" => [ "Jesper" , "Anne Helene" ] );
61 print sort(@ListOfPictures);
62
63 print "\n\n== ALL OF (JESPER, ANNE HELEN) ==\n";
64 @ListOfPictures=matchAllOptions( "Persons" => [ "Jesper" , "Anne Helene" ] );
65 print sort(@ListOfPictures);
66
67 print "\n\n== PERSONS=Jesper, Locations=Mallorca ==\n";
68 @ListOfPictures=matchAllOptions(
69 "Persons" => [ "Jesper" ],
70 "Locations" => [ "Mallorca" ]
71 );
72 print sort(@ListOfPictures);
73
74
75
76 $, = "" ; # print bla,bla prints "blabla"
77
78 print "\n\n==Print all infos known about specific pictures\n";
79 print "\n\n== Drag&Drop pictures from Kimdaba ==\n";
80 @ListOfPictures=letMeDraganddropPictures();
81 printImage( $_ ) foreach @ListOfPictures;
82
83  
84 =head1 DESCRIPTION
85  
86 From the website : http://ktown.kde.org/kimdaba
87  
88 KimDaBa or KDE Image Database is a tool which you can use to easily sort your
89 images. It provides many functionnalities to sort them and find them easily.
90  
91 =head2 Datastructures
92  
93 The infos available in the database are directly translated in following perl datastructures.
94 (See the index.xml file to see how it looks like)
95
96 note : the reading of man perllol is highly recommended
97  
98 =head3 C<%imageattributes>
99  
100 HASH OF (url of the picture, REF. HASH OF (attribute, value) )
101  
102 Now and in the rest of the document, B<url> is given locally from the root directory,
103 such as "Folder1/Subfolder/img001.jpg",
104 it's neither file:/home/user/Images/Folder1/Subfolder1/img001.jpg nor http://www.google.com/images/logo.gif
105  
106 An B<HASH> corresponding to this B<url> could be
107  
108 (
109 monthFrom=>"1",
110 dayFrom=>"18",
111 hourFrom=>"19",
112 yearTo=>"0",
113 monthTo=>"0",
114 md5sum=>"7f120e3cfb698ce0d7bb6e4e454c1a8b",
115 minuteFrom=>"29",
116 file=>"2005-01-09-Gif/img_0290.jpg",
117 label=>"img_0290",
118 angle=>"0",
119 dayTo=>"0",
120 secondFrom=>"46",
121 yearFrom=>"2005",
122 description=>""
123 )
124  
125 =head3 C<%imageoptions>
126  
127 HASH of (url, REF. HASH OF (optoin, REF. LIST OF value) )
128  
129 C<url> is given locally from the root directory, such as "Folder1/Subfolder/img001.jpg"
130  
131 An C<HASH> corresponding to this C<url> could be
132  
133 (
134 Keywords => [ "holiday" ],
135 Locations => [ "Mallorca" ],
136 Persons => [ "Anne Helene", "Jesper" ]
137 )
138  
139 =head3 C<%alloptions>
140  
141 HASH of (option, REF. LIST of values)
142  
143 Could be something like :
144  
145 (
146 Keywords => [ "beers", "holiday", "new wave", "silo falls over", "Anne Helene's 30 years birthday" ]m
147 Locations => ...,
148 Persons => ...,
149 OtherCategory => ...
150 )
151  
152 =head3 C<%membergroups>
153  
154 membergroups are called categories depending on your version of Kimdaba.
155  
156 HASH : (Locations => REF (HASH : USA => [ Chicago, Los Angeles ] ) )
157  
158 Beware, you can have loops between membergroups.
159  
160 =head3 C<%kimdabaconfig>
161  
162 HASH of (attributes, values)
163  
164 Fast all KimDaBa settings are stored in the index.xml file, as attribute of the "KimDaBA/config" XML element.
165 So using this hash you can access many of the user preferences, for example it could be something like :
166  
167 (
168 viewSortTye=>>"0",
169 passwd=>"",
170 ensureImageWindowsOnScreen=>"1",
171 viewerCacheSize=>"25",
172 albumCategory=>"",
173 showDrawings=>"1",
174 htmlBaseURL=>"file:///home2/jmfayard/public_html",
175 previewSize=>"256",
176 thumbSize=>"64",
177 displayLabels=>"1",
178 launchViewerFullScreen=>"0",
179 windowWidth-0=>"800",
180 autoShowThumbnailView=>"0",
181 showInfoBox=>"1",
182 windowWidth-1=>"800",
183 slideShowWidth_1280=>"600",
184 viewerHeight_1280=>"450",
185 fromDate=>"2005-01-01",
186 htmlDestURL=>"file:///home2/jmfayard/public_html",
187 trustTimeStamps=>"0",
188 windowHeight-0=>"600",
189 thumbNailBackgroundColor=>"#000000",
190 windowHeight-1=>"600",
191 slideShowInterval=>"5",
192 toDate=>"2006-01-01",
193 exclude=>"1",
194 infoBoxPosition=>"6",
195 locked=>"0",
196 showDate=>"1",
197 imageDirectory=>"/tmp/kimdaba-demo-jmfayard",
198 searchForImagesOnStartup=>"1",
199 autoSave=>"5",
200 version=>"1",
201 viewerWidth_1280=>"600",
202 launchSlideShowFullScreen=>"0",
203 showDescription=>"1",
204 maxImages=>"100",
205 useEXIFComments=>"1",
206 useEXIFRotate=>"1",
207 showTime=>"1",
208 htmlBaseDir=>"/home2/jmfayard/public_html",
209 slideShowHeight_1280=>"450",
210 )
211  
212  
213  
214 =head2 Fonctions
215  
216 =cut
217  
218 BEGIN {
219 use Exporter ();
220 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
221  
222 $VERSION = 0.5;
223 @ISA = qw(Exporter);
224 @EXPORT = qw( %alloptions %kimdabaconfig %membergroups
225 %imageoptions %imageattributes
226 &printImage &getRootFolder &parseDB
227 &matchAllOptions &matchAnyOption &letMeDraganddropPictures
228 &askForPictures
229 &makeKimFile );
230 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
231  
232 # your exported package globals go here,
233 # as well as any optionally exported functions
234 #@EXPORT_OK = qw(%imageoptions %imageattributes);
235 }
236 our @EXPORT_OK;
237  
238 # exported package globals go here
239 our %imageattributes;
240 our %imageoptions;
241 our %alloptions;
242 our %kimdabaconfig;
243 our %membergroups;
244  
245 # non-exported package globals go here
246  
247 # initialize package globals, first exported ones
248 %imageattributes=();
249 %imageoptions=();
250 %alloptions=();
251 %kimdabaconfig=();
252 %membergroups=();
253  
254 # then the others (which are still accessible as $Some::Module::stuff)
255  
256 # all file-scoped lexicals must be created before
257 # the functions below that use them.
258  
259 # file-private lexicals go here
260 my $option="" ;
261 my $image=""; # image element that we currently handle
262 my $optionname=""; # currently handle option with name $option for image $image
263 my @values=(); # currently found values
264 my %alloptionshashed;
265 my $folder; # I need it for askForPictures
266  
267  
268  
269 =head3 C<&letMeDraganddropPictures()>
270  
271 print "\n\n== Drag&Drop pictures from Kimdaba ==\n";
272 @ListOfPictures = &letMeDraganddropPictures();
273  
274 Wait until the user drag and drop pictures from Kimdaba and Konqueror
275 and return a list of url.
276  
277 =cut
278  
279 sub letMeDraganddropPictures
280 {
281 my @res=();
282 my $line=<STDIN>;
283 chomp $line;
284 # for pictures having a "'" in their filename
285 $line=~s#'\\''#\\#g;
286 my @a = ( $line =~ m/'[^']+'/g );
287
288 my $folder2 = $kimdabaconfig{"imageDirectory"};
289 foreach (@a)
290 { # Change '/autre/Photos/USA/2004-08-09_Monument_Valley/Monument_Valley_05.JPG'
291 # in USA/2004-08-09_Monument_Valley/Monument_Valley_05.JPG
292 s#$folder##;
293 s#$folder2##; # in case where $folder="." or similar
294 s#(file:)?/+##;
295 s#^'## ;
296 s#'$## ;
297 s#\\#'#g;
298 push @res, $_;
299 }
300  
301 # Now check which urls are really correct :
302 @res =grep { exists $imageoptions{$_} } @res;
303 return @res;
304 }
305  
306  
307 ##########
308  
309 =head3 C<< &matchAllOptions(HASH of (option => REF List of values)) >>
310  
311 Returns a list of urls. See the example in the synopsis.
312  
313 =head3 C<< &matchAnyOption(HASH of (option => REF List of values)) >>
314  
315 Returns a list of urls. See the example in the synopsis.
316  
317 =cut
318  
319 sub matchAllOptions
320 {
321 return @{ matchOptions( 1, @_) };
322 }
323 sub matchAnyOption
324 {
325 return @{ matchOptions( 0, @_) };
326 }
327  
328 sub matchOptions
329 {
330 my ($matchall, %request)=@_;
331 my @urlsfound=();
332 my @checkoptions=keys %request;
333 URL: for my $url (keys %imageattributes)
334 {
335 my %options = ();
336 %options= %{ $imageoptions{$url} } if (exists $imageoptions{$url} );
337 OPTION: for my $option ( @checkoptions )
338 {
339 unless (exists $options{$option} ) {
340 if ( scalar @{ $request{$option} } == 0 ) {
341 next OPTION;
342 } else {
343 next URL;
344 }
345 }
346
347  
348 my @values_image =@{ $options{$option} }; # (Anne Helen)
349 my @values_searched=@{ $request{$option} }; # (Jesper, Anne Helen)
350 for my $req (@values_searched)
351 {
352 my $res = scalar grep { $_ eq $req } @values_image;
353 if ( ($res == 0) && ($matchall) ) {
354 next URL;
355 } elsif ( ($res!=0) && (!$matchall) ) { # if trouvé, here
356 next OPTION;
357 }
358 }
359
360 # If we went this far, this means that we...
361 if ($matchall) {
362 next OPTION; # ... found a value corresponding to each of the options
363 } else {
364 next URL; # ... never found a value corresponding to one of the options
365 }
366 }
367 push @urlsfound, $url;
368
369 }
370 return [ @urlsfound ];
371 }
372  
373 =head3 C<&getRootFolder()>
374  
375 my $folder=getRootFolder();
376 parseDB( "$folder" );
377  
378 Returns the absolute path of the root directory.
379 You should run the demo, keep the files, and use /tmp/kimdaba-demo-$USER
380 when you are experimenting.
381 Thanks to this function, the root directory can
382 - passed as first argument on the command line ($ kim_script /tmp/kimdaba-demo-$USER )
383 - or will be asked to the user
384  
385 =head3 C<&parseDB( $folder )>
386  
387 Readonly access to most information available in the index.xml file.
388 To modify a database, see B<&makeKimFile()>
389  
390 =cut
391  
392 sub getRootFolder
393 {
394 no warnings;
395 ($folder) = grep { -d } @main::ARGV;
396 $folder = "~/Images" unless (-d $folder );
397 $folder = $ENV{PWD} unless (-d $folder );
398 until ( (-d "$folder") && (-r "$folder/index.xml") )
399 {
400 print "In which folder are your pictures stored ?\n";
401 chomp( $folder=<STDIN>);
402 }
403 return $folder;
404 }
405  
406 =head3 C<&printImage( url )>
407  
408 printImage( $url );
409  
410 Interesting to debug. Its code also shows how to access the hashes %imageattributes and %imageoptions :
411  
412 sub printImage {
413 my ($file)= @_;
414
415 print "=== $file ===\n" ;
416 print "Attributes : ";
417 my %attributes = %{ $imageattributes{$file} } ;
418 while( my ($attr, $value) = each( %attributes ) )
419 {
420 print " $attr=>$value ; ";
421 }
422 print "\n";
423
424 my %options = %{ $imageoptions{$file} };
425 print "Options: \n" ;
426 while( my ($key, $r_values) = each( %options ) )
427 {
428 print "\t$key ==> ", join('; ', @$r_values ) , "\n";
429 }
430 print "\n";
431 }
432  
433 =cut
434  
435 sub printImage {
436 my ($file)= @_;
437  
438 print "=== $file ===\n" ;
439 print "Attributes : ";
440 my %attributes = %{ $imageattributes{$file} } ;
441 while( my ($attr, $value) = each( %attributes ) )
442 # for my $attr ( keys %{ $imageattributes{$file} } )
443 {
444 print " $attr=>$value ; ";
445 }
446 print "\n";
447
448 my %options = %{ $imageoptions{$file} };
449 print "Options: \n" ;
450 # for my $key ( sort keys %options )
451 while( my ($key, $r_values) = each( %options ) )
452 {
453 print "\t$key ==> ", join('; ', @$r_values ) , "\n";
454 }
455 print "\n";
456 }
457  
458  
459  
460  
461 ##### <Parsing of the database goes here> ######
462 sub parseDB ($)
463 {
464 my ($folder)=@_;
465 my $p1 = new XML::Parser(
466 Style => 'Subs'
467 );
468 croak "Can not find KimDaBa's database"
469 unless (-r "$folder/index.xml");
470 $p1->parsefile( "$folder/index.xml");
471 }
472 sub member {
473 my ( $p, $el, %attrs ) = @_ ;
474 my ($groupname,$member) =
475 ( $attrs{"group-name"}, $attrs{"member"} );
476 # index.xml format has changed at Fri Dec 3
477 my $category=$attrs{"option-group"} if ( exists $attrs{"option-group"} );
478 $category=$attrs{"category"} if ( exists $attrs{"category"} );
479
480 if (! exists( $membergroups{$category} ) ) {
481 $membergroups{$category} = {
482 $groupname => [ $member ]
483 };
484
485 } elsif (! exists( $membergroups{$category}{$groupname} ) ) {
486 $membergroups{$category}{$groupname} = [ $member ] ;
487 } else {
488 my $r_list = $membergroups{$category}{$groupname};
489 push @$r_list, $member;
490 }
491 }
492  
493 sub config {
494 my ( $p, $el, %attrs ) = @_ ;
495 %kimdabaconfig=%attrs;
496 }
497 sub image {
498 my ( $p, $el, %attrs ) = @_ ;
499 $image = $attrs{"file"} ;
500 $imageattributes{$image} = \%attrs;
501 }
502 sub image_ {
503 my ( $p, $el ) = @_;
504 $image = "";
505 }
506
507 sub options {
508 my ( $p, $el, %attrs ) = @_ ;
509 return if ($image eq "") ; # We are in KimDaBa>config>SearchInfo>Options>Option
510 # or in KimDaBa>Options
511 $imageoptions{$image} = {} ;
512 }
513 sub option {
514 my ( $p, $el, %attrs ) = @_ ;
515 return if ($image eq "") ; # We are in KimDaBa>config>SearchInfo>Options>Option
516 # or in KimDaBa>Options
517 $optionname=$attrs{"name"};
518 @values=();
519 }
520 sub option_ {
521 my ( $p, $el ) = @_;
522 if ($image eq "") {
523 $optionname="";
524 return;
525 }
526 $imageoptions{$image}->{$optionname} = [ @values ];
527 $alloptionshashed{$optionname} = {}
528 unless( exists $alloptionshashed{$optionname} );
529 for my $value (@values) {
530 $alloptionshashed{$optionname}{$value}=1;
531 }
532 $optionname="";
533 }
534  
535 sub value {
536 my ( $p, $el, %attrs ) = @_ ;
537 return if ( $optionname eq "" ) ;
538 push @values, $attrs{"value"};
539 }
540 sub KimDaBa_ {
541 # %alloptionshashed is hash of hash for efficiency reasons, but we want to return
542 # a more clean hash of list.
543 my $nb= scalar %alloptionshashed;
544 for (keys %alloptionshashed) {
545 $alloptions{ $_ } = [ keys %{ $alloptionshashed{$_} } ];
546 }
547 }
548 ##### <Parsing of the database ends here> ######
549  
550  
551  
552  
553 =head3 C<&makeKimFile( $destdir, $name, @list )>
554  
555 Instead of modifying directly the database (which could easily be dangerous
556 for your data), you write a kimdaba export file (*.kim)
557 then you use the import fonction in kimdaba (no dangerous, you are in control)
558  
559 A .kim file is a zip archive containning an index.xml file, and
560 a Thumbnail directory. You just have to create the index.xml file
561 (say in '/tmp') then you call :
562  
563 C<makeKimFile( "/tmp", "perl_output.kim", @ListOfPictures );>
564  
565 where
566  
567 /tmp/index.xml is the file created by you
568 /tmp/perl_output.kim is the resulting kimdaba import ile
569 @ListOfPictures is a list of urls present in /tmp/index.xml
570  
571 Not that the KimDaBa import feature has some limitations.
572  
573 Example :
574  
575 use Image::Kimdaba;
576
577 my @ListOfPictures;
578
579 my $folder=getRootFolder();
580 parseDB( "$folder" );
581
582 print "\n\n== Drag&Drop pictures from Kimdaba ==\n";
583 @ListOfPictures=letMeDraganddropPictures();
584 print join("\n", sort(@ListOfPictures));
585 print "--\n";
586
587 my $destdir="/tmp";
588 open( EXPORT, "> ${destdir}/index.xml");
589 print EXPORT <<FIN
590 <?xml version="1.0" encoding="UTF-8"?>
591 <KimDaBa-export location="external" >
592 FIN
593 ;
594
595 for my $url (@ListOfPictures)
596 {
597 my $description="yeah! I changed the description";
598 my $md5sum="";
599 if (
600 (exists $imageattributes{$url})
601 &&
602 (exists $imageattributes{$url}{'md5sum'})
603 &&
604 (! $imageattributes{$url}{'md5sum'} eq "")
605 )
606 {
607 $md5sum="md5sum=\"$imageattributes{$url}{'md5sum'}\" ";
608 }
609
610
611 my $value="Test Add Another Keyword";
612 print EXPORT <<FIN
613 <image description="$description" $md5sum file="$url" >
614 <options>
615 <option name="Keywords" >
616 <value value="Test Add a keyword" />
617 <value value="$value" />
618 </option>
619 </options>
620 </image>
621 FIN
622 ;
623 }
624
625 print EXPORT <<FIN
626 </KimDaBa-export>
627 FIN
628 ;
629 close( EXPORT );
630
631
632 makeKimFile( $destdir, "perl_export.kim", @ListOfPictures);
633  
634  
635 =cut
636  
637 sub makeKimFile
638 {
639 my ($destdir,$name,@ListOfPictures)=@_;
640 system( "rm -rf ${destdir}/Thumbnails" );
641 system( "mkdir -p ${destdir}/Thumbnails" );
642 for my $url (@ListOfPictures)
643 {
644 next unless( -e "${folder}/${url}" );
645 # ( my $dest = $url) =~ s#(.*)/(.*)#\2#;
646 my ($dirname,$basename) = ( $url =~ m#(.*)/(.*)# );
647 my $thumb="${folder}/${dirname}/ThumbNails/"
648 . "$kimdabaconfig{'thumbSize'}x$kimdabaconfig{'thumbSize'}"
649 . "-$imageattributes{$url}{'angle'}"
650 . "-$basename";
651 if (-e $thumb) {
652 my $a=symlink $thumb, "${destdir}/Thumbnails/$basename";
653 next;
654 }
655 print "Creating thumbnail for $url...\n";
656 $url=~s/'/'\\''/g;
657 $basename=~s/'/'\\''/g;
658 system(
659 "convert -size 128x128 '$folder/$url' -resize 128x128 '${destdir}/Thumbnails/$basename'"
660 );
661 }
662 chdir $destdir or croak "$!";
663 unlink $name;
664 system( "zip", "-r", $name, "index.xml", "Thumbnails" );
665 print "KimDaBa export file created : ${destdir}/${name}\n";
666 }
667  
668  
669 1; # don't forget to return a true value from the file
670  
671  
672  
673  
674 # Desactived for now, because it's rather pointless and adds a dependcy on Term::Readline
675  
676 ##sub askForPictures
677 ##{
678 ## my @res;
679 ## print <<EOF
680 ##Now specify a list of urls of pictures that this script will handle.
681 ##You can write any perl code. Then Ctrl-D when you are done.
682 ##Common examples:
683 ## # simple list
684 ## \@res=( "img004.jpg" , "img006.jpg" , "img010.jpg" );
685 ## # pictures not on disk
686 ## \@res=grep { ! -e "$folder/\$_" } keys \%imageoptions;
687 ## # pictures rotated in Kimdaba but not in the real life
688 ## @res=grep { $imageattributes{$_}{"angle"}!=0 } keys %imageattributes;
689 ## # kimdaba's queries
690 ## \@res=matchAllOptions( "Persons" => [ "Jesper" , "Anne Helene" ] );
691 ## \@res=matchAllOptions( "Persons" => [ "Jesper" ], "Locations" => [ "Mallorca" ]);
692 ## \@res=matchAnyOption( "Keywords" => [ "ForMyScript" ] );
693 ##
694 ##EOF
695 ##;
696 ## use Term::ReadLine;
697 ## my $term = new Term::ReadLine 'Kimdaba Query';
698 ## my $prompt = "Kim> ";
699 ## my $OUT = $term->OUT || \*STDOUT;
700 ##
701 ## while(1)
702 ## {
703 ## while ( defined (my $perlcode = $term->readline($prompt)) ) {
704 ## my $res = eval ($perlcode);
705 ## warn $@ if $@;
706 ## print $OUT $res, "\n" unless $@;
707 ## $term->addhistory($_) if /\S/;
708 ## }
709 ##
710 ### Now check which urls are really correct :
711 ## @res=grep { exists $imageoptions{$_} } @res;
712 ## print "Following pictures were found\n";
713 ## print join("\n",@res),"\n\n";
714 ## print "Continue with those picutres? [yes]/no : ";
715 ## $_=<STDIN>;
716 ## /no/ or last;
717 ## }
718 ## return @res;
719 ##}
720  
721 =head1 BUGS/CAVEATS/etc
722  
723 A lot ;-)
724  
725 =head1 AUTHOR
726  
727 Jean-Michel Fayard ; jmfayard{at}moufrei.de
728  
729 =head1 SEE ALSO
730  
731 B<perllol>