Esempio n. 1
0
    def _moveFilesToPublish(self):
        base_url    = "http://bubblebathbay.shotgunstudio.com"
        script_name = 'playBlastPublisher'
        api_key     = '718daf67bfd2c7e974f24e7cbd55b86bb101c4e5618e6d5468bc4145840e4558'

        sgsrv = Shotgun(base_url = base_url , script_name = script_name, api_key = api_key, ensure_ascii=True, connect=True)
        selectedShots = [item.text(0) for item in self.treeWidgetItems if item.checkState(0)]
        if selectedShots:
            for each in selectedShots:
                episode = each.split('sh')[0]
                shotName = '%s_sh%s' % (each.split('sh')[0], each.split('sh')[1].split('Lay')[0])
                self.publishPath = self.publishingPath(episode, shotName)
                for root, dirs, files in os.walk(self.shFldPath):
                    for fl in sorted(files):
                        if fl.endswith('.mov') and fl == '%s.mov' % each:
                            srcPath = os.path.join(root,fl)
                            self.playblastName = fl
                            while os.path.exists(os.path.join(self.publishPath, fl)):
                                allFiles= os.listdir(self.publishPath)
                                publishFiles = []
                                if allFiles:
                                    for allFile in allFiles:
                                        if allFile.endswith('.mov'):
                                            publishFiles.append(allFile)
                                versionNumber = int(sorted(publishFiles)[-1].split('.v')[1].split('.mov')[0])
                                versionNumber += 1
                                if versionNumber < 10:
                                    publishFileName = '%sLayout.v%03d.mov' % (shotName.replace('_', ''), versionNumber)
                                    self.publishPath = os.path.join(self.publishPath, publishFileName)
                                    self.playblastName = os.path.basename(self.publishPath)
                                else:
                                    publishFileName = '%sLayout.v%02d.mov' % (shotName.replace('_', ''), versionNumber)
                                    self.publishPath = os.path.join(self.publishPath, publishFileName)
                                    self.playblastName = os.path.basename(self.publishPath)

                            shutil.copy2(srcPath, self.publishPath)
                            publishMovPath = os.path.join(self.publishingPath(episode, shotName), self.playblastName)
                            getShotTasks =  sgsrv.find_one('Shot',  filters = [["code", "is", shotName]], fields=['id', 'tasks'])

                            for key, values in getShotTasks.iteritems():
                                if key == 'tasks':
                                    for value in values:
                                        if value['name'] == 'Layout':
                                            self.taskId = value['id']
                            if self.publishPath.endswith('review'):
                                self.publishPath = os.path.join(self.publishPath,fl)
                                self.playblastName = fl
                            data = { 'project': {'type':'Project','id': 66},
                                     'code':  self.playblastName,
                                     'description': 'Layout playblast published',
                                     'sg_path_to_movie': publishMovPath,
                                     'sg_status_list': 'rev',
                                     'entity': {'type':'Shot', 'id':getShotTasks['id']},
                                     'sg_task': {'type':'Task', 'id':self.taskId},
                                     'user': {'type':'HumanUser', 'id':92} }
                            result = sgsrv.create('Version', data)
                            result2 = sgsrv.upload("Version", result['id'], publishMovPath, "sg_uploaded_movie")
                print "Done"
    def _pubBttn(self):
        base_url    = "http://bubblebathbay.shotgunstudio.com"
        script_name = 'playBlastPublisher'
        api_key     = '718daf67bfd2c7e974f24e7cbd55b86bb101c4e5618e6d5468bc4145840e4558'

        sgsrv = Shotgun(base_url = base_url , script_name = script_name, api_key = api_key, ensure_ascii=True, connect=True)

        selectedShots = sorted([item.text(0) for item in self.shotTreeWidgetItems if item.checkState(0)])
        for shot in selectedShots:
            if shot in self.srcPath.keys():
                destPath = self._getPublishPath(shot)
                srcPath = self.srcPath[str(shot)]
                ext = os.path.splitext(srcPath)[-1]
#                 print os.path.basename(srcPath)
#                 while os.path.exists(os.path.join(str(destPath), os.path.basename(srcPath))):
#                     print "In Loop"
#                     print os.path.basename(srcPath)
#                     allFiles= os.listdir(destPath)
#                     publishFiles = []
#                     if allFiles:
#                         for allFile in allFiles:
#                             if allFile.endswith(ext):
#                                 print allFile
#                                 publishFiles.append(allFile)
#                     versionNumber = int(sorted(publishFiles)[-1].split('.v')[1].split(ext)[0])
#                     versionNumber += 1
#                     if versionNumber < 10:
#                         publishFileName = '%sLayout.v%03d%s' % (shotName.replace('_', ''), versionNumber, ext)
#                         self.publishPath = os.path.join(self.publishPath, publishFileName)
#                         self.playblastName = os.path.basename(self.publishPath)
#                     else:
#                         publishFileName = '%sLayout.v%02d%s' % (shotName.replace('_', ''), versionNumber, ext)
#                         self.publishPath = os.path.join(self.publishPath, publishFileName)
#                         self.playblastName = os.path.basename(self.publishPath)
#                 shutil.copy2(srcPath, destPath)

                shotName = '%s_%s' % (self._getEpisodeName(shot), self._getShotName(shot))
                getShotTasks =  self.tk.shotgun.find_one('Shot',  filters = [["code", "is", shotName]], fields=['id', 'tasks'])
                taskName = self.comboBox.currentText()
                self.playblastName = os.path.basename(srcPath)
                publishMovPath = os.path.join(destPath, self.playblastName).replace('\\', '/')
                shutil.copy2(srcPath, destPath)
                for task in getShotTasks['tasks']:
                    if task['name'] == taskName:
                        taskId = task['id']
                        data = { 'project': {'type':'Project','id': 66},
                             'code':  self.playblastName,
                             'description': 'Playblast published',
                             'sg_path_to_movie': publishMovPath,
                             'sg_status_list': 'rev',
                             'entity': {'type':'Shot', 'id':getShotTasks['id']},
                             'sg_task': {'type':'Task', 'id':taskId},
                             'user': {'type':'HumanUser', 'id':92} }
                        result = sgsrv.create('Version', data)
                        result2 = sgsrv.upload("Version", result['id'], publishMovPath, "sg_uploaded_movie")
                        print "Published %s" % self.playblastName
    def _pubBttn(self):
        base_url    = "http://bubblebathbay.shotgunstudio.com"
        script_name = 'playBlastPublisher'
        api_key     = '718daf67bfd2c7e974f24e7cbd55b86bb101c4e5618e6d5468bc4145840e4558'

        sgsrv = Shotgun(base_url = base_url , script_name = script_name, api_key = api_key, ensure_ascii=True, connect=True)

        selectedShots = sorted([item.text(0) for item in self.shotTreeWidgetItems if item.checkState(0)])
        for shot in selectedShots:
            if shot in self.srcPath.keys():
                destPath = self._getPublishPath(shot)
                srcPath = self.srcPath[str(shot)]
                ext = os.path.splitext(srcPath)[-1]
#                 print os.path.basename(srcPath)
#                 while os.path.exists(os.path.join(str(destPath), os.path.basename(srcPath))):
#                     print "In Loop"
#                     print os.path.basename(srcPath)
#                     allFiles= os.listdir(destPath)
#                     publishFiles = []
#                     if allFiles:
#                         for allFile in allFiles:
#                             if allFile.endswith(ext):
#                                 print allFile
#                                 publishFiles.append(allFile)
#                     versionNumber = int(sorted(publishFiles)[-1].split('.v')[1].split(ext)[0])
#                     versionNumber += 1
#                     if versionNumber < 10:
#                         publishFileName = '%sLayout.v%03d%s' % (shotName.replace('_', ''), versionNumber, ext)
#                         self.publishPath = os.path.join(self.publishPath, publishFileName)
#                         self.playblastName = os.path.basename(self.publishPath)
#                     else:
#                         publishFileName = '%sLayout.v%02d%s' % (shotName.replace('_', ''), versionNumber, ext)
#                         self.publishPath = os.path.join(self.publishPath, publishFileName)
#                         self.playblastName = os.path.basename(self.publishPath)
#                 shutil.copy2(srcPath, destPath)

                shotName = '%s_%s' % (self._getEpisodeName(shot), self._getShotName(shot))
                getShotTasks =  self.tk.shotgun.find_one('Shot',  filters = [["code", "is", shotName]], fields=['id', 'tasks'])
                taskName = self.comboBox.currentText()
                self.playblastName = os.path.basename(srcPath)
                publishMovPath = os.path.join(destPath, self.playblastName).replace('\\', '/')
                shutil.copy2(srcPath, destPath)
                for task in getShotTasks['tasks']:
                    if task['name'] == taskName:
                        taskId = task['id']
                        data = { 'project': {'type':'Project','id': 66},
                             'code':  self.playblastName,
                             'description': 'Playblast published',
                             'sg_path_to_movie': publishMovPath,
                             'sg_status_list': 'rev',
                             'entity': {'type':'Shot', 'id':getShotTasks['id']},
                             'sg_task': {'type':'Task', 'id':taskId},
                             'user': {'type':'HumanUser', 'id':92} }
                        result = sgsrv.create('Version', data)
                        result2 = sgsrv.upload("Version", result['id'], publishMovPath, "sg_uploaded_movie")
                        print "Published %s" % self.playblastName
Esempio n. 4
0
sg = Shotgun("https://objeus.shotgunstudio.com", SCRIPT_NAME, SCRIPT_KEY)

echars = sg.find('CustomEntity06', [], ['code'])
efiles = sg.find('Attachment',
                 [['attachment_links', 'type_is', 'CustomEntity06']],
                 ['attachment_links'])
efilenames = {}
for efile in efiles:
    efilenames[efile['attachment_links'][0]['name']] = efile['id']
print efilenames
enames = {}
for echar in echars:
    enames[echar['code']] = echar
print enames

chars = glob('chars/*.json')
for char in chars:
    with open(char) as json_data:
        temp = json.load(json_data)
    json_data.close()
    data = {'code': temp['name'], 'description': temp['desc']}
    if temp['name'] not in enames:
        data['project'] = {'type': 'Project', 'id': 70}
        id = sg.create('CustomEntity06', data, ['id'])['id']
    else:
        if temp['name'] in efilenames:
            sg.delete('Attachment', efilenames[temp['name']])
        id = sg.update('CustomEntity06', enames[temp['name']]['id'],
                       data)['id']
    sg.upload('CustomEntity06', id, char, 'sg_json')
Esempio n. 5
0
class studioShotgun(object):
    def __init__(self, path, name, key, project):
        self.SERVER_PATH = path
        self.SCRIPT_NAME = name     
        self.SCRIPT_KEY = key
        self.project_id = project
        self.sg = Shotgun(self.SERVER_PATH, self.SCRIPT_NAME, self.SCRIPT_KEY)

    #----------------------------------------------------------------------
    ## set Project id by ID
    def setProjectId(self, newId):
        self.project_id = newId

    #----------------------------------------------------------------------
    ## set Project id by ID
    def setProjectName(self, name):
        newId = 0
        projects = self.sg.find('Project', [], ['name'])
        for project in projects:
            if project['name'] == name:
                newId = project['id']

        self.project_id = newId

    #----------------------------------------------------------------------
    ## find asset by name
    def findAssetByName(self, name):
        fields = ['id', 'code', 'sg_asset_type', 'tasks']
        filters = [['project', 'is', {'type': 'Project', 'id': self.project_id}], ['code', 'is', name]]
        
        result = self.sg.find('Asset', filters, fields)
    
        return result
    
    #----------------------------------------------------------------------
    ## find shot by name
    def findShotByName(self, episode, shot):
        fields = ['id', 'code', 'sg_asset_type', 'tasks', 'sg_sequence']
        filters = [['project', 'is', {'type': 'Project', 'id': self.project_id}], ['code', 'is', shot]]
        
        result = self.sg.find('Shot', filters, fields)
    
        for x in result:
            name = x['sg_sequence']['name'].split('_')[0]
            if name == episode:
                return x
    
        return []

    #----------------------------------------------------------------------
    ## upload thumbnail to asset
    def uploadThumbnail(self, asset, thumbnail):
        upload = 0
        asset = self.findAssetByName(asset)
        if asset:
            upload = self.sg.upload_thumbnail("Asset", asset[0]['id'], thumbnail)
    
        return upload

    #----------------------------------------------------------------------
    ## create new asset
    def createAsset(self, asset, assetType, template, assetFile='', description=''):
        ## find asset
        asset = self.findAssetByName(asset)
        
        if not asset:
            ## create asset + task template
            filters = [['code', 'is', template]]
            template = self.sg.find_one('TaskTemplate', filters)
            
            data = {'project': {'type': 'Project', 'id': self.project_id}, 
                    'code': asset,
                    'description': description, 
                    'sg_asset_type': assetType, 
                    'sg_url_perforce': assetFile, 
                    'task_template': template}
    
            asset = self.sg.create('Asset', data)
    
        return asset

    #----------------------------------------------------------------------
    ## update file path in asset
    def updateAssetFilePath(self, asset, filename):
        asset = self.findAssetByName(asset)
    
        data = {'sg_url_perforce': filename}
        asset = self.sg.update("Asset", asset[0]['id'], data)
    
        return asset

    #----------------------------------------------------------------------
    ## create new version
    def createVersion(self, shotId, taskId, userId, filename, comment=''):
        curTime = datetime.now().strftime('%Y.%m.%d_%H.%M')
        fname = str(filename.split('/')[-1].split('.')[0]) + '_' + curTime
    
        data = {'project': {'type': 'Project', 'id': self.project_id},
                'code': fname,
                'description': comment,
                'sg_status_list': 'rev',
                'entity': {'type': 'Shot', 'id': shotId},
                'sg_task': {'type': 'Task', 'id': taskId},
                'user': {'type': 'HumanUser', 'id': userId}}
        
        result = self.sg.create('Version', data)
        
        upload = self.sg.upload('Version', result['id'], filename, 'sg_uploaded_movie')
    
        return [result, upload]

    #----------------------------------------------------------------------
    ## get user data from shotgum
    def getUserData(self, user):
        filters = [['login', 'is', user]]
        user = self.sg.find('HumanUser', filters)

        if user:
            return user[0]
        else:
            return []

    #----------------------------------------------------------------------
    ## get all user from project
    def getAllUsers(self):
        fields = ['id', 'login', 'name', 'projects', 'department']
        filters = [['projects', 'is', {'type': 'Project', 'id': self.project_id}]]
        users = self.sg.find('HumanUser', filters, fields)
    
        return users
