John Hurst

Version 1.5.5


Table of Contents

1 The Main Program
1.1 Setup
1.2 Define miscellaneous subroutines
1.3 Collect the Command Line Options
1.4 Perform the Top Level Visit
1.5 write list file
1.6 Plan for new data structure
2 The visit routine
2.1 initialize variables for visit routine
2.2 open index.xml and write header
2.3 get information from album XML file
2.4 write tree element to index.xml
2.5 sort fnames into directories and images
2.6 Visit All Directories
2.7 scan all images and process them
2.8 wind up index file
3 Descriptions
3.1 read descriptions file and create dictionary
3.2 wind up descriptions file
4 the addToIndex routine definition
5 the addToList routine definition
6 the makeImage routine
7 the makeSubImages routine
7.1 New SubImage generalized size definitions
8 the retrieve support routines definition
9 The index.xml file format
10 Indices

1. The Main Program is a Python program that organizes digital photographic images into a set of browsable web pages. The images are assumed to be organized into directories. (A separate program,, is available to perform this function.) These directories form the basis for browsing amongst the generated web pages.

Within each directory, an index.xml file is generated. This XML file is renderable into HTML by a separate XSL program, albums.xsl, also available separately. The format and structure of these directories is user-controlled, and photos can be arranged by subject, date, location, etc., etc.. Within a directory, photos are arranged by the order specified in an associated descriptions file, containing the image name and an image description. The initial sequence of image names is generated automatically for any image found in the directory, but not present in the descriptions file. The descriptions file is created if one is not found. See the section The index.xml file format for details.

Within each directory, an albums.xml file describes the content of the directory, and is used to generate the associated index.xml file. The albums.xml file contains the path name of the directory relative to the root directory of all photos managed by the system, along with the directory description and name, and a path to a thumbnail image that will represent the directory. This thumbnail image can be one of the photos contained within the directory, or elsewhere, and thus can be stylised to suit the directory contents.

"" 1.1 =
<interpreter definition 1.2> <banner 1.3> <basic usage information 1.4> <todos 1.5> <imports 1.6> <initialization 1.7,1.8,1.9,1.10,1.11,1.12,3.1,7.1> <define miscellaneous subroutines 1.13,1.14,1.19,2.6> <the addToList routine definition 5.1> <the makeImage routine definition 6.1> <the makeSubImages routine definition 7.2> <the addToIndex routine definition 4.1> <the visit routine definition 2.1> <the retrieve routine definition 8.2> <collect the command line options 1.15> <perform the top level visit 1.16> <write list file 1.20> **** Chunk omitted!

1.1 Setup

<interpreter definition 1.2> = #! /usr/bin/python
Chunk referenced in 1.1
<banner 1.3> =
######################################################################## # # # p h o t o . p y # # # ########################################################################
Chunk referenced in 1.1
<basic usage information 1.4> =
# A program to build photo album web pages. # # John Hurst # version <current version 11.1>, <current date 11.2> # # This program recursively scans a set of directories (given as # command line parameters) for images that comprise a photo album to # be rendered into a set of web pages. A file 'index.xml' is created # in each (sub)directory, containing a list of images and # subdirectories. This file can be rendered by an XML stylesheet # 'album.xsl' into HTML pages.
Chunk referenced in 1.1
<todos 1.5> =
# TODO # 20060306 flag descriptions that do not have full details (and auto # copy this to a 'NOT COMPLETE' line in higher level # album.xml data). #
Chunk referenced in 1.1
<imports 1.6> =
import cgi import EXIF import getopt import hashlib #import md5 import os import os.path import re import stat import subprocess import sys import time import xml.dom from xml.dom import Node from xml.dom.minidom import parse from xml.parsers.expat import ExpatError
Chunk referenced in 1.1

<initialization 1.7> =
indexdict={} debug=0
Chunk referenced in 1.1
Chunk defined in 1.7,1.8,1.9,1.10,1.11,1.12,3.1,7.1

Initialize the debug flag. This is currently set manually, but eventually we expect to make it a command line option.

<initialization 1.8> =
lists = {}
Chunk referenced in 1.1
Chunk defined in 1.7,1.8,1.9,1.10,1.11,1.12,3.1,7.1

Initialize the variable 'lists'. This is a python directory, where the keys are (os) directories paths rooted at the album subdirectory (the cli parameters), and the entries are lists of image file names within that directory. This is used to build a list of images within each (os) directory traversed. The list/directory is initially empty.

<initialization 1.9> =
descriptions={} sounds={} protected={}
Chunk referenced in 1.1
Chunk defined in 1.7,1.8,1.9,1.10,1.11,1.12,3.1,7.1

Initialize the variable 'descriptions'. This is a python directory, where the keys are image file names, and the entries are descriptions/captions for the image concerned. It is built from the eponymously named file 'descriptions' in the directory currently being scanned.

<initialization 1.10> =
Chunk referenced in 1.1
Chunk defined in 1.7,1.8,1.9,1.10,1.11,1.12,3.1,7.1

Define the XSL script used to render all XML files built by this program.

<initialization 1.11> =
ignorePat=re.compile("(.*(_\d+x\d+)\..*$)|(.xvpics)") medmatch=re.compile(".*_640x480.JPG") bigmatch=re.compile(".*_1600x1200.JPG") thumbmatch=re.compile(".*_128x128.JPG") identifyPat = re.compile(".* (\d+)x(\d+)( |\+).*") treepat=re.compile('.*/(200[/\d]+)')
Chunk referenced in 1.1
Chunk defined in 1.7,1.8,1.9,1.10,1.11,1.12,3.1,7.1

<initialization 1.12> =
maxmissing = 0 maxdir = ''
Chunk referenced in 1.1
Chunk defined in 1.7,1.8,1.9,1.10,1.11,1.12,3.1,7.1

