Ejemplo n.º 1
0
def netPaste():
    # Define temp directory on the network.
    filePath = '/data/share/nuke/netCopy/'
    fileList = nuke.getFileNameList(filePath)

    # Opens dialog box with pulldown choice of username.
    result = nuke.choice("NetPaste", "Pick Username", fileList)

    # If nothing is selected, do nothing.
    if result is None:
        return

    # Otherwise, select username and move to next step
    choice = fileList[result]

    # Define user file directory
    filePath2 = (os.path.join(filePath, choice))
    fileList2 = nuke.getFileNameList(filePath2)

    # Opens dialog box with pulldown choice.
    result2 = nuke.choice("NetPaste", "Pick NetCopy", fileList2)

    # If the Cancel button is pressed, do nothing.
    if result is None or result2 is None:
        return

    # Otherwise, import script of selected username.
    choice2 = fileList2[result2]
    nuke.nodePaste(os.path.join(filePath2, choice2))

    # Run cleanup
    cleanup(60, '/data/share/nuke/netCopy/')
Ejemplo n.º 2
0
def getMissingFrames(node):
    parent = os.path.dirname(node['file'].value())
    if len(nuke.getFileNameList(parent)) > 1:
        nuke.selectAll()
        nuke.invertSelection()
        node.setSelected(1)
        nuke.zoomToFitSelected()
        nuke.message('missing frames: ' +
                     ",".join(nuke.getFileNameList(parent)))
Ejemplo n.º 3
0
def findRendersFromDirectory(dir):
    seqs = []
    exists = []
    print 'looking for sibling renders'
    for path, dirs, files in os.walk(dir):
        fList = nuke.getFileNameList(path, True)
        for item in fList:
            item = item.replace('exrsl', '')
            if 'exr' in item:
                foundPath = path + '/' + item
                fileOnly = foundPath.split(' ')[0]
                if not fileOnly in exists:
                    print foundPath
                    exists.append(fileOnly)
                    seqs.append(foundPath.replace('\\', '/'))

    if len(seqs) < 2:
        print 'looking for cousin renders'
        dir = os.path.dirname(dir)
        seqs = []
        for path, dirs, files in os.walk(dir):
            fList = nuke.getFileNameList(path, True)
            for item in fList:
                item = item.replace('exrsl', '')
                if 'exr' in item:
                    foundPath = path + '/' + item
                    fileOnly = foundPath.split(' ')[0]
                    if not fileOnly in exists:
                        print foundPath
                        exists.append(fileOnly)
                        seqs.append(foundPath.replace('\\', '/'))

    commonPath = os.path.commonprefix(seqs)
    print commonPath
    #get commonName
    names = []
    for each in seqs:
        names.append(each.split(' ')[0].split('/')[-1].split('.')[0])

    commonName = os.path.commonprefix(names)
    print commonName
    uniquePaths = []
    uniqueNames = []
    for seq in seqs:
        uniquePath = seq.replace(commonPath, "").split(" ")[0]
        #diffuse/_Hammer_Beauty_v043.diffuse.0157.exr
        frameNum = re.findall(r".[0-9]{4}.", uniquePath)
        #commented out to avoid placing #### at shot number
        #if len(frameNum)>0:
        #    uniquePath=uniquePath.replace(frameNum[-1],".####.")
        if not uniquePath in uniquePaths:
            uniquePaths.append(uniquePath)
            uniqueNames.append("".join(
                uniquePath.split("/")[-1].replace(
                    commonName, "").split(".")[:-2]))  #passName.####.exr

    return uniquePaths, uniqueNames, commonPath, commonName
Ejemplo n.º 4
0
def getAOVs(dir_renderVersion):
    '''get renderLayer, then passes
	@path: Render root path (ie. '/TIO_orbit_1k_v001'), str
	return: {<renderLayer>: [<renderPasses>]}
	'''
    ls_aov = {}  # {RenderLayer: [RenderPasses, RenderPasses]}
    for l in nuke.getFileNameList(dir_renderVersion):
        thisLayer = [
            p for p in nuke.getFileNameList(joinPath(dir_renderVersion, l))
        ]
        ls_aov[l] = thisLayer

    return ls_aov
