""" Raw Image MetaData Plugin ========================= Sample class which can be used as a plugin for Peter's Flexible Renaming Kit (PFrank) Just copy the class definition (no need to copy the other declarations or test code) to your PFrankUser.py file and add a reference to the class in the PFrankUser.py 'UserRenamerList' table. Or just rename this file as PFrankUser.py and move it to your PFrank install folder if you don't want any other plugins. More details can be found in the PFrankUser.py.template file that is included with the PFrank download. Feb 1, 2008 Initial Creation 0.1 """ ########################################## # list your imported modules here. # If you get import errors, then the modules are not # present in the environment. In this case you will have to # insert the required module in the PFrank install folder. ########################################## # start of user imported modules import re import string # end of user imported modules. ########################################## # The following modules must always be imported ########################################## # start of required imported modules try : from SearchRep_init import configurator from SearchRepBase import SearchRepBase from SearchRepConstants import * except : print "importing initstubs" from SearchRep_initStubs import configurator from SearchRepBaseStubs import * # end of required imported modules class UserRawImageMetaData (SearchRepBase) : """ This is a sample renamer class. The SearchRepLower base class is mandatory. This is an example of taking the output of a third party program from the windows command line and using that output to rename a file/folder The application in this case is exiv2 which is used to extract meta-data from image files. Exiv2 is useful because unlike the core PFrank program, it can extract meta data from raw image files. A sample output of exiv2 is: File name : test.jpg File size : 1495355 Bytes Camera make : Canon Camera model : Canon PowerShot A620 Image timestamp : 2007:07:27 11:12:41 Image number : 113-1373 Exposure time : 1/1250 s Aperture : F3.5 Exposure bias : 0 Flash : No, auto, red-eye reduction Flash bias : 0 EV Focal length : 14.9 mm Subject distance: 90 ISO speed : 50 Exposure mode : Easy shooting (Auto) Metering mode : Multi-segment Macro mode : Off Image quality : Fine Exif Resolution : 3072 x 2304 White balance : Auto Thumbnail : JPEG, 3892 Bytes Copyright : Exif comment : This particular plugin command will insert the 'Image timestamp' before the filename. This class can be used as a template for inserting other image meta data into the filename. TO USE THIS COMMAND, YOU MUST INSTALL THE EXIV2 UTILITY BEFOREHAND. THEN IF NECESSARY MODIFY THE PATH TO EXIV2 IN THE 'FIXNAMES' METHOD BELOW """ def __init__ (self) : # call base class initializer. This is mandatory SearchRepBase.__init__(self) # This is the ID string that will appear in the pre-defined command # pull down list. It will also appear in the custom list when # inserted. The id will also be used in the scan summary # The name 'self.idstring' must not change. Set the assigned string # on the right-hand side of the assignment statement to whatever # name you want. self.idstring = "(User) - Insert Raw Image Date/Time before " """ Definitions for the parameter line numbers output by the exiv2 tool It is assumed that the output of exiv2 for all files will always display lines in the same order. The following line order is obtained from exiv2 version 0.18 """ self.EXIV2_LINE_FILE_NAME = 0 self.EXIV2_LINE_FILE_SIZE = 1 self.EXIV2_LINE_MIME_TYPE = 2 self.EXIV2_LINE_IMAGE_SIZE = 3 self.EXIV2_LINE_CAMERA_MAKE = 4 self.EXIV2_LINE_CAMERA_MODEL = 5 self.EXIV2_LINE_IMAGE_TIMESTAMP = 6 self.EXIV2_LINE_IMAGE_NUMBER = 7 self.EXIV2_LINE_EXPOSURE_TIME = 8 self.EXIV2_LINE_APERTURE = 9 self.EXIV2_LINE_EXPOSURE_BIAS = 10 self.EXIV2_LINE_FLASH = 11 self.EXIV2_LINE_FLASH_BIAS = 12 self.EXIV2_LINE_FOCAL_LENGTH = 13 self.EXIV2_LINE_SUBJECT_DISTANCE = 14 self.EXIV2_LINE_ISO_SPEED = 15 self.EXIV2_LINE_EXPOSURE_MODE = 16 self.EXIV2_LINE_METERING_MODE = 17 self.EXIV2_LINE_MACRO_MODE = 18 self.EXIV2_LINE_IMAGE_QUALITY = 19 self.EXIV2_LINE_EXIF_RESOLUTION = 20 self.EXIV2_LINE_WHITE_BALANCE = 21 self.EXIV2_LINE_THUMBNAIL = 22 self.EXIV2_LINE_COPYRIGHT = 23 self.EXIV2_LINE_EXIF_COMMENT = 24 # can use these extensions to do some filtering self.rawextensions = [ ".raf", #(Fuji) ".crw", ".cr2", # (Canon) ".tif", ".kdc", ".dcr", # (Kodak) ".mrw", # (Minolta) ".nef", # (Nikon) ".orf", # (Olympus) ".dng", # (Adobe) ".ptx", ".pef", # (Pentax) ".arw", ".srf", # (Sony) ".x3f", # (Sigma) ".erf", # (Epson) ".mef", ".mos", # (Mamiya) ".raw", #(Panasonic) ".r3d", #(Red) ] def initforscan(self, VerificationTest=False) : """ This function is called whenever a new scan or rescan is made. Use it to reset anything that needs to be reinitialized before a scan. This function is mandatory. The function is also called during verification of the class. Use the VerificationTest flag to block execution of anything you don't want executed before scanning. """ pass def getDateTime(self, imagedata): timedateline = imagedata[self.EXIV2_LINE_IMAGE_TIMESTAMP].split() #print "timedateline is: ", timedateline if len(timedateline) == 5 : # valid data date = timedateline[3] time = timedateline[4] return date.replace(':','') + '_' + time.replace(':','') else : return "" def fixnames(self, filename, VerificationTest=False) : """ This function converts name of file to a new name. Input: string representing the old filename or portion (either All, Prefix, or Extension) The name does not include the path to the file. Output: change indicator True if change to input string occurred, otherwise False string representing the new filename When the old filename string is passed into this routine, then depending on where this user command is placed in the custom list, the string could be in the middle of a transformation. e.g. if the original filename was ABCDEF.jpg, and the first command of the custom list inserted a counter in front of the name, and the second command was this user command, then the filename string that is passed in could be something like 0010-ABCDEF.jpg. This name of course no longer looks like the original name. If you needed to extract meta data from the file, then you would not be able to use the passed in string. Therefore the global variable 'configurator.filename' is provided which has the full path to the filename. You can then just open that name, extract the meta data, and then close the file. The function is also called during verification of the class by PFrank. Use the VerificationTest flag to block execution of anything you don't want executed before scanning. TO USE THIS COMMAND, YOU MUST INSTALL THE EXIV2 UTILITY BEFOREHAND. THEN IF NECESSARY MODIFY THE PATH TO EXIV2 BELOW """ # set up default return parameters in advance newname = filename change = False # just return if a verification test if VerificationTest : return change, filename # full path to original filename fullPathForFile = configurator.filename ######################################################################### # the following extension check is commented out for now. ######################################################################### # check if this is a regular image file; if not then return #basepath, filen = os.path.split(fullPathForFile) #name, extension = os.path.splitext(filen) #if extension not in self.rawextensions : # return change, filename ######################################################################### # set up path to the exiv2 tool here. This may be different # for different users! ######################################################################### exivpath = os.path.join("C:\\Program Files\exiv2", "exiv2.exe") exivpath = os.path.normpath(exivpath) #print "exivpath is: ", exivpath, fullPathForFile ######################################################################### # Insert code to modify the filename here ######################################################################### # get the exiv2 data. Note that quotes must be placed around the command and # separately around the original filename and then another pair of quotes needs to be # placed around the entire command-file ... AAARRRRGGG! proceed = True try : inhandle, outhandle, errhandle = os.popen3(' \""%s" "%s"\" '%(exivpath, fullPathForFile )) except : proceed = False if proceed : error = errhandle.read() if error != "" : if error.find("exception") != -1 or error.find("image") != -1 or error.find("Exif") != -1 : # don't care about exiv2 exceptions/errors since file might not be correct image type pass else : # some other problem - maybe file doesn't exist? print "Error '%s' detected for File: '%s'"%(error, fullPathForFile) else : # read output into a line array imagedata = outhandle.readlines() datetime = self.getDateTime(imagedata) if datetime != "" : # valid data newname = datetime + '_' + filename else : # invalid time/date line; therefore no change newname= filename try : inhandle.close() outhandle.close() errhandle.close() except : pass ######################################################################### # these statements are mandatory ######################################################################### change = False if filename != newname : change = True return change, newname ######################################################################### # end of the class definition ######################################################################### ################################################################### # Create the Renamer Objects in a list. The list is mandatory. # The name of the list must not change. # You can list as many names in the list as you like. PFrank will try to # load all of them. Each name in the list must correspond to the # name of a user command renaming class. A name can only appear # once in the list. # # User Command Objects are created with the following syntax: # ClassName() # i.e. the name of the class followed by () ################################################################### UserRenamerList = [ #UserRenamer1(), # object created for first user renaming class #UserRenamer2(), # object created for second user renaming class UserRawImageMetaData(), ] ###################################### # Code for testing the renamer objects ###################################### if __name__ == '__main__' : """ This is some test code to test the renaming objects. Test the code using the python IDLE tool to verify that things work. Then try importing the file to PFrank """ import os userpath = os.getcwd() userpath = os.path.normpath(userpath) print "\ ***NOTICE: Before first editing a user command file, you might need to \n\ associate an editor with .py files to prevent the unintentional execution \n\ of the user command file when trying to edit it.\n\ If the association is not made with an editor, the command window you\n\ are looking at now will shortly disappear!\n\ The user command file is called PFRankUser.py and is located at:\n\ %s\n\n\ After this association is made, you can delete this notice and the timed \n\ delay which follows.\n\ "%userpath import time time.sleep(1) print "Initializing Local Stubs" ################################################################### # Stubs for Local Testing. These are in addition to the # stubs imported earlier. # only perform this extra initialization for the create folder command # initialize current folder config option for testing Username3 #configurator.optionlist[SEARCHREP_COMMANDFILEDIRECTORY_ID] = os.getcwd() #print "current folder is: '%s'\n"%configurator.optionlist[SEARCHREP_COMMANDFILEDIRECTORY_ID] print "Testing User Defined Renaming Classes" # this is a table of sample filenames for testing # Assume that the files are in the current folder. nameTable = [ "C:\\Program Files\\exiv2\\test.jpg", "TestFile.txt", #"TestFile1.jpg", #"Test32File3.mp3", #"Test1.mp3", #"33T.ogg" ] # run all the initializers for renamer in UserRenamerList : renamer.initforscan() # run all name fixers for renamer in UserRenamerList : print "*************Testing Renamer: ", renamer.idstring for name in nameTable : fullpath = os.path.join(os.getcwd(), name) configurator.filename = os.path.normpath(fullpath) change, newname = renamer.fixnames(name) print "Oldname is: ", name print "Newname is: ", newname assert (change == (not name == newname)) print ""