HomePreviousNext

bookmark Asset Library Python API:

The python API of MG-Asset Library. You could use these python function and classes to create, manage  and use the asset libraries in your own python scripts.

The main usages are to use it to batch adding asset records, or making MA files.

bookmark Prerequisite:

Your Maya has MGTools Pro3 or later version installed.

bookmark The Asset Library API python module:

The py file locates in your MGTools folder/invoke/MG_PyUtil/MG_AssetLibAPI.py.

With MGTools installed, you could just use these code to import the module:

import MG_PyUtil.MG_AssetLibAPI as assetAPI

There are also detailed description for each function or class methods, the manual below has nearly the same content with the comments in the source file.

The <type> in each annotation of a parameter  stands for the parameter type.

 

 

bookmark Quick Links:

The utility functions more

The Classes MGAssetProj more

The Classes MGAssetCategory more

The Classes MGAssetRecord more

Example Codes more

 

bookmark The utility functions:

def MGAssetLibUtil_isLibraryWindowOpen ( )

Description:  Test if MG-AssetLibrary tool is opened in Maya.

Return:  True if opened, False if not.

 

def MGAssetLibUtil_openProjectIfLibraryToolOpen ( projFilePath )

Description: If MG-AssetLibrary tool is loaded in Maya, then open the project file. This will reopen the project if it is already opened.

Parameter:  projFilePath: <str> represent a MG-AssetLibrary asset project file full path.

Return: None

 

def MGAssetLibUtil_openCategoryIfLibraryToolOpen ( projectName, categoryName )

Description: if MG-AssetLibrary tool is loaded in Maya, and the project is already opened, then this will read the category into the UI. This will also reopen the category if it is already opened.

Parameter:  projName: <str> A existed project name

categoryName: <str> A existed category name in the project projName.

Return: None

 

def MGAssetLibUtil_warning ( warnMessage )

Description: Helper function to issue a warning in Maya.

Parameter:  warnMessage: <str> The message content text.

Return: None

 

def MGAssetLibUtil_getLocalRoot ( )

Description: Get MG-AssetLibrary local root directory, ending with "/".

Return: str

 

def MGAssetLibUtil_getLocalProjectDir ( projectName )

Description:  Get MG-AssetLibrary local project directory via the projectName you've provided.

Parameters: projectName: <str> The project name.

Return: str

 

def MGAssetLibUtil_getLocalProjectFilePath ( projectName )

Description: Get MG-AssetLibrary local project file full path via the projectName you've provided. It is a full path to a .assetproj file.

Parameters: projectName: <str> The project name.

Return: str

 

def MGAssetLibUtil_getLocalCategoryFilePath ( projectName, categoryName )

Description: Get MG-AssetLibrary local category file full path via the projectName and categoryName you've provided. It is a file with a extension : .asset

Parameters: projectName: <str> The project name.

categoryName: <str> The category name.

Return: str

 

def MGAssetLibUtil_validName ( name )

Description: Validate the name with the Maya node naming rules:

The leading character should be '_' or English letter, while the other characters should be '_' or English letters or numeric letter.

The characters not meet the condition will be replaced with '_'.

Parameters: name: <str> The name to validate.

Return: str, which is the validated version of name.

 

def MGAssetLibUtil_compareTwoFileDate ( file1, file2 )

Description: Compare two files with their modification dates.

Parameters: file1: <str> A file path

file2: <str> A file path

Return:  int.

If both files does not exist, return 0;

if file1 exists but file2 doesn't, return 1, if file1 does not exists but file2 does, return -1;

if both exist:

If file1 is newer than file2, return 1;

if file1 is the same modification date with file2, return 0;

if file1 is older than file2, return -1.

 

def MGAssetLibUtil_searchFilesFromDirectory ( searchDir, patternStr, searchDepthLimit, currentSearchDepth )

Description: This is a doit function, invoked by the two functions below. It search files that matches the patternStr within the directory searchDir.

Parameters: searchDir: <str> represents a directory.

patternStr: <str> Note that patternStr should be '*.extension' like.  If not the function will add '*.' at the front of it.

searchDepthLimit: <int> The limit of the search directory depth.  Value 1 for not searching the sub-folders.

The value 0 or less than 0 indicates that the search is unlimited in depth.

currentSearchDepth: <int> Serves as a helper parameter indicate the current searching depth for stopping the recurrence purpose,

for the call you should always input 1 for this parameter.

Return:  list of str , return a empty list if no matched files found.

 

def MGAssetLibUtil_searchPreviewImagesFromDirectory ( searchDir, imageExtensions, searchDepthLimit )

