Example #1
0
def testGetBestReader():
	assert_equals("tuttle.turbojpegreader", tuttle.getBestReader("path/to/image.jpg"))
	assert_equals("tuttle.turbojpegreader", tuttle.getBestReader(".jpg"))
	assert_equals("tuttle.turbojpegreader", tuttle.getBestReader("jpg"))
	assert_equals("tuttle.turbojpegreader", tuttle.getBestReader("JPG"))
	assert_raises(RuntimeError, tuttle.getBestReader, "/JPG")
	assert_raises(RuntimeError, tuttle.getBestReader, "/non/existing/path")

	allJpegReaders = ('tuttle.turbojpegreader', 'tuttle.jpegreader', 'tuttle.oiioreader', 'tuttle.imagemagickreader')
	foundListReaders = tuttle.getReaders("jpg")
	assert_equals(allJpegReaders, foundListReaders)
Example #2
0
def testGetBestReader():
    assert_equals("tuttle.turbojpegreader",
                  tuttle.getBestReader("path/to/image.jpg"))
    assert_equals("tuttle.turbojpegreader", tuttle.getBestReader(".jpg"))
    assert_equals("tuttle.turbojpegreader", tuttle.getBestReader("jpg"))
    assert_equals("tuttle.turbojpegreader", tuttle.getBestReader("JPG"))
    assert_raises(RuntimeError, tuttle.getBestReader, "/JPG")
    assert_raises(RuntimeError, tuttle.getBestReader, "/non/existing/path")

    allJpegReaders = ('tuttle.turbojpegreader', 'tuttle.jpegreader',
                      'tuttle.oiioreader', 'tuttle.imagemagickreader')
    foundListReaders = tuttle.getReaders("jpg")
    assert_equals(allJpegReaders, foundListReaders)
Example #3
0
def getReaderId(inputSequence):
	"""
	Get tuttle node id of best reader for the given sequence.
	"""
        readerNodeId = 0
	try:
		readerNodeId = tuttle.getBestReader(inputSequence)
                return readerNodeId
	except Exception:
		raise ValueError("Could not read input. Please give a filename as first argument.")
Example #4
0
def getReaderId(inputSequence):
    """
	Get tuttle node id of best reader for the given sequence.
	"""
    readerNodeId = 0
    try:
        readerNodeId = tuttle.getBestReader(inputSequence)
        return readerNodeId
    except Exception:
        raise ValueError(
            "Could not read input. Please give a filename as first argument.")
Example #5
0
 def getPluginName(self, logger):
     """
     Return complete node name from the pluginId and its arguments.
     Plugin's arguments can be used to get best reader/writer.
     @note Get best reader if the given name is 'r'.
     @note Get best writer if the given name is 'w'.
     @exception if cannot find the plugin name which corresponds to the plugin id
     """
     if self.isGenericReader() or self.isGenericWriter():
         if len(self._arguments) == 0:
             logger.warning(
                 'Cannot guess the best reader/writer node without any filename specified.'
             )
         # get filename
         filename = self._arguments[0][1]
         # return best reader
         if self.isGenericReader():
             bestReader = tuttle.getBestReader(filename)
             logger.info('Use "' + bestReader + '" to read "' + filename +
                         '".')
             return bestReader
         # return best writer
         elif self.isGenericWriter():
             bestWriter = tuttle.getBestWriter(filename)
             logger.info('Use "' + bestWriter + '" to write "' + filename +
                         '".')
             return bestWriter
     else:
         pluginsMap = tuttle.core().getImageEffectPluginCache(
         ).getPluginsByID()
         # get plugins name which match with the given id
         pluginNames = []
         for pluginName in pluginsMap:
             # if the given id exactly matches the plugin id
             # plugin id = plugin name without its group
             if self._pluginId == pluginName[pluginName.rfind('.') + 1:]:
                 return pluginName
             # else if the given id is contains in the plugin name
             elif self._pluginId in pluginName:
                 pluginNames.append(pluginName)
         # one plugin matches
         if len(pluginNames) == 1:
             return pluginNames[0]
         # more than one matches
         elif len(pluginNames) > 1:
             logger.warning(
                 'Cannot guess the best match for plugin name "' +
                 self._pluginId + '".')
             logger.warning('Possible choices are: "' +
                            ', '.join(pluginNames) + '".')
     # cannot find a best reader/writer or no plugin name matches with the id
     raise RuntimeError('Plugin with id "' + self._pluginId +
                        '" not found.')