Ejemplo n.º 5
0
        def files(self):
            """Return files in input dir. """
            ret = []

            if not os.path.isdir(self.input_dir):
                return ret
            dirs = list(x[0] for x in os.walk(self.input_dir))
            for dir_ in dirs:
                # Get footage in subdir
                if not re.match(self.dir_pat,
                                os.path.basename(dir_.rstrip('\\/'))):
                    continue

                footages = [
                    i for i in nuke.getFileNameList(dir_, True)
                    if not i.endswith(('副本', '.lock'))
                ]
                if footages:
                    for f in footages:
                        if os.path.isdir(os.path.join(dir_, f)):
                            continue
                        if re.match(self.footage_pat, f, flags=re.I):
                            ret.append(f)
            ret.sort()
            self._files = ret
            return ret
Ejemplo n.º 6
0
    def loadPlates(self,sel_assetname,sel_version,sel_checker,assettype='Plate'):
        self.assetconfig = self.ED_assetconfig[assettype]
        self.assetpath = self.assetconfig['path']
        self.nodeclass = self.assetconfig['class']

        if sel_checker == 'F'or sel_checker == 'P':
            if sel_checker == 'F':
                sel_checker = 'linear'
            elif sel_checker == 'P':
                sel_checker = 'proxy'

            loadfolder = sel_checker + '_' + sel_version
            loadpath = self.assetpath + '/' + sel_assetname + '/' + 'versions' + '/' + loadfolder + '/' + 'full' + '/'

        elif sel_checker == 'S':
            self.assetpath = self.folder + '/' + 'data' + '/' + 'scans'
            sel_checker = sel_assetname
            loadfolder = sel_checker + '_' + sel_version
            loadpath = self.assetpath + '/' + 'versions' + '/' + loadfolder + '/' 

        for seq in nuke.getFileNameList(loadpath ):
            if seq != 'metadata':
                readNode = nuke.createNode(self.nodeclass)
                readNode.knob('file').fromUserText(loadpath + seq)
            else:
                pass

        self.loadLensDist(sel_assetname, sel_version, loadfolder)
Ejemplo n.º 7
0
    def import_resource(self, dir_path):
        """Import footages from config dictionary."""

        # Get all subdir
        dirs = list(x[0] for x in os.walk(dir_path))
        self.task_step('导入素材')
        for dir_ in dirs:
            # Get footage in subdir
            LOGGER.info('文件夹 %s:', dir_)
            if not re.match(BATCH_CONFIG['dir_pat'],
                            os.path.basename(dir_.rstrip('\\/'))):
                LOGGER.info('\t不匹配文件夹正则, 跳过')
                continue

            files = nuke.getFileNameList(utf8(dir_))
            footages = [
                u(i) for i in files if not u(i).endswith(('副本', '.lock'))
            ] if files else []
            if footages:
                for f in footages:
                    if os.path.isdir(e(os.path.join(dir_, f))):
                        LOGGER.info('\t文件夹: %s', f)
                        continue
                    LOGGER.info('\t素材: %s', f)
                    if re.match(CONFIG['footage_pat'], f, flags=re.I):
                        n = nuke.createNode(
                            'Read', utf8('file {{{}/{}}}'.format(dir_, f)))
                        n['on_error'].setValue(utf8('nearest frame'))
                    else:
                        LOGGER.info('\t\t不匹配素材正则, 跳过')
        LOGGER.info('{:-^30s}'.format('结束 导入素材'))

        if not nuke.allNodes('Read'):
            raise FootageError(dir_path)
Ejemplo n.º 8
0
def updateTemplate():
    thisNode = nuke.thisNode()
    # nuke.root().begin()
    if nuke.selectedNodes():
        for sel_node in nuke.selectedNodes():
            if sel_node.Class() == 'Read':
                # oldpass = sel_node['file'].getValue().split('_')[-2]
                nuke.root().end()
                new_path = thisNode['new_path'].getValue()
                pass_list = nuke.getFileNameList(new_path)
                thisknob = nuke.thisKnob().name()

                if thisknob == 'custom':
                    pass_name = thisNode.knob('pass_name').getValue()
                else:
                    pass_name = thisknob
                our_pass = [s for s in pass_list if pass_name in s]

                if our_pass == []:
                    nuke.message('Pass not found !')
                else:
                    sel_node['file'].fromUserText(new_path + str(our_pass[0]))

            elif sel_node:
                if sel_node.name() == thisNode.name():
                    nuke.message('Don\'t select this node !')
            else:
                nuke.message("Select a node first.")