maxmissing, maxdir are variables that track the directory with the maximum number of missing descriptions. This is purely a convenient device to point the user to where most documenting effort is required!

1.2 Define miscellaneous subroutines

<define miscellaneous subroutines 1.13> =
jpgPat=re.compile('(.*)\.(j|J)(p|P)(g|G)$') def trimJPG(name): res=jpgPat.match(name) if res: return name
Chunk referenced in 1.1
Chunk defined in 1.13,1.14,1.19,2.6
<define miscellaneous subroutines 1.14> =
def attrString(el): if el.hasAttributes(): str='' nl=el.attributes if debug: print "looking at attributes of length %d" % (nl.length) for i in range(nl.length): attr=nl.item(i) str+=' %s="%s"' % (,attr.value) return str else: return '' def flatString(elem): if elem.nodeType==Node.TEXT_NODE: return elem.nodeValue elif elem.nodeType==Node.ELEMENT_NODE: attrs=attrString(elem) str="" for el in elem.childNodes: str+=str+flatString(el) return "<%s%s>%s</%s>" % (elem.tagName,attrs,str,elem.tagName) else: return "[unknown nodeType]" def flatStringNodes(nodelist): str='' for node in nodelist: str+=flatString(node) return str
Chunk referenced in 1.1
Chunk defined in 1.13,1.14,1.19,2.6

1.3 Collect the Command Line Options

There are four command line options:

turn on debugging
Force the generate of the image XML files. This is useful if other relevant components have changed, such as the XSL files, which are not known about here.
Do not generate the large subimages.
Recursively traverse any subdirectories for further images.
Generate only the thumbnail subimages.
<collect the command line options 1.15> =
(opts,args) = getopt.getopt(sys.argv[1:],'dflrs:tv') forceXmls=recurse=thumbsOnly=False; large=True for (option,value) in opts: if option == '-d': debug=True elif option == '-f': forceXmls=True elif option == '-r': recurse=True elif option == '-l': large=False elif option == '-t': thumbsOnly=True elif option == '-v': print "<current version 11.1>" sys.exit(0)
Chunk referenced in 1.1

1.4 Perform the Top Level Visit

<perform the top level visit 1.16> =
visitdirs = args # if there are no directories to visit, include at least current directory if len(visitdirs)==0: visitdirs = ['.'] for dir in visitdirs: checkdir = os.path.abspath(dir) (h,t) = os.path.split(checkdir) (titl,nph,nalb,thm,descr,nmiss)=visit(0,checkdir,lists) atTop=False while not atTop: reldir=os.path.relpath(checkdir) msg = "Directory %s has %d images " % (reldir,nph) msg += "and %d missing descriptions" % (nmiss) print msg <explore next higher level to update counts 1.17>
Chunk referenced in 1.1

We visit every directory given as arguments to the program invocation. If no arguments are given, then visit the current directory.

All the real work of visiting a directory and computing the index XML files is done by the visit procedure, which returns a tuple of potentially changed values that are of relevance to higher level directory index XML files. These are, respectively: the title of the visited directory; the number of photos or images contained in the directory and its sub-directories; the number of albums ditto; the thumbnail to characterize the directory; the description of the directory; and the number of missing descriptions in the directory and its sub-directories.

These values are then propogated to higher level photo albums (directories) via the chunk <explore next higher level to update counts >, which also recomputes updated values of the tuple described above.

<explore next higher level to update counts 1.17> =
try: higherdir=checkdir+'/..' highername=higherdir+'/index.xml' higherindex=open(highername) higherdom=parse(higherindex) higherindex.close() if debug: print "parsed %s" % (highername) direlements=higherdom.getElementsByTagName('directory') countalbums=countphotos=countmissing=0 maxmissing=0;maxdir="" <scan all directory elements, updating counts 1.18> (titl,nph,nalb,thm,descr,nmiss)=\ ('',countphotos,countalbums,'','',countmissing) try: summary=higherdom.getElementsByTagName('summary')[0] summary.setAttribute('photos',"%d" % (nph)) summary.setAttribute('albums',"%d" % (nalb)) summary.setAttribute('missing',"%d" % (nmiss)) summary.setAttribute('maxmissing',"%d" % (maxmissing)) summary.setAttribute('maxdir',maxdir) except: pass # no summary to worry about newxml=higherdom.toxml() if debug: print newxml higherindex=open(highername,'w') higherindex.write(newxml) higherindex.close() checkdir=os.path.abspath(higherdir) (h,t) = os.path.split(checkdir) except IOError: #print "No higher level index.xml file" atTop=True except ExpatError: print "XML error in higher level index.xml file" atTop=True
Chunk referenced in 1.16

The next higher directory is identified and the index.xml file parsed. This is used to identify all the directory elements, which are scanned to update the key parameters. The title, thumbnail and descriptions are reset, since these will not change in the higher level summaries.

The summary element is then recomputed, and the index.xml file rewritten.

Note that this rewriting may not be necessary if none of the key variables have changed. This is not currently tested.

<scan all directory elements, updating counts 1.18> =
for direl in direlements: if direl.getAttribute('name')==t: if debug: print "found directory %s!" % (t) if titl: direl.setAttribute('title',titl) direl.setAttribute('albums',"%d" % nalb) direl.setAttribute('images',"%d" % nph) if thm: direl.setAttribute('thumb',t+'/'+thm) if descr: direl.setAttribute('description',descr) if nmiss==0: if direl.hasAttribute('missing'): direl.removeAttribute('missing') else: direl.setAttribute('missing',"%d" % nmiss) countalbums+= collectAttribute(direl,'albums') countalbums+= 1 # include one album for this directory countphotos+= collectAttribute(direl,'images') miss=collectAttribute(direl,'missing') countmissing+=miss if miss>maxmissing: maxmissing=miss maxdir=direl.getAttribute('name')
Chunk referenced in 1.17
<define miscellaneous subroutines 1.19> =
def collectAttribute(d,a): if d.hasAttribute(a): v=d.getAttribute(a) try: return(int(v)) except: print "Cannot convert attribute '%s' with value '%s'" % (a,v) return(-1) else: return 0
Chunk referenced in 1.1
Chunk defined in 1.13,1.14,1.19,2.6