Example #6
0
def loadGraph(scene):
    logging.warning("loadGraph : " + str(scene))
    tuttleGraph = tuttle.Graph()

    nodes = []
    for node in scene['nodes']:
        if node['plugin'] == 'reader':
            filename = next(p["value"] for p in node['parameters']
                            if p["id"] == "filename")
            nodePlugin = tuttle.getBestReader(str(filename))
            logging.warning("Auto reader choice: " + nodePlugin)
        elif node['plugin'] == 'writer':
            filename = next(p["value"] for p in node['parameters']
                            if p["id"] == "filename")
            nodePlugin = tuttle.getBestWriter(str(filename))
            logging.warning("Auto reader choice: " + nodePlugin)
        else:
            nodePlugin = str(node['plugin'])

        tuttleNode = tuttleGraph.createNode(nodePlugin)

        node['name'] = tuttleNode.getName()
        for parameter in node['parameters']:
            param = tuttleNode.getParam(str(parameter["id"]))

            # Remap unicode to str. TODO: check if it's still needed.
            if isinstance(parameter["value"], unicode):
                parameter["value"] = str(parameter["value"])

            if isinstance(parameter["value"], list):
                for i, v in enumerate(parameter["value"]):
                    param.setValueAtIndex(i, v, tuttle.eChangeUserEdited)
            else:
                param.setValue(parameter["value"], tuttle.eChangeUserEdited)
        nodes.append(tuttleNode)
        # logging.warning("tuttleNode: " + str(tuttleNode))

    for connection in scene['connections']:
        # TODO: replace src/dst with from/to.
        tuttleGraph.connect([
            nodes[connection['src']['id']],
            nodes[connection['dst']['id']],
        ])

    return tuttleGraph
Example #7
0
 def getPluginName(self, logger):
     """
     Return complete node name from the pluginId and its arguments.
     Plugin's arguments can be used to get best reader/writer.
     @note Get best reader if the given name is 'r'.
     @note Get best writer if the given name is 'w'.
     @exception if cannot find the plugin name which corresponds to the plugin id
     """
     if self.isGenericReader() or self.isGenericWriter():
         if len(self._arguments) == 0:
             logger.warning('Cannot guess the best reader/writer node without any filename specified.')
         # get filename
         filename = self._arguments[0][1]
         # return best reader
         if self.isGenericReader():
             bestReader = tuttle.getBestReader(filename)
             logger.info('Use "' + bestReader + '" to read "' + filename + '".')
             return bestReader
         # return best writer
         elif self.isGenericWriter():
             bestWriter = tuttle.getBestWriter(filename)
             logger.info('Use "' + bestWriter + '" to write "' + filename + '".')
             return bestWriter
     else:
         pluginsMap = tuttle.core().getImageEffectPluginCache().getPluginsByID()
         # get plugins name which match with the given id
         pluginNames = []
         for pluginName in pluginsMap:
             # if the given id exactly matches the plugin id
             # plugin id = plugin name without its group
             if self._pluginId == pluginName[pluginName.rfind('.') + 1:]:
                 return pluginName
             # else if the given id is contains in the plugin name
             elif self._pluginId in pluginName:
                 pluginNames.append(pluginName)
         # one plugin matches
         if len(pluginNames) == 1:
             return pluginNames[0]
         # more than one matches
         elif len(pluginNames) > 1:
             logger.warning('Cannot guess the best match for plugin name "' + self._pluginId +'".')
             logger.warning('Possible choices are: "' + ', '.join(pluginNames) +'".')
     # cannot find a best reader/writer or no plugin name matches with the id
     raise RuntimeError('Plugin with id "' + self._pluginId + '" not found.')