Ejemplo n.º 9
0
def makeAOVPaths(aov_type):
    pass_list = nuke.getFileNameList(_render_dir)
    arnold_lighting_aovs = [
        'diffuse_direct', 'diffuse_indirect', 'specular_direct',
        'specular_indirect', 'emission', 'transmission', 'sss', 'coat']
    arnold_utility_aovs = ['N', 'P', 'Z', 'shadow_matte', 'shadow', 'motionVector']
    arnold_crypto_aovs = ['crypto_asset', 'crypto_material', 'crypto_object']
    arnold_lightgroups_aovs = ['emission', 'transmission', 'RGBA_']
    aov_groups = {
        'lighting': arnold_lighting_aovs,
        'lightgroups': arnold_lightgroups_aovs,
        'utility': arnold_utility_aovs,
        'crypto': arnold_crypto_aovs
    }
    aov_paths = []

    if aov_type == 'beauty':
        for p in pass_list:
            if 'beauty' in p:
                aov_paths = [p]
                break
        return aov_paths
    # search for aov name in sequence path and add it to path list
    if aov_type in aov_groups.keys():
        for aov in aov_groups[aov_type]:
            aov_paths.extend([p for p in pass_list if aov in p])
        return aov_paths
    else:
        return None
Ejemplo n.º 10
0
def pathHandler(dropped_data, recursive=True):
    if os.path.isdir(dropped_data):
        for each in nuke.getFileNameList(dropped_data, False, False, bool(recursive), False):
            pathHandler(os.path.join(dropped_data, each))
        return True
    else:
        return fileHandler(dropped_data)
Ejemplo n.º 11
0
def pathHandler(dropped_data, recursive=True):
    if os.path.isdir(dropped_data):
        for each in nuke.getFileNameList(dropped_data, False, False, bool(recursive), False):
            pathHandler(os.path.join(dropped_data, each))
        return True
    else:
        return fileHandler(dropped_data)
Ejemplo n.º 12
0
def readFromWrite():
    nodes = nuke.selectedNodes()
    for node in nodes:
        assert node.Class() == 'Write'
        filename = nuke.filename(node)

        while True:
            dir = os.path.dirname(filename)
            print("Looking for:", filename)

            try:
                fileset = nuke.getFileNameList(dir)[0]
                print("Found fileset on disk: ", fileset)
                break
            except:
                print("Version not found, searching for previous takes.")
                prefix, num = re.search(r'(v)(\d+)', filename,
                                        re.IGNORECASE).groups()
                new_ver = str(int(num) - 1).zfill(len(num))
                assert int(new_ver) > 0, "NO VERSIONS FOUND"
                filename = re.sub(r'v(\d+)', prefix + new_ver, filename)

        fileset = os.path.join(dir, fileset)
        read = nuke.createNode('Read')
        read['file'].fromUserText(fileset)
        read.setXYpos(node.xpos(), node.ypos() + 120)
Ejemplo n.º 13
0
def findRendersFromDirectory(dir):
    seqs = []
    for path, dirs, files in os.walk(dir):
        fList = nuke.getFileNameList(path, True)
        for item in fList:
            item = item.replace('exrsl', '')
            if 'exr' in item:
                foundPath = path + '/' + item
                seqs.append(foundPath.replace('\\', '/'))

    if len(seqs) < 2:
        if nuke.ask(
                'No other passes found in selected Read directory, search in parent directory instead?'
        ):
            dir = os.path.dirname(dir)
            seqs = []
            for path, dirs, files in os.walk(dir):
                fList = nuke.getFileNameList(path, True)
                for item in fList:
                    item = item.replace('exrsl', '')
                    if 'exr' in item:
                        foundPath = path + '/' + item
                        seqs.append(foundPath.replace('\\', '/'))

    commonPath = os.path.commonprefix(seqs)
    print commonPath
    #get commonName
    names = []
    for each in seqs:
        names.append(each.split(' ')[0].split('/')[-1].split('.')[0])

    commonName = os.path.commonprefix(names)
    print commonName
    uniquePaths = []
    uniqueNames = []
    for seq in seqs:
        uniquePath = seq.replace(commonPath, "").split(" ")[0]
        if not uniquePath in uniquePaths:
            uniquePaths.append(uniquePath)
            uniqueNames.append("".join(
                uniquePath.split("/")[-1].replace(
                    commonName, "").split(".")[:-2]))  #passName.####.exr

    return uniquePaths, uniqueNames, commonPath, commonName