1.5 write list file

<write list file 1.20> =
keys=lists.keys() for k in keys: try: listn=k+"/list" listf=open(listn,"w") except: print "Cannot open %s" % (listn) continue for a in lists[k]: listf.write(a+"\n") listf.close()
Chunk referenced in 1.1

Open the file list in each of the directories visited, and write a list of images found in that directory to the file. This may not be entirely accurate, and needs to be confirmed that it does work correctly. It has not been used recently, and may be superflous to needs. It has now been commented out (v1.2.3).

1.6 Plan for new data structure

In order to develop this program further, it is suggested that a full data structure for each image and album be developed. This data structure would be populated in some way, and would then provide the data for writing the index.xml file. How is it populated?

  1. from the current index.xml file
  2. from the album.xml file
  3. from the image file
  4. from the descriptions file
  5. from the command line (?)

There would be a list of such data components for each directory visited (hence a local variable to routine visit). This list could be sorted on one or more of its attributes to provide a range of views.

Components of the new data structure:

name the name of the image or album
title a title or caption for the image/album
date/time the date and time of the image
threads (new theme) a list of thread names
shutter/aperture shutter speed and aperture opening
film speed
flash used

2. The visit routine

<the visit routine definition 2.1> =
def visit(level,dirname, lists): global descriptions, sounds, protected, indexdict <initialize variables for visit routine 2.2> <read descriptions file and create dictionary 3.2> fnames=os.listdir(".") fnames.sort() dirs=[]; <sort fnames into directories and images 2.7> <open index.xml and write header 2.3> <get information from album XML file 2.4> reldir=os.path.relpath(dirname) indent=' '*level print '%sScanning directory "%s" ... (%s)' % (indent,reldir,title) <write tree element to index.xml 2.5> if not thumb: if len(images)>0: thumb=images[0] if thumb[-4:len(thumb)].lower()=='.jpg': thumb=thumb[0:-4] <visit all directories 2.8> indexout+=' <thumbnail>%s</thumbnail>\n' % (thumb) #sys.stdout.write("%d" % (len(images))) <scan all images and process them 2.9> indexout+=' <summary photos="%d" albums="%d" missing="%d" maxmissing="%d" maxdir="%s" minmissing="%d" mindir="%s"/>\n' % \ (nphotos,nalbums,missingdescrs,maxmissing,maxdir,minmissing,mindir) <wind up index file 2.10> <wind up descriptions file 3.3> os.chdir(saved) return (title,nphotos,nalbums,thumb,description,missingdescrs)
Chunk referenced in 1.1

2.1 initialize variables for visit routine

<initialize variables for visit routine 2.2> =
nphotos=nalbums=missingdescrs=gotdescrfile=0 listmissingimages=[] albumdom=None; title=""; thumb=description="" maxmissing=0; maxdir=""; minmissing=999999; mindir="" saved = os.getcwd() try: os.chdir(dirname) except OSError: print "*** Cannot open that directory - do you have the correct path?" sys.exit(1) mdescr=-1 images=[]
Chunk referenced in 2.1
the number of image files found in this subdirectory (album)
the number of subalbums (subdirectories containing images) found in this subdirectory
the number of images for which no description was found in the descriptions file
set if the descriptions file was succesfully read
a list of those images for which a description was found, but no image file
the XML-parsed album file
the title of this album (subdirectory)
the thumbnail image used to represent this album
the description of this album

2.2 open index.xml and write header

<open index.xml and write header 2.3> =
try: indexf=open("index.xml","r") indexf.close() #print "read index.xml" indexdom=parse("index.xml") except: indexin=''; indexdom=None #print "parsed index.xml" #print indexdom.toprettyxml() #print "HELP" if indexdom: indexdict={} indexarr=indexdom.getElementsByTagName('image') for image in indexarr: #print image.toprettyxml() if image.hasAttribute('gps'): gps=image.getAttribute('gps') name=image.getAttribute('name') indexdict[name]=gps #print name,gps #print indexdict else: print "could not load indexdom" sys.exit(1) try: albumdom=parse("album.xml") except: print "Cannot parse album.xml in directory %s" % dirname indexout='' indexout+='<?xml version="1.0" ?>\n' indexout+='<?xml-stylesheet type="text/xsl" ' indexout+='href="%s"?>\n' % ALBUMXSL indexout+='<album>\n'
Chunk referenced in 2.1

2.3 get information from album XML file

<get information from album XML file 2.4> =
if albumdom: indexout+=' <title>' try: titles=albumdom.getElementsByTagName('title') title=titles[0].firstChild.nodeValue except: title="" indexout+=title indexout+='</title>\n' thumbs=albumdom.getElementsByTagName('thumbnail') fc=thumbs[0].firstChild if fc: thumb=fc.nodeValue else: print ' '*level,"There is no thumbnail defined in %s/album.xml" % (dirname) albumdescr=albumdom.getElementsByTagName('description') if not albumdescr: try: albumdescr=albumdom.getElementsByTagName('shortdesc') except: albumdescr="" try: description=albumdescr[0].firstChild.nodeValue description=description.strip() except: description="" indexout+=' <description>' indexout+=description indexout+='</description>\n' commentary=albumdom.getElementsByTagName('commentary') if commentary: commentary=commentary[0] str=commentary.toprettyxml() else: commentary=albumdom.getElementsByTagName('longdesc') str=""; l=commentary.length for i in range(l): n = commentary.item(i) children = n.childNodes for c in children: if debug: print "Looking at child node %s" % c if c.nodeValue: str+=c.nodeValue indexout+=' <commentary>' indexout+=str indexout+='</commentary>\n'
Chunk referenced in 2.1