Esempio n. 6
0
    class genericUtils:
        def __init__(self):
            self.sg = Shotgun('https://' + URL, name, API)

        def getFields(self, entity):
            '''get the fields for a type/entity as a list so we can pass it as an arg easily
            this is used all the time to make sure we get all the fields that we may ever need for a type/entity
            '''
            allFields = []
            fields = self.sg.schema_field_read(entity)
            for field in fields:
                allFields.append(field)
            return allFields

        def project(self, project):
            '''Gets the Shotgun project name and ID
            '''
            retFields = self.getFields('Project')
            project = project.replace('_', ' ')
            return self.sg.find_one("Project", [["name", "is", project]],
                                    retFields)

        def sequence(self, project, sequence):
            '''Returns the shotgun sequence name and ID 
            Parameters : (project, sequence)
            '''
            retFields = self.getFields('Sequence')
            return self.sg.find_one(
                "Sequence",
                [["code", "is", sequence], ['project', 'is', project]],
                retFields)

        def shot(self, project, shot):
            '''Returns the shotgun shot name and ID 
            Parameters : (project, shot)
            '''
            retFields = self.getFields('Shot')
            return self.sg.find_one(
                'Shot', [['code', 'is', shot], ['project', 'is', project]],
                retFields)

        def createProject(self, project):
            '''Creates a project in Shotgun given a project name
            Parameters : (project)
            '''
            filters = [['code', 'is', 'a']]
            template = self.sg.find_one('Project', [['name', 'is', 'a']],
                                        ['layout_project', 'id'])
            data = {'name': project, 'layout_project': template}
            return self.sg.create('Project', data)

        def createSequence(self, project, sequence):
            '''Creates a sequence in shotgun given 
            Parameters : (project, sequence)
            '''
            data = {
                'project': {
                    "type": "Project",
                    "id": project['id']
                },
                'code': sequence
            }
            return self.sg.create('Sequence', data)

        def createShot(self, project, shot, seq='', taskTemplateName=''):
            '''Creates a sequence in shotgun given 
            Parameters : (project, shot, seq='', taskTemplateName='Basic shot template'
            '''
            filters = [['code', 'is', taskTemplateName]]
            template = self.sg.find_one('TaskTemplate', filters)

            data = {
                'project': {
                    "type": "Project",
                    "id": project['id']
                },
                'code': shot,
                'task_template': template,
                'description': '',
                'self.sg_sequence': seq,
                'self.sg_status_list': 'wtg'
            }
            result = self.sg.create('Shot', data)
            return result

        def notesFind(self, shotID):
            '''Find all notes on a shot 
            Parameters : (shotID)
            Output : Note data :
            ['tasks', 'attachments', 'updated_at', 'replies', 'id', 'subject', 'playlist', '
            addressings_to', 'created_by', 'content', 'sg_status_list', 'reply_content', 
            'updated_by', 'addressings_cc', 'read_by_current_user', 'user', 'note_links', 
            'created_at', 'sg_note_from', 'project', 'sg_note_type', 'tag_list']        
            '''
            note = self.sg.find('Note', [['note_links', 'is', shotID]],
                                ['subject', 'content', 'created_at'],
                                [{
                                    'field_name': 'created_at',
                                    'direction': 'desc'
                                }])
            return note

        def notesFindLatest(self, shotID):
            '''Find the latest note on a shot
            Parameters : (shotID)
            Call with notesFindLatest(shot)['content'] for the note content only
            Output : Note data:
            ['tasks', 'attachments', 'updated_at', 'replies', 'id', 'subject', 'playlist', '
            addressings_to', 'created_by', 'content', 'sg_status_list', 'reply_content', 
            'updated_by', 'addressings_cc', 'read_by_current_user', 'user', 'note_links', 
            'created_at', 'sg_note_from', 'project', 'sg_note_type', 'tag_list']        
            '''
            note = self.notesFind(shotID)[0]
            return note

        def notesCreate(self, project, shotID, subject, content):
            '''Create a note for a shot given
            Parameters : (project, shotID, subject, content)
            Output : noteID
            '''
            # enter data here for a note to create
            data = {
                'subject': subject,
                'content': content,
                'note_links': [shotID],
                'project': project
            }
            # create the note
            noteID = self.sg.create('Note', data)
            return noteID

        def versionCreate(self,
                          project,
                          shot,
                          verName,
                          description,
                          framePath,
                          firstFrame,
                          lastFrame,
                          clientName=None,
                          sourceFile=None,
                          task=None,
                          user=None,
                          final=False,
                          makeThumb=False,
                          makeThumbShot=False):
            '''Create a version
            Parameters : (project, shotID, verName, description, framePath, firstFrame, lastFrame, clientName=None, sourceFile=None, task=None)
            Output : versionID
            '''

            data = {
                'project': project,
                'code': verName,
                'description': description,
                'sg_path_to_frames': framePath,
                #'sg_frame_range': str(firstFrame) + '-' + str(lastFrame),
                'sg_first_frame': int(firstFrame),
                'sg_last_frame': int(lastFrame),
                'sg_status_list': 'rev',
                'entity': shot
            }
            #if user != None:
            #data['user']
            if task != None:
                filters = [['content', 'is', task], ['entity', 'is', shot]]
                taskID = self.sg.find_one('Task', filters)
                data['sg_task'] = taskID
            #if final == True and 'send
            # in case we're putting a client version in here we need this code.
            # we are expecting a field called self.sg_client_name in the version table.
            # please make sure you create this in the shotgun setup
            # read the schema and if the client_name is not found, create it.
            '''
            versionFields = self.sg.schema_field_read('Version')
            if 'sg_client_name' not in versionFields and clientName != None:
                newField = self.sg.schema_field_create('Version','text','Client Name')
            if clientName != None :
                data['sg_client_name'] =  clientName
        
            #'user': {'type':'HumanUser', 'id':165} }
            # here we need to create a field for storing the source file that created this version.
            # if it's not there, create the field, and if it's there just update it.
            
            if 'sg_source_file' not in versionFields and sourceFile != None:
                newField = self.sg.schema_field_create('Version','text','Source File')
            if sourceFile != None:
                data['sg_source_file'] = sourceFile
            '''

            versionData = self.sg.create('Version', data)
            # handle the thumbnail grabbing here
            middleFrame = (int(firstFrame) + int(lastFrame)) / 2
            padding, padString = fxpipe.framePad(framePath)
            paddedFrame = padString % (middleFrame)
            if makeThumb == True:
                thumbData = self.sg.upload_thumbnail(
                    'Version', versionData['id'],
                    framePath.replace(padding, paddedFrame))
            if makeThumbShot == True:
                thumbData = self.sg.upload_thumbnail(
                    'Shot', shot['id'],
                    framePath.replace(padding, paddedFrame))
            return versionData

        #add a task version to the system
        def versionCreateTask(self,
                              project,
                              shot,
                              verName,
                              description,
                              framePath,
                              firstFrame,
                              lastFrame,
                              task,
                              sourceFile=''):
            '''
            DEPRECATED : USE versionCreate instead with the task='TASKNAME'
            Parameters : (project, shot, verName, description, framePath, firstFrame, lastFrame, task, sourceFile = '')
            Output : Version ID
            '''
            filters = [['content', 'is', task], ['entity', 'is', shot]]
            taskID = self.sg.find_one('Task', filters)
            data = {
                'project': project,
                'code': verName,
                'description': description,
                'self.sg_path_to_frames': framePath,
                'frame_range': str(firstFrame) + '-' + str(lastFrame),
                'self.sg_first_frame': firstFrame,
                'self.sg_last_frame': lastFrame,
                #'self.sg_uploaded_movie': '/Users/throb/Downloads/test.m4v',
                #'self.sg_first_frame': 1,
                #'self.sg_last_frame': 100,
                'self.sg_status_list': 'rev',
                'self.sg_task': taskID,
                'entity': shot
            }
            # here we need to create a field for storing the source file that created this version.
            # if it's not there, create the field, and if it's there just update it.
            try:
                tmp2 = {}
                tmp2 = tmp['self.sg_source_file']
            except:
                newField = self.sg.schema_field_create('Version', 'text',
                                                       'Source File')
            if sourceFile != '':
                data['self.sg_source_file'] = sourceFile

            return self.sg.create('Version', data)

        # look for specific version
        def versionFind(self, versionID):
            '''Find all versions in a shot with most recent first
            Parameters : (shotID)
            Output : Version data:
            ['sg_version_type', 'open_notes_count', 'code', 'playlists', 'sg_task', 'image',
            'updated_at', 'sg_output', 'sg_path_to_frames', 'tasks', 'frame_range', 'id', 
            'description', 'sg_uploaded_movie_webm', 'open_notes', 'tank_published_file', 
            'task_template', 'created_by', 'sg_movie_type', 'sg_status_list', 'notes', 
            'sg_client_name', 'sg_uploaded_movie_mp4', 'updated_by', 'sg_send_for_final', 
            'user', 'sg_uploaded_movie_frame_rate', 'entity', 'step_0', 'sg_client_version', 
            'sg_uploaded_movie_transcoding_status', 'created_at', 'sg_qt', 'project', 
            'filmstrip_image', 'tag_list', 'frame_count', 'flagged']        
            '''
            retFields = self.getFields('Version')
            return self.sg.find('Version', [['id', 'is', versionID]],
                                retFields, [{
                                    'field_name': 'created_at',
                                    'direction': 'desc'
                                }])[0]

        # look for versions in a shot:
        def versionFindShot(self, shotID):
            '''Find all versions in a shot with most recent first
            Parameters : (shotID)
            Output : Version data:
            ['sg_version_type', 'open_notes_count', 'code', 'playlists', 'sg_task', 'image',
            'updated_at', 'sg_output', 'sg_path_to_frames', 'tasks', 'frame_range', 'id', 
            'description', 'sg_uploaded_movie_webm', 'open_notes', 'tank_published_file', 
            'task_template', 'created_by', 'sg_movie_type', 'sg_status_list', 'notes', 
            'sg_client_name', 'sg_uploaded_movie_mp4', 'updated_by', 'sg_send_for_final', 
            'user', 'sg_uploaded_movie_frame_rate', 'entity', 'step_0', 'sg_client_version', 
            'sg_uploaded_movie_transcoding_status', 'created_at', 'sg_qt', 'project', 
            'filmstrip_image', 'tag_list', 'frame_count', 'flagged']        
            '''
            retFields = self.getFields('Version')
            return self.sg.find('Version', [['entity', 'is', shotID]],
                                retFields, [{
                                    'field_name': 'created_at',
                                    'direction': 'desc'
                                }])

        def versionFindLatest(self, shotID):
            '''Find only the most recent version
            Parameters : (shotID)
            Output : Version data:
            ['sg_version_type', 'open_notes_count', 'code', 'playlists', 'sg_task', 'image',
            'updated_at', 'sg_output', 'sg_path_to_frames', 'tasks', 'frame_range', 'id', 
            'description', 'sg_uploaded_movie_webm', 'open_notes', 'tank_published_file', 
            'task_template', 'created_by', 'sg_movie_type', 'sg_status_list', 'notes', 
            'sg_client_name', 'sg_uploaded_movie_mp4', 'updated_by', 'sg_send_for_final', 
            'user', 'sg_uploaded_movie_frame_rate', 'entity', 'step_0', 'sg_client_version', 
            'sg_uploaded_movie_transcoding_status', 'created_at', 'sg_qt', 'project', 
            'filmstrip_image', 'tag_list', 'frame_count', 'flagged']         
            '''
            retFields = self.getFields('Version')
            return self.sg.find_one('Version', [['entity', 'is', shotID]],
                                    retFields, [{
                                        'field_name': 'created_at',
                                        'direction': 'desc'
                                    }])

        # search for the latest task given shotID and task info
        def versionFindLatestTask(self, shotID, task):
            retFields = self.getFields('Version')
            # first look for the task and get the ID
            filters = [['content', 'is', task], ['entity', 'is', shotID]]
            taskID = self.sg.find_one('Task', filters)
            # then look for the latest
            #version using the task ID.  note that we need to use the [0] or else we're sending the array versus the hash
            versionLatest = self.sg.find_one(
                'Version',
                [['entity', 'is', shotID], ['self.sg_task', 'is', taskID]],
                retFields, [{
                    'field_name': 'created_at',
                    'direction': 'desc'
                }])
            return versionLatest

        ## The following requires a field called "client_version" be added to shotgun
        def versionClientUpdate(self,
                                shotID,
                                version,
                                clientVersionName='Client Version'):
            '''This takes the shotID and version (int) and updates the shot with this client version number
            Sometimes the client wants to see different version numbers versus the internal ones.  This option allows for it.
            You will need to create a field.  Client Version is what I have used but you can specify what you want here.
            Parameters: (shotID, version, clientVersionName ='Client Version')
            Output : Version data
            '''
            sgFieldName = 'sg_' + clientVersionName.lower().replace(' ', '_')
            data = {sgFieldName: version}
            try:
                result = self.sg.update('Shot', shotID['id'], data)
            except:
                newField = self.sg.schema_field_create('Shot', 'number',
                                                       clientVersionName)
                result = self.sg.update('Shot', shotID['id'], data)
            return result

        def uploadQT(self, entityType, item, path):
            '''Upload a file to shotgun in the 'self.sg_qt' field.
            If you do this for a shot, you will need to add this to a field
            the field should be called 'qt' as shotgun will add the self.sg_ to it
            Shotgun provides the self.sg_qt for versions automatically
            Parameters: (entity,item,path)
            uploadQT ('Version',versionData, '/my/file.mov')
            '''
            # Make sure first letter is capitalized
            entity = entityType.capitalize()

            # upload that mother
            if entity.lower() == 'shot':
                try:
                    result = self.sg.upload(entity, item['id'], path, 'sg_qt')
                except:
                    newField = self.sg.schema_field_create('Shot', 'url', 'QT')
                    result = self.sg.upload(entity, item['id'], path, 'sg_qt')

            elif entity.lower() == 'version':
                result = self.sg.upload(entity, item['id'], path,
                                        'sg_uploaded_movie')
            return result

        def versionClientGet(self, shotID, clientVersion='Client Version'):
            '''Get latest client version number
            Parameters : (hotID, clientVersion='Client Version')
            Output : Version data
            '''
            sgFieldName = 'sg_' + clientVersionName.lower().replace(' ', '_')
            try:
                currentVersion = shotID[sgFieldName]
            except:
                currentVersion = 0
            if currentVersion == None:
                return 0
            return currentVersion

        def playlistFind(self, project, playlistName):
            '''Search for a playlist given a project and name
            Parameters : (project, playlistName)
            Output : playlist data:
            ['code', 'description', 'versions', 'created_at', 'sg_cinesync_session_url', 
            'updated_at', 'created_by', 'project', 'filmstrip_image', 'notes', 'image', 
            'updated_by', 'sg_cinesync_session_key', 'sg_status', 'tag_list', 'id', 
            'sg_date_and_time']        
            '''
            retFields = self.getFields('Playlist')
            return self.sg.find_one(
                'Playlist',
                [['code', 'is', playlistName], ['project', 'is', project]],
                retFields)

        def playlistCreate(self,
                           project,
                           playlistName,
                           playlistDescription=''):
            '''Create a playlist given a playlist name
            Parameters : (project, playlistName, playlistDescription='')
            Output : playlist data
            '''
            data = {
                'project': project,
                'code': playlistName,
                'description': playlistDescription
            }
            return self.sg.create('Playlist', data)

        # Add a version to a playlist
        def playlistAddVersion(self, project, playlistName, version):
            '''
            Description :\n
            This adds a version (existing version in the system) to a playlist.\n
            You need to give it: (in order)\r
            shotgun connection class\r
            project (dict of the project info including name and id)\r
            playlist name (string of the name of the playlist)\r
            version (dict of the version you wish to add\n
            It will return with a dict of the playlist
            '''

            my_playlist_list = self.sg.find_one(
                'Playlist',
                [['code', 'is', playlistName], ['project', 'is', project]],
                ['versions'])
            if len(my_playlist_list):
                ver_list = my_playlist_list['versions']
                ver_list.append({
                    'type': 'Version',
                    'name': version['code'],
                    'id': version['id']
                })
                result = self.sg.update('Playlist', my_playlist_list['id'],
                                        {'versions': ver_list})
                return result

        def playlistInfo(self, project, playlistName):
            '''Get playlist info (eg version name and description)
            Parameters : (project, playlistName)
            Output : version data
            '''
            data = []
            versionData = []
            retFields = self.getFields('Version')
            for versionInPlaylist in self.sg.find_one(
                    'Playlist',
                [['code', 'is', playlistName], ['project', 'is', project]],
                ['versions'])['versions']:
                data.append(
                    self.sg.find_one('Version',
                                     [['id', 'is', versionInPlaylist['id']]],
                                     retFields))
            #for items in data:
            #   versionData.append({'name':items['code'],'desc':items['description'],'first_frame':items['self.sg_first_frame})
            return data

        def getTimeShot(self, shot):
            '''Given shot (as dict) return total time on shot as [0] and other times for each task on shot
            '''
            outputData = []
            retFields = ['content', 'time_logs_sum']
            totalTime = 0
            for curTask in shot['tasks']:
                taskData = self.sg.find_one('Task',
                                            [['id', 'is', curTask['id']]],
                                            fields=retFields)
                totalTime += taskData['time_logs_sum']
                outputData.append({
                    'name': taskData['content'],
                    'time': taskData['time_logs_sum']
                })
            outputData.insert(0, {'name': shot['code'], 'time': totalTime})
            return outputData