Ejemplo n.º 14
0
def readFromWrite():
    read_list = []
    sel_list = nuke.selectedNodes()
    for sel in sel_list:
        if sel.Class() in ['Write', 'Read']:
            filepath = sel['file'].evaluate()
            filenamebase = filepath.split('/')[-1].split('.')[0]
            ext = filepath.split('.')[-1]
            dirpath = op.dirname(filepath)
            print nuke.getFileNameList(dirpath)
            for elt in nuke.getFileNameList(dirpath):
                if filenamebase in elt and elt.split('.')[-1].split(
                        ' ')[0] == ext:
                    read = nuke.createNode('Read')
                    read['file'].fromUserText(dirpath + '/' + elt)
                    read.setXYpos(sel.xpos() + 50, sel.ypos() + 20)
                    read_list.append(read)
    for read in read_list:
        read.setSelected(True)
Ejemplo n.º 15
0
def get_filenames(url):
    ret = []
    if not os.path.isdir(e(url)):
        return ret
    for dirpath, _, _ in os.walk(e(url)):
        dirpath = u(dirpath.replace('\\', '/'))
        filenames = nuke.getFileNameList(e(dirpath, 'UTF-8'))
        filenames = ['{}/{}'.format(dirpath, u(i)) for i in filenames]
        ret.extend(filenames)
    return ret
Ejemplo n.º 16
0
def findExrsFromDirectory(dir,alreadyExisting):
    seqs=[]
    for path, dirs, files in os.walk(dir):
		if not path in alreadyExisting:
			fList= nuke.getFileNameList(path,True)
			for item in fList:
				item=item.replace('exrsl','')
				if 'exr' in item and "####" in item and 'beauty' in item:
					dirModTime=os.path.getmtime(path)
					foundPath=path+'/'+item+':'+str(dirModTime)
					seqs.append(foundPath.replace('\\','/'))
    return seqs
Ejemplo n.º 17
0
def getLastFrame(filePath):
    dirPath = filePath.rsplit("\\", 1)[0]
    array = nuke.getFileNameList(dirPath + "\\")
    for i in array:
        if ".tmp" in i:
            array.remove(i)
        elif ".mov" in i:
            array.remove(i)
        else:
            pass
    lastFrame = array[0].split("-")[-1]

    return int(lastFrame)
Ejemplo n.º 18
0
def run(node):
  clipboard = QtGui.QApplication.clipboard()


  filename = node['file'].evaluate()

  filesplit =  filename.rsplit('.',-2)
  filesplit[1] = '%0'+str(len(filesplit[1]))+'d'
  filep = '.'.join(filesplit) 
  filenameFrame =  nuke.getFileNameList(os.path.dirname(filep))[0].rsplit(' ',-1)[1]

  clipboard.setText(( filep+" "+filenameFrame))
  nuke.nodePaste("%clipboard%")
Ejemplo n.º 19
0
def scan(p):
    imageFormats = ["jpeg", "jpg", "tiff", "exr", "dpx", "png", "mov"]
    sequences = []
    stillImages = []

    if os.path.isdir(p):
        # find file sequences
        if nuke.getFileNameList(p):
            seqs = nuke.getFileNameList(p)
            # filter out directories
            seqs = [
                os.path.join(p, seq) for seq in seqs
                if not os.path.isdir(os.path.join(p, seq))
            ]
            if seqs:
                # get still images
                stim = [
                    seq for seq in seqs
                    if os.path.splitext(seq)[-1][1:] in imageFormats
                ]
                if stim:
                    stillImages.extend(stim)

                # filter out non sequences
                seqs = [
                    seq for seq in seqs if (" " in seq and os.path.splitext(
                        seq.split(" ")[0])[-1][1:] in imageFormats)
                ]
                if seqs:
                    sequences.extend(seqs)

    for i in os.listdir(p):
        np = p + i + '/'
        if not os.path.isdir(np):
            continue
        newScan = scan(np)
        sequences.extend(newScan[0])
        stillImages.extend(newScan[1])
    return sequences, stillImages
