Commits

beroe committed 4ce5498

New version of exif script to change creation dates too

Comments (0)

Files changed (1)

fileutils/exif_and_xattr_set.py

 	- exif keywords
 	- exif credit in various forms
 	- xattr usertags, hopefully for future spotlight indexing
+	- if the Finder creation date is bad, tries to replace with EXIF creation
 	
 Tags are generated from the subfolder name and the base folder name
 
 
 Edit the values in the initcreditstring() function to match your own info
 
+TODO: Get GPS data from other database or file and embed
 
+Version 1.06 - Parses files a bit differently and fixes dates
 Version 1.05 - Steve Haddock - haddock at mbari dot org...
+
 #####################################################
 """
 
 import os, sys
 import subprocess
+import glob
 
 
 def initcreditstring(NameString = "Steven Haddock", email = "haddock at mbari dot org"):
 
 	CreateDict = {
 	'CreatorAddress'       : 'MBARI',
-	'CreatorRegion'        : 'CA',
 	'CreatorPostalCode'    : '95039',
-	'CreatorWorkURL'       : '"http://jellywatch.org"',
+	'CreatorWorkURL'       : '"http://www.mbari.org/~haddock"',
 	'CreatorCountry'       : 'USA',
 	'CreatorWorkTelephone' : '831-775-1793'
 	}
 		# xattr.setxattr (F,OptionalTag+Field,TagText.encode('utf8'))
 
 		XattrCommand = 'xattr -w {0} \'{1}\' "{2}"'.format(OptionalTag + Field,TagText.encode("utf8"),F)
-		print XattrCommand
+		if DEBUG: print XattrCommand
 		#sys.stderr.write("XATTR: {}\n".format(XattrCommand))
 		# ProcOut = subprocess.Popen(XattrCommand, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=True) 
 		ProcString = subprocess.check_output(XattrCommand, stderr=subprocess.STDOUT,shell=True) 
 	return Result
 
 
+def	getfilecreatedate(filename):
+	# use exiftool with epochsecond format
+	exifcommand = 'exiftool -v0 -createdate -S  "%s" ' % (filename)
+
+	#returns FinderCreationDate in 01/28/2007 11:05:31 format
+	findercommand = 'GetFileInfo -d "%s"' %(filename)
+	# print exifcommand
+
+	fpipe = os.popen(findercommand)
+	fdata = fpipe.readlines()
+	
+	if fdata:
+		try:
+			fyear = int(fdata[0].split(" ")[0].split("/")[2])
+			if (fyear>1968):
+				freturn = fyear
+			else:
+				freturn = 0
+		except:
+			print fdata
+			freturn=0
+	else:
+		freturn = 0
+
+	expipe = os.popen(exifcommand)
+	exdata = expipe.readlines()
+	# print "EXDATA,",exdata
+	try:
+		dateline = exdata[0].replace("CreateDate: ","")
+		exyear = int(dateline.split(":")[0])
+		if (exyear > 0):
+			dates = dateline.replace(":","").replace(" ","")
+			return dateline,dates,freturn
+		else:
+			return 0,0,freturn
+	except:
+		return 0,0,freturn
+		
+def setcreatedate(F,DateTag):
+	DateList = DateTag.rstrip().split(" ")
+	YearSwitch = DateList[0].split(":") # This has year first
+
+	# Put the year last and join with /
+	if int(YearSwitch[0])> 1980:
+		# Put the year last and join with /
+		NewString = "/".join([ YearSwitch[1],YearSwitch[2],YearSwitch[0]])
+		DateString = NewString + " " + DateList[1]
+		# print DateString
+		sys.stderr.write(".")
+		setcommand = 'SetFile -d "{0}" "{1}"'.format(DateString,F)
+		ProcString = subprocess.check_output(setcommand, stderr=subprocess.STDOUT,shell=True) 
+	else:
+		ProcString = ""
+	return ProcString
+
+
+	# Only do this for old images, not new ones
 
 
 def writeexifkeywords(F,KeywordList,CreditLine):
 		"""
 
 def write_xattr_to_folder(D,TagList):
-	"""recursive approach to xattr with -rw"""
+	"""recursive approach to xattr with -rw. will fail with error if file is locked..."""
 	# PLIST approach - is necessary!
 	plistFront = '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><array>'
 	plistEnd = '</array></plist>'
 FileCount = 0
 XFileCount = 0
 NonImageCount = 0
