#!/usr/bin/env python
# Copyright ©Dave Pawson 2007
# This program is free software; you can 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, see .
import sys
import codecs
import string
import os
from optparse import OptionParser
from decimal import Decimal
import fpformat
#
# Module function:
#
function ="""This program does the following things
0. Assumes you have processed an image containing exif metadata, using
$exiftool -a -u -g1 -s -t
1. reads input params for filename(s)
2. Parses the file(s)
3. Converts to N3 rdf
5. Re-writes the files in N3, with extension @@FIXME
"""
version="1.2"
date ="2007-08-17"
outfile=""
out=None
infile=""
prog ="exifrdf"
copyright="Copyrght (C) 2007 Dave Pawson"
requiredArgs=2
description=False # don't add dc:title, dc:description
geo=False # don't add geo data
setOpt = False # command line boolean
debug=0
#
#Metadata globals
#
filename='' # filename
path='' # path to filename
width=0 # Image width, px?
height=0 # Image height, px?
def mainProg():
global infile,outfile
global out
header()
if (debug >5):
print "Processing %s to %s" % (infile, outfile)
inp = codecs.open(infile,"r","utf-8")
for line in inp:
processLine(line)
if (debug == 4):
print "Meta: path %s\n file %s\n width %s\n Height %s" % (path, filename, width, height)
inp.close()
tail()
out.close()
return
#
#Process a single line of the exif data
#
def processLine(line):
if line[0:4] =="----":
if debug > 3:
print "*****************Section %s" % line[4:-4]
out.write("# %s\n" % line[4:-4])
else:
tag= line.split('\t')[0]
value=line.split('\t')[1]
value=value[0:-1]
out.write("exif:%s \"%s\";\n" %(tag,value))
extractMeta(tag, value)
return
#
#Extract @@FIXME values from exif data
#
def extractMeta(tag, value):
global filename, path, width, height
if (tag=='FileName'):
filename=value
if (tag =='Directory'):
if (value=='.'):
path=os.getcwd() # replace . by actual directory
else:
path=value
path = path + os.sep
if (tag =='ImageWidth'):
width=value
if (tag == 'ImageHeight'):
height=value
#
# Select a geo position from a list
# returns the geo string e.g. geo:lat 52.2345; \n geo:long -93.1234
# E.g. see http://www.realestate3d.com/gps/world-latlong.htm
def selectGeo():
geos = {
'home' : "00.00 -1.00",
'hitchin' : "51.54 -0.14",
'karachi' : "24.85 67.033"
}
l = []
#input = raw_input("Select geo tags? Hit any key to select or Return to skip > ")
key = 0
for nm,loc in geos.iteritems():
print "%i %s" %(key, nm)
l.append(nm)
key +=1
while 1:
input = raw_input("Enter a number, Rtn to skip >")
if input:
idx = string.atoi(input,0)
if idx < len(l):
input = l[idx ]
if geos.has_key(input):
(lat,lon) = string.split(geos[input]," ")
#print "Using Name, %s Lat %s, Long %s " % (input, lat, lon)
return "geo:lat %s;\ngeo:long %s;" % (lat, lon)
break
else:
print "Entry not found, try again"
break
#
#See if user wants to enter actual coordinates, or select
# from an existing position.
#
def trygeo():
while 1:
print("Enter position of photo? ")
resp = raw_input("e to enter values, s to select from list, Rtn to skip ")
if resp:
if resp=="e":
return getPos()
if resp=="s":
return selectGeo()
else:
print "Invalid selection"
else:
return ""
#
#Obtain Lat and Long from user
#
def getPos():
while 1:
lat =raw_input("Enter latitude, -90 ... +90 ")
if lat:
latn = float(lat)
if (-90.0 < latn) and (latn < 90.):
break
else:
print "Invalid"
while 1:
lon =raw_input("Enter longitudeitude, -90 ... +90 ")
if lon:
lonn = float(lon)
if (-180.0 < lonn) and (lonn < 180.):
break
else:
print "Invalid"
return "geo:lat %s;\ngeo:long %s;" % (latn, lonn)
#
#Print out the header
#
def header():
headertxt="""
# -*- N3 -*-
@prefix owl: .
@prefix log: .
@prefix xs: .
@prefix exif: .
@prefix rdf: .
@prefix rdfs: .
@prefix dc: .
@prefix dcterms: .
@prefix foaf: .
@prefix wordnet: .
@prefix geo: .
@prefix lang: .
@prefix : <#> .
"""
out.write(headertxt)
out.write ("exif:data a exif:dataset;\n")
out.write ("dc:date \"%s\";\n" % date)
#
#Output the tail of the piece
#
def tail():
if description:
input = raw_input("Enter dc:title >")
if input:
out.write( "dc:title \"%s\";\n" % input)
input = raw_input("Enter dc:description >")
if input:
out.write("dc:description \"%s\";\n" % input)
if geo:
out.write(trygeo())
out.write(".\n\n")
#
# Print usage instructions
#
def usage():
str="""
%s.py, Version %s Date %s %s
Assumes you have processed an image containing exif metadata, using
$exiftool -a -u -g1 -s -t
This program processes the output of that tool.
$> python %s.py -i infile -o outfile [options]
for console output set -o -
""" % (prog, version, date, copyright, prog)
return str
#
# Main program entry
#
def main():
global infile, outfile, description, out, geo
parser = OptionParser(usage=usage())
parser.add_option("-i","--input",dest="infilenm",
help="Input file to process")
parser.add_option("-o","--output",dest="outfilenm",
default="-",
help="Output filename for results")
parser.add_option("-d", action="store_true", dest="description",
help="set to add title and description"
)
parser.add_option("-g", action="store_true", dest="geo",
help="set to add geographical data, lat and long")
(options, args) = parser.parse_args()
if not (options.infilenm ):
parser.print_help()
sys.exit(2)
infile =options.infilenm
if options.outfilenm=="" :
outfile=sys.stdout
else:
outfile=options.outfilenm
description = options.description
geo = options.geo
#Now validate parameters
#if not( os.path.isdir(directory)):
# sys.stderr.write ("\t\t Error, '%s' is not a directory\n" % directory)
# sys.exit(2)
if not(os.path.isfile(infile)):
sys.stderr.write ("\t\t Error, %s should be a file\n" % infile)
sys.exit(2)
try:
if (outfile <>"-"):
out = open(outfile,'w')
else:
out = sys.stdout
except EnvironmentError:
sys.stderr.write("%s not writable, Quitting" %outfile)
sys.exit(2)
if debug > 5:
print "%s.main: %s Version %s, Processing %s to %s" % (prog,prog,version,infile,outfile)
mainProg()
if (debug > 5): sys.stderr.write("%s.main, Finished" % (prog))
if __name__ == '__main__':
main()