Ejemplo n.º 20
0
    def _create_channel_read_node(self, default_path, channel, x, y,
                                  sg_publish_data):

        import nuke

        path = default_path.replace("primary", channel)

        if channel == "DeepID":
            temp = os.path.dirname(path)
            deep_path = nuke.getFileNameList(temp)[0]
            deep_path = os.path.join(temp, deep_path)

            DeepRead = nuke.createNode("DeepRead")
            DeepRead.knob('file').fromUserText(deep_path)
            DeepRead['xpos'].setValue(x)
            DeepRead['ypos'].setValue(y + 100)
            nuke.Layer('other', ['id'])
            deep_exp = nuke.nodes.DeepExpression()
            deep_exp['xpos'].setValue(x)
            deep_exp['ypos'].setValue(y + 150)
            deep_exp.setInput(0, DeepRead)
            deep_exp['chans0'].setValue('other')
            deep_exp['chans1'].setValue('none')
            deep_exp['other.id'].setValue('exponent(id)')

            DRC = nuke.nodes.DeepRecolor()
            DRC['xpos'].setValue(x)
            DRC['ypos'].setValue(y + 200)
            DRC.setInput(0, deep_exp)
            constant = nuke.nodes.Constant()
            constant['xpos'].setValue(DRC.xpos() + 200)
            constant['ypos'].setValue(DRC.ypos() - 23)
            DRC.setInput(1, constant)
            DP = nuke.nodes.DeepPicker()
            DP['xpos'].setValue(x)
            DP['ypos'].setValue(y + 250)
            DP.setInput(0, DRC)

        else:

            read_node = nuke.createNode("Read")
            read_node["file"].fromUserText(path)
            seq_range = self._find_sequence_range(path)
            read_node['xpos'].setValue(x)
            read_node['ypos'].setValue(y + 100)
            if self._get_colorspace(sg_publish_data) == "ACES2065-1":
                read_node['colorspace'].setValue("ACES - ACEScg")

            if seq_range:
                read_node["first"].setValue(seq_range[0])
                read_node["last"].setValue(seq_range[1])
Ejemplo n.º 21
0
def PathHandler( dropdata ):
	value = dropdata
	if os.path.isdir(value):
		recurse = True

		validList = nuke.getFileNameList(value, False, bool(recurse), False)
		if validList:
			for each in validList:
				data = os.path.join(str(value), str(each))
				try:
					PathHandler(data)
				except Exception, e:
					log_('Error: %s' % e)
					pass
Ejemplo n.º 22
0
 def add_source(self):
     source = self.panel.sourceKnob.value()
     source = '{} {}'.format(
         source,
         nuke.getFileNameList(os.path.dirname(source))[0].split(' ')[1])
     output_format = self.panel.formatKnob.value()
     dest = self.panel.outputKnob.value()
     if not all([source, output_format, dest]):
         return
     data = (source, output_format, dest)
     if data not in self.file_settings:
         self.file_settings.append(data)
     self.panel.sourceKnob.setValue('')
     self.panel.outputKnob.setValue('')
Ejemplo n.º 23
0
def createReadNode(folderPath, nodeName):
    """
    Method to create Read nodes for every render pass
    :param folderPath: location to folder where the sequence of images are stored
    :param nodeName: name of the node
    :return: NONE
    """
    try:
        for seq in nuke.getFileNameList(folderPath):
            readNode = nuke.createNode('Read')
            readNode.knob('name').setValue(nodeName)
        readNode.knob('file').fromUserText(folderPath + '\\' + seq)
    except:
        print 'Error concatenating string ' + sys.exc_info()[0]
Ejemplo n.º 24
0
    def loadEditRef(self,sel_assetname,sel_version,sel_checker,assettype='Edit_ref'):
        self.assetconfig = self.ED_assetconfig[assettype]
        self.assetpath = self.assetconfig['path']
        self.nodeclass = self.assetconfig['class']

        sel_checker = 'edit_reference'
        loadfolder = sel_checker + '_' + sel_version
        loadpath = self.assetpath + '/' + loadfolder + '/'
        #print loadpath

        for seq in nuke.getFileNameList(loadpath ):

            readNode = nuke.createNode(self.nodeclass)
            readNode.knob('file').fromUserText(loadpath + seq)    
Ejemplo n.º 25
0
def readFromWrite():
    '''create read from write'''
    for n in nuke.selectedNodes('Write'):
        path = os.path.dirname(n['file'].value())
        exrs = nuke.getFileNameList(path)[
            0]  # ['albedo_1k_v001.####.exr 1-96']
        frames, range = exrs.split(' ')
        first, last = range.split('-')
        first = int(first)
        last = int(last)
        nuke.nodes.Read(file=os.path.join(path, frames),
                        name=os.path.basename(path),
                        first=first,
                        last=last,
                        label=os.path.basename(path))