Description: Search images that matched the any pattern in imageExtensions within the directory searchDir.

Parameters: searchDir: <str> An existed directory to search in.

imageExtensions: <list / str> Note that each item in imageExtensions should be '*.extension' like.

                     If not the function will add '*.' at the front of it.

searchDepthLimit: <int> The limit of the search directory depth.  Value 1 for not searching the sub-folders.

The value 0 or less than 0 indicates that the search is unlimited in depth.

Return:  list of str

 

def MGAssetLibUtil_searchMayaFileFromDirectory (searchDir, searchMA, searchMB,searchDepthLimit )

Description: Search maya scene file within the directory searchDir.

Parameters: searchDir: <str> An existed directory to search in.

searchMA: <bool> Indicate the maya ascii file should be searched.

searchMB: <bool> Indicate the maya binary file should be searched. Note that searchMA and searchMB should not be both False.

searchDepthLimit: <int> The limit of the search directory depth.  Value 1 for not searching the sub-folders.

The value 0 or less than 0 indicates that the search is unlimited in depth.

Return:  list of str

 

def MGAssetLibUtil_getBasename ( filepath )

Description: Get the basename of a file path or a file name.

Parameters: filepath: <str> A file full path.  Note that it is a dirname, this function will return empty string.

Return: str

 

def MGAssetLibUtil_makeMayaAsciiFile ( overrideIfExists, MAFile, referenceFiles, namespaceList=[], deferList=[] )

Description: Generate a maya ascii file based on the info you have input.

Parameters: overrideIfExists: <bool> Decide whether override an existed maya ascii file.

MAFile: <str> The full path of the target maya ascii file.

referenceFiles: <list of strings> The asset full path that will be referenced in the target maya ascii file.

namespaceList: <list of strings> If namespaceList doesn't provide items as many as referenceFiles does,

this function will use the validated version of the basename of referenceFiles item instead.

deferList: <list of int> If it doesn't provide items as many as referenceFiles does, 0 will be used.

Return: bool,  True if the function succeed else False.

 

bookmark The classes:

The object model is really simple. The API contains three level of data classes: MGAssetProj > MGAssetCategory > MGAssetRecord

MGAssetProj object contains multiple MGAssetCategory objects, while MGAssetCategory could have multiple MGAssetRecord objects.

 

bookmark The Classes MGAssetProj:

MGAssetProj.__init__ ( projectName='', projectAnnotation='', globalPath='', statePresets=[] )

Description: Init the MGAssetProj object.

When constructing the project object, if the projectName you passed in already exist in your local library root dir,

then it will skip all the other parameters you passed in , initialize the object from the existed asset project file.

Parameters: projectName: <str> A validated version of this parameter will be actually used.

If this parameter is an empty string, you should call initFromProjctFile() to make the instance valid.

projectAnnotation: <str> A project annotation string.

globalPath: <str> A path that specify the global root of the project.

statePresets: <list of str> A list of string, each string is of format: "statename stateColorFloatR stateColorFloatG stateColorFloatB"

eg. "approved 0.2 0.8 0.2"

 

MGAssetProj.initExistCategories ( )

Description: Read the project local directory, create MGAssetCategory object via the existed category files.

Return: int. Return the initialized category count.

 

MGAssetProj.initFromProjectFile ( projectFilePath )

Description: Init the MGAssetProj object with a existed project file (*.assetproj).

Parameters: projectFilePath: <str> A full path to a asset project file.

Return: bool. Return True if succeed else False.

 

MGAssetProj.isValid ( )

Description: Test if this MGAssetProj instance is valid.

Return: bool

 

MGAssetProj.doesProjectExist ( )

Description: Test if this project file already exists.

Return: bool

 

MGAssetProj.getName ( )

Description: Get the project name.

Return: str

 

MGAssetProj.getProjectDir ( )

Description: Get the project local directory path.

Return: str

 

MGAssetProj.getProjectFilePath ( )

Description: Get the project local directory file full path (*.assetproj).

Return: str

 

MGAssetProj.addStates ( newStatePresets )

Description: Add state presets to project.

Parameters: newStatePresets: <str / list of str>  It is a list of string or just a single string, each element / the string is of format: "statename stateColorFloatR stateColorFloatG stateColorFloatB"

          eg. "approved 0.2 0.8 0.2"

Return: bool

 

MGAssetProj.getStates ( )

Description: Get the project's state list.

Return: list

 

MGAssetProj.addCategory ( categoryName )

Description: Add a category called categoryName into the project.

Parameters:  categoryName: <str> The category name. Should not be an empty string.

Return: None / MGAssetCategory. Return the new created MGAssetCategory instance on success, or None if failed.

 