Esempio n. 7
0
class genericUtils:
    def __init__(self):
        self.sg = Shotgun('https://' + URL,name,API)

    def getFields (self, entity):
        '''get the fields for a type/entity as a list so we can pass it as an arg easily
        this is used all the time to make sure we get all the fields that we may ever need for a type/entity
        '''
        allFields = []
        fields = self.sg.schema_field_read(entity)
        for field in fields:
            allFields.append(field)
        return allFields  
    
    def project (self, project):
        '''Gets the Shotgun project name and ID
        '''
        retFields = self.getFields('Project')
        project = project.replace('_', ' ')
        return self.sg.find_one("Project", [["name", "is", project]], retFields )   

    def sequence (self, project, sequence):
        '''Returns the shotgun sequence name and ID 
        Parameters : (project, sequence)
        '''
        retFields = self.getFields('Sequence')
        return self.sg.find_one("Sequence", [["code", "is", sequence],['project','is',project]], retFields)
    
    def shot (self, project, shot):
        '''Returns the shotgun shot name and ID 
        Parameters : (project, shot)
        '''        
        retFields = self.getFields('Shot')
        return self.sg.find_one('Shot',[['code','is',shot],['project','is',project]],retFields)
    
    def createProject (self, project):
        '''Creates a project in Shotgun given a project name
        Parameters : (project)
        '''        
        filters = [['code','is','a']]
        template = self.sg.find_one('Project',[['name','is','a']],['layout_project','id'])
        data = {'name':project,
                'layout_project': template
                }
        return self.sg.create('Project',data)
    
    def createSequence (self, project, sequence):
        '''Creates a sequence in shotgun given 
        Parameters : (project, sequence)
        '''        
        data = {'project': {"type":"Project","id": project['id']},
                 'code': sequence}
        return self.sg.create('Sequence', data)
    
    def createShot (self, project, shot, seq='', taskTemplateName=''):
        '''Creates a sequence in shotgun given 
        Parameters : (project, shot, seq='', taskTemplateName='Basic shot template'
        '''          
        filters = [['code','is',taskTemplateName ]]
        template = self.sg.find_one('TaskTemplate',filters)
    
        data = { 'project': {"type":"Project","id": project['id']},
                 'code': shot,
                 'task_template' : template,
                 'description': '',
                 'self.sg_sequence': seq,
                 'self.sg_status_list': 'wtg' }
        result = self.sg.create('Shot', data)
        return result
    
    def notesFind (self, shotID):
        '''Find all notes on a shot 
        Parameters : (shotID)
        Output : Note data :
        ['tasks', 'attachments', 'updated_at', 'replies', 'id', 'subject', 'playlist', '
        addressings_to', 'created_by', 'content', 'sg_status_list', 'reply_content', 
        'updated_by', 'addressings_cc', 'read_by_current_user', 'user', 'note_links', 
        'created_at', 'sg_note_from', 'project', 'sg_note_type', 'tag_list']        
        '''
        note = self.sg.find('Note',[['note_links','is', shotID]],['subject','content', 'created_at'],[{'field_name':'created_at','direction':'desc'}])
        return note
    
    def notesFindLatest (self, shotID):
        '''Find the latest note on a shot
        Parameters : (shotID)
        Call with notesFindLatest(shot)['content'] for the note content only
        Output : Note data:
        ['tasks', 'attachments', 'updated_at', 'replies', 'id', 'subject', 'playlist', '
        addressings_to', 'created_by', 'content', 'sg_status_list', 'reply_content', 
        'updated_by', 'addressings_cc', 'read_by_current_user', 'user', 'note_links', 
        'created_at', 'sg_note_from', 'project', 'sg_note_type', 'tag_list']        
        '''
        note = self.notesFind(shotID)[0]
        return note
    
    
    def notesCreate(self, project, shotID, subject, content):
        '''Create a note for a shot given
        Parameters : (project, shotID, subject, content)
        Output : noteID
        '''
        # enter data here for a note to create
        data = {'subject':subject,'content':content,'note_links':[shotID],'project':project}
        # create the note
        noteID = self.sg.create('Note',data)
        return noteID
    
    def versionCreate(self, project, shot, verName, description, framePath, firstFrame, lastFrame, clientName=None, sourceFile=None, task=None, user=None, final=False, makeThumb=False, makeThumbShot=False):
        '''Create a version
        Parameters : (project, shotID, verName, description, framePath, firstFrame, lastFrame, clientName=None, sourceFile=None, task=None)
        Output : versionID
        '''
          
        data = {'project': project,
                'code': verName,
                'description': description,
                'sg_path_to_frames': framePath,
                #'sg_frame_range': str(firstFrame) + '-' + str(lastFrame),
                'sg_first_frame' : int(firstFrame),
                'sg_last_frame' : int(lastFrame),
                'sg_status_list': 'rev',
                'entity': shot}
        #if user != None:
            #data['user']
        if task != None:
            filters = [['content','is',task],['entity','is',shot]]
            taskID = self.sg.find_one('Task',filters)  
            data['sg_task']=taskID
        #if final == True and 'send
        # in case we're putting a client version in here we need this code.
        # we are expecting a field called self.sg_client_name in the version table.
        # please make sure you create this in the shotgun setup
        # read the schema and if the client_name is not found, create it.
        '''
        versionFields = self.sg.schema_field_read('Version')
        if 'sg_client_name' not in versionFields and clientName != None:
            newField = self.sg.schema_field_create('Version','text','Client Name')
        if clientName != None :
            data['sg_client_name'] =  clientName
    
        #'user': {'type':'HumanUser', 'id':165} }
        # here we need to create a field for storing the source file that created this version.
        # if it's not there, create the field, and if it's there just update it.
        
        if 'sg_source_file' not in versionFields and sourceFile != None:
            newField = self.sg.schema_field_create('Version','text','Source File')
        if sourceFile != None:
            data['sg_source_file'] = sourceFile
        '''
        
        versionData = self.sg.create('Version',data)
        # handle the thumbnail grabbing here
        middleFrame = (int(firstFrame) + int(lastFrame)) / 2
        padding, padString = fxpipe.framePad(framePath)
        paddedFrame = padString % (middleFrame)
        if makeThumb == True:
            thumbData = self.sg.upload_thumbnail('Version', versionData['id'], framePath.replace(padding,paddedFrame))
        if makeThumbShot == True:
            thumbData = self.sg.upload_thumbnail('Shot', shot['id'], framePath.replace(padding,paddedFrame))   
        return versionData      

   
    #add a task version to the system
    def versionCreateTask(self, project, shot, verName, description, framePath, firstFrame, lastFrame, task, sourceFile = ''):
        '''
        DEPRECATED : USE versionCreate instead with the task='TASKNAME'
        Parameters : (project, shot, verName, description, framePath, firstFrame, lastFrame, task, sourceFile = '')
        Output : Version ID
        '''
        filters = [['content','is',task],['entity','is',shot]]
        taskID = self.sg.find_one('Task',filters)
        data = {'project': project,
                'code': verName,
                'description': description,
                'self.sg_path_to_frames': framePath,
                'frame_range': str(firstFrame) + '-' + str(lastFrame),
                'self.sg_first_frame' : firstFrame,
                'self.sg_last_frame' : lastFrame,
                #'self.sg_uploaded_movie': '/Users/throb/Downloads/test.m4v',
                #'self.sg_first_frame': 1,
                #'self.sg_last_frame': 100,
                'self.sg_status_list': 'rev',
                'self.sg_task': taskID,
    
                'entity': shot}
        # here we need to create a field for storing the source file that created this version.
        # if it's not there, create the field, and if it's there just update it.
        try:
            tmp2 = {}
            tmp2 = tmp['self.sg_source_file']
        except:
            newField = self.sg.schema_field_create('Version','text','Source File')
        if sourceFile != '':
            data['self.sg_source_file'] = sourceFile
    
        return self.sg.create('Version',data)
    # look for specific version
    def versionFind(self, versionID):
        '''Find all versions in a shot with most recent first
        Parameters : (shotID)
        Output : Version data:
        ['sg_version_type', 'open_notes_count', 'code', 'playlists', 'sg_task', 'image',
        'updated_at', 'sg_output', 'sg_path_to_frames', 'tasks', 'frame_range', 'id', 
        'description', 'sg_uploaded_movie_webm', 'open_notes', 'tank_published_file', 
        'task_template', 'created_by', 'sg_movie_type', 'sg_status_list', 'notes', 
        'sg_client_name', 'sg_uploaded_movie_mp4', 'updated_by', 'sg_send_for_final', 
        'user', 'sg_uploaded_movie_frame_rate', 'entity', 'step_0', 'sg_client_version', 
        'sg_uploaded_movie_transcoding_status', 'created_at', 'sg_qt', 'project', 
        'filmstrip_image', 'tag_list', 'frame_count', 'flagged']        
        '''        
        retFields = self.getFields('Version')
        return self.sg.find('Version',[['id','is',versionID]],retFields,[{'field_name':'created_at','direction':'desc'}])[0]
    
    # look for versions in a shot:
    def versionFindShot(self, shotID):
        '''Find all versions in a shot with most recent first
        Parameters : (shotID)
        Output : Version data:
        ['sg_version_type', 'open_notes_count', 'code', 'playlists', 'sg_task', 'image',
        'updated_at', 'sg_output', 'sg_path_to_frames', 'tasks', 'frame_range', 'id', 
        'description', 'sg_uploaded_movie_webm', 'open_notes', 'tank_published_file', 
        'task_template', 'created_by', 'sg_movie_type', 'sg_status_list', 'notes', 
        'sg_client_name', 'sg_uploaded_movie_mp4', 'updated_by', 'sg_send_for_final', 
        'user', 'sg_uploaded_movie_frame_rate', 'entity', 'step_0', 'sg_client_version', 
        'sg_uploaded_movie_transcoding_status', 'created_at', 'sg_qt', 'project', 
        'filmstrip_image', 'tag_list', 'frame_count', 'flagged']        
        '''        
        retFields = self.getFields('Version')
        return self.sg.find('Version',[['entity','is',shotID]],retFields,[{'field_name':'created_at','direction':'desc'}])
    
    def versionFindLatest(self, shotID):
        '''Find only the most recent version
        Parameters : (shotID)
        Output : Version data:
        ['sg_version_type', 'open_notes_count', 'code', 'playlists', 'sg_task', 'image',
        'updated_at', 'sg_output', 'sg_path_to_frames', 'tasks', 'frame_range', 'id', 
        'description', 'sg_uploaded_movie_webm', 'open_notes', 'tank_published_file', 
        'task_template', 'created_by', 'sg_movie_type', 'sg_status_list', 'notes', 
        'sg_client_name', 'sg_uploaded_movie_mp4', 'updated_by', 'sg_send_for_final', 
        'user', 'sg_uploaded_movie_frame_rate', 'entity', 'step_0', 'sg_client_version', 
        'sg_uploaded_movie_transcoding_status', 'created_at', 'sg_qt', 'project', 
        'filmstrip_image', 'tag_list', 'frame_count', 'flagged']         
        '''
        retFields = self.getFields('Version')
        return self.sg.find_one('Version',[['entity','is',shotID]],retFields,[{'field_name':'created_at','direction':'desc'}])
    
    # search for the latest task given shotID and task info
    def versionFindLatestTask(self, shotID, task):
        retFields = self.getFields('Version')
        # first look for the task and get the ID
        filters = [['content','is',task],['entity','is',shotID]]
        taskID = self.sg.find_one('Task',filters)
        # then look for the latest
        #version using the task ID.  note that we need to use the [0] or else we're sending the array versus the hash
        versionLatest = self.sg.find_one('Version',[['entity','is',shotID],['self.sg_task','is',taskID]],retFields,[{'field_name':'created_at','direction':'desc'}])
        return versionLatest
    
    ## The following requires a field called "client_version" be added to shotgun
    def versionClientUpdate (self, shotID, version, clientVersionName ='Client Version'):
        '''This takes the shotID and version (int) and updates the shot with this client version number
        Sometimes the client wants to see different version numbers versus the internal ones.  This option allows for it.
        You will need to create a field.  Client Version is what I have used but you can specify what you want here.
        Parameters: (shotID, version, clientVersionName ='Client Version')
        Output : Version data
        '''
        sgFieldName = 'sg_' + clientVersionName.lower().replace(' ','_')
        data = { sgFieldName: version}
        try:
            result = self.sg.update('Shot', shotID['id'], data)
        except:
            newField = self.sg.schema_field_create('Shot', 'number', clientVersionName)
            result = self.sg.update('Shot', shotID['id'], data)
        return result
    

    def uploadQT (self, entityType, item, path):
        '''Upload a file to shotgun in the 'self.sg_qt' field.
        If you do this for a shot, you will need to add this to a field
        the field should be called 'qt' as shotgun will add the self.sg_ to it
        Shotgun provides the self.sg_qt for versions automatically
        Parameters: (entity,item,path)
        uploadQT ('Version',versionData, '/my/file.mov')
        '''
        # Make sure first letter is capitalized
        entity = entityType.capitalize()

        # upload that mother
        if entity.lower() == 'shot':
            try:
                result = self.sg.upload (entity, item['id'], path,'sg_qt')
            except:
                newField = self.sg.schema_field_create('Shot', 'url', 'QT')
                result = self.sg.upload (entity, item['id'], path,'sg_qt')
    
        elif entity.lower() == 'version':
            result = self.sg.upload (entity, item['id'], path,'sg_uploaded_movie')
        return result
    
 
    def versionClientGet (self, shotID, clientVersion='Client Version'):
        '''Get latest client version number
        Parameters : (hotID, clientVersion='Client Version')
        Output : Version data
        '''        
        sgFieldName = 'sg_' + clientVersionName.lower().replace(' ','_')
        try :
            currentVersion = shotID[sgFieldName]
        except :
            currentVersion = 0
        if currentVersion == None:
            return 0
        return currentVersion
    
    def playlistFind (self, project, playlistName):
        '''Search for a playlist given a project and name
        Parameters : (project, playlistName)
        Output : playlist data:
        ['code', 'description', 'versions', 'created_at', 'sg_cinesync_session_url', 
        'updated_at', 'created_by', 'project', 'filmstrip_image', 'notes', 'image', 
        'updated_by', 'sg_cinesync_session_key', 'sg_status', 'tag_list', 'id', 
        'sg_date_and_time']        
        '''        
        retFields = self.getFields('Playlist')
        return self.sg.find_one('Playlist',[['code','is',playlistName],['project','is',project]],retFields)
    
    def playlistCreate (self, project, playlistName, playlistDescription=''):
        '''Create a playlist given a playlist name
        Parameters : (project, playlistName, playlistDescription='')
        Output : playlist data
        '''        
        data = {'project':project,'code':playlistName, 'description':playlistDescription}
        return self.sg.create('Playlist',data)
    
    # Add a version to a playlist
    def playlistAddVersion (self, project, playlistName, version):
        '''
        Description :\n
        This adds a version (existing version in the system) to a playlist.\n
        You need to give it: (in order)\r
        shotgun connection class\r
        project (dict of the project info including name and id)\r
        playlist name (string of the name of the playlist)\r
        version (dict of the version you wish to add\n
        It will return with a dict of the playlist
        '''
    
        my_playlist_list = self.sg.find_one('Playlist',[['code','is',playlistName],['project','is',project]],['versions']);
        if len(my_playlist_list):
            ver_list = my_playlist_list['versions'];
            ver_list.append({'type':'Version','name':version['code'],'id':version['id']})
            result = self.sg.update('Playlist', my_playlist_list['id'], {'versions' : ver_list})
            return result
    
    def playlistInfo (self, project, playlistName):
        '''Get playlist info (eg version name and description)
        Parameters : (project, playlistName)
        Output : version data
        '''        
        data = []
        versionData = []
        retFields = self.getFields('Version')
        for versionInPlaylist in self.sg.find_one('Playlist',[['code','is',playlistName],['project','is',project]],['versions'])['versions']:
            data.append (self.sg.find_one('Version',[['id','is',versionInPlaylist['id']]],retFields))
        #for items in data:
         #   versionData.append({'name':items['code'],'desc':items['description'],'first_frame':items['self.sg_first_frame})
        return data        
    
    def getTimeShot(self, shot):
        '''Given shot (as dict) return total time on shot as [0] and other times for each task on shot
        '''
        outputData = []
        retFields = ['content','time_logs_sum']
        totalTime = 0
        for curTask in shot['tasks']:
            taskData = self.sg.find_one('Task',[['id','is',curTask['id']]],fields=retFields)
            totalTime += taskData['time_logs_sum']
            outputData.append({'name':taskData['content'],'time':taskData['time_logs_sum']})
        outputData.insert(0,{'name':shot['code'],'time':totalTime})
        return outputData
