Saturday, October 27, 2012

A few Python tips for Maya

Hi,
I thought some of these example tips I made may be helpful. There probably are lots of bugs in them but they show examples ranging from adding a label to an image (convert), to opening up a Maya file from the command line (standalone).

cheers,
Nate

#================================================================= images and convert

##@file image.py
#
#(Tested Maya 2008)
#
#@author Nathaniel Anozie
#
#@note Inpired By James Parks (arcsecond dot net) for learning about unix image calls in python
#
#@note Inpired By Nicklas Puetz (nicklaspuetz dot blogspot dot com) for learning file handling tips
#
#@defgroup image Image Editing tools
#@{
#ex: add a label to an image
##

import os
#import re



##add the label specified to a duplicate of the input image name and save it in same directory as input image
#
##
def addLabel( file = '/Users/noa/Desktop/temp/picture.png', camLabel = 'CAM_AS_0001', frameLabel = '00000'  ):
    
    #compute output labeled image name using source image and source directory
    filePath, fileName = os.path.split(file)
    filePrefix,ext = os.path.splitext(fileName)
    labeledImage = filePrefix+'Out'+ext  #adding a simple suffix to source image name to give output name
    labeledImagePath = filePath+'/'+labeledImage
    
    print 'Great this is the labeled image path %s \n' %labeledImagePath
    
    if os.path.isdir(filePath) & ( os.path.exists(labeledImagePath) == False ):
        print 'Great Found Directory >> %s and found no File at Output path >> %s \n' %(filePath,labeledImagePath)
    
        if os.path.isfile(file):
            #this does the adding of label and saving new image out
            os.system( 'convert '+file+' -background white -fill black \
            -font Courier -pointsize 24 label:'+camLabel+' -gravity center -append'+' '+labeledImagePath )    
        else:
            print 'Requires file exist >>%s \n' %file
    else:
        print 'Requires Directory >> %s and no File at Output path >> %s \n' %(filePath,labeledImagePath)

            
            
            
##makes a camera and frame label at specified path, defaults to fixed labels
#
#@bug limited error checking for overwriting existing image
##
def makeLabel( file = '/Users/noa/Desktop/temp/picture.png', camLabel = '/Users/noa/Desktop/temp/cam.png', frameLabel = '/Users/noa/Desktop/temp/frame.png'  ):
    
    camFilePath, camFileName = os.path.split(camLabel)
    frameFilePath, frameFileName = os.path.split(frameLabel)
    
    if os.path.isdir(camFilePath) & os.path.isdir(frameFilePath):
        print 'Great Found Directory %s %s' %(camFilePath,frameFilePath)
        
    #os.path.isfile(path)
    #os.path.isdir(path)
        if ( os.path.exists(camLabel) == False ) & ( os.path.exists(frameLabel) == False ) :
            print('Great Day Not overwriting Files\n')
            
            #camera label
            cameraPrefix = 'CAM'
            sceneLabel = 'AS'
            cameraNumber = '0001'
            cameraVersion = ''
            os.system( 'convert -background white -fill black \
            -font Courier -pointsize 24 label:'+cameraPrefix+'_'+sceneLabel+'_'+cameraNumber+cameraVersion+' '+camLabel )
            
            #frame label
            frameNumber = '00000'
            os.system( 'convert -background white -fill black \
            -font Courier -pointsize 24 label:'+frameNumber+' '+frameLabel )
        else:
            print 'Requires Files to Not Exist %s %s' %(camLabel,frameLabel)
        
    else:
        print 'Requires Directory Exist %s %s' %(camFilePath,frameFilePath)
  
        
##
#@}
##
#=================================================================


#================================================================= filter and os.walk for finding files
##@file getFile.py
#
#(Tested Maya 2008)
#
#@author Nathaniel Anozie
#
##

##given a directory print all the maya files, note it will look in all sub directories of that directory to
#
#@note inspired by Alex Martelli's example on recursive file searching (aleax dot it)
#
##
def getAllFileInDirectory(d = '/Users/noa/Desktop/temp', ext = '*.ma'):
    import os,fnmatch

    #hold all the file names
    result = []
    
    if os.path.isdir(d):
        print 'Great Found Directory >> %s\n' %d
        
        #files = os.listdir(d)
        for base, dirs, files in os.walk(d):
            
            #print good files only, files with proper extension
            mayaFiles = fnmatch.filter( files, ext )
            
            #add a good files to result
            result.extend(  os.path.join(base,f) for f in mayaFiles  )
            
    else:
        print 'Requires Directory >> %s' %d   
    
    return result
#=================================================================


#================================================================= opening a maya file from command line
#!/usr/bin/python


##print skinned geometry
#@note insired by Matt Estela examples on using getopt and option arguments (tokeru dot com)
##
def bindGeo():
    import maya.mel, maya.cmds
    
    #find skinned geometry
    suffix = 'geo'
    
    #find un_skinned geometry
    noSkinGeo = 'finalGeo'
    
    skinnedGeo = []
    
    try:
        maya.cmds.select('*_'+suffix)
    except TypeError:
        print 'Requires geometry with suffix>>%s' %suffix
    
    skinnedGeo = maya.cmds.ls(selection=True)
    
    for obj in skinnedGeo:
        skinCluster = maya.mel.eval('findRelatedSkinCluster'+' '+obj)        
        print 'Great found skinned geo and skinCluster >>%s >>%s' %(obj,skinCluster)   
        influences = []
        try:
            influences = maya.cmds.skinCluster(skinCluster,q=True,inf=True)
            print 'influences for >>%s and skinCluster >>%s' %(obj,skinCluster)
            for inf in influences:
                print inf
            print 'influences >>'
        except TypeError:
            print 'Requires skinCluster to query influences>>%s' %skinCluster
                      