Example #8
0
def loadGraph(scene):
    logging.warning("loadGraph : " + str(scene))
    tuttleGraph = tuttle.Graph()

    nodes = []
    for node in scene['nodes']:
        if node['plugin'] == 'reader':
            filename = next(p["value"] for p in node['parameters'] if p["id"] == "filename")
            nodePlugin = tuttle.getBestReader(str(filename))
            logging.warning("Auto reader choice: " + nodePlugin)
        elif node['plugin'] == 'writer':
            filename = next(p["value"] for p in node['parameters'] if p["id"] == "filename")
            nodePlugin = tuttle.getBestWriter(str(filename))
            logging.warning("Auto reader choice: " + nodePlugin)
        else:
            nodePlugin = str(node['plugin'])

        tuttleNode = tuttleGraph.createNode(nodePlugin)

        node['name'] = tuttleNode.getName()
        for parameter in node['parameters']:
            param = tuttleNode.getParam(str(parameter["id"]))

            # Remap unicode to str. TODO: check if it's still needed.
            if isinstance(parameter["value"], unicode):
                parameter["value"] = str(parameter["value"])

            if isinstance(parameter["value"], list):
                for i, v in enumerate(parameter["value"]):
                    param.setValueAtIndex(i, v, tuttle.eChangeUserEdited)
            else:
                param.setValue(parameter["value"], tuttle.eChangeUserEdited)
        nodes.append(tuttleNode)
        # logging.warning("tuttleNode: " + str(tuttleNode))

    for connection in scene['connections']:
        # TODO: replace src/dst with from/to.
        tuttleGraph.connect([
            nodes[connection['src']['id']],
            nodes[connection['dst']['id']],
        ])

    return tuttleGraph
Example #9
0
def convertScenePatterns(scene):
    '''
    Replace PATTERNS with real filepaths.
    :param scene: dict with nodes, params and connections.
    :return: (scene, outputFilepaths)
    '''
    outputScene = copy.deepcopy(scene)
    # Preload general plugins to use getBestReader/getBestWriter.
    tuttle.core().getPluginCache().addDirectoryToPath(globalOfxPluginPath)
    tuttle.core().preload(False)
    logging.debug("outputScene: " + str(outputScene))

    outputResources = []
    for node in outputScene['nodes']:

        if 'plugin' in node and node['plugin'] is not 'reader':
            logging.debug("Retrieve bundleId from plugin: " +
                          str(node['plugin']))
            resp = requests.get(catalogRootUri + "/bundle/" + node['plugin'] +
                                '/bundle')
            if resp.status_code == 404:
                logging.warning("Cannont retrieve bundleId for plugin: " +
                                str(node['plugin']))
            else:
                respJson = resp.json()
                node["bundleId"] = respJson['bundleId']
                logging.debug("bundleId: " + str(respJson['bundleId']))

        for parameter in node['parameters']:
            logging.warning('param: %s %s', parameter['id'],
                            parameter['value'])
            if isinstance(parameter['value'], (str, unicode)):

                if 'plugin' not in node and '{RESOURCES_DIR}' in parameter[
                        'value']:
                    parameter['value'] = parameter['value'].replace(
                        '{RESOURCES_DIR}', config.resourcesPath)
                    node['plugin'] = tuttle.getBestReader(
                        str(parameter['value']))

                if 'plugin' not in node and '{UNIQUE_OUTPUT_FILE}' in parameter[
                        'value']:
                    node['plugin'] = tuttle.getBestWriter(
                        str(parameter['value']))

    # Declare Bundles paths to TuttleOFX
    bundleIds = []
    for node in outputScene['nodes']:
        if 'bundleId' in node:
            bundleIds.append(node['bundleId'])
        else:
            logging.error("No bundle defined for node: " + str(node))
    bundlePaths = [
        os.path.join(pluginsStorage, str(bundleId)) for bundleId in bundleIds
    ]
    logging.debug("bundlePaths: " + str(bundlePaths))
    configLocalPluginPath(bundlePaths)

    logging.debug("outputScene after conversion: " + str(outputScene))

    # Create a Tuttle Graph to generate the UID for each node
    tuttleGraphTmp = loadGraph(outputScene)
    # logging.warning("tuttleGraphTemp" + str(tuttleGraphTmp))
    # logging.warning("outputScene" + str(outputScene))
    nodesHashMap = tuttle.NodeHashContainer()
    tuttleGraphTmp.computeGlobalHashAtTime(nodesHashMap, 0.0)

    for node in outputScene['nodes']:
        for parameter in node['parameters']:
            logging.warning('param: %s %s', parameter['id'],
                            parameter['value'])
            if isinstance(parameter['value'], (str, unicode)):

                if '{UNIQUE_OUTPUT_FILE}' in parameter['value']:
                    prefix, suffix = parameter['value'].split(
                        '{UNIQUE_OUTPUT_FILE}')
                    nodeHash = str(nodesHashMap.getHash(node['name'], 0.0))
                    node['hash'] = nodeHash
                    filename = nodeHash + suffix
                    filepath = os.path.join(config.renderDirectory,
                                            cache.cachePathFromFile(filename))
                    outputResources.append(filename)
                    parameter['value'] = filepath

    return (outputScene, outputResources)