class StoryboardFileManagement(QWidget):
    def __init__(self, defaultSource = '', parent = None):
        QWidget.__init__(self, parent)
        self.setWindowTitle('StoryBoard File Processing')
        self.parent = parent
        ## Connect to shotgun
    
        from shotgun_api3 import Shotgun

        ## Instance the api for talking directly to shotgun. 
        base_url    = "http://bubblebathbay.shotgunstudio.com"
        script_name = 'audioUploader'
        api_key     = 'bbfc5a7f42364edd915656d7a48d436dc864ae7b48caeb69423a912b930bc76a'
        
        print 'Connecting to shotgun....'
        self.sgsrv = Shotgun(base_url = base_url , script_name = script_name, api_key = api_key, ensure_ascii=True, connect=True)
        
        ## Get the user name
        self.user = getpass.getuser()

        ## Define the variable for the source folder and destination folder (local and remote as it were)
        self.sourceFolder = defaultSource or ''
        self.fileBoxes = []
        
        ## Build the UI
        self.mainLayout = QVBoxLayout(self)
        
        self.epNumLayout = QHBoxLayout()
        self.epNumLabel = QLabel('EpNum:')
        self.epNumber = QLineEdit('', self)
        self.epNumber.setStyleSheet('QLineEdit {background-color: red; border: 2px solid 1 ; border-radius: 6px;}')
        self.epNumber.textChanged.connect(self.epTextChange)   
        self.epNumber.setText('ep')
        
        self.epNumLayout.addWidget(self.epNumLabel)
        self.epNumLayout.addWidget(self.epNumber)

        ## Set the layout for the source text input and browse button        
        self.pathLayout = QHBoxLayout(self)
        self.sourceLabel = QLabel('Set Src Path:')
        ## Define the widgets for this layout
        self.sourceInput = QLineEdit(self)
        self.sourceInput.textChanged.connect(self.doFileCheckboxes)
        self.browseButton = QPushButton('Browse')
        self.browseButton.released.connect(partial(self._browseDialog, dest = False))
        ## Add the widgets to the layout
        self.pathLayout.addWidget(self.sourceLabel)
        self.pathLayout.addWidget(self.sourceInput)       
        self.pathLayout.addWidget(self.browseButton)        
        
        self.optionsLayout = QHBoxLayout(self)
        self.makeSGEntries = QCheckBox(self)
        self.makeSGEntries.setChecked(True)
        self.makeSGEntries.setText('Make SGun Entries?')
        
        self.goButton = QPushButton('Transfer SBrd Files To Episode Version Folders')
        self.goButton.setStyleSheet('QPushButton {background-color: green; border: 2px solid 1 ; border-radius: 6px;}')   
        self.goButton.clicked.connect(self._doit)
        
        self.optionsLayout.addWidget(self.makeSGEntries)
        self.optionsLayout.addWidget(self.goButton)
        
        self.split = HR.Widget_hr()
        self.mainLayout.addWidget(self.split)

        self.mainLayout.addLayout(self.epNumLayout)
        self.mainLayout.addLayout(self.pathLayout)
        self.mainLayout.addLayout(self.optionsLayout)
        
        ### Now do the check boxes for files....
        self.scrollLayout = QScrollArea(self)
        self.scrollLayout.setMinimumHeight(300)
        
        self.filesGroupBox = QGroupBox(self.scrollLayout)
        self.filesGroupBox.setFlat(True)
        
        self.scrollLayout.setWidget(self.filesGroupBox)
        self.scrollLayout.setWidgetResizable(True)
        
        self.fileLayout = QGridLayout(self.filesGroupBox)
        
        self.mainLayout.addWidget(self.scrollLayout)

    def epTextChange(self):
        if len(self.epNumber.text()) > 5:
            self.epNumber.setStyleSheet('QLineEdit {background-color: red; border: 2px solid 1 ; border-radius: 6px;}')
            self.goButton.setStyleSheet('QPushButton {background-color: red; border: 2px solid 1 ; border-radius: 6px;}')   
            self.goButton.setText('BAD EP NUMBER')
            self.goButton.setEnabled(False)
        elif self.epNumber.text() != 'ep' and len(self.epNumber.text()) == 5:
            self.epNumber.setStyleSheet('QLineEdit {background-color: green; border: 2px solid 1 ; border-radius: 6px;}')
            self.goButton.setStyleSheet('QPushButton {background-color: green; border: 2px solid 1 ; border-radius: 6px;}')   
            self.goButton.setText('Transfer SBrd Files To Episode Version Folders')
            self.goButton.setEnabled(True)
        else:
            self.epNumber.setStyleSheet('QLineEdit {background-color: red; border: 2px solid 1 ; border-radius: 6px;}')
            self.goButton.setStyleSheet('QPushButton {background-color: red; border: 2px solid 1 ; border-radius: 6px;}')   
            self.goButton.setText('BAD EP NUMBER')
            self.goButton.setEnabled(False)

    def _toggleAll(self):
        """
        A quick toggle for all the type checkboxes to on or off
        """
        for eachType in self.fileBoxes:
            if eachType.text() == 'ALL':
                if eachType.isChecked():
                    for eachSubType in self.fileBoxes:
                        if eachSubType.text() != 'ALL':
                            eachSubType.setChecked(True)
                else:
                    for eachSubType in self.fileBoxes:
                        if eachSubType.text() != 'ALL':
                            eachSubType.setChecked(False)
                
    def doFileCheckboxes(self, myPath = ''):
        """
        Process all the folders/files found into checkboxes for processing
        """ 
        ## try to get the epNumber from a file
        epNum = str(os.listdir(self.sourceInput.text())[0].split('_')[0])
        if epNum == '.DS' or epNum == '.DS_Store':
            getFiles = os.listdir(self.sourceInput.text())
            for each in getFiles:
                if ".mov" in each:
                    epNum = each.split('_')[0]
        #print 'I AM A BAD NAUGHTY VARIABLE!: %s' % epNum

        if epNum:
            self.epNumber.setText(epNum)
            
        if self.fileBoxes != []:
            for each in self.fileBoxes:
                each.setParent(None)
                sip.delete(each)
                each = None

        self.files = []
        self.fileBoxes = []
       
        ## First add the ALL checkbox
        self.ALL = QCheckBox(self)
        self.ALL.setChecked(False)
        self.ALL.setText('ALL') 
        self.ALL.toggled.connect(self._toggleAll)
        
        self.fileBoxes.append(self.ALL)
        self.fileLayout.addWidget(self.ALL, 0, 0)
        
        ## Now process the folder and add the folders found as checkboxes.
        try:
            if myPath:
                if sys.platform == 'win32':
                    self.sourceFolder = myPath.replace('/', '\\')
                else:
                    self.sourceFolder = myPath
            else:
                self.sourceFolder = str(self.sourceInput.text())

            for eachFile in os.listdir(self.sourceFolder):
                if eachFile.endswith('.mov'):
                    self.files.append(eachFile)
        except:
            self.files =  ['No mov files found...']

        self.colCount = 10
        r = 1
        c = 1
        for eachType in sorted(self.files):
            self.fileCheckBox = QCheckBox(self)
            self.fileCheckBox.setChecked(False)
            self.fileCheckBox.setText(eachType)
            self.fileBoxes.append(self.fileCheckBox)
            if c == self.colCount:
                r = r + 1
                c = 1
            self.fileLayout.addWidget(self.fileCheckBox, r, c)
            c = c + 1

    def _browseDialog(self, dest = False):
        """
        This opens up a QFileDialog hard set to browse into the assets folder by default. 
        @param dest: To set if you are setting the destination input or the source input
        @type dest: Boolean 
        """
        try:
            if sys.platform == 'win32':
                myPath = QFileDialog(self, 'rootDir', 'O:/EPISODE DELIVERY').getExistingDirectory().replace('\\', '/')
            else:
                myPath = QFileDialog(self, 'rootDir', '/Volumes/LemonSky/OUT TO LEMONSKY/EPISODE DELIVERY').getExistingDirectory().replace('\\', '/')
        except :
            myPath = QFileDialog(self, 'rootDir', '').getExistingDirectory().replace('\\', '/')

        ## try to get the epNumber from a file
        epNum = os.listdir(myPath)[0].split('_')[0]
        if epNum:
            self.epNumber.setText(epNum)
        self.sourceInput.setText(myPath)
        self.sourceFolder = str(myPath)
        self.doFileCheckboxes(myPath)
                 
    def _versionUp(self, path):
        return int(max(os.listdir(path)).split('.v')[-1].split('.mov')[0]) + 1 
    
    def addStoryboardVersionToShotgun(self, path, epName, shotName, verNum, fullVersPublishName):
        """
        Function to add the audio asset to shotgun correctly for tasks etc and the pipeline to see it
        """
        #self.shotNum = each.text().split('.mov')[0]
        #self.addStoryboardVersionToShotgun(str(self.shotReviewDir), str(self.epName), self.shotNum, self.vNum, self.shotReviewFileName)
        ## Now start processing stuff..
        self.epName     = epName.lower()
        self.shotName   = shotName.lower()
        self.boardName  = fullVersPublishName.lower()
        self.taskName   = 'StoryBoard'
        self.sg_version = verNum
               
        self.pathToMovie = '%s%s' % (path, self.boardName)
        
        ## First find it the task exists
        self.getShotTasks =  self.sgsrv.find_one('Shot',  filters = [["code", "is", self.shotName]], fields=['id', 'tasks'])
        
        ## Now check and see if the task we need is there...
        self.tasks = []
        self.taskList = []
        if self.getShotTasks:
            for eachTaskDict in self.getShotTasks['tasks']:
                self.tasks.append(eachTaskDict['name'])
                self.taskList.append(eachTaskDict)

            if self.taskName not in self.tasks:
                ## Create new task for the shot
                self.myNewTask = self.sgsrv.create(
                                                   'Task', 
                                                   {
                                                    'project': 
                                                            {
                                                             'type': 'Project',
                                                             'id': 66
                                                             }, 
                                                    'step': {
                                                             'type': 'Step', 
                                                             'id': 72, 
                                                             'name': 'StoryBoard'
                                                            }, 
                                                    'content': 'StoryBoard',
                                                    'sg_status_list': 'apr',
                                                    'template_task': {
                                                                      'type': 'Task', 
                                                                      'id': 31333
                                                                      }
                                                    }
                                                   )
                self.taskId = int(self.myNewTask['id'])
                ## Returns {'project': {'type': 'Project', 'id': 66, 'name': 'bubblebathbay'}, 'step': {'type': 'Step', 'id': 72, 'name': 'StoryBoard'}, 'type': 'Task', 'id': 32335}
                 
                ## Add this dict to the list of dict for updating the shot task list with.
                self.taskList.append({'type': 'Task', 'id': self.myNewTask['id'], 'name': 'StoryBoard'})
    
                ## Now update the shots task list.
                self.sgsrv.update(
                                  'Shot', 
                                  self.getShotTasks['id'], 
                                  {
                                   'project': {
                                               'type':'Project',
                                               'id':66
                                               }, 
                                   'tasks': self.taskList
                                   }
                                  )
                print 'Successfully updated shot %s with task %s' % (self.shotName, self.taskId)
    
                ## Now create a version for this
                print 'Adding version %s to %s now' % (self.boardName, self.shotName)
                data = { 'project': {'type':'Project','id': 66},
                         'code': self.boardName,
                         'description': 'I am not a fluffy bunny!',
                         'sg_path_to_movie': self.pathToMovie,
                         'sg_status_list': 'rev',
                         'entity': {'type':'Shot', 'id':self.getShotTasks['id']},
                         'sg_task': {'type':'Task', 'id':self.taskId},
                         'sg_status_list': 'vwd',
                         'user': {'type':'HumanUser', 'id':53} }
                result = self.sgsrv.create('Version', data)
                
                ## Now upload to shotgun
                print 'Uploading version %s to %s now' % (self.boardName, self.shotName)
                result2 = self.sgsrv.upload("Version", result['id'], self.pathToMovie, "sg_uploaded_movie")
                self._turnOffCheckBox('%s.mov' % self.shotName)
            else:
                ## Get the story board task id
                for eachTask in self.taskList:
                    if eachTask['name'] == 'StoryBoard':
                        self.taskId = eachTask['id']
                
                ## Now create a version for this
                print 'Adding version %s to %s now' % (self.boardName, self.shotName)
                data = { 'project': {'type':'Project','id': 66},
                         'code': self.boardName,
                         'description': 'I am not a fluffy bunny!',
                         'sg_path_to_movie': self.pathToMovie,
                         'sg_status_list': 'rev',
                         'entity': {'type':'Shot', 'id':self.getShotTasks['id']},
                         'sg_task': {'type':'Task', 'id':self.taskId},
                         'sg_status_list': 'vwd',
                         'user': {'type':'HumanUser', 'id': 53} }
                result = self.sgsrv.create('Version', data)
                
                ## Now upload to shotgun
                print 'Uploading version %s to %s now' % (self.boardName, self.shotName)
                result2 = self.sgsrv.upload("Version", result['id'], self.pathToMovie, "sg_uploaded_movie")
                self._turnOffCheckBox('%s.mov' % self.shotName)

        else:
            print 'NO TASKS EXIST FOR %s skipping...' % self.shotName 
            self._turnOffCheckBox('%s.mov' % self.shotName)
        
    def _turnOffCheckBox(self, shotName):
        """
        Func for turning off the uploaded movies as we progress through them so if we error out we have 
        a way to see what has been processed already
        """
        for each in self.fileBoxes:
            if str(each.text()) == shotName:
                each.setChecked(False)
                self.repaint()    

    def _checkTypes(self):
        anythingChecked = False
        if self.fileBoxes:
            for each in self.fileBoxes:
                if each.isChecked():
                    anythingChecked = True
        return anythingChecked

    def _setINPROG(self):
        self.goButton.setText('IN PROGRESS...')
        self.goButton.setStyleSheet('QPushButton {background-color: red; border: 2px solid 1 ; border-radius: 6px;}')
        self.repaint()
        return True
        
    def _doit(self):
        if self._setINPROG():
            if not self._checkTypes():
                self.goButton.setText('OOPS..')
                self.goButton.setStyleSheet('QPushButton {background-color: darkred; border: 2px solid 1 ; border-radius: 6px;}')
                self.reply = QMessageBox.question(self, 'Nope!', "Nothing to transfer. Try selecting something and try again", QMessageBox.Ok)
            else:
                self.processStoryBoardFolder()
    
    def processStoryBoardFolder(self):
        """
        Function to copy over all the audio files from a single output folder into the correct locations for
        the bubblebathbay IDrive audios folders
        @param epNum: The episode name  
        @param pathToFolder: The path to the folder full of wav files you want to copy over.
        @type pathToFolder: String
        @type epNum: String
        NOTE: this tool has been written around the following audio output naming convention from TOONBOOM
        ep106_sh001.wav
        ep106_sh002.wav
        ep106_sh002_A.wav
        """

        if self.epNumber.text() !=  'ep':
            for each in self.fileBoxes:
                if each.isChecked() and each.text() != 'ALL':
                    ## We will always start with a base version number of 0 as the audio files from Toonboom
                    ## Do NOT have any versioning...Therefore iteration folders from toonboom can be correctly versioned into
                    ## the publish wav folders without freaking out....
                    self.vNum = '000'
                    self.epName = str(self.epNumber.text()).lower()
                    self.shotNum = str(each.text()).split('.mov')[0].lower()
                                       
                    if sys.platform == 'win32':
                        self.shotReviewDir = 'I:/lsapipeline/episodes/%s/%s/SBoard/publish/review/' % ( self.epName, self.shotNum)
                    else:
                        self.shotReviewDir = '/Volumes/lsapipeline/episodes/%s/%s/SBoard/publish/review/' % ( self.epName, self.shotNum)
                        
                    self.shotReviewFileName = '%s_BOARD.v%s.mov'  %  (self.shotNum, self.vNum)
                    self.finalPath          = '%s%s' % (self.shotReviewDir, self.shotReviewFileName)       
                    
                    ## Check for folder, if it doesn't exist make it
                    if not os.path.isdir(self.shotReviewDir):
                        os.makedirs(self.shotReviewDir)
                                       
                    ## Now check for existing file, if so version it up just in case so we don't even delete.
                    if os.path.isfile(self.finalPath):
                        newVersNum =  self._versionUp(self.shotReviewDir)
                        if newVersNum <= 10:
                            self.vNum = '00%s' %newVersNum
                        elif newVersNum <= 100:
                            self.vNum = '0%s' %newVersNum
                        else:
                            self.vNum = '%s' %newVersNum
                        ## Now update the name and path vars as final.
                        self.shotReviewFileName = '%s_BOARD.v%s.mov'  %  (self.shotNum, self.vNum)
                        self.finalPath          = '%s%s' % (self.shotReviewDir, self.shotReviewFileName)
                    
                    ## Now get the original path for the audio file we are copying.
                    originalPath = '%s\\%s' % (self.sourceFolder, each.text())
                
                    ## Now perform the copy.
                    shutil.copyfile(originalPath, self.finalPath)
                    #p = subprocess.Popen(cmd, cwd=None, shell=True, bufsize=4096)
                    # Wait until process terminates
                    #while p.poll() is None:
                     #   time.sleep(0.5)
                    print 'Copied file: %s  to \t%s' % (each.text(), self.finalPath)
                    
                    if self.makeSGEntries.isChecked():
                        print 'Adding StoryBoard item to shotgun... %s: ' % self.shotReviewFileName
                        self.addStoryboardVersionToShotgun(str(self.shotReviewDir), str(self.epName), str(self.shotNum), str(self.vNum), str(self.shotReviewFileName))
            
            print 'Finished processing files'
            self.goButton.setText('COMPLETED... click to do over...')
            self.goButton.setStyleSheet('QPushButton {background-color: yellow; border: 2px solid 1 ; border-radius: 6px;}')
        else:
            self.goButton.setText('Invalid Ep Number... click to do over...')
            self.goButton.setStyleSheet('QPushButton {background-color: blue; border: 2px solid 1 ; border-radius: 6px;}')
            print 'You must set a valid episode number!!!'