def usage():
    print "usage: bindGeo [-f|--file]"
    print "-f,--file  find bound geometry in "
    
    
def main():
    import getopt,sys
  
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hf:", ["help","file="])
    except getopt.GetoptError, err:
        #print help info and exit
        print str(err)
        usage()
        sys.exit(2)
    
    file = '/Users/noa/Desktop/temp/sphere.ma'    
    
    for o, a in opts:
        if o in ("-h","--help"):
            usage()
            sys.exit()
        elif o in ("-f","--file"):
            file = a
            

    bindGeo()
        
    
if __name__ == '__main__':
    import maya.standalone
    maya.standalone.initialize(name="python")
    print 'current _name is: '+__name__
    main()
#================================================================= 

#================================================================= making a maya file from command line
#!/usr/bin/python


def makeSphere(f = '/Users/noa/Desktop/temp/sphere.ma'):
    
    import os,sys
    import maya.standalone, maya.cmds #$MAYA_LOCATION/bin/mayapy makeSphere.py 
    #needed instead of python makeSphere.py so can find maya modules
   
    
    #doing this so dont overwrite a directory or file etc
    filePath, fileName = os.path.split(f)
    
    #make sure have a maya file were writing to
    fileBaseName, fileExtension = os.path.splitext(fileName)
    
    if os.path.isdir(filePath) & (fileExtension == '.ma'):
        print 'Great Found Directory >> %s\n' %filePath
        
        if not os.path.isfile(f):
            print 'making sphere in maya\n'
            
            try:
                maya.standalone.initialize(name='python')
            except:
                sys.stderr.write("Failed Initialize Maya standalone application")
                raise
                
            print 'Great Were inside of Maya\n'
            
            #put inside of maya code here
            #
            
            #make a sphere
            maya.cmds.polySphere()
            
            #create a new maya file
            maya.cmds.file(rename=f)
            maya.cmds.file(save=True,type='mayaAscii')
            
            
        else:
            print '--skipping file already exists >> %s' %f
    else:
        print 'Requires Directory >> %s' %filePath
        print 'Requires .ma >> %s' %fileName

    
def usage():
    print "usage: makeSphere [-f|--file]"
    print "-f,--file  save sphere in "
    
    
def main():
    import getopt, sys
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hf:", ["help","file="])
    except getopt.GetoptError, err:
        #print help info and exit
        print str(err)
        usage()
        sys.exit(2)
    
    file = '/Users/noa/Desktop/temp/sphere.ma'    
    
    for o, a in opts:
        if o in ("-h","--help"):
            usage()
            sys.exit()
        elif o in ("-f","--file"):
            file = a
            
    makeSphere(file)
    
if __name__ == '__main__':
    print 'current _name is: '+__name__
    main()
#================================================================= 


#=================================================================parsing a string ideas
##@file parse.py
#
#@author Nathaniel Anozie
#
#@note inpspired by Matt Estela (tokeru dot com) for learning about ValueError exception with dictionaries
#
#@defgroup parse Parse A formatted string
#@{
#Ex: parsing a camera and frame name format etc
##


def parseCamera_unitTest():
    parseCamera()
    

##parse a form of name like cameraName_cameraAttribute_frameNumber_value and print parsed argument
#
##
def parseCamera( name = ['camera1_translateX_00000_1.0','camera1_translateX_00001_1.0',
    'camera1_translateY_00000_5.0','camera1_translateY_00001_10.0',
    'camera2_translateX_00000_1.0','camera2_translateX_00001_1.0',
    'camera2_translateY_00000_5.0','camera2_translateY_00001_10.0'] ):
        #print name[0]
       
  
        
        for arg in name:
            
            try:
                camera, attribute, frame, value = arg.split("_")
            
                print 'cam >> %s attribute >> %s frame >> %s value >> %s' %(camera,attribute,frame,value)
            except ValueError:
                print '--skipping cannot parse data %s\n' %arg
                
        
##
#@}
##
#=================================================================

#================================================================= open maya file in command line simple example 
#!/usr/bin/python

#@note Inspired by Justin Israel (justinfx dot com) for learning more about Maya standalone



##move camera in currently open file
#
##
def moveCam(filename='/Users/noa/Desktop/temp/sphere.ma', assetSuffix = 'cam', tx = 10.0):
    import maya.cmds
    #open the maya file here in the function
    #except if cannot open file
    try:
        maya.cmds.file(filename,o=True)
    except RuntimeError:
        print 'Require file exist >>%s' %filename
    cam = []
    
    try:
        maya.cmds.select('*_'+assetSuffix)
    except TypeError:
        print 'Requires geometry with assetSuffix>>%s' %assetSuffix
    
    cam = maya.cmds.ls(selection=True)
    
    for obj in cam:
        try:
            print 'Great Found Camera >>%s' %obj
            #move camera
            maya.cmds.select(obj,replace=True)
            maya.cmds.move(tx,0.0,0.0,obj,x=True,y=True,z=True,relative=True,worldSpace=True)
        except TypeError:
            print 'Requires camera>>%s' %obj
        #save file on each change
        maya.cmds.file(s=True,f=True)
    
        
        
        
if __name__ == '__main__':
    import maya.standalone
    maya.standalone.initialize(name="python")
    
    import sys
    print "Args:",sys.argv[1:]
    files = ['/Users/noa/Desktop/temp/sphere.ma','/Users/noa/Desktop/temp/sphere1.ma','/Users/noa/Desktop/temp/sphere3.ma']
    for f in files:
        moveCam(f)
       
#=================================================================