2.4 write tree element to index.xml

<write tree element to index.xml 2.5> =
indexout+=" <tree>" treepath=os.getcwd() #(prev,next)=getPrevNext(treepath) res=treepat.match(treepath) if res:'/' if debug: print "treepath=%s" % treepath #indexout=' <tree prev="%s" next="%s">' % (prev,next) indexout+=treepath indexout+='</tree>\n'
Chunk referenced in 2.1
<define miscellaneous subroutines 2.6> =
def getPrevNext(treePath): return('','')
Chunk referenced in 1.1
Chunk defined in 1.13,1.14,1.19,2.6

2.5 sort fnames into directories and images

<sort fnames into directories and images 2.7> =
dirIgnores=re.compile("(movies)|(sounds)") if debug: print images for f in fnames: res=ignorePat.match(f) if res: if debug: print "ignoring %s" % (f) continue if os.path.isdir(f): if not dirIgnores.match(f): dirs.append(f) else: print ' '*level,"skipping subdirectory %s" % (f) continue if os.path.isfile(f): (r,e)=os.path.splitext(f) if e.lower() in ['.jpg','.avi']: if r not in images: images.append(f) listmissingimages.append(f) continue
Chunk referenced in 2.1

Sort the list of all files in this directory into directories and images. We detect the first from an os.path.isdir call, and the second by checking its extension, which must be either .JPG or .jpg (or capitalisations in between).

2.6 Visit All Directories

<visit all directories 2.8> =
for d in dirs: missd=0 if recurse: if debug: print "in dir %s, about to visit %s ..." % (dirname,d) ad=os.path.abspath(d) (dtitle,nimages,ndirs,thumbn,ddescr,missd)=visit(level+1,d,lists) else: res=retrieve(d) if res: (dtitle,nimages,ndirs,thumbn,ddescr,missd)=res else: continue nphotos+=nimages; nalbums+=ndirs+1 missingdescrs+=missd if missd>maxmissing: maxmissing = missd maxdir = d if missd>0 and missd<minmissing: minmissing = missd mindir = d if not thumb: thumb=d+"/"+thumbn if thumbn[-4:len(thumbn)].lower()=='.jpg': thumbn=thumbn[0:-4] indexout+=' <directory title="%s" name="%s"\n' % (dtitle,d) indexout+=' albums="%d"\n' % (ndirs) indexout+=' images="%d"\n' % (nimages) if missd: indexout+=' missing="%d"\n' % (missd) indexout+=' thumb="%s"\n' % (d+"/"+thumbn) indexout+=' description="%s"/>\n' % (ddescr)
Chunk referenced in 2.1

2.7 scan all images and process them

<scan all images and process them 2.9> =
inum=0 lastimage=len(images)-1 for i in images: iprev=images[0]; inext=images[lastimage] if inum>0: iprev=images[inum-1] if inum<lastimage: inext=images[inum+1] (descr,hasGPS)=makeSubImages(level,lists,i,iprev,inext,mdescr) if descr==-1:{Note 2.9.1} continue if not descr: missingdescrs+=1 addToList(lists,i) indexout+=addToIndex(lists,i,descr,hasGPS) inum+=1 nphotos+=len(images)
Chunk referenced in 2.1
{Note 2.9.1}
dud descriptions file entry, ignore it

2.8 wind up index file

<wind up index file 2.10> =
indexout+='</album>\n' if indexout != indexin: indexof = open("index.xml","w") indexof.write(indexout) indexof.close() print ' '*level,"... index.xml"
Chunk referenced in 2.1

3. Descriptions

This is a revision of the literate structure to bring all descriptions related material together.

<initialization 3.1> =
descrpat = re.compile("([^ *]+?)(\.JPG)?( |\*)(.*?)( # (.*))?$")
Chunk referenced in 1.1
Chunk defined in 1.7,1.8,1.9,1.10,1.11,1.12,3.1,7.1

descrpat is a pattern to match image names. Note that the first pattern must be non-greedy, or the '.JPG' gets swallowed, and the fourth pattern likewise, or the ' # ' gets swallowed.

The third pattern has been added (v1.3.0) to flag protected images that must not be shown publically.

3.1 read descriptions file and create dictionary

<read descriptions file and create dictionary 3.2> =
try: descrf=open("descriptions","r") mdescr=os.stat("descriptions")[stat.ST_MTIME] gotdescrfile=1 for l in descrf.readlines(): res=descrpat.match(l) if res: if not ext: ext=".JPG" protect=('*') if protect: protected[filen]=True if debug: print filen,ext,comment,soundname descriptions[filen]=imgtitle if comment: sounds[filen]=soundname print ' '*level,"Got a sound file:%s" % (soundname) images.append(filen) else: images.append(l.rstrip()) except IOError: print "cannot open descriptions file in directory %s" % dirname descriptions={} sounds={} protected={}
Chunk referenced in 2.1

Build the python dictionary of descriptions. We attempt to open a file in the current directory called descriptions, and use that to initialize the dictionary. The file has the format of one entry per line for each photo, with the name of the photo at the start of the line (with or without the .JPG extension), followed by at least one blank, followed by the descritive text, terminated by the end of line.

3.2 wind up descriptions file