class StoryboardFileManagement(QWidget):
    def __init__(self, defaultSource='', parent=None):
        QWidget.__init__(self, parent)
        self.setWindowTitle('StoryBoard File Processing')
        self.parent = parent
        ## Connect to shotgun

        from shotgun_api3 import Shotgun

        ## Instance the api for talking directly to shotgun.
        base_url = "http://bubblebathbay.shotgunstudio.com"
        script_name = 'audioUploader'
        api_key = 'bbfc5a7f42364edd915656d7a48d436dc864ae7b48caeb69423a912b930bc76a'

        print 'Connecting to shotgun....'
        self.sgsrv = Shotgun(base_url=base_url,
                             script_name=script_name,
                             api_key=api_key,
                             ensure_ascii=True,
                             connect=True)

        ## Get the user name
        self.user = getpass.getuser()

        ## Define the variable for the source folder and destination folder (local and remote as it were)
        self.sourceFolder = defaultSource or ''
        self.fileBoxes = []

        ## Build the UI
        self.mainLayout = QVBoxLayout(self)

        self.epNumLayout = QHBoxLayout()
        self.epNumLabel = QLabel('EpNum:')
        self.epNumber = QLineEdit('', self)
        self.epNumber.setStyleSheet(
            'QLineEdit {background-color: red; border: 2px solid 1 ; border-radius: 6px;}'
        )
        self.epNumber.textChanged.connect(self.epTextChange)
        self.epNumber.setText('ep')

        self.epNumLayout.addWidget(self.epNumLabel)
        self.epNumLayout.addWidget(self.epNumber)

        ## Set the layout for the source text input and browse button
        self.pathLayout = QHBoxLayout(self)
        self.sourceLabel = QLabel('Set Src Path:')
        ## Define the widgets for this layout
        self.sourceInput = QLineEdit(self)
        self.sourceInput.textChanged.connect(self.doFileCheckboxes)
        self.browseButton = QPushButton('Browse')
        self.browseButton.released.connect(
            partial(self._browseDialog, dest=False))
        ## Add the widgets to the layout
        self.pathLayout.addWidget(self.sourceLabel)
        self.pathLayout.addWidget(self.sourceInput)
        self.pathLayout.addWidget(self.browseButton)

        self.optionsLayout = QHBoxLayout(self)
        self.makeSGEntries = QCheckBox(self)
        self.makeSGEntries.setChecked(True)
        self.makeSGEntries.setText('Make SGun Entries?')

        self.goButton = QPushButton(
            'Transfer SBrd Files To Episode Version Folders')
        self.goButton.setStyleSheet(
            'QPushButton {background-color: green; border: 2px solid 1 ; border-radius: 6px;}'
        )
        self.goButton.clicked.connect(self._doit)

        self.optionsLayout.addWidget(self.makeSGEntries)
        self.optionsLayout.addWidget(self.goButton)

        self.split = HR.Widget_hr()
        self.mainLayout.addWidget(self.split)

        self.mainLayout.addLayout(self.epNumLayout)
        self.mainLayout.addLayout(self.pathLayout)
        self.mainLayout.addLayout(self.optionsLayout)

        ### Now do the check boxes for files....
        self.scrollLayout = QScrollArea(self)
        self.scrollLayout.setMinimumHeight(300)

        self.filesGroupBox = QGroupBox(self.scrollLayout)
        self.filesGroupBox.setFlat(True)

        self.scrollLayout.setWidget(self.filesGroupBox)
        self.scrollLayout.setWidgetResizable(True)

        self.fileLayout = QGridLayout(self.filesGroupBox)

        self.mainLayout.addWidget(self.scrollLayout)

    def epTextChange(self):
        if len(self.epNumber.text()) > 5:
            self.epNumber.setStyleSheet(
                'QLineEdit {background-color: red; border: 2px solid 1 ; border-radius: 6px;}'
            )
            self.goButton.setStyleSheet(
                'QPushButton {background-color: red; border: 2px solid 1 ; border-radius: 6px;}'
            )
            self.goButton.setText('BAD EP NUMBER')
            self.goButton.setEnabled(False)
        elif self.epNumber.text() != 'ep' and len(self.epNumber.text()) == 5:
            self.epNumber.setStyleSheet(
                'QLineEdit {background-color: green; border: 2px solid 1 ; border-radius: 6px;}'
            )
            self.goButton.setStyleSheet(
                'QPushButton {background-color: green; border: 2px solid 1 ; border-radius: 6px;}'
            )
            self.goButton.setText(
                'Transfer SBrd Files To Episode Version Folders')
            self.goButton.setEnabled(True)
        else:
            self.epNumber.setStyleSheet(
                'QLineEdit {background-color: red; border: 2px solid 1 ; border-radius: 6px;}'
            )
            self.goButton.setStyleSheet(
                'QPushButton {background-color: red; border: 2px solid 1 ; border-radius: 6px;}'
            )
            self.goButton.setText('BAD EP NUMBER')
            self.goButton.setEnabled(False)

    def _toggleAll(self):
        """
        A quick toggle for all the type checkboxes to on or off
        """
        for eachType in self.fileBoxes:
            if eachType.text() == 'ALL':
                if eachType.isChecked():
                    for eachSubType in self.fileBoxes:
                        if eachSubType.text() != 'ALL':
                            eachSubType.setChecked(True)
                else:
                    for eachSubType in self.fileBoxes:
                        if eachSubType.text() != 'ALL':
                            eachSubType.setChecked(False)

    def doFileCheckboxes(self, myPath=''):
        """
        Process all the folders/files found into checkboxes for processing
        """
        ## try to get the epNumber from a file
        epNum = str(os.listdir(self.sourceInput.text())[0].split('_')[0])
        if epNum == '.DS' or epNum == '.DS_Store':
            getFiles = os.listdir(self.sourceInput.text())
            for each in getFiles:
                if ".mov" in each:
                    epNum = each.split('_')[0]
        #print 'I AM A BAD NAUGHTY VARIABLE!: %s' % epNum

        if epNum:
            self.epNumber.setText(epNum)

        if self.fileBoxes != []:
            for each in self.fileBoxes:
                each.setParent(None)
                sip.delete(each)
                each = None

        self.files = []
        self.fileBoxes = []

        ## First add the ALL checkbox
        self.ALL = QCheckBox(self)
        self.ALL.setChecked(False)
        self.ALL.setText('ALL')
        self.ALL.toggled.connect(self._toggleAll)

        self.fileBoxes.append(self.ALL)
        self.fileLayout.addWidget(self.ALL, 0, 0)

        ## Now process the folder and add the folders found as checkboxes.
        try:
            if myPath:
                if sys.platform == 'win32':
                    self.sourceFolder = myPath.replace('/', '\\')
                else:
                    self.sourceFolder = myPath
            else:
                self.sourceFolder = str(self.sourceInput.text())

            for eachFile in os.listdir(self.sourceFolder):
                if eachFile.endswith('.mov'):
                    self.files.append(eachFile)
        except:
            self.files = ['No mov files found...']

        self.colCount = 10
        r = 1
        c = 1
        for eachType in sorted(self.files):
            self.fileCheckBox = QCheckBox(self)
            self.fileCheckBox.setChecked(False)
            self.fileCheckBox.setText(eachType)
            self.fileBoxes.append(self.fileCheckBox)
            if c == self.colCount:
                r = r + 1
                c = 1
            self.fileLayout.addWidget(self.fileCheckBox, r, c)
            c = c + 1

    def _browseDialog(self, dest=False):
        """
        This opens up a QFileDialog hard set to browse into the assets folder by default. 
        @param dest: To set if you are setting the destination input or the source input
        @type dest: Boolean 
        """
        try:
            if sys.platform == 'win32':
                myPath = QFileDialog(
                    self, 'rootDir',
                    'O:/EPISODE DELIVERY').getExistingDirectory().replace(
                        '\\', '/')
            else:
                myPath = QFileDialog(
                    self, 'rootDir',
                    '/Volumes/LemonSky/OUT TO LEMONSKY/EPISODE DELIVERY'
                ).getExistingDirectory().replace('\\', '/')
        except:
            myPath = QFileDialog(self, 'rootDir',
                                 '').getExistingDirectory().replace('\\', '/')

        ## try to get the epNumber from a file
        epNum = os.listdir(myPath)[0].split('_')[0]
        if epNum:
            self.epNumber.setText(epNum)
        self.sourceInput.setText(myPath)
        self.sourceFolder = str(myPath)
        self.doFileCheckboxes(myPath)

    def _versionUp(self, path):
        return int(max(os.listdir(path)).split('.v')[-1].split('.mov')[0]) + 1

    def addStoryboardVersionToShotgun(self, path, epName, shotName, verNum,
                                      fullVersPublishName):
        """
        Function to add the audio asset to shotgun correctly for tasks etc and the pipeline to see it
        """
        #self.shotNum = each.text().split('.mov')[0]
        #self.addStoryboardVersionToShotgun(str(self.shotReviewDir), str(self.epName), self.shotNum, self.vNum, self.shotReviewFileName)
        ## Now start processing stuff..
        self.epName = epName.lower()
        self.shotName = shotName.lower()
        self.boardName = fullVersPublishName.lower()
        self.taskName = 'StoryBoard'
        self.sg_version = verNum

        self.pathToMovie = '%s%s' % (path, self.boardName)

        ## First find it the task exists
        self.getShotTasks = self.sgsrv.find_one(
            'Shot',
            filters=[["code", "is", self.shotName]],
            fields=['id', 'tasks'])

        ## Now check and see if the task we need is there...
        self.tasks = []
        self.taskList = []
        if self.getShotTasks:
            for eachTaskDict in self.getShotTasks['tasks']:
                self.tasks.append(eachTaskDict['name'])
                self.taskList.append(eachTaskDict)

            if self.taskName not in self.tasks:
                ## Create new task for the shot
                self.myNewTask = self.sgsrv.create(
                    'Task', {
                        'project': {
                            'type': 'Project',
                            'id': 66
                        },
                        'step': {
                            'type': 'Step',
                            'id': 72,
                            'name': 'StoryBoard'
                        },
                        'content': 'StoryBoard',
                        'sg_status_list': 'apr',
                        'template_task': {
                            'type': 'Task',
                            'id': 31333
                        }
                    })
                self.taskId = int(self.myNewTask['id'])
                ## Returns {'project': {'type': 'Project', 'id': 66, 'name': 'bubblebathbay'}, 'step': {'type': 'Step', 'id': 72, 'name': 'StoryBoard'}, 'type': 'Task', 'id': 32335}

                ## Add this dict to the list of dict for updating the shot task list with.
                self.taskList.append({
                    'type': 'Task',
                    'id': self.myNewTask['id'],
                    'name': 'StoryBoard'
                })

                ## Now update the shots task list.
                self.sgsrv.update(
                    'Shot', self.getShotTasks['id'], {
                        'project': {
                            'type': 'Project',
                            'id': 66
                        },
                        'tasks': self.taskList
                    })
                print 'Successfully updated shot %s with task %s' % (
                    self.shotName, self.taskId)

                ## Now create a version for this
                print 'Adding version %s to %s now' % (self.boardName,
                                                       self.shotName)
                data = {
                    'project': {
                        'type': 'Project',
                        'id': 66
                    },
                    'code': self.boardName,
                    'description': 'I am not a fluffy bunny!',
                    'sg_path_to_movie': self.pathToMovie,
                    'sg_status_list': 'rev',
                    'entity': {
                        'type': 'Shot',
                        'id': self.getShotTasks['id']
                    },
                    'sg_task': {
                        'type': 'Task',
                        'id': self.taskId
                    },
                    'sg_status_list': 'vwd',
                    'user': {
                        'type': 'HumanUser',
                        'id': 53
                    }
                }
                result = self.sgsrv.create('Version', data)

                ## Now upload to shotgun
                print 'Uploading version %s to %s now' % (self.boardName,
                                                          self.shotName)
                result2 = self.sgsrv.upload("Version", result['id'],
                                            self.pathToMovie,
                                            "sg_uploaded_movie")
                self._turnOffCheckBox('%s.mov' % self.shotName)
            else:
                ## Get the story board task id
                for eachTask in self.taskList:
                    if eachTask['name'] == 'StoryBoard':
                        self.taskId = eachTask['id']

                ## Now create a version for this
                print 'Adding version %s to %s now' % (self.boardName,
                                                       self.shotName)
                data = {
                    'project': {
                        'type': 'Project',
                        'id': 66
                    },
                    'code': self.boardName,
                    'description': 'I am not a fluffy bunny!',
                    'sg_path_to_movie': self.pathToMovie,
                    'sg_status_list': 'rev',
                    'entity': {
                        'type': 'Shot',
                        'id': self.getShotTasks['id']
                    },
                    'sg_task': {
                        'type': 'Task',
                        'id': self.taskId
                    },
                    'sg_status_list': 'vwd',
                    'user': {
                        'type': 'HumanUser',
                        'id': 53
                    }
                }
                result = self.sgsrv.create('Version', data)

                ## Now upload to shotgun
                print 'Uploading version %s to %s now' % (self.boardName,
                                                          self.shotName)
                result2 = self.sgsrv.upload("Version", result['id'],
                                            self.pathToMovie,
                                            "sg_uploaded_movie")
                self._turnOffCheckBox('%s.mov' % self.shotName)

        else:
            print 'NO TASKS EXIST FOR %s skipping...' % self.shotName
            self._turnOffCheckBox('%s.mov' % self.shotName)

    def _turnOffCheckBox(self, shotName):
        """
        Func for turning off the uploaded movies as we progress through them so if we error out we have 
        a way to see what has been processed already
        """
        for each in self.fileBoxes:
            if str(each.text()) == shotName:
                each.setChecked(False)
                self.repaint()

    def _checkTypes(self):
        anythingChecked = False
        if self.fileBoxes:
            for each in self.fileBoxes:
                if each.isChecked():
                    anythingChecked = True
        return anythingChecked

    def _setINPROG(self):
        self.goButton.setText('IN PROGRESS...')
        self.goButton.setStyleSheet(
            'QPushButton {background-color: red; border: 2px solid 1 ; border-radius: 6px;}'
        )
        self.repaint()
        return True

    def _doit(self):
        if self._setINPROG():
            if not self._checkTypes():
                self.goButton.setText('OOPS..')
                self.goButton.setStyleSheet(
                    'QPushButton {background-color: darkred; border: 2px solid 1 ; border-radius: 6px;}'
                )
                self.reply = QMessageBox.question(
                    self, 'Nope!',
                    "Nothing to transfer. Try selecting something and try again",
                    QMessageBox.Ok)
            else:
                self.processStoryBoardFolder()

    def processStoryBoardFolder(self):
        """
        Function to copy over all the audio files from a single output folder into the correct locations for
        the bubblebathbay IDrive audios folders
        @param epNum: The episode name  
        @param pathToFolder: The path to the folder full of wav files you want to copy over.
        @type pathToFolder: String
        @type epNum: String
        NOTE: this tool has been written around the following audio output naming convention from TOONBOOM
        ep106_sh001.wav
        ep106_sh002.wav
        ep106_sh002_A.wav
        """

        if self.epNumber.text() != 'ep':
            for each in self.fileBoxes:
                if each.isChecked() and each.text() != 'ALL':
                    ## We will always start with a base version number of 0 as the audio files from Toonboom
                    ## Do NOT have any versioning...Therefore iteration folders from toonboom can be correctly versioned into
                    ## the publish wav folders without freaking out....
                    self.vNum = '000'
                    self.epName = str(self.epNumber.text()).lower()
                    self.shotNum = str(each.text()).split('.mov')[0].lower()

                    if sys.platform == 'win32':
                        self.shotReviewDir = 'I:/lsapipeline/episodes/%s/%s/SBoard/publish/review/' % (
                            self.epName, self.shotNum)
                    else:
                        self.shotReviewDir = '/Volumes/lsapipeline/episodes/%s/%s/SBoard/publish/review/' % (
                            self.epName, self.shotNum)

                    self.shotReviewFileName = '%s_BOARD.v%s.mov' % (
                        self.shotNum, self.vNum)
                    self.finalPath = '%s%s' % (self.shotReviewDir,
                                               self.shotReviewFileName)

                    ## Check for folder, if it doesn't exist make it
                    if not os.path.isdir(self.shotReviewDir):
                        os.makedirs(self.shotReviewDir)

                    ## Now check for existing file, if so version it up just in case so we don't even delete.
                    if os.path.isfile(self.finalPath):
                        newVersNum = self._versionUp(self.shotReviewDir)
                        if newVersNum <= 10:
                            self.vNum = '00%s' % newVersNum
                        elif newVersNum <= 100:
                            self.vNum = '0%s' % newVersNum
                        else:
                            self.vNum = '%s' % newVersNum
                        ## Now update the name and path vars as final.
                        self.shotReviewFileName = '%s_BOARD.v%s.mov' % (
                            self.shotNum, self.vNum)
                        self.finalPath = '%s%s' % (self.shotReviewDir,
                                                   self.shotReviewFileName)

                    ## Now get the original path for the audio file we are copying.
                    originalPath = '%s\\%s' % (self.sourceFolder, each.text())

                    ## Now perform the copy.
                    shutil.copyfile(originalPath, self.finalPath)
                    #p = subprocess.Popen(cmd, cwd=None, shell=True, bufsize=4096)
                    # Wait until process terminates
                    #while p.poll() is None:
                    #   time.sleep(0.5)
                    print 'Copied file: %s  to \t%s' % (each.text(),
                                                        self.finalPath)

                    if self.makeSGEntries.isChecked():
                        print 'Adding StoryBoard item to shotgun... %s: ' % self.shotReviewFileName
                        self.addStoryboardVersionToShotgun(
                            str(self.shotReviewDir), str(self.epName),
                            str(self.shotNum), str(self.vNum),
                            str(self.shotReviewFileName))

            print 'Finished processing files'
            self.goButton.setText('COMPLETED... click to do over...')
            self.goButton.setStyleSheet(
                'QPushButton {background-color: yellow; border: 2px solid 1 ; border-radius: 6px;}'
            )
        else:
            self.goButton.setText('Invalid Ep Number... click to do over...')
            self.goButton.setStyleSheet(
                'QPushButton {background-color: blue; border: 2px solid 1 ; border-radius: 6px;}'
            )
            print 'You must set a valid episode number!!!'