Example #10
0
if len(argv) != 3:
    print "Script args : [email protected] [email protected]"
    exit()

pathIn = argv[1]
pathOut = argv[2]
# ComputeOption init
co = tuttle.ComputeOptions()
co.setVerboseLevel(tuttle.eVerboseLevelError)
## Create handle and set it in ComputeOptions
handle = ProgressHandle(start)
co.setProgressHandle(handle)
# Create nodes
extIn = os.path.splitext(pathIn)[1]
extOut = os.path.splitext(pathOut)[1]
readerInPlug = tuttle.getBestReader(extIn)
writerOutPlug = tuttle.getBestWriter(extOut)
if len(readerInPlug) == 0:
    print "ERROR: unsupported input file : " + extIn
    exit()
if len(writerOutPlug) == 0:
    print "ERROR: unsupported input file : " + extOut
    exit()
# Create graph
g = tuttle.Graph()
# Creade nodes
print "--- Create read in node : " + pathIn
readerIn = g.createNode(readerInPlug, filename=pathIn).asImageEffectNode()
# Time domain setup
g.setup()
td = readerIn.getTimeDomain()
Example #11
0
def convertScenePatterns(scene):
    '''
    Replace PATTERNS with real filepaths.
    :param scene: dict with nodes, params and connections.
    :return: (scene, outputFilepaths)
    '''
    outputScene = copy.deepcopy(scene)
    # Preload general plugins to use getBestReader/getBestWriter.
    tuttle.core().getPluginCache().addDirectoryToPath(globalOfxPluginPath)
    tuttle.core().preload(False)
    logging.debug("outputScene: " + str(outputScene))

    outputResources = []
    for node in outputScene['nodes']:

        if 'plugin' in node and node['plugin'] is not 'reader':
            logging.debug("Retrieve bundleId from plugin: " + str(node['plugin']))
            resp = requests.get(catalogRootUri + "/bundle/" + node['plugin'] + '/bundle')
            if resp.status_code == 404:
              logging.warning("Cannont retrieve bundleId for plugin: " + str(node['plugin']))
            else:
              respJson = resp.json()
              node["bundleId"] = respJson['bundleId']
              logging.debug("bundleId: " + str(respJson['bundleId']))

        for parameter in node['parameters']:
            logging.warning('param: %s %s', parameter['id'], parameter['value'])
            if isinstance(parameter['value'], (str, unicode)):

                if 'plugin' not in node and '{RESOURCES_DIR}' in parameter['value']:
                    parameter['value'] = parameter['value'].replace('{RESOURCES_DIR}', config.resourcesPath)
                    node['plugin'] = tuttle.getBestReader(str(parameter['value']))

                if 'plugin' not in node and '{UNIQUE_OUTPUT_FILE}' in parameter['value']:
                    node['plugin'] = tuttle.getBestWriter(str(parameter['value']))

    # Declare Bundles paths to TuttleOFX
    bundleIds = []
    for node in outputScene['nodes']:
        if 'bundleId' in node:
            bundleIds.append(node['bundleId'])
        else:
            logging.error("No bundle defined for node: " + str(node))
    bundlePaths = [os.path.join(pluginsStorage, str(bundleId)) for bundleId in bundleIds]
    logging.debug("bundlePaths: " + str(bundlePaths))
    configLocalPluginPath(bundlePaths)

    logging.debug("outputScene after conversion: " + str(outputScene))

    # Create a Tuttle Graph to generate the UID for each node
    tuttleGraphTmp = loadGraph(outputScene)
    # logging.warning("tuttleGraphTemp" + str(tuttleGraphTmp))
    # logging.warning("outputScene" + str(outputScene))
    nodesHashMap = tuttle.NodeHashContainer()
    tuttleGraphTmp.computeGlobalHashAtTime(nodesHashMap, 0.0)

    for node in outputScene['nodes']:
        for parameter in node['parameters']:
            logging.warning('param: %s %s', parameter['id'], parameter['value'])
            if isinstance(parameter['value'], (str, unicode)):

                if '{UNIQUE_OUTPUT_FILE}' in parameter['value']:
                    prefix, suffix = parameter['value'].split('{UNIQUE_OUTPUT_FILE}')
                    nodeHash = str(nodesHashMap.getHash(node['name'], 0.0))
                    node['hash'] = nodeHash
                    filename = nodeHash + suffix
                    filepath = os.path.join(config.renderDirectory, cache.cachePathFromFile(filename))
                    outputResources.append(filename)
                    parameter['value'] = filepath

    return (outputScene, outputResources)
