OP-4643 - refactored according to review

Function turned into single filepath input.
This commit is contained in:
Petr Kalis 2023-01-16 18:22:08 +01:00
parent 65b454c42c
commit 9fc4070e06
2 changed files with 57 additions and 58 deletions

View file

@ -1047,12 +1047,12 @@ def convert_ffprobe_fps_to_float(value):
return dividend / divisor return dividend / divisor
def convert_colorspace_for_input_paths( def convert_colorspace(
input_paths, input_path,
output_dir, out_filepath,
config_path, config_path,
source_color_space, source_colorspace,
target_color_space, target_colorspace,
logger=None logger=None
): ):
"""Convert source files from one color space to another. """Convert source files from one color space to another.
@ -1063,13 +1063,13 @@ def convert_colorspace_for_input_paths(
frame template frame template
Args: Args:
input_paths (str): Paths that should be converted. It is expected that input_path (str): Paths that should be converted. It is expected that
contains single file or image sequence of samy type. contains single file or image sequence of samy type.
output_dir (str): Path to directory where output will be rendered. out_filepath (str): Path to directory where output will be rendered.
Must not be same as input's directory. Must not be same as input's directory.
config_path (str): path to OCIO config file config_path (str): path to OCIO config file
source_color_space (str): ocio valid color space of source files source_colorspace (str): ocio valid color space of source files
target_color_space (str): ocio valid target color space target_colorspace (str): ocio valid target color space
logger (logging.Logger): Logger used for logging. logger (logging.Logger): Logger used for logging.
""" """
@ -1083,21 +1083,18 @@ def convert_colorspace_for_input_paths(
# Don't add any additional attributes # Don't add any additional attributes
"--nosoftwareattrib", "--nosoftwareattrib",
"--colorconfig", config_path, "--colorconfig", config_path,
"--colorconvert", source_color_space, target_color_space "--colorconvert", source_colorspace, target_colorspace
] ]
for input_path in input_paths: # Prepare subprocess arguments
# Prepare subprocess arguments
oiio_cmd.extend([ oiio_cmd.extend([
input_arg, input_path, input_arg, input_path,
]) ])
# Add last argument - path to output # Add last argument - path to output
base_filename = os.path.basename(input_path) oiio_cmd.extend([
output_path = os.path.join(output_dir, base_filename) "-o", out_filepath
oiio_cmd.extend([ ])
"-o", output_path
])
logger.debug("Conversion command: {}".format(" ".join(oiio_cmd))) logger.debug("Conversion command: {}".format(" ".join(oiio_cmd)))
run_subprocess(oiio_cmd, logger=logger) run_subprocess(oiio_cmd, logger=logger)

View file