Esempio n. 10
0
class ShotgunUtils():
    '''
    a light version of the shotgun utils class to connect and update shotgun task for external artist
    '''
    def __init__(self):
        '''
        creates the connection to the shotgun site by api
        '''
        '''   shotgun conection '''
        SERVER_PATH = "https://hcpstudio.shotgunstudio.com"
        SCRIPT_NAME = 'Tracker'
        SCRIPT_KEY = '99b5c166044037cc2d04646b1dfd58b2f44e8a146b710b425b8f561f2a21e49d'

        self.sg = Shotgun(SERVER_PATH, SCRIPT_NAME, SCRIPT_KEY)
        self.userId = None
        self.userDic = {}
        self.tasks = None
        self.projectPath = None

    def getsgParameters(self, sgType, parameter=None):
        schema = self.sg.schema_field_read(sgType, parameter)
        print schema

    def getUserId(self, userName):

        filters = [['name', 'is', userName]]
        field = ['id', 'name', 'sg_projectpath', 'sg_keyword', 'login']

        user = self.sg.find_one('HumanUser', filters, field)

        if user:
            self.userId = user['id']
            self.projectPath = user['sg_projectpath']
            self.userDic = user

            return user['id']

        else:
            print "no {0} User found ".format(userName)
            return None

    def taskByUser(self):

        if not self.userId == None:

            filter = [[
                'task_assignees', 'is', {
                    'type': 'HumanUser',
                    'id': self.userId
                }
            ], ['sg_status_list', 'is_not', 'fin'],
                      ['sg_status_list', 'is_not', 'apr'],
                      ['sg_status_list', 'is_not', 'cmpt']]

            fields = [
                'id', 'content', 'sg_status_list', 'start_date', 'due_date',
                'sg_complexity', 'sg_priority_1', 'sg_note', 'project',
                'entity', 'sg_digitalmedia', 'sg_displayname'
            ]

            order = [{
                'field_name': 'due_date',
                'direction': 'asc'
            }, {
                'field_name': 'sg_priority_1',
                'direction': 'asc'
            }, {
                'field_name': 'sg_complexity',
                'direction': 'desc'
            }]

            taskList = self.sg.find('Task', filter, fields, order)

            if taskList:
                self.tasks = taskList
                return taskList

            else:

                self.tasks = []

                print "no task Asigned to: ", self.userId
                return taskList

        else:
            taskList = []

            print "no Id found"
            return taskList

    def getTaskById(self, taskId):

        filter = [['id', 'is', taskId]]

        fields = [
            'id', 'content', 'sg_status_list', 'start_date', 'due_date',
            'sg_complexity', 'sg_priority_1', 'sg_note', 'project', 'entity',
            'sg_digitalmedia', 'sg_displayname'
        ]

        task = self.sg.find_one('Task', filter, fields)

        if task:
            return task

        else:
            print 'no task found'
            return None

    def updateStatusFromUser(self, taskId, status):

        task = self.getTaskById(taskId)

        if task:

            project = task['project']
            sgStatus = status

            data = {'project': project, 'sg_status_list': sgStatus}

            self.sg.update('Task', taskId, data)
            return 1

        else:
            print 'No task by this id'
            return None

    def updateProjectPath(self, projectPath):

        data = {'sg_projectpath': projectPath}

        self.sg.update('HumanUser', self.userId, data)

    def getNotes(self, sgTaskId):

        task = self.getTaskById(sgTaskId)
        if task:
            filters = [['tasks', 'is', task]]
            fields = ['content', 'created_at', 'user', 'addressings_to']
            order = [{'field_name': 'created_at', 'direction': 'asc'}]

            notes = self.sg.find('Note', filters, fields, order)

            return notes

        else:
            print 'no Task'
            return None

    def createNote(self, taskId, content):

        task = self.getTaskById(taskId)

        if task:

            data = {
                'project': task['project'],
                'content': content,
                'tasks': [task],
                'user': self.userDic,
                'subject': 'Note'
            }

            note = self.sg.create('Note', data)
            return note['id']

        else:
            return None

    def uploadAttachment(self, taskId, filePath, tag):

        task = self.getTaskById(taskId)

        if task:

            entity = task['entity']
            if entity:

                entityType = entity['type']
                entityId = entity['id']

                uploadedfile = self.sg.upload(entityType, entityId, filePath)

                if uploadedfile:
                    data = {'sg_type': tag, 'sg_taskid': taskId}
                    self.sg.update('Attachment', uploadedfile, data)
                    return uploadedfile
                else:
                    return None
            else:
                print 'no entity set'
                return None

    def downloadAttachment(self, taskId, downloadPath, parent=None):

        filters = [['sg_taskid', 'is', taskId], ['sg_type', 'is', 'REFERENCE']]
        fields = ['id', 'attachment_links', 'filename', 'created_at']
        attachments = self.sg.find('Attachment', filters, fields)

        if attachments:
            progressBar = QtGui.QProgressBar(parent)
            progressBar.show()
            size = len(attachments)

            for x, attach in enumerate(attachments):

                extension = path.splitext(attach['filename'])
                dt = attach['created_at'].strftime("%Y_%m_%d_%H-%M-%S")
                name = attach['attachment_links'][0]['id']

                namePadded = '{0}_{3}.{1:04d}{2}'.format(
                    name, x, extension[-1], dt)

                fullPath = path.join(downloadPath, namePadded)

                dwFile = self.sg.download_attachment(attach, fullPath,
                                                     attach['id'])

                progressBar.setValue(((x + 1) / size) * 100)

            progressBar.close()
            return attachments
        else:
            return None

    def uploadReference(self, entityType, entityId, filePath, tag, taskId):

        uploadedfile = self.sg.upload(entityType, entityId, filePath)

        if uploadedfile:
            data = {
                'sg_type': tag,
                'sg_type': 'REFERENCE',
                'sg_taskid': taskId
            }
            self.sg.update('Attachment', uploadedfile, data)

            return uploadedfile

        else:
            return None