Ejemplo n.º 26
0
def jopsPathHandler(dropdata):
    if os.path.isdir(dropdata):

        recurse = False

        try:
            recurse = nuke.toNode('preferences')["j_ops_drop_recurse"].getValue()
        except (SyntaxError, NameError):
            pass
        
        for each in nuke.getFileNameList(dropdata, False, False, bool(recurse), False):
            jopsPathHandler(os.path.join(dropdata,each))
        return True
    else:
        return jopsFileHandler(dropdata)
Ejemplo n.º 27
0
def search_run(path, *args):
    print path
    first_layer = nuke.getFileNameList(path)
    node_list = []
    print "test info 1", first_layer
    for first_ff in first_layer:
        first_path = os.path.join(path, first_ff)
        if os.path.isdir(first_path):
            print("FOLDER!!!!!!!!!!!!!!!!!!!!!!")
            search_run(first_path)
        else:
            pathfile = first_path.replace("\\", "/")
            readnode = nuke.createNode("Read")
            readnode['file'].fromUserText(pathfile)
            node_list.append((readnode))
Ejemplo n.º 28
0
    def slot_source_knob(self):
        self.message.setValue('')
        source = self.file_knob.value()
        for value in self.sources.values():
            if source == value.split(' ')[0]:
                self.message.setValue('source already been added')
                return

        source_name = os.path.basename(source).split('.')[0]
        for f in nuke.getFileNameList(os.path.dirname(source)):
            if source_name in f:
                source_path = '{} {}'.format(source, f.split(' ')[1])
                break

        self.sources[source_name] = source_path
        self.source_list.setValue(self.source_list.value() + \
            '#{} {}\n'.format(self.count, source_name))
Ejemplo n.º 29
0
def updateFrameRange():

    for readNodes in nuke.selectedNodes():

        name = readNodes.knob('file').getValue().split('/')[-1].split('%')[0]
        fileType = readNodes.knob('file').getValue().split('/')[-1].split('.')[-1]
        path = '/'.join(readNodes.knob('file').getValue().split('/')[:-1])+'/'
        fRange = ''

        for frameNumbers in nuke.getFileNameList(path):
            if name in frameNumbers:
                if fileType in frameNumbers:
                    fRange = frameNumbers.split(' ')[-1]
        readNodes.knob('first').setValue(int(fRange.split('-')[0]))
        readNodes.knob('last').setValue(int(fRange.split('-')[1]))
        readNodes.knob('origfirst').setValue(int(fRange.split('-')[0]))
        readNodes.knob('origlast').setValue(int(fRange.split('-')[1]))
Ejemplo n.º 30
0
def createRead(path):
    '''create read from path
    @path: full path for AOV, str
    return: aov read node, obj
    '''

    exrs = nuke.getFileNameList(path)[0]  # ['albedo.####.exr 1-96']
    frames, range = exrs.split(' ')
    first, last = range.split('-')
    first = int(first)
    last = int(last)
    aov = nuke.nodes.Read(file=os.path.join(path, frames).replace('\\', '/'),
                          name=os.path.basename(path),
                          first=first,
                          last=last,
                          label=os.path.basename(path))

    return aov
def main():
    nSel = nuke.selectedNodes()

    frmRate = str(nuke.root().fps())

    ffmpegLocation = os.path.dirname(os.path.dirname(
        os.path.dirname(__file__))) + '/mlShotManager/ffmpeg.exe'
    #print ffmpegLocation

    #create dailies directory
    if nSel:
        date = str(datetime.date.today()).split("-")
        dateFormatted = date[0] + '-' + date[1] + '-' + date[2]

        path = nuke.root().name()
        user = '******'
        dailiesDir = "/".join(
            path.split("/")[0:3]) + "/dailies/" + dateFormatted + "/comp/"

        try:
            os.makedirs(dailiesDir)
        except WindowsError:
            pass

    #send to ffmpeg
    for n in nSel:

        if 'file' in n.knobs():
            path = n['file'].value()
            parentDir = "/".join(path.split("/")[:-1])
            range = nuke.getFileNameList(parentDir)[0].split(" ")[-1]
            first, last = range.split("-")
            startFrame = first.zfill(4)
            output = dailiesDir + path.split("/")[-1].split(".")[0] + ".mov"
            nuke.message('writing ' + output)
            #cmd= [ffmpegLocation +' -f image2 -start_number '+startFrame+' -i '+path+' -c:v libx264 -g 1 -tune stillimage -crf 18 -bf 0 -vf fps='+frmRate+' -pix_fmt yuv420p -s 960x540 '+output]
            cmd = [
                ffmpegLocation + ' -f image2 -start_number ' + startFrame +
                ' -r ' + frmRate + ' -i ' + path +
                ' -c:v libx264 -g 1 -tune stillimage -crf 18 -bf 0 -r ' +
                frmRate + ' -force_fps -pix_fmt yuv420p -s 960x540 ' + output
            ]

            subprocess.Popen(cmd, shell=True)