MGAssetProj.getCategoryObjects ( )

Description: Get all the MGAssetCategory objects in the project.

Return: list of MGAssetCategory. Return a list of MGAssetCategory on success, or an empty list if failed.

 

MGAssetProj.getCategoryNames ( )

Description: Get all the category names in the project.

Return: list of str. Return a list of category names on success, or an empty list if failed.

 

MGAssetProj.writeProjectToDisk ( )

Description: Write the project object to MG-AssetLibrary local root directory. The file will be '*.assetproj'.

It will override even if the old project exists.  Will open the project in MG-AssetLibrary UI if the UI is opened.

Will raise an exception if this project object is invalid.

Return: bool. Return Ture if succeed.

 

MGAssetProj.getCategoryObjectByName ( categoryName )

Description: Get the MGAssetCategory object that has the name: categoryName.

Parameters: categoryName: <str> The category name.

Return: MGAssetCategory / None.   Return MGAssetCategory instance if found, else return None.

 

MGAssetProj.writeCategoryToDisk ( categoryObject )

Description:  Write the category object to disk (*.asset). It will override even if the old category exists.

Will open the category in MG-AssetLibrary UI if the UI is there and the project is also opened.

Will raise an exception if this project object is invalid.

Parameters: categoryObject: <MGAssetCategory> Should be an valid MGAssetCategory instance.

Return: bool.  Return Ture if succeed.

 

MGAssetProj.writeAllCategoriesToDisk ( )

Description:  Write all the category objects to disk (*.asset). It will override even if the old categories exists.

Will open the category in MG-AssetLibrary UI if the UI is there and the project is also opened.

Will raise an exception if this project object is invalid.

Return: bool.  Return Ture if succeed.

 

MGAssetProj.openProjectInMGAssetLibrary ( )

Description:  Open this project in MG-AssetLibrary tool if the tool is opened.

Return: bool.

 

MGAssetProj.openCategoryInMGAssetLibrary ( categoryName )

Description: Open the category in MG-AssetLibrary tool if the tool is there and the project is also opened.

Parameters: categoryName: <MGAssetCategory / str> This parameter could be a MGAssetCategory instance or a category name string.

Return: bool

 

MGAssetProj.__str__ ( )

Description: The method used to print this instance.

Return: str.

 

MGAssetProj.getLastError ( )

Description: Get the last error string.

Return: str.  Return an empty string if no error happened.

 

bookmark The Classes MGAssetCategory:

MGAssetCategory.__init__ ( projectObject, categoryName = '' )

Description: Init a MGAssetCategory object.

Use MGAssetProj.addCategory() method to create an instance of MGAssetCategory.

Or you can call MGAssetCategory(projectObject) to create an invalid instance, and then call initFromCategoryFile(categoryFile) to initialize it.

Parameters: projectObject: <MGAssetProj> Should be an valid MGAssetProj instance.

categoryName: <str> The category name, will validate it and use the validated version.

If this parameter is an empty string, you should call initFromCategoryFile(categoryFile) to initialize it,

or else this instance will be invalid.

 

MGAssetCategory.initFromCategoryFile ( categoryFile )

Description: Init the MGAssetCategory object with an existed category file (*.asset). If the instance is successfully initialized, return True, else False.

Parameters: categoryFile: <str> Should be an existed '*.asset' file full path.

Return: bool

 

MGAssetCategory.getName ( )

Description: Get the category name.

Return: str

 

MGAssetCategory.isValid ( )

Description: Test if this MGAssetCategory instance is valid.

Return: bool

 

MGAssetCategory.getCategoryFilePath ( )

Description: Get the category file full path. (path to a '*.asset' file)

Return: str.

 

MGAssetCategory.doesCategoryFileExist ( )

Description: Test the category file actually exists.

Return: bool

 

MGAssetCategory.clearAssetRecords ( )

Description: Clear all asset records in this category.

Return: bool. False if the category instance is invalid, True else.

 

MGAssetCategory.doesAssetRecordExist ( mayaFilePath )

Description: Test if the record already exist in the category via the asset path.

Parameters:  mayaFilePath: <str> A maya scene file full path.

Return: bool.

 

MGAssetCategory.addAssetRecords ( mayaFiles,namespaces=[],states=[],previewImages=[],notes=[], sizeDatas = [], dateDatas = [], versionDatas = [] )

Description: Create a MGAssetRecord instance and add it to the category if not existed.

If Failed, will return a empty list, else a list of MGAssetRecord instances.

Parameters:  mayaFiles: <str / list of str> The Maya scene full paths.