Esempio n. 11
0
payload = blob['data']

sg = Shotgun(config['shotgun_url'], config['script_name'], config['script_api_key'], 'api3_preview')

if method == 'find':
  result = sg.find(payload['entity'], payload['filters'], payload['fields'], payload['order'], payload['filter_operator'], payload['limit'], payload['retired_only'])
elif method == 'find_one':
  result = sg.find_one(payload['entity'], payload['filters'], payload['fields'], payload['order'], payload['filter_operator'])
elif method == 'create':
  result = sg.create(payload['entity'], payload['data'])
elif method == 'update':
  result = sg.update(payload['entity'], payload['id'], payload['data'])
elif method == 'delete':
  result = sg.delete(payload['entity'], payload['id'])
elif method == 'upload':
  result = sg.upload(payload['entity'], payload['id'], payload['path'], payload['field_name'], payload['display_name'])
elif method == 'upload_thumbnail':
  result = sg.upload_thumbnail(payload['entity'], payload['id'], payload['path'])
elif method == 'schema_field_read':
  result = sg.schema_field_read(payload['entity'])
elif method == 'schema_field_create':
  result = sg.schema_field_create(payload['entity'], payload['type'], payload['name'], payload['attrs'])
elif method == '_url_for_attachment_id':
  entity_id = payload['id']

  # Do a lot of legwork (based on Shotgun.download_attachment())
  sid = sg._get_session_token()
  domain = urlparse(sg.base_url)[1].split(':',1)[0]
  cj = cookielib.LWPCookieJar()
  c = cookielib.Cookie('0', '_session_id', sid, None, False, domain, False, False, "/", True, False, None, True, None, None, {})
  cj.set_cookie(c)
Esempio n. 12
0
        'id': goodID,
        'type': inputType
    },
    'description': description,
    'sg_task': {
        'id': 2252,
        'type': 'Task'
    },
    'user': {
        'id': 88,
        'type': 'HumanUser'
    },
    'sg_status_list': 'rev',
    'project': {
        'id': 110,
        'type': 'Project'
    }
}
result = sg.create("Version", data)
correctPath = False
while correctPath == False:
    file_path = raw_input("Set the file path (include extension):\n")
    if os.path.isfile(file_path):
        sg.upload("Version",
                  result['id'],
                  file_path,
                  field_name="sg_uploaded_movie",
                  display_name="Media")
        correctPath = True