Example #12
0
from pyTuttle import tuttle
tuttle.core().preload(False)

if len(argv) != 4:
    print "Script args : [email protected] movOut.mov lutFile"
    exit()

in_seq = argv[1]
out_mov = argv[2]
lutfile = argv[3]

# Create graph
g = tuttle.Graph()

# Create reader node
reader = g.createNode(tuttle.getBestReader(os.path.splitext(in_seq)[-1]),
                      filename=in_seq).asImageEffectNode()

g.setup()
td = reader.getTimeDomain()
g.setupAtTime(td.min, [reader])

# Create writer node
writer = g.createNode("tuttle.avwriter",filename=out_mov).asImageEffectNode()

# Create LUT node
lut = g.createNode("tuttle.ocio.lut", filename=lutfile)

# Connect nodes
g.connect([reader, lut, writer])
Example #13
0
from pyTuttle import tuttle
tuttle.core().preload(False)

if len(argv) != 4:
    print "Script args : [email protected] movOut.mov lutFile"
    exit()

in_seq = argv[1]
out_mov = argv[2]
lutfile = argv[3]

# Create graph
g = tuttle.Graph()

# Create reader node
reader = g.createNode(tuttle.getBestReader(os.path.splitext(in_seq)[-1]),
                      filename=in_seq).asImageEffectNode()

g.setup()
td = reader.getTimeDomain()
g.setupAtTime(td.min, [reader])

# Create writer node
writer = g.createNode("tuttle.avwriter", filename=out_mov).asImageEffectNode()

# Create LUT node
lut = g.createNode("tuttle.ocio.lut", filename=lutfile)

# Connect nodes
g.connect([reader, lut, writer])