<wind up descriptions file 3.3> =
if not gotdescrfile: if os.path.exists('descriptions'): print "OOPS!! attempt to overwrite existing descriptions file" else: descr=open('descriptions','w') for i in images: descr.write(trimJPG(i)+' \n') descr.close() elif listmissingimages: print "There are images not mentioned in the descriptions file:" print "appending them to the descriptions file." descr=open('descriptions','a') for i in listmissingimages: descr.write(trimJPG(i)+' \n') descr.close()
Chunk referenced in 2.1

We finalise the descriptions file. Two scenarios are relevant: either a) the descriptions file does not exist, in which case we build a new one, with just the image names of those images found in the directory scan, or b) the descriptions file exists, but there are images found not mentioned in it. In this latter case, we append image names to the file. No attempt is made to insert them in their 'correct' position.

If there are no changes required, the descriptions file is untouched. The existence of the descriptions file is determined by whether the flag gotdescrfile is set.

4. the addToIndex routine definition

<the addToIndex routine definition 4.1> =
def addToIndex(lists,imagename,descr,hasGPS): (r,e)=os.path.splitext(imagename) # this was inserted to try an control the length of captions. It # is dangerous, however, as it can munge the well-formedness of # any contained XML. #if len(descr)>200: # descr=descr[0:200] + ' ...' gps='' if hasGPS: gps=' gps="yes"' return ' <image name="%s"%s>%s</image>\n' % (r,gps,descr) # was cgi.escape(descr)
Chunk referenced in 1.1

I've changed my mind a couple of times about escaping the description string. Currently the string is not escaped, meaning that any special XML characters (ampersand, less than, etc.) must be entered in escaped form. But this model does allow URLs and the like to appear in the description captions.

5. the addToList routine definition

<the addToList routine definition 5.1> =
# 'addToList' is called to add an image name to the list of images. # See above for the format of the data structure 'list'. It is # assumed that the image name is a full path from the album root ((one # of) the CLI parameter(s)). The directory part is removed and used # to match against the keys of 'lists'. A new entry is created if # this path has not previously been seen. The image name is then # added to this list, if it is not already there. def addToList(lists,imagefile): (base,tail)=os.path.split(os.path.abspath(imagefile)) (name,ext)=os.path.splitext(tail) if lists.has_key(base): a = lists[base] else: a = [] lists[base] = a if not name in a: a.append(name)
Chunk referenced in 1.1

6. the makeImage routine

<the makeImage routine definition 6.1> =
def makeImage(level,orgwd,orght,newwd,newht,newname,orgname,orgmod): # orgwd: original image width # orght: original image height # newwd: new image width # newht: new image height # newname: new image file name # orgname: original image file name # orgmod: original image modification date/time # if debug: print "makeImage(%d,%d,%d,%d,%s,%s,%s)" % \ (orgwd,orght,newwd,newht,newname,orgname,orgmod) if orght>orgwd: # portrait mode, swap height and width t=newht newht=newwd newwd=t if orght>newht: # check that resolution is large enough newmod=0 if os.path.isfile(newname): newmod=os.stat(newname)[stat.ST_MTIME] if orgmod>newmod: print ' '*level,"Writing %s at %dx%d ..." % (newname,newwd,newht) size=" -size %dx%d " % (orgwd,orght) resize=" -resize %dx%d " % (newwd,newht) if debug: print size+orgname+resize+newname os.system("/sw/bin/convert"+size+orgname+resize+newname) pass return
Chunk referenced in 1.1

7. the makeSubImages routine

This routine is responsible for building all the smaller images from the master image.

7.1 New SubImage generalized size definitions

We define here data structures to handle generalized sub-image size definitions. Not yet active.

<initialization 7.1> =
imageSizeDefs=[(128,128,"thumb"),(384,288,"small"),\ (640,480,"medium"),(1200,900,"large"),(0,0,"original")] imageSizes=[]; derivedImageMatch=[] for (wd,ht,sizeName) in imageSizeDefs: imageSizes.append("%dx%d" % (wd,ht)) derivedImageMatch.append(re.compile(".*_%dx%d.JPG" % (wd,ht)))
Chunk referenced in 1.1
Chunk defined in 1.7,1.8,1.9,1.10,1.11,1.12,3.1,7.1

Initialize the image size parameters. imageSizeDefs is normative, and defines all required image sizes. The first entry is deemed to be the thumbnail size, and an entry of (0,0) refers to the original size. imageSizes is an equivalent list of strings in the form %dx%d, and derivedImageMatch is an equivalent list of patterns to match image names of those sizes. (Except the last, which fix!)

<the makeSubImages routine definition 7.2> =
def makeSubImages(level,lists,imagename,iprev,inext,mdescr): global descriptions,forceXmls (r,e)=os.path.splitext(imagename) if not e: e='JPG' imagename="%s.%s" % (r,e) if not os.path.isfile(imagename): e='jpg' imagename="%s.%s" % (r,e) if debug: print "making sub images for %s, e=%s, forceXmls=%s" % (imagename,e,forceXmls) thumbn=r+"_128x128.JPG" smalln=r+"_384x288.JPG" medn=r+"_640x480.JPG" bign=r+"_1200x900.JPG" viewn=r+".xml" <return on missing image file 7.3> <get all modification times 7.4> <makeSubImages: make any sub images required 7.5> # check if there is a new description olddescr=descr="" try: oldxmldom=parse(viewn) olddescr=oldxmldom.getElementsByTagName('description') olddescr=flatStringNodes(olddescr[0].childNodes) olddescr=olddescr.strip() except: print "Could not get old description for %s" % viewn pass if descriptions.has_key(r): descr=descriptions[r].strip() # create the new IMAGE.xml if the descriptions file exists # (mdescr>0) and is more recent than IMAGE.xml, or the IMAGE.JPG # is more recent than IMAGE.xml, and there is a new description if debug: print "mdescr=%d, mview=%d, mfile=%d" % (mdescr,mview,mfile) hasGPS=indexdict.has_key(r) #print indexdict #print "checking %s, it has %s gps" % (r,hasGPS) if forceXmls or \ (mview==0) or \ ( (olddescr!=descr) and \ ( (mdescr>0 and mdescr>mview) or \ (mfile>mview)\ )\ ): <makeSubImages: write image xml file 7.6> return (descr,hasGPS)
Chunk referenced in 1.1
<return on missing image file 7.3> =
if not os.path.isfile(imagename): if descriptions.has_key(r): descr=descriptions[r].strip() return (descr,False) else: print "descriptions entry '%s' : image not found" % (imagename) return (None,False)
Chunk referenced in 7.2