Ejemplo n.º 32
0
def updateFrameRange():

    for readNodes in nuke.selectedNodes():

        name = readNodes.knob('file').getValue().split('/')[-1].split('%')[0]
        fileType = readNodes.knob('file').getValue().split('/')[-1].split(
            '.')[-1]
        path = '/'.join(
            readNodes.knob('file').getValue().split('/')[:-1]) + '/'
        fRange = ''

        for frameNumbers in nuke.getFileNameList(path):
            if name in frameNumbers:
                if fileType in frameNumbers:
                    fRange = frameNumbers.split(' ')[-1]
        readNodes.knob('first').setValue(int(fRange.split('-')[0]))
        readNodes.knob('last').setValue(int(fRange.split('-')[1]))
        readNodes.knob('origfirst').setValue(int(fRange.split('-')[0]))
        readNodes.knob('origlast').setValue(int(fRange.split('-')[1]))
Ejemplo n.º 33
0
def read_from_write():
    # Create read nodes from selected write nodes
    nodes = [n for n in nuke.selectedNodes() if 'file' in n.knobs()]
    excluded = [
        'Read',
    ]
    for node in nodes:
        if node.Class() in excluded:
            continue
        pos = get_pos(node)
        filepath = node['file'].getValue()
        if '[' in filepath:
            # contains tcl expression. use evaluate instead.
            filepath_eval = node['file'].evaluate()

        dirname = os.path.dirname(filepath)
        filename = os.path.basename(filepath)
        if '#' in filename:
            is_sequence = True
            filename_base = filename.split('#')[0]
        elif r'%' in filename:
            is_sequence = True
            filename_base = filename.split(r'%')[0]
        else:
            is_sequence = False
        if is_sequence:
            sequences = nuke.getFileNameList(dirname)
            for seq in sequences:
                if seq.startswith(filename_base):
                    filepath = os.path.join(dirname, seq)
                    break
        read = nuke.createNode('Read',
                               'file {{{0}}}'.format(filepath),
                               inpanel=False)
        set_pos(read, pos[0], pos[1] + grid[1] * 4)
        # match colorspace
        colorspace = node['colorspace'].value()
        if '(' in colorspace and ')' in colorspace:
            # parse out role
            colorspace = colorspace.split('(')[1].split(')')[0]
        read['colorspace'].setValue(colorspace)
        read['raw'].setValue(node['raw'].getValue())
Ejemplo n.º 34
0
def createRead(path):
    '''create read from path
    /.../<RenderVersion>/<RenderLayer>/<RenderPasses>/
    /.../TIO_orbit_1k_v001/rs_rsl_car/albeto/
    @path: full path for AOV, str
    return: aov read node, obj
    '''

    exrs = nuke.getFileNameList(path)[0]  # ['albedo_1k_v001.####.exr 1-96']
    frames, range = exrs.split(' ')
    first, last = range.split('-')
    first = int(first)
    last = int(last)
    aov = nuke.nodes.Read(file=os.path.join(path, frames).replace('\\', '/'),
                          name=os.path.basename(path),
                          first=first,
                          last=last,
                          label=os.path.basename(path))

    return aov
Ejemplo n.º 35
0
def createRead(path):
    '''create read from path
	@path: full path for AOV, (str)
	return: aov read node, (obj)
	'''

    exrs = nuke.getFileNameList(path)[0]  # ['albedo.####.exr 1-96']
    frames, range = exrs.split(' ')
    first, last = range.split('-')
    first = int(first)
    last = int(last)
    aov = nuke.nodes.Read(file=joinPath(path, frames),
                          name=os.path.basename(path),
                          first=first,
                          last=last,
                          label=os.path.basename(path))
    isData = True if aov.name() in DATA_AOV else False
    aov['raw'].setValue(isData)

    return aov