+CHANGEDATE = True
+
 if __name__ == "__main__": 
 	# Flist = sys.argv[1:]
 	BaseDir = os.getcwd()
 	# Use this method if we are going to use the file lists later, but apparently not...
 	# AllFiles = [x for x in os.walk(BaseDir)]
 	# SubDirs = AllFiles[0][1]
-	# FileLists = [y[2] for y in AllFiles][1:]
+	# FileList = [y[2] for y in AllFiles][1:]
 	for Direct in SubDirs:
 		# File-by-file approach not used
 		# try:
 		
 		# folder-based xattr function -- not used
 		xout = write_xattr_to_folder(Direct,[BaseName, DirectName])
+		
 		if DEBUG and xout:
 			sys.stderr.write("** Output from xattr: {0}\n{1}\n".format(Direct,xout))
 
 		# Either use glob.glob or os.walk or ...
 				# The FileList has all files, including .DS_Store
+		#print DirectName, "DIRNAME"
+		# Trying by-file because 
+		# This works for - but what about other options??
+		
+		FileList = glob.glob(DirectName + "/*") 
+		# print FileList
+		XFileSubCount = 0
+		for FileName in FileList:
+			fn = FileName.lower()
+			ComboName = os.path.join(Direct,FileName)
 			
-		# XFileSubCount = 0
-		# for FileName in FileList:
-		# 	fn = FileName.lower()
-		# 	ComboName = os.path.join(Direct,FileName)
-		# 	
-		# 	if (".jpg" in fn) or (".nef" in fn) or (".raw" in fn) or (".jpeg" in fn) or (".png" in fn) or (".tif" in fn):
-		# 		sys.stderr.write("{0}, ".format(FileName.split(".")[:-1][0]))
-		# 		XFileSubCount += 1
-		# 		# writeexifkeywords(ComboName, [BaseName, Direct], CreditLine)
-		# 		writexattrs(ComboName, [BaseName, Direct])
-		# 	else:
-		# 		if len(fn) > 2:
-		# 			NonImageCount += 1	
-		# 			
+			if (".jpg" in fn) or (".nef" in fn) or (".raw" in fn) or (".jpeg" in fn) or (".png" in fn) or (".tif" in fn):
+				# sys.stderr.write("{0}, ".format(FileName.split(".")[:-1][0]))
+				# writeexifkeywords(ComboName, [BaseName, Direct], CreditLine)
+				# Changed from BaseName
+				# sys.stderr.write("**Combo:{0}, File:{1}\n".format(ComboName,FileName))
+				# writexattrs(FileName, [BaseName, Direct])
+				dateline,datestr,freturn = getfilecreatedate(FileName)
+				
+				# Use exif date info to change dates.
+				if dateline and (freturn < 1970):
+				# writexattrs(F=Fname, DateTag = dateline)
+					# print dateline, datestr, datestr[:12]
+					#touchmoddate(F=Fname,DateTag = datestr[:12])
+					setcreatedate(FileName,dateline)
+					XFileSubCount += 1
+					
+				
+			else:
+				if len(fn) > 2:
+					NonImageCount += 1	
+					
 		# if XFileSubCount != NumberProcessed:
 		# 	sys.stderr.write("\n ** File count mismatch {0}[x] vs {1}[e] in folder {2}, ".format(XFileSubCount,NumberProcessed,Direct))
-		# XFileCount += XFileSubCount
-		print "..."
-	# sys.stderr.write("\n ### Finished processing {0} exif and {2} xattr files in {1} folder(s). ({3} non-images)\n".format(FileCount,DirCount,XFileCount,NonImageCount))
-	sys.stderr.write("\n ### Finished processing {0} EXIF files in {1} folder(s)\n".format(FileCount,DirCount))
+	# 	XFileCount += XFileSubCount
+	# 	print "..."
+	sys.stderr.write("\n ### Finished processing {0} exif and {2} changedate files in {1} folder(s). ({3} non-images)\n".format(FileCount,DirCount,XFileSubCount,NonImageCount))
+	#sys.stderr.write("\n ### Finished processing {0} EXIF files in {1} folder(s)\n".format(FileCount,DirCount))