@ -10,7 +10,7 @@ from openpype.lib import (
) )
from openpype.lib.transcoding import ( from openpype.lib.transcoding import (
convert_colorspace_for_input_paths, convert_colorspace,
get_transcode_temp_directory, get_transcode_temp_directory,
) )
@ -69,7 +69,7 @@ class ExtractColorTranscode(publish.Extractor):
continue continue
colorspace_data = repre["colorspaceData"] colorspace_data = repre["colorspaceData"]
source_color_space = colorspace_data["colorspace"] source_colorspace = colorspace_data["colorspace"]
config_path = colorspace_data.get("configData", {}).get("path") config_path = colorspace_data.get("configData", {}).get("path")
if not os.path.exists(config_path): if not os.path.exists(config_path):
self.log.warning("Config file doesn't exist, skipping") self.log.warning("Config file doesn't exist, skipping")
@ -80,8 +80,8 @@ class ExtractColorTranscode(publish.Extractor):
for _, output_def in profile.get("outputs", {}).items(): for _, output_def in profile.get("outputs", {}).items():
new_repre = copy.deepcopy(repre) new_repre = copy.deepcopy(repre)
new_staging_dir = get_transcode_temp_directory()
original_staging_dir = new_repre["stagingDir"] original_staging_dir = new_repre["stagingDir"]
new_staging_dir = get_transcode_temp_directory()
new_repre["stagingDir"] = new_staging_dir new_repre["stagingDir"] = new_staging_dir
files_to_convert = new_repre["files"] files_to_convert = new_repre["files"]
if not isinstance(files_to_convert, list): if not isinstance(files_to_convert, list):
@ -92,27 +92,28 @@ class ExtractColorTranscode(publish.Extractor):
output_extension = output_def["output_extension"] output_extension = output_def["output_extension"]
output_extension = output_extension.replace('.', '') output_extension = output_extension.replace('.', '')
if output_extension: if output_extension:
new_repre["name"] = output_extension if new_repre["name"] == new_repre["ext"]:
new_repre["name"] = output_extension
new_repre["ext"] = output_extension new_repre["ext"] = output_extension
files_to_convert = self._rename_output_files(
files_to_convert, output_extension)
files_to_convert = [os.path.join(original_staging_dir, path)
for path in files_to_convert]
target_colorspace = output_def["output_colorspace"] target_colorspace = output_def["output_colorspace"]
if not target_colorspace: if not target_colorspace:
raise RuntimeError("Target colorspace must be set") raise RuntimeError("Target colorspace must be set")
convert_colorspace_for_input_paths( for file_name in files_to_convert:
files_to_convert, input_filepath = os.path.join(original_staging_dir,
new_staging_dir, file_name)
config_path, output_path = self._get_output_file_path(input_filepath,
source_color_space, new_staging_dir,
target_colorspace, output_extension)
self.log convert_colorspace(
) input_filepath,
output_path,
config_path,
source_colorspace,
target_colorspace,
self.log
)
instance.context.data["cleanupFullPaths"].extend( instance.context.data["cleanupFullPaths"].extend(
files_to_delete) files_to_delete)
@ -130,16 +131,16 @@ class ExtractColorTranscode(publish.Extractor):
instance.data["representations"].append(new_repre) instance.data["representations"].append(new_repre)
def _rename_output_files(self, files_to_convert, output_extension): def _get_output_file_path(self, input_filepath, output_dir,
"""Change extension of converted files.""" output_extension):
renamed_files = [] """Create output file name path."""
for file_name in files_to_convert: file_name = os.path.basename(input_filepath)
file_name, _ = os.path.splitext(file_name) file_name, input_extension = os.path.splitext(file_name)
new_file_name = '{}.{}'.format(file_name, if not output_extension:
output_extension) output_extension = input_extension
renamed_files.append(new_file_name) new_file_name = '{}.{}'.format(file_name,
files_to_convert = renamed_files output_extension)
return files_to_convert return os.path.join(output_dir, new_file_name)
def _get_profile(self, instance): def _get_profile(self, instance):
"""Returns profile if and how repre should be color transcoded.""" """Returns profile if and how repre should be color transcoded."""
@ -161,10 +162,10 @@ class ExtractColorTranscode(publish.Extractor):
if not profile: if not profile:
self.log.info(( self.log.info((
"Skipped instance. None of profiles in presets are for" "Skipped instance. None of profiles in presets are for"
" Host: \"{}\" | Families: \"{}\" | Task \"{}\"" " Host: \"{}\" | Families: \"{}\" | Task \"{}\""
" | Task type \"{}\" | Subset \"{}\" " " | Task type \"{}\" | Subset \"{}\" "
).format(host_name, family, task_name, task_type, subset)) ).format(host_name, family, task_name, task_type, subset))
self.log.debug("profile: {}".format(profile)) self.log.debug("profile: {}".format(profile))
return profile return profile
@ -181,18 +182,19 @@ class ExtractColorTranscode(publish.Extractor):
if repre.get("ext") not in self.supported_exts: if repre.get("ext") not in self.supported_exts:
self.log.debug(( self.log.debug((
"Representation \"{}\" of unsupported extension. Skipped." "Representation '{}' of unsupported extension. Skipped."
).format(repre["name"])) ).format(repre["name"]))
return False return False
if not repre.get("files"): if not repre.get("files"):
self.log.debug(( self.log.debug((
"Representation \"{}\" have empty files. Skipped." "Representation '{}' have empty files. Skipped."
).format(repre["name"])) ).format(repre["name"]))
return False return False
if not repre.get("colorspaceData"): if not repre.get("colorspaceData"):
self.log.debug("Repre has no colorspace data. Skipped.") self.log.debug("Representation '{}' has no colorspace data. "
"Skipped.")
return False return False
return True return True