""" Insert String Matched by Regular Expression 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. Apr 13, 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 : from SearchRep_initStubs import configurator from SearchRepBaseStubs import SearchRepBase # end of required imported modules class UserInsertMatchedStringBefore (SearchRepBase) : """ This is a sample renamer class. The SearchRepLower base class is mandatory. This class uses a regex search string to match a string inside a file. The matched string can then be inserted in the name in the desired location. """ 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 Matched Content before" # Regex used to look for some user defined string. # For this case, the string will be separated by whitespace and will # be matched in group 2. self.mySearchString = re.compile(r""" (?i)(\s+)(pfrank)(\s+) # look for the word 'pfrank' separated by whitespace """, re.VERBOSE) 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 by PFrank. Use the VerificationTest flag to block execution of anything you don't want executed before scanning. """ pass def insertString(self, foundstring, filename) : return (foundstring + '_' + filename) 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. """ # just return if a verification test if VerificationTest : return False, filename # full path to original filename fullPathForFile = configurator.filename newname = filename ######################################################################### # Open the file and search for the string specified by the regex ######################################################################### # assume the file is plain text and not unicode f = open(fullPathForFile, 'r') for line in f.readlines(): #print "line is: ", line groups = self.mySearchString.findall(line) #print "groups are: ", groups if groups != [] : if len(groups[0]) == 3 : # check if group 2 has a string if groups[0][1] != '' : # set the found string to the value in group 2 foundstring = groups[0][1] # modify filename by adding the found string as a prefix newname = self.insertString(foundstring, filename) break f.close() ######################################################################### # these statements are mandatory ######################################################################### change = False if filename != newname : change = True return change, newname # end of the class definition for Renamer5 class UserInsertMatchedStringAfter (UserInsertMatchedStringBefore) : """ Superclass of the matched content inserter. This variant inserts the string after the specified location. """ def __init__ (self) : # call base class initializer. This is mandatory UserInsertMatchedStringBefore.__init__(self) # name of plugin command self.idstring = "(User) - Insert Matched Content after" def insertString(self, foundstring, filename) : return (filename + '_' + foundstring) ################################################################### # 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 = [ UserInsertMatchedStringBefore(), UserInsertMatchedStringAfter(), ] ###################################### # 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 = [ " YY.MM.DD - Tour 235311.jpg", " YY.MM.DD - Tour 000204.jpg", " YY.MM.DD - Tour 120204.jpg", " YY.MM.DD - Tour 060204.jpg", " YY.MM.DD - Tour 990204.jpg", ] # 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 ""