Check that the image file exists. If it doesn't, then there are two possible reasons. Firstly, the image file has been removed for space reasons, in which case there will be an entry in the descriptions database, and we return that without attempting to make any sub images.

Alternatively, no such descriptions entry means the image is genuinely missing, and therefore we should print a warning message, and return a missing image flag.

<get all modification times 7.4> =
mfile=os.stat(imagename)[stat.ST_MTIME] mthumb=msmall=mmed=mbig=mfile-1 mview=0 if os.path.isfile(thumbn): mthumb=os.stat(thumbn)[stat.ST_MTIME] if os.path.isfile(smalln): msmall=os.stat(smalln)[stat.ST_MTIME] if os.path.isfile(medn): mmed=os.stat(medn)[stat.ST_MTIME] if os.path.isfile(bign): mbig=os.stat(bign)[stat.ST_MTIME] if os.path.isfile(viewn): mview=os.stat(viewn)[stat.ST_MTIME] if debug: print "%d > (%d,%d,%d)" % (mfile,mthumb,mmed,mbig)
Chunk referenced in 7.2

Get all the modification times. The default modification times are that mview is the oldest, mfile is the youngest, and all the others are in between.

<makeSubImages: make any sub images required 7.5> =
if mfile>min(mthumb,msmall,mmed,mbig): p=subprocess.Popen(["/sw/bin/identify",imagename],stdout=subprocess.PIPE,stderr=subprocess.PIPE) (cmd_out,cmd_stderr)=p.communicate(None) if cmd_stderr: print "error in identify for %s ... (%s)" % (imagename,cmd_stderr) return (None,False) names=[thumbn,medn,bign,imagename] (b,t)=os.path.split(imagename) if debug: print "base=%s, tail=%s" % (b,t) if debug: print "Making images for %s" % (imagename) res=identifyPat.match(cmd_out) if res: wd=int( ht=int( smallwd=384.0; medwd=640.0; largewd=1200.0 smallht=288.0; medht=480.0; largeht=900.0 if wd>ht: smallwd=int(smallwd*(float(wd)/float(ht))) medwd=int(medwd*(float(wd)/float(ht))) largewd=int(largewd*(float(wd)/float(ht))) else: smallht=int(smallwd*(float(ht)/float(wd))) medht=int(medwd*(float(ht)/float(wd))) largeht=int(largewd*(float(ht)/float(wd))) makeImage(level,wd,ht,128,128,thumbn,imagename,mfile) if not thumbsOnly: makeImage(level,wd,ht,smallwd,smallht,smalln,imagename,mfile) makeImage(level,wd,ht,medwd,medht,medn,imagename,mfile) if large: makeImage(level,wd,ht,largewd,largeht,bign,imagename,mfile) count=1
Chunk referenced in 7.2

(20110717:172812) The variables smallwd, medwd, largeht are introduced to ensure that the resulting images all have a consistent height, if not width. This was introduced because panoramas came out with the same width as convention 4x3s, making the height impossible small.

<makeSubImages: write image xml file 7.6> =
print ' '*level,"Writing %s ..." % (viewn), imagef=open(imagename,'rb') exiftags={} try: exiftags=EXIF.process_file(imagef) except ValueError: print "cannot extract exif data from %s" % imagename for tag in exiftags.keys(): if debug: print "%s = %s" % (tag,exiftags[tag]) imagexmlf = open(viewn,"w") imagexmlf.write('<?xml version="1.0" ?>\n') imagexmlf.write('<?xml-stylesheet type="text/xsl" ') imagexmlf.write('href="%s"?>\n' % ALBUMXSL) imagexmlf.write('<album>\n') (rp,ep)=os.path.splitext(iprev) (rn,en)=os.path.splitext(inext) treepath=os.getcwd()+'/' res=treepat.match(treepath) if res: imagexmlf.write(' <tree>%s</tree>\n' % ( imagexmlf.write(' <view name="%s" \n' % (r)) imagexmlf.write(' prev="%s" next="%s"\n' % (rp,rn)) if protected.has_key(r): imagexmlf.write(' access="localhost"\n') if sounds.has_key(r): snd=sounds[r] print " Adding sound: %s" % (snd) imagexmlf.write(' audio="sounds/SND_%s.WAV"\n' % (snd)) imagexmlf.write(' >\n') imagexmlf.write(' <description>\n') imagexmlf.write(' %s\n' % descr) # was cgi.escape(descr) imagexmlf.write(' </description>\n') if exiftags.has_key('Image Model'): camera=exiftags['Image Model'].__str__().strip() imagexmlf.write(' <camera>%s</camera>\n' % camera) hasGPS=False if exiftags.has_key('EXIF DateTimeOriginal'): datetime=exiftags['EXIF DateTimeOriginal'] imagexmlf.write(' <datetime>%s</datetime>\n' % datetime) if exiftags.has_key('EXIF ExposureTime'): shutter=exiftags['EXIF ExposureTime'] imagexmlf.write(' <shutter>%s</shutter>\n' % shutter) if exiftags.has_key('EXIF FNumber'): aperture=exiftags['EXIF FNumber'] try: aperture=str(eval(str(aperture)+'.0')) except: pass imagexmlf.write(' <aperture>%s</aperture>\n' % aperture) if exiftags.has_key('GPS GPSLatitudeRef'): hasGPS=True latRef=exiftags['GPS GPSLatitudeRef'] if exiftags.has_key('GPS GPSLatitude'): latitude=exiftags['GPS GPSLatitude'] if debug: print latitude res=re.match('\[(\d+), (\d+), *(\d+)/(\d+).*\]',latitude.__str__()) if res: latdegrees=int( latminutes=int( secnum secden latseconds=float(secnum)/float(secden) else: res=re.match('\[(\d+), (\d+), *(\d+).*\]',latitude.__str__()) if res: latdegrees=int( latminutes=int( latseconds=float( else: res=re.match('\[(\d+), *(\d+)/(\d+), (\d+).*\]',latitude.__str__()) if res: latdegrees=int( latminutes=float( if latminutes>60.0: latseconds=latminutes % 60 latminutes=latminutes // 60 else: latseconds=int( else: latdegrees=0 latminutes=0 latseconds=0.0 print "Cannot decode latitude %s" % (latitude.__str__()) imagexmlf.write(' <latitude hemi="%s" degrees="%d" minutes="%d" seconds="%f"/>\n' % \ (latRef,latdegrees,latminutes,latseconds)) if exiftags.has_key('GPS GPSLongitudeRef'): longRef=exiftags['GPS GPSLongitudeRef'] if exiftags.has_key('GPS GPSLongitude'): longitude=exiftags['GPS GPSLongitude'] if debug: print longitude res=re.match('\[(\d+), (\d+), *(\d+)/(\d+).*\]',longitude.__str__()) if res: londegrees=int( lonminutes=int( secnum secden lonseconds=float(secnum)/float(secden) else: res=re.match('\[(\d+), (\d+), *(\d+).*\]',longitude.__str__()) if res: londegrees=int( lonminutes=int( lonseconds=float( else: res=re.match('\[(\d+), *(\d+)/(\d+), (\d+).*\]',longitude.__str__()) if res: londegrees=int( lonminutes=float( if lonminutes>60.0: lonseconds=lonminutes % 60 lonminutes=lonminutes // 60 else: lonseconds=int( else: londegrees=0 lonminutes=0 lonseconds=0.0 print "Cannot decode longitude %s" % (latitude.__str__()) imagexmlf.write(' <longitude hemi="%s" degrees="%d" minutes="%d" seconds="%f"/>\n' % \ (longRef,londegrees,lonminutes,lonseconds)) print 'Lat:%d %d %7.4f %s' % (latdegrees,latminutes,latseconds,latRef), print 'Long:%d %d %7.4f %s' % (londegrees,lonminutes,lonseconds,longRef), imagexmlf.write(' </view>\n') imagexmlf.write('</album>\n') imagexmlf.close() print
Chunk referenced in 7.2

See comment under <the addToIndex routine definition 4.1> regarding escaping the description string.

8. the retrieve support routines definition

<the retrieve support routines definition 8.1> =
def getNodeValue(dom,field,missing): try: val = dom.getElementsByTagName(field).item(0).firstChild.nodeValue except: val=missing return val def retrieveField(field): try: val = index.getElementsByTagName(field).item(0).firstChild.nodeValue except: val="[could not retrieve %s]" % (field) return val
Chunk referenced in 8.2

These two support routines for retrieve encapsulate data extraction from the DOM model. They perform the same basic operation, differeing only in the default parameters required.

<the retrieve routine definition 8.2> =
def retrieve(d): <the retrieve support routines definition 8.1> missing=0 try: index = parse(d+'/index.xml') except: (etype,eval,etrace)=sys.exc_info() print "Not scanning directory %s because no index.xml found" % (d) print " (error type %s)" % (etype) return None if debug: print "Successfully parsed index.xml in directory %s" % (d) try: album = parse(d+'/album.xml') except: (etype,eval,etrace)=sys.exc_info() print "Cannot open album.xml in directory %s because %s" % (d,etype) album=None title = retrieveField('title') description = retrieveField('description') imageElems=index.getElementsByTagName('image') summary=index.getElementsByTagName('summary').item(0) photos=int(summary.getAttribute('photos')) albums=int(summary.getAttribute('albums')) missing=int(summary.getAttribute('missing')) # sort out the vexed problem of the thumbnail if album: albumThumbs=album.getElementsByTagName('thumbnail') else: albumThumbs='' thumbDefault=getNodeValue(index,'thumbnail','') thumb=thumbDefault if not thumbDefault: thumbDefault=getNodeValue(album,'thumbnail','') if debug: print " albumThumb: %s" % (thumbDefault) if not thumbDefault: thumb=thumbDefault miss=index.getElementsByTagName('missingdescriptions') if miss: missing=int(miss.item(0).firstChild.nodeValue) if 0: print "retrieved:" print " title: %s" % (title) print " photos: %d" % (photos) print " albums: %d" % (albums) print " thumb: %s" % (thumb) print " description: %s" % (description) return (title,photos,albums,thumb,description,missing)
Chunk referenced in 1.1

retrieve is called when we do not wish to recursively visit a subdirectory. Instead, relevant details from the subdirectory are extracted ('retrieved') from an index.xml file, which has been constructed when the relevant subdirectory was visited.

There is a slight problem with identifying a thumbnail for this album, since the definite source is that in the album.xml file. However, this may be blank, in which has we need to promote the first thumbnail within the directory (or subdirectories where the directory has no images of its own).

9. The index.xml file format

The following description defines the collection of XML elements used to build an index.xml file.

Note that lowercase names are the names of the element tags; capitalized names are element content; names starting with @ are attributes (with string values: attributes that must be digit strings are so identified).

indexfile   = title description commentary tree 
              directory* thumbnail image*
title       = TextNode .
description = TextNode .
commentary  = TextNode .
tree        = TextNode .
directory   = @title @name @albums @images @missing @thumb @description Empty .
thumbnail   = TextNode .
image       = @name TextNode .
summary     = @albums @maxdir @maxmissing @missing @photos .
@albums     = Digits .
@images     = Digits .
@missing    = Digits .
@maxmissing = Digits .
@photos     = Digits .

Explanation of attributes:

The title of the directory or album (for the human reader). This attribute is derived from the title element of the specified (sub-)directory
The name of the directory (the Unix name)
digit string defining the number of sub-directories
digit string defining the number of photos/images in this directory and any sub-directories (albums and sub-albums)
digit string defining the number of missing descriptions for all enclosed images

10. Indices

File Name Defined in 1.1
Chunk Name Defined in Used in
banner 1.3 1.1
basic usage information 1.4 1.1
collect the command line options 1.15 1.1
current date 11.2 1.4
current version 11.1 1.4, 1.15
define miscellaneous subroutines 1.13, 1.14, 1.19, 2.6 1.1
define miscellaneous subroutines 1.13, 1.14, 1.19, 2.6 1.1
define miscellaneous subroutines 1.13, 1.14, 1.19, 2.6 1.1
explore next higher level to update counts 1.17 1.16
get all modification times 7.4 7.2
get information from album XML file 2.4 2.1
imports 1.6 1.1
initialization 1.7, 1.8, 1.9, 1.10, 1.11, 1.12, 3.1, 7.1 1.1
initialization 1.7, 1.8, 1.9, 1.10, 1.11, 1.12, 3.1, 7.1 1.1
initialization 1.7, 1.8, 1.9, 1.10, 1.11, 1.12, 3.1, 7.1 1.1
initialize variables for visit routine 2.2 2.1
interpreter definition 1.2 1.1
makeSubImages: make any sub images required 7.5 7.2
makeSubImages: write image xml file 7.6 7.2
open index.xml and write header 2.3 2.1
perform the top level visit 1.16 1.1
read descriptions file and create dictionary 3.2 2.1
return on missing image file 7.3 7.2
scan all directory elements, updating counts 1.18 1.17
scan all images and process them 2.9 2.1
sort fnames into directories and images 2.7 2.1
the addToIndex routine definition 4.1 1.1
the addToList routine definition 5.1 1.1
the makeImage routine definition 6.1 1.1
the makeSubImages routine definition 7.2 1.1
the retrieve routine definition 8.2 1.1
the retrieve support routines definition 8.1 8.2
the visit routine definition 2.1 1.1
todos 1.5 1.1
visit all directories 2.8 2.1
wind up descriptions file 3.3 2.1
wind up index file 2.10 2.1
write list file 1.20 1.1
write tree element to index.xml 2.5 2.1
Identifier Defined in Used in
addToIndex 4.1
addToList 5.1
debug 1.7
descriptions 1.9 2.1, 3.2, 3.2, 7.2, 7.2, 7.2
descrpat 3.1 3.2
getNodeValue 8.1
ignorePat 1.11 2.7
listmissingimages 2.2 2.7, 3.3, 3.3
lists 1.8
makeImage 6.1 7.5, 7.5, 7.5, 7.5
makeSubImages 7.2 2.9
retrieve 8.2 2.8
retrieveField 8.1
visit 2.1 1.16, 2.8

Document History

20060314:183617 ajh 1.0.0 add single directory pass as default, -r to recursively scan subdirectories (major revision)
20060418:170216 ajh 1.0.1 add exception handling to a number of XML accesses
20060502:161718 ajh 1.1.0 add various options to omit processing all sizes
20060512:174933 ajh 1.1.1 add image names to descriptions file if not already there
20060515:064337 ajh 1.1.2 fixed bug with entry in decriptions not having an image file
20060601:165937 ajh 1.1.3 add tree field, and -f option to force generation of .xml files
20060603:231034 ajh 1.2.0 remove double previous/next, since now done dynamically in XSLT sheet.
20060608:175540 ajh 1.2.1 fix bug in descriptions with http escape chars
20060611:184930 ajh 1.2.2 fix bug when missing images
20060616:160512 ajh 1.2.2 clean up some description handling
20060628:114452 ajh 1.2.3 start non-destructive update of index files
20060630:065926 ajh 1.2.4 fix bug in scoping of retrieve support routines
20061022:102528 ajh 1.2.5 return non-escaping of description strings
20070419:153749 ajh 1.2.6 ignore movies in (recursive) scanning for directories
20070812:092952 ajh 1.2.7 missing files are not omitted from album if a description exists
20080210:224120 ajh 1.2.8 minor bug in generating sound links: restructured descriptions section
20090914:164528 ajh 1.3.0 add protected flag to descriptions file, generates access attribute in xml file
20090923:152614 ajh 1.4.0 traverse all directories back to root, filling in updated values
20090924:134427 ajh 1.4.1 fixed bug in new code
20110602:180115 ajh 1.4.2 upgrade popen to use subprocess module
20110714:094436 ajh 1.4.3 Improve commentary
20110714:191909 ajh 1.5.0 add GPS data
20110716:192730 ajh 1.5.1 fix whole numbered seconds for latitude
20110717:163005 ajh 1.5.2 fix whole numbered seconds for longitude
20110721:174705 ajh 1.5.3 add camera model
20110806:163853 ajh 1.5.4 tidy GPS reporting
20110819:115130 ajh 1.5.5 add handling of iPhone GPS coords
<current version 11.1> = 1.5.5
Chunk referenced in 1.4 1.15
<current date 11.2> = 20110806:163853
Chunk referenced in 1.4