print "All done, enjoy!"
time.sleep(5)
                             v = sg.create('Version', data)
                             if v != None:
                                 vid = v['id']
                                 rps = r.split('/')
                                 # ---------- drive -------- shotgun ------ project ------ scene -------- shot --------- task --------- review
                                 reviewpath = rps[0] + '/' + rps[
                                     1] + '/' + rps[2] + '/' + rps[
                                         3] + '/' + rps[4] + '/' + rps[
                                             5] + '/' + "review" + '/'
                                 if not os.path.exists(reviewpath):
                                     os.mkdir(reviewpath)
                                 reviewvid = reviewpath + os.path.basename(
                                     rvid)
                                 shutil.copy2(rvid, reviewvid)
                                 sg.upload_thumbnail("Version", vid, r)
                                 sg.upload("Version", vid, reviewvid,
                                           'sg_uploaded_movie')
                             else:
                                 print "error: couldn't create new version: %s" % vn
                         else:
                             print "error: can't find task: %s" % tn
                     else:
                         print "error: can't find shot: %s" % sn
                 else:
                     print "error: can't find sequence: %s" % qn
             else:
                 print "error: user %s isn't in shotgun" % un
         else:
             print "error: can't find project: %s" % pn
     else:
         print "error: couldn't make the mp4: %s" % rvid
 else:
    def _moveFilesToPublish(self):
        base_url = "http://bubblebathbay.shotgunstudio.com"
        script_name = 'playBlastPublisher'
        api_key = '718daf67bfd2c7e974f24e7cbd55b86bb101c4e5618e6d5468bc4145840e4558'

        sgsrv = Shotgun(base_url=base_url,
                        script_name=script_name,
                        api_key=api_key,
                        ensure_ascii=True,
                        connect=True)
        selectedShots = [
            item.text(0) for item in self.treeWidgetItems if item.checkState(0)
        ]
        if selectedShots:
            for each in selectedShots:
                episode = each.split('sh')[0]
                shotName = '%s_sh%s' % (each.split('sh')[0],
                                        each.split('sh')[1].split('Lay')[0])
                self.publishPath = self.publishingPath(episode, shotName)
                for root, dirs, files in os.walk(self.shFldPath):
                    for fl in sorted(files):
                        ext = os.path.splitext(fl)[-1]
                        if (fl.endswith('.mov') and
                            (fl
                             == '%s.mov' % each)) or (fl.endswith('.MOV') and
                                                      (fl == "%s.MOV" % each)):
                            srcPath = os.path.join(root, fl)
                            #                             print srcPath, ext
                            self.playblastName = fl
                            while os.path.exists(
                                    os.path.join(self.publishPath, fl)):
                                allFiles = os.listdir(self.publishPath)
                                publishFiles = []
                                if allFiles:
                                    for allFile in allFiles:
                                        if allFile.endswith(ext):
                                            print allFile
                                            publishFiles.append(allFile)
                                versionNumber = int(
                                    sorted(publishFiles)[-1].split('.v')
                                    [1].split(ext)[0])
                                versionNumber += 1
                                if versionNumber < 10:
                                    publishFileName = '%sLayout.v%03d%s' % (
                                        shotName.replace(
                                            '_', ''), versionNumber, ext)
                                    self.publishPath = os.path.join(
                                        self.publishPath, publishFileName)
                                    self.playblastName = os.path.basename(
                                        self.publishPath)
                                else:
                                    publishFileName = '%sLayout.v%02d%s' % (
                                        shotName.replace(
                                            '_', ''), versionNumber, ext)
                                    self.publishPath = os.path.join(
                                        self.publishPath, publishFileName)
                                    self.playblastName = os.path.basename(
                                        self.publishPath)

                            shutil.copy2(srcPath, self.publishPath)

                            publishMovPath = os.path.join(
                                self.publishingPath(episode, shotName),
                                self.playblastName)

                            getShotTasks = sgsrv.find_one(
                                'Shot',
                                filters=[["code", "is", shotName]],
                                fields=['id', 'tasks'])

                            for key, values in getShotTasks.iteritems():
                                if key == 'tasks':
                                    for value in values:
                                        if value['name'] == 'Layout':
                                            self.taskId = value['id']
                            if self.publishPath.endswith('review'):
                                self.publishPath = os.path.join(
                                    self.publishPath, fl)
                                self.playblastName = fl
                            data = {
                                'project': {
                                    'type': 'Project',
                                    'id': 66
                                },
                                'code': self.playblastName,
                                'description': 'Layout playblast published',
                                'sg_path_to_movie': publishMovPath,
                                'sg_status_list': 'rev',
                                'entity': {
                                    'type': 'Shot',
                                    'id': getShotTasks['id']
                                },
                                'sg_task': {
                                    'type': 'Task',
                                    'id': self.taskId
                                },
                                'user': {
                                    'type': 'HumanUser',
                                    'id': 92
                                }
                            }
                            result = sgsrv.create('Version', data)
                            result2 = sgsrv.upload("Version", result['id'],
                                                   publishMovPath,
                                                   "sg_uploaded_movie")
                print "Done"
Esempio n. 15
0
from shotgun_api3 import Shotgun

url = "http://nad.shotgunstudio.com"
script_name = "ThibaultGenericScript"
key = "e014f12acda4074561022f165e8cd1913af2ba4903324a72edbb21430abbb2dc"
project_id = 146 # Demo Project

sg = Shotgun(url, script_name, key)

filename = "Z:/Groupes-cours/NAND999-A15-N01/Nature/assets/mod/.thumb/banc_02_full.jpg"
result = sg.upload("Version",1048,filename,"sg_uploaded_movie")




my_local_file = {
    'attachment_links': [{'type':'Version','id':1048}],
    'project': {'type':'Project','id':146}
    }


asset = sg.find_one("Asset", [["code","is","afficheOeuvre"]], ["code"])

sg_user = sg.find_one('HumanUser', [['login', 'is', "houdon.thibault"]])
data = {
    'project': {'type':'Project','id':project_id},
    'note_links': [asset],
    'user': sg_user,
    'content':'Test',
    'subject':"Thibault's Note on afficheOeuvre"
    }
Esempio n. 16
0
command = [
    'ffmpeg', '-y', '-i', src, '-f', 'webm', '-vcodec', 'libvpx', '-pix_fmt',
    'yuv420p', '-vf', "scale=trunc((a*oh)/2)*2:720", '-g', '30', '-b:v',
    '2000k', '-vpre', '720p', '-quality', 'realtime', '-cpu-used', '0',
    '-qmin', "10", "-qmax", "42", '-acodec', 'libvorbis', '-aq', '60', '-ac',
    '2', dst + '.webm'
]
pipe = sp.Popen(command, stdout=sp.PIPE, bufsize=10**8)

# 另外一种通过subprocess进行转换 webm
# vcodec = "-pix_fmt yuv420p -vcodec libvpx -vf 'scale=trunc((a*oh)/2)*2:720' -g 30 -b:v 2000k -vpre 720p -quality realtime -cpu-used 0 -qmin 10 -qmax 42"
# acodec = "-acodec libvorbis -aq 60 -ac 2"
# subprocess.call(['ffmpeg', '-i', src, vcodec, acodec,'-f webm', dst + '.webm'])

# 序列帧转换参数
# vcodec = "-r frame_count/seconds -i src_file -f image2 thumb_files-%02d.jpeg"

# 将转码完成的mp4,webm上传到Shotgun审看的字段
upload_mp4 = sg.upload('Version', version_id, 'sample.mp4',
                       'sg_uploaded_movie_mp4')
# print(upload_mp4)
upload_webm = sg.upload('Version', version_id, 'sample.webm',
                        'sg_uploaded_movie_webm')
# print(upload_webm)

# 上传缩率图,和filmstrip
upload_thumb = sg.upload_thumbnail("Version", version_id, img)
# print(upload_thumb)
upload_film_thumb = sg.upload_filmstrip_thumbnail("Version", version_id, img)
# print(upload_film_thumb)
Esempio n. 17
0
    },
    'description': description,
    'sg_task': {
        'id': 2252,
        'type': 'Task'
    },
    'user': {
        'id': 92,
        'type': 'HumanUser'
    },
    'sg_status_list': 'rev',
    'project': {
        'id': 110,
        'type': 'Project'
    }
}
try:
    result = sg.create("Version", data)
    print "Creating new version of the %s %s" % (typeToUpload, ID)
    #file_path = 'C:\\Users\\Nacho\\Pictures\\turtle.jpg'
    print "The new version have the ID: %s" % sg.upload(
        "Version",
        result["id"],
        file_path,
        field_name="sg_uploaded_movie",
        display_name="Media")
except Exception as e:
    print e
print "Version added Succesfully. Bye!"
time.sleep(5)
Esempio n. 18
0
efilenames = {}
for efile in efiles:
    efilenames[efile['attachment_links'][0]['name']] = efile['id']
print efilenames
enames = {}
for eper in epers:
    enames[eper['code']] = eper
print enames

pers = glob('pers/*.json')
for per in pers:
    with open(per) as json_data:
        temp = json.load(json_data)
    json_data.close()
    data = {
        'code': temp['name'],
        'description': temp['desc'],
        'sg_arcana': temp['arcana'],
        'sg_level': (int)(temp['level']),
        'sg_json': None
    }
    if temp['name'] not in enames:
        data['project'] = {'type': 'Project', 'id': 70}
        id = sg.create('CustomEntity07', data, ['id'])['id']
    else:
        id = sg.update('CustomEntity07', enames[temp['name']]['id'],
                       data)['id']
        if temp['name'] in efilenames:
            sg.delete('Attachment', efilenames[temp['name']])
    sg.upload('CustomEntity07', id, per, 'sg_json')
Esempio n. 19
0
class studioShotgun(object):
    def __init__(self, path, name, key, project):
        self.SERVER_PATH = path
        self.SCRIPT_NAME = name
        self.SCRIPT_KEY = key
        self.project_id = project
        self.sg = Shotgun(self.SERVER_PATH, self.SCRIPT_NAME, self.SCRIPT_KEY)

    #----------------------------------------------------------------------
    ## set Project id by ID
    def setProjectId(self, newId):
        self.project_id = newId

    #----------------------------------------------------------------------
    ## set Project id by ID
    def setProjectName(self, name):
        newId = 0
        projects = self.sg.find('Project', [], ['name'])
        for project in projects:
            if project['name'] == name:
                newId = project['id']

        self.project_id = newId

    #----------------------------------------------------------------------
    ## find asset by name
    def findAssetByName(self, name):
        fields = ['id', 'code', 'sg_asset_type', 'tasks']
        filters = [[
            'project', 'is', {
                'type': 'Project',
                'id': self.project_id
            }
        ], ['code', 'is', name]]

        result = self.sg.find('Asset', filters, fields)

        return result

    #----------------------------------------------------------------------
    ## find shot by name
    def findShotByName(self, episode, shot):
        fields = ['id', 'code', 'sg_asset_type', 'tasks', 'sg_sequence']
        filters = [[
            'project', 'is', {
                'type': 'Project',
                'id': self.project_id
            }
        ], ['code', 'is', shot]]

        result = self.sg.find('Shot', filters, fields)

        for x in result:
            name = x['sg_sequence']['name'].split('_')[0]
            if name == episode:
                return x

        return []

    #----------------------------------------------------------------------
    ## upload thumbnail to asset
    def uploadThumbnail(self, asset, thumbnail):
        upload = 0
        asset = self.findAssetByName(asset)
        if asset:
            upload = self.sg.upload_thumbnail("Asset", asset[0]['id'],
                                              thumbnail)

        return upload

    #----------------------------------------------------------------------
    ## create new asset
    def createAsset(self,
                    asset,
                    assetType,
                    template,
                    assetFile='',
                    description=''):
        ## find asset
        asset = self.findAssetByName(asset)

        if not asset:
            ## create asset + task template
            filters = [['code', 'is', template]]
            template = self.sg.find_one('TaskTemplate', filters)

            data = {
                'project': {
                    'type': 'Project',
                    'id': self.project_id
                },
                'code': asset,
                'description': description,
                'sg_asset_type': assetType,
                'sg_url_perforce': assetFile,
                'task_template': template
            }

            asset = self.sg.create('Asset', data)

        return asset

    #----------------------------------------------------------------------
    ## update file path in asset
    def updateAssetFilePath(self, asset, filename):
        asset = self.findAssetByName(asset)

        data = {'sg_url_perforce': filename}
        asset = self.sg.update("Asset", asset[0]['id'], data)

        return asset

    #----------------------------------------------------------------------
    ## create new version
    def createVersion(self, shotId, taskId, userId, filename, comment=''):
        curTime = datetime.now().strftime('%Y.%m.%d_%H.%M')
        fname = str(filename.split('/')[-1].split('.')[0]) + '_' + curTime

        data = {
            'project': {
                'type': 'Project',
                'id': self.project_id
            },
            'code': fname,
            'description': comment,
            'sg_status_list': 'rev',
            'entity': {
                'type': 'Shot',
                'id': shotId
            },
            'sg_task': {
                'type': 'Task',
                'id': taskId
            },
            'user': {
                'type': 'HumanUser',
                'id': userId
            }
        }

        result = self.sg.create('Version', data)

        upload = self.sg.upload('Version', result['id'], filename,
                                'sg_uploaded_movie')

        return [result, upload]

    #----------------------------------------------------------------------
    ## get user data from shotgum
    def getUserData(self, user):
        filters = [['login', 'is', user]]
        user = self.sg.find('HumanUser', filters)

        if user:
            return user[0]
        else:
            return []

    #----------------------------------------------------------------------
    ## get all user from project
    def getAllUsers(self):
        fields = ['id', 'login', 'name', 'projects', 'department']
        filters = [[
            'projects', 'is', {
                'type': 'Project',
                'id': self.project_id
            }
        ]]
        users = self.sg.find('HumanUser', filters, fields)

        return users