Ejemplo n.º 36
0
def sb_addViewerLuts(lutPath, addCineonLut = True):

    lutFormats = ["3dl", "csp", "cube", "vf", "lut"]
    colorspace = ["linear", "cineon","log", "logC", "AlexaV3LogC", "panalog", "slog", "sRGB", "rec709"]

    if os.path.exists(lutPath) == False:
        print "sb_addViewerLuts: LUT folder does not exsist."
        return

    # Make sure there is a / in the end of the folder path.
    if not lutPath.endswith("/"):
        lutPath = "{0}/".format(lutPath)

    # Get supported luts.
    allFiles = nuke.getFileNameList(lutPath)
    luts = []
    for i in allFiles:
        for j in lutFormats:
            if i.endswith( "." + j.lower() ):
                luts.append(i)
    
    if len(luts) == 0:
        print "No supported luts available."
        return

    added_luts = []
    skipped_luts = []

    for i in luts:
        lutOK = False
        input = ""
        currLutPath = lutPath + i
        splitFileName = os.path.splitext(i)
        lutName = splitFileName[0].strip()
        lutExt = splitFileName[1][1:].strip().lower()
        try:
            splitLutName = re.split('2',lutName,1)
            displayName = splitLutName[1].replace("_", " ")
        except IndexError:
            skipped_luts.append(i)
            continue

        # Get the input colorspace.
        for k in colorspace:
            if splitLutName[0].lower() == k.lower():
                input = k
                lutOK = True
                break

        if lutOK:
            # Get correct naming for input space.
            if input == "linear":
                input = "Linear"
            elif input == "lin":
                input = "Linear" 
            elif input == "cineon":
                input = "Cineon" 
            elif input == "log":
                input = "Cineon"
            elif input == "logC":
                input = "AlexaV3LogC"
            elif input == "alexav3logc":
                input = "AlexaV3LogC"
            elif input == "panalog":
                input = "Panalog"
            elif input == "slog":
                input = "SLog"
            elif input == "srgb":
                input = "sRGB"
            elif input == "rec709":
                input = "rec709"

            # Register the lut.
            lutSyntax = "vfield_file {0} colorspaceIn {1}".format(currLutPath, input)
            nuke.ViewerProcess.register(displayName, nuke.createNode, ("Vectorfield", lutSyntax))
            added_luts.append(i)

    # Add default Cineon as a lut.
    if addCineonLut:
        nuke.ViewerProcess.register("Cineon", nuke.createNode, ("ViewerProcess_1DLUT", "current Cineon"))
        added_luts.append("Cineon")

    # Give feedback in terminal.
    if len(skipped_luts) > 0:
        print "sb_addViewerLuts did not register the following LUTs as they do not use the supported naming convention: {0}".format(", ".join(skipped_luts))

    if len(added_luts) > 0:
        print "sb_addViewerLuts registered the following LUTs: {0}".format(", ".join(added_luts))
    else:
        print "sbAddViewerLuts did not register any LUTs."
Ejemplo n.º 37
-1
def sb_autoAddGizmos(gizmoPath, menuName, subMenuName = "", mainIcon = "", subIcon = ""):

    if not os.path.exists(gizmoPath):
        return

    # Get supported luts.
    allFiles = nuke.getFileNameList(gizmoPath)
    gizmos = []
    for i in allFiles:
        if i.endswith(".gizmo"):
            gizmos.append(i)
    
    if len(gizmos) == 0:
        print "sb_autoAddGizmos: No gizmos found."
        return

    t = nuke.toolbar("Nodes")
    customMenu = t.findItem(menuName)

    if not customMenu:
        customMenu = t.addMenu(menuName, icon = mainIcon)

    if subMenuName:
        customMenu = customMenu.addMenu(subMenuName, icon = subIcon)

    for i in sorted(gizmos):
        gizmoName = os.path.splitext(i)[0].strip()
        gizmoNameFix = gizmoName.replace("_", " ")
        customMenu.addCommand(gizmoNameFix, "nuke.createNode(\"" + gizmoName +"\")")