namespaces: <str / list of str> The namespaces. Will use the validated version of the basename of mayaFiles if it is vacant.      

states: <str / list of str> Each item should just be state name, don't append the color info.  

previewImages: <str / list of str> Each item should be paths of image files, connected with character ';'

notes: <str / list of str> Each item is a annotation for the asset item.

sizeDatas: <str / list of str> Each item is a size string for the asset item, in format of such as 1,560KB.

If vacant will test and use the actually file size string.  

dateDatas: <str / list of str> Each item is a modification date string for the asset item,  in format 'DD/MM/YYYY hh:mm:ss'. eg. 4/10/2014 21:55:4

If vacant then will test and use the actually file modification date string.

versionDatas: <str / list of str> Each item is a maya version string of the asset item,

If vacant then will test and use the actually file version string.

Return: list of MGAssetRecord objects.

 

MGAssetCategory.deleteAssetRecords ( mayaFiles )

Description: Delete the records already exist in the category via the asset path list.

Parameters:  mayaFiles: <str / list of str> Maya scene full paths.

Return: int. Return the actually deleted record count.

 

MGAssetCategory.getDataString ( )

Description: Get the data string of this category. It is the content when the category is written to disk.

It is also the content get printed when you call print(categoryObject)

Return: str

 

MGAssetCategory.writeToDisk ( )

Description: Write the category into disk with a file ends with *.asset.

Return: bool, True if success.

 

MGAssetCategory.__str__ ( )

Description: The method used to print this instance.

Return: str.

 

bookmark The Classes MGAssetRecord:

MGAssetRecord.__init__ ( categoryObject, assetPath, assetName='', assetStateStr='', previewImageStr='', noteStr='', sizeStr='', dateStr='', versionStr = '' )

Description: Init a MGAssetRecord object.

Use MGAssetCategoryObj.addAssetRecords() method to create a instance of MGAssetRecord.

Parameters: categoryObject: <MGAssetCategory> It should be a valid MGAssetCategory instance.

assetPath: <str> It should be a full path to a maya scene file. This parameter should not be an empty string and should endswith either '*.ma' or '*.mb'

assetName: <str> The namespace of the maya file.  Will use validated version of the basename of assetPath if this parameter is an empty string.

assetStateStr: <str> The state name. No state color string included please, only the state name.

previewImageStr: <str> The preview images.  A string that could contain multiple image file paths, separate the paths with ';' please.

noteStr: <str> A annotation string for this asset record.

sizeStr: <str> A string represent the file size, in KB unit. eg. 1,150KB.

If this parameter or the dateStr parameter is an empty string, will test and fill in the actually size of the assetPath.

dateStr: <str> A string represent the file modification date, in format 'DD/MM/YYYY hh:mm:ss'. eg. 4/10/2014 21:55:4

If this parameter or the sizeStr parameter is an empty string, will test and fill in the actually date of the assetPath.

versionStr: <str> The version string of the maya scene file. eg.2015

If this parameter is an empty string, will test and fill in the actually version of the assetPath.

 

MGAssetRecord.isValid ( )

Description: Test if this MGAssetRecord instance is valid.

Return: bool

 

MGAssetRecord.getAssetPath ( )

Description: Get the maya scene file full path from this instance.

Return: str. Will return an empty string if this instance is invalid.

 

MGAssetRecord.getDataString ( )

Description: Get the data string of this instance. The result will also be used in print(instance) call.

Return: str. Will return an empty string if this instance is invalid.

 

MGAssetRecord.__str__ ( )

Description: The method used to print this instance.

Return: str. Will return an empty string if this instance is invalid.

 

bookmark Example Code:

>>

>>

 

 

>>

>>

>>

>>

>>

>>

>>

>>

>>

>>

 

 

 

 

import MG_PyUtil.MG_AssetLibAPI as assetAPI

projectObj = assetAPI.MGAssetProj ( "PyAPI", "Test project for MGAssetLibrary Python API.",

                                                  'D:/temp/Miguel/test/Lib_PyAPI',

                                                    [ 'Pending 1 0 0', 'Working 0 0 1', 'Approved 0 1 0' ] )                            

projectObj.writeProjectToDisk() #write it to disk

print projectObj

charCate = projectObj.addCategory ( 'character' )

print 'The category object\'s validity:', charCate.isValid ()

print charCate   #now it is empty

assetObjs = charCate.addAssetRecords ( 'K:/Data/Char/ciggarette.ma' )

print 'The asset object\'s validity:', assetObjs[0].isValid()

print charCate   #now the cateogry is not empty

projectObj.getCategoryObjects()

charCate.writeToDisk() #write it to disk


HomePreviousNext