Skip to content

api

AYON Autodesk Flame api

ClipLoader

Bases: LoaderPlugin

A basic clip loader for Flame

This will implement the basic behavior for a loader to inherit from that will containerize the reference and will implement the remove and update logic.

Source code in client/ayon_flame/api/plugin.py
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
class ClipLoader(LoaderPlugin):
    """A basic clip loader for Flame

    This will implement the basic behavior for a loader to inherit from that
    will containerize the reference and will implement the `remove` and
    `update` logic.

    """
    log = log

    options = [
        qargparse.Boolean(
            "handles",
            label="Set handles",
            default=0,
            help="Also set handles to clip as In/Out marks"
        )
    ]

    _mapping = None
    _host_settings = None

    @classmethod
    def apply_settings(cls, project_settings):

        plugin_type_settings = (
            project_settings
            .get("flame", {})
            .get("load", {})
        )

        if not plugin_type_settings:
            return

        plugin_name = cls.__name__

        plugin_settings = None
        # Look for plugin settings in host specific settings
        if plugin_name in plugin_type_settings:
            plugin_settings = plugin_type_settings[plugin_name]

        if not plugin_settings:
            return

        print(">>> We have preset for {}".format(plugin_name))
        for option, value in plugin_settings.items():
            if option == "enabled" and value is False:
                print("  - is disabled by preset")
            elif option == "representations":
                continue
            else:
                print("  - setting `{}`: `{}`".format(option, value))
            setattr(cls, option, value)

    def get_colorspace(self, context):
        """Get colorspace name

        Look either to version data or representation data.

        Args:
            context (dict): version context data

        Returns:
            str: colorspace name or None
        """
        version_entity = context["version"]
        version_attributes = version_entity["attrib"]
        colorspace = version_attributes.get("colorSpace")

        if (
            not colorspace
            or colorspace == "Unknown"
        ):
            colorspace = context["representation"]["data"].get(
                "colorspace")

        return colorspace

    @classmethod
    def get_native_colorspace(cls, input_colorspace):
        """Return native colorspace name.

        Args:
            input_colorspace (str | None): colorspace name

        Returns:
            str: native colorspace name defined in mapping or None
        """
        # TODO: rewrite to support only pipeline's remapping
        if not cls._host_settings:
            cls._host_settings = get_current_project_settings()["flame"]

        # [Deprecated] way of remapping
        if not cls._mapping:
            mapping = (
                cls._host_settings["imageio"]["profilesMapping"]["inputs"])
            cls._mapping = {
                input["ocioName"]: input["flameName"]
                for input in mapping
            }

        native_name = cls._mapping.get(input_colorspace)

        if not native_name:
            native_name = get_remapped_colorspace_to_native(
                input_colorspace, "flame", cls._host_settings["imageio"])

        return native_name

get_colorspace(context)

Get colorspace name

Look either to version data or representation data.

Parameters:

Name Type Description Default
context dict

version context data

required

Returns:

Name Type Description
str

colorspace name or None

Source code in client/ayon_flame/api/plugin.py
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
def get_colorspace(self, context):
    """Get colorspace name

    Look either to version data or representation data.

    Args:
        context (dict): version context data

    Returns:
        str: colorspace name or None
    """
    version_entity = context["version"]
    version_attributes = version_entity["attrib"]
    colorspace = version_attributes.get("colorSpace")

    if (
        not colorspace
        or colorspace == "Unknown"
    ):
        colorspace = context["representation"]["data"].get(
            "colorspace")

    return colorspace

get_native_colorspace(input_colorspace) classmethod

Return native colorspace name.

Parameters:

Name Type Description Default
input_colorspace str | None

colorspace name

required

Returns:

Name Type Description
str

native colorspace name defined in mapping or None

Source code in client/ayon_flame/api/plugin.py
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
@classmethod
def get_native_colorspace(cls, input_colorspace):
    """Return native colorspace name.

    Args:
        input_colorspace (str | None): colorspace name

    Returns:
        str: native colorspace name defined in mapping or None
    """
    # TODO: rewrite to support only pipeline's remapping
    if not cls._host_settings:
        cls._host_settings = get_current_project_settings()["flame"]

    # [Deprecated] way of remapping
    if not cls._mapping:
        mapping = (
            cls._host_settings["imageio"]["profilesMapping"]["inputs"])
        cls._mapping = {
            input["ocioName"]: input["flameName"]
            for input in mapping
        }

    native_name = cls._mapping.get(input_colorspace)

    if not native_name:
        native_name = get_remapped_colorspace_to_native(
            input_colorspace, "flame", cls._host_settings["imageio"])

    return native_name

FlameCreator

Bases: Creator

Creator class wrapper

Source code in client/ayon_flame/api/plugin.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class FlameCreator(Creator):
    """Creator class wrapper
    """
    settings_category = "flame"

    def __init__(self, *args, **kwargs):
        super(Creator, self).__init__(*args, **kwargs)
        self.presets = get_current_project_settings()[
            "flame"]["create"].get(self.__class__.__name__, {})

    def create(self, product_name, instance_data, pre_create_data):
        """Prepare data for new instance creation.

        Args:
            product_name(str): Product name of created instance.
            instance_data(dict): Base data for instance.
            pre_create_data(dict): Data based on pre creation attributes.
                Those may affect how creator works.
        """
        # adding basic current context resolve objects
        self.project = flib.get_current_project()
        self.sequence = flib.get_current_sequence(flib.CTX.selection)

        selected = pre_create_data.get("use_selection", False)
        self.selected = flib.get_sequence_segments(
            self.sequence,
            selected=selected
        )

create(product_name, instance_data, pre_create_data)

Prepare data for new instance creation.

Parameters:

Name Type Description Default
product_name(str)

Product name of created instance.

required
instance_data(dict)

Base data for instance.

required
pre_create_data(dict)

Data based on pre creation attributes. Those may affect how creator works.

required
Source code in client/ayon_flame/api/plugin.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def create(self, product_name, instance_data, pre_create_data):
    """Prepare data for new instance creation.

    Args:
        product_name(str): Product name of created instance.
        instance_data(dict): Base data for instance.
        pre_create_data(dict): Data based on pre creation attributes.
            Those may affect how creator works.
    """
    # adding basic current context resolve objects
    self.project = flib.get_current_project()
    self.sequence = flib.get_current_sequence(flib.CTX.selection)

    selected = pre_create_data.get("use_selection", False)
    self.selected = flib.get_sequence_segments(
        self.sequence,
        selected=selected
    )

FlameHost

Bases: HostBase, ILoadHost, IPublishHost

Source code in client/ayon_flame/api/pipeline.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class FlameHost(HostBase, ILoadHost, IPublishHost):
    name = "flame"

    # object variables
    _publish_context_data = {}

    def get_containers(self):
        return ls()

    def install(self):
        """Installing all requirements for Nuke host"""
        install()

    def get_context_data(self):
        # TODO: find a way to implement this
        return deepcopy(self._publish_context_data)

    def update_context_data(self, data, changes):
        # TODO: find a way to implement this
        self._publish_context_data = deepcopy(data)

install()

Installing all requirements for Nuke host

Source code in client/ayon_flame/api/pipeline.py
47
48
49
def install(self):
    """Installing all requirements for Nuke host"""
    install()

HiddenFlameCreator

Bases: HiddenCreator

HiddenCreator class wrapper

Source code in client/ayon_flame/api/plugin.py
21
22
23
24
25
26
27
28
29
30
31
32
33
class HiddenFlameCreator(HiddenCreator):
    """HiddenCreator class wrapper
    """
    settings_category = "flame"

    def collect_instances(self):
        pass

    def update_instances(self, update_list):
        pass

    def remove_instances(self, instances):
        pass

MediaInfoFile

Bases: object

Class to get media info file clip data

Raises:

Type Description
IOError

MEDIA_SCRIPT_PATH path doesn't exists

TypeError

Not able to generate clip xml data file

ParseError

Missing clip in xml clip data

IOError

Not able to save xml clip data to file

Attributes:

Name Type Description
str

MEDIA_SCRIPT_PATH path to flame binary

logging.Logger

log logger

TODO: add method for getting metadata to dict

Source code in client/ayon_flame/api/lib.py
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
class MediaInfoFile(object):
    """Class to get media info file clip data

    Raises:
        IOError: MEDIA_SCRIPT_PATH path doesn't exists
        TypeError: Not able to generate clip xml data file
        ET.ParseError: Missing clip in xml clip data
        IOError: Not able to save xml clip data to file

    Attributes:
        str: `MEDIA_SCRIPT_PATH` path to flame binary
        logging.Logger: `log` logger

    TODO: add method for getting metadata to dict
    """
    MEDIA_SCRIPT_PATH = "/opt/Autodesk/mio/current/dl_get_media_info"

    log = log

    _clip_data = None
    _start_frame = None
    _fps = None
    _drop_mode = None
    _file_pattern = None

    def __init__(self, path, logger=None):

        # replace log if any
        if logger:
            self.log = logger

        # test if `dl_get_media_info` path exists
        self._validate_media_script_path()

        # derivate other feed variables
        feed_basename = os.path.basename(path)
        feed_dir = os.path.dirname(path)
        feed_ext = os.path.splitext(feed_basename)[1][1:].lower()

        with maintained_temp_file_path(".clip") as tmp_path:
            self.log.info("Temp File: {}".format(tmp_path))
            self._generate_media_info_file(tmp_path, feed_ext, feed_dir)

            # get collection containing feed_basename from path
            self.file_pattern = self._get_collection(
                feed_basename, feed_dir, feed_ext)

            if (
                not self.file_pattern
                and os.path.exists(os.path.join(feed_dir, feed_basename))
            ):
                self.file_pattern = feed_basename

            # get clip data and make them single if there is multiple
            # clips data
            xml_data = self._make_single_clip_media_info(
                tmp_path, feed_basename, self.file_pattern)
            self.log.debug("xml_data: {}".format(xml_data))
            self.log.debug("type: {}".format(type(xml_data)))

            # get all time related data and assign them
            self._get_time_info_from_origin(xml_data)
            self.log.debug("start_frame: {}".format(self.start_frame))
            self.log.debug("fps: {}".format(self.fps))
            self.log.debug("drop frame: {}".format(self.drop_mode))
            # get all resolution related data and assign them
            self._get_resolution_info_from_origin(xml_data)

            try:
                self.log.debug("width: {}".format(self.width))
                self.log.debug("height: {}".format(self.height))
                self.log.debug("pixel aspect: {}".format(self.pixel_aspect))

            except AttributeError:
                self.log.debug("audio: true")

            self.clip_data = xml_data

    def _get_typed_value(self, xml_obj):
        """ Get typed value from xml object

        Args:
            xml_obj (xml.etree.ElementTree.Element): xml object

        Returns:
            str: value
        """
        if hasattr(xml_obj, "type"):
            if xml_obj.type in ["int", "uint"]:
                return int(xml_obj.text)
            if xml_obj.type == "float":
                return float(xml_obj.text)
            if xml_obj.type == "string":
                return str(xml_obj.text)

        return xml_obj.text

    def _get_collection(self, feed_basename, feed_dir, feed_ext):
        """ Get collection string

        Args:
            feed_basename (str): file base name
            feed_dir (str): file's directory
            feed_ext (str): file extension

        Raises:
            AttributeError: feed_ext is not matching feed_basename

        Returns:
            str: collection basename with range of sequence
        """
        partialname = self._separate_file_head(feed_basename, feed_ext)
        self.log.debug("__ partialname: {}".format(partialname))

        # make sure partial input basename is having correct extensoon
        if not partialname:
            raise AttributeError(
                "Wrong input attributes. Basename - {}, Ext - {}".format(
                    feed_basename, feed_ext
                )
            )

        # get all related files
        files = [
            f for f in os.listdir(feed_dir)
            if partialname == self._separate_file_head(f, feed_ext)
        ]

        # ignore reminders as we dont need them
        collections = clique.assemble(files)[0]

        # in case no collection found return None
        # it is probably just single file
        if not collections:
            return

        # we expect only one collection
        collection = collections[0]

        self.log.debug("__ collection: {}".format(collection))

        if collection.is_contiguous():
            return self._format_collection(collection)

        # add `[` in front to make sure it want capture
        # shot name with the same number
        number_from_path = self._separate_number(feed_basename, feed_ext)
        search_number_pattern = "[" + number_from_path
        # convert to multiple collections
        _continues_colls = collection.separate()
        for _coll in _continues_colls:
            coll_to_text = self._format_collection(
                _coll, len(number_from_path))
            self.log.debug("__ coll_to_text: {}".format(coll_to_text))
            if search_number_pattern in coll_to_text:
                return coll_to_text

    @staticmethod
    def _format_collection(collection, padding=None):
        padding = padding or collection.padding
        # if no holes then return collection
        head = collection.format("{head}")
        tail = collection.format("{tail}")
        range_template = "[{{:0{0}d}}-{{:0{0}d}}]".format(
            padding)
        ranges = range_template.format(
            min(collection.indexes),
            max(collection.indexes)
        )
        # if no holes then return collection
        return "{}{}{}".format(head, ranges, tail)

    def _separate_file_head(self, basename, extension):
        """ Get only head with out sequence and extension

        Args:
            basename (str): file base name
            extension (str): file extension

        Returns:
            str: file head
        """
        # in case sequence file
        found = re.findall(
            r"(.*)[._][\d]*(?=.{})".format(extension),
            basename,
        )
        if found:
            return found.pop()

        # in case single file
        name, ext = os.path.splitext(basename)

        if extension == ext[1:]:
            return name

    def _separate_number(self, basename, extension):
        """ Get only sequence number as string

        Args:
            basename (str): file base name
            extension (str): file extension

        Returns:
            str: number with padding
        """
        # in case sequence file
        found = re.findall(
            r"[._]([\d]*)(?=.{})".format(extension),
            basename,
        )
        if found:
            return found.pop()

    @property
    def clip_data(self):
        """Clip's xml clip data

        Returns:
            xml.etree.ElementTree: xml data
        """
        return self._clip_data

    @clip_data.setter
    def clip_data(self, data):
        self._clip_data = data

    @property
    def start_frame(self):
        """ Clip's starting frame found in timecode

        Returns:
            int: number of frames
        """
        return self._start_frame

    @start_frame.setter
    def start_frame(self, number):
        self._start_frame = int(number)

    @property
    def fps(self):
        """ Clip's frame rate

        Returns:
            float: frame rate
        """
        return self._fps

    @fps.setter
    def fps(self, fl_number):
        self._fps = float(fl_number)

    @property
    def drop_mode(self):
        """ Clip's drop frame mode

        Returns:
            str: drop frame flag
        """
        return self._drop_mode

    @drop_mode.setter
    def drop_mode(self, text):
        self._drop_mode = str(text)

    @property
    def file_pattern(self):
        """Clips file pattern.

        Returns:
            str: file pattern. ex. file.[1-2].exr
        """
        return self._file_pattern

    @file_pattern.setter
    def file_pattern(self, fpattern):
        self._file_pattern = fpattern

    def _validate_media_script_path(self):
        if not os.path.isfile(self.MEDIA_SCRIPT_PATH):
            raise IOError("Media Script does not exist: `{}`".format(
                self.MEDIA_SCRIPT_PATH))

    def _generate_media_info_file(self, fpath, feed_ext, feed_dir):
        """ Generate media info xml .clip file

        Args:
            fpath (str): .clip file path
            feed_ext (str): file extension to be filtered
            feed_dir (str): look up directory

        Raises:
            TypeError: Type error if it fails
        """
        # Create cmd arguments for gettig xml file info file
        cmd_args = [
            self.MEDIA_SCRIPT_PATH,
            "-e", feed_ext,
            "-o", fpath,
            feed_dir
        ]

        try:
            # execute creation of clip xml template data
            run_subprocess(cmd_args)
        except TypeError as error:
            raise TypeError(
                "Error creating `{}` due: {}".format(fpath, error))

    def _make_single_clip_media_info(self, fpath, feed_basename, path_pattern):
        """ Separate only relative clip object form .clip file

        Args:
            fpath (str): clip file path
            feed_basename (str): search basename
            path_pattern (str): search file pattern (file.[1-2].exr)

        Raises:
            ET.ParseError: if nothing found

        Returns:
            ET.Element: xml element data of matching clip
        """
        with open(fpath) as f:
            lines = f.readlines()
            _added_root = itertools.chain(
                "<root>", deepcopy(lines)[1:], "</root>")
            new_root = ET.fromstringlist(_added_root)

        # find the clip which is matching to my input name
        xml_clips = new_root.findall("clip")
        matching_clip = None
        for xml_clip in xml_clips:
            clip_name = xml_clip.find("name").text
            self.log.debug("__ clip_name: `{}`".format(clip_name))
            if clip_name not in feed_basename:
                continue

            # test path pattern
            for out_track in xml_clip.iter("track"):
                for out_feed in out_track.iter("feed"):
                    for span in out_feed.iter("span"):
                        # start frame
                        span_path = span.find("path")
                        self.log.debug(
                            "__ span_path.text: {}, path_pattern: {}".format(
                                span_path.text, path_pattern
                            )
                        )
                        if path_pattern in span_path.text:
                            matching_clip = xml_clip

        if matching_clip is None:
            # return warning there is missing clip
            raise ET.ParseError(
                "Missing clip in `{}`. Available clips {}".format(
                    feed_basename, [
                        xml_clip.find("name").text
                        for xml_clip in xml_clips
                    ]
                ))

        return matching_clip

    def _get_time_info_from_origin(self, xml_data):
        """Set time info to class attributes

        Args:
            xml_data (ET.Element): clip data
        """
        try:
            for out_track in xml_data.iter("track"):
                for out_feed in out_track.iter("feed"):
                    # start frame
                    out_feed_nb_ticks_obj = out_feed.find(
                        "startTimecode/nbTicks")
                    self.start_frame = self._get_typed_value(
                        out_feed_nb_ticks_obj)

                    # fps
                    out_feed_fps_obj = out_feed.find(
                        "startTimecode/rate")
                    self.fps = self._get_typed_value(out_feed_fps_obj)

                    # drop frame mode
                    out_feed_drop_mode_obj = out_feed.find(
                        "startTimecode/dropMode")
                    self.drop_mode = self._get_typed_value(
                        out_feed_drop_mode_obj)
                    break
        except Exception as msg:
            self.log.warning(msg)

    def _get_resolution_info_from_origin(self, xml_data):
        """Set resolution info to class attributes

        Args:
            xml_data (ET.Element): clip data
        """
        try:
            for out_track in xml_data.iter("track"):
                for out_feed in out_track.iter("feed"):
                    # width
                    out_feed_width_obj = out_feed.find("storageFormat/width")
                    self.width = int(self._get_typed_value(out_feed_width_obj))

                    # height
                    out_feed_height_obj = out_feed.find("storageFormat/height")
                    self.height = int(
                        self._get_typed_value(out_feed_height_obj))

                    # pixel aspect ratio
                    out_feed_pixel_aspect_obj = out_feed.find(
                        "storageFormat/pixelRatio")
                    self.pixel_aspect = float(
                        self._get_typed_value(out_feed_pixel_aspect_obj))
                    break
        except Exception as msg:
            self.log.warning(msg)

    @staticmethod
    def write_clip_data_to_file(fpath, xml_element_data):
        """ Write xml element of clip data to file

        Args:
            fpath (string): file path
            xml_element_data (xml.etree.ElementTree.Element): xml data

        Raises:
            IOError: If data could not be written to file
        """
        try:
            # save it as new file
            tree = cET.ElementTree(xml_element_data)
            tree.write(
                fpath, xml_declaration=True,
                method="xml", encoding="UTF-8"
            )
        except IOError as error:
            raise IOError(
                "Not able to write data to file: {}".format(error))

clip_data property writable

Clip's xml clip data

Returns:

Type Description

xml.etree.ElementTree: xml data

drop_mode property writable

Clip's drop frame mode

Returns:

Name Type Description
str

drop frame flag

file_pattern property writable

Clips file pattern.

Returns:

Name Type Description
str

file pattern. ex. file.[1-2].exr

fps property writable

Clip's frame rate

Returns:

Name Type Description
float

frame rate

start_frame property writable

Clip's starting frame found in timecode

Returns:

Name Type Description
int

number of frames

write_clip_data_to_file(fpath, xml_element_data) staticmethod

Write xml element of clip data to file

Parameters:

Name Type Description Default
fpath string

file path

required
xml_element_data Element

xml data

required

Raises:

Type Description
IOError

If data could not be written to file

Source code in client/ayon_flame/api/lib.py
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
@staticmethod
def write_clip_data_to_file(fpath, xml_element_data):
    """ Write xml element of clip data to file

    Args:
        fpath (string): file path
        xml_element_data (xml.etree.ElementTree.Element): xml data

    Raises:
        IOError: If data could not be written to file
    """
    try:
        # save it as new file
        tree = cET.ElementTree(xml_element_data)
        tree.write(
            fpath, xml_declaration=True,
            method="xml", encoding="UTF-8"
        )
    except IOError as error:
        raise IOError(
            "Not able to write data to file: {}".format(error))

OpenClipSolver

Bases: MediaInfoFile

Source code in client/ayon_flame/api/plugin.py
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
class OpenClipSolver(flib.MediaInfoFile):
    create_new_clip = False

    log = log

    def __init__(self, openclip_file_path, feed_data, logger=None):
        self.out_file = openclip_file_path

        # replace log if any
        if logger:
            self.log = logger

        # new feed variables:
        feed_path = feed_data.pop("path")

        # initialize parent class
        super(OpenClipSolver, self).__init__(
            feed_path,
            logger=logger
        )

        # get other metadata
        self.feed_version_name = feed_data["version"]
        self.feed_colorspace = feed_data.get("colorspace")
        self.log.debug("feed_version_name: {}".format(self.feed_version_name))

        # layer rename variables
        self.layer_rename_template = feed_data["layer_rename_template"]
        self.layer_rename_patterns = feed_data["layer_rename_patterns"]
        self.context_data = feed_data["context_data"]

        # derivate other feed variables
        self.feed_basename = os.path.basename(feed_path)
        self.feed_dir = os.path.dirname(feed_path)
        self.feed_ext = os.path.splitext(self.feed_basename)[1][1:].lower()
        self.log.debug("feed_ext: {}".format(self.feed_ext))
        self.log.debug("out_file: {}".format(self.out_file))
        if not self._is_valid_tmp_file(self.out_file):
            self.create_new_clip = True

    def _is_valid_tmp_file(self, file):
        # check if file exists
        if os.path.isfile(file):
            # test also if file is not empty
            with open(file) as f:
                lines = f.readlines()

            if len(lines) > 2:
                return True

            # file is probably corrupted
            os.remove(file)
            return False

    def make(self):

        if self.create_new_clip:
            # New openClip
            self._create_new_open_clip()
        else:
            self._update_open_clip()

    def _clear_handler(self, xml_object):
        for handler in xml_object.findall("./handler"):
            self.log.info("Handler found")
            xml_object.remove(handler)

    def _create_new_open_clip(self):
        self.log.info("Building new openClip")

        for tmp_xml_track in self.clip_data.iter("track"):
            # solve track (layer) name
            self._rename_track_name(tmp_xml_track)

            tmp_xml_feeds = tmp_xml_track.find('feeds')
            tmp_xml_feeds.set('currentVersion', self.feed_version_name)

            for tmp_feed in tmp_xml_track.iter("feed"):
                tmp_feed.set('vuid', self.feed_version_name)

                # add colorspace if any is set
                if self.feed_colorspace:
                    self._add_colorspace(tmp_feed, self.feed_colorspace)

                self._clear_handler(tmp_feed)

        tmp_xml_versions_obj = self.clip_data.find('versions')
        tmp_xml_versions_obj.set('currentVersion', self.feed_version_name)
        for xml_new_version in tmp_xml_versions_obj:
            xml_new_version.set('uid', self.feed_version_name)
            xml_new_version.set('type', 'version')

        self._clear_handler(self.clip_data)
        self.log.info("Adding feed version: {}".format(self.feed_basename))

        self.write_clip_data_to_file(self.out_file, self.clip_data)

    def _get_xml_track_obj_by_uid(self, xml_data, uid):
        # loop all tracks of input xml data
        for xml_track in xml_data.iter("track"):
            track_uid = xml_track.get("uid")
            self.log.debug(
                ">> track_uid:uid: {}:{}".format(track_uid, uid))

            # get matching uids
            if uid == track_uid:
                return xml_track

    def _rename_track_name(self, xml_track_data):
        layer_uid = xml_track_data.get("uid")
        name_obj = xml_track_data.find("name")
        layer_name = name_obj.text

        if (
            self.layer_rename_patterns
            and not any(
                re.search(lp_.lower(), layer_name.lower())
                for lp_ in self.layer_rename_patterns
            )
        ):
            return

        formatting_data = self._update_formatting_data(
            layerName=layer_name,
            layerUID=layer_uid
        )
        name_obj.text = StringTemplate(
            self.layer_rename_template
        ).format(formatting_data)

    def _update_formatting_data(self, **kwargs):
        """ Updating formatting data for layer rename

        Attributes:
            key=value (optional): will be included to formatting data
                                  as {key: value}
        Returns:
            dict: anatomy context data for formatting
        """
        self.log.debug(">> self.clip_data: {}".format(self.clip_data))
        clip_name_obj = self.clip_data.find("name")
        data = {
            "originalBasename": clip_name_obj.text
        }
        # include version context data
        data.update(self.context_data)
        # include input kwargs data
        data.update(kwargs)
        return data

    def _update_open_clip(self):
        self.log.info("Updating openClip ..")

        out_xml = ET.parse(self.out_file)
        out_xml = out_xml.getroot()

        self.log.debug(">> out_xml: {}".format(out_xml))
        # loop tmp tracks
        updated_any = False
        for tmp_xml_track in self.clip_data.iter("track"):
            # solve track (layer) name
            self._rename_track_name(tmp_xml_track)

            # get tmp track uid
            tmp_track_uid = tmp_xml_track.get("uid")
            self.log.debug(">> tmp_track_uid: {}".format(tmp_track_uid))

            # get out data track by uid
            out_track_element = self._get_xml_track_obj_by_uid(
                out_xml, tmp_track_uid)
            self.log.debug(
                ">> out_track_element: {}".format(out_track_element))

            # loop tmp feeds
            for tmp_xml_feed in tmp_xml_track.iter("feed"):
                new_path_obj = tmp_xml_feed.find(
                    "spans/span/path")
                new_path = new_path_obj.text

                # check if feed path already exists in track's feeds
                if (
                    out_track_element is not None
                    and self._feed_exists(out_track_element, new_path)
                ):
                    continue

                # rename versions on feeds
                tmp_xml_feed.set('vuid', self.feed_version_name)
                self._clear_handler(tmp_xml_feed)

                # update fps from MediaInfoFile class
                if self.fps is not None:
                    tmp_feed_fps_obj = tmp_xml_feed.find(
                        "startTimecode/rate")
                    tmp_feed_fps_obj.text = str(self.fps)

                # update start_frame from MediaInfoFile class
                if self.start_frame is not None:
                    tmp_feed_nb_ticks_obj = tmp_xml_feed.find(
                        "startTimecode/nbTicks")
                    tmp_feed_nb_ticks_obj.text = str(self.start_frame)

                # update drop_mode from MediaInfoFile class
                if self.drop_mode is not None:
                    tmp_feed_drop_mode_obj = tmp_xml_feed.find(
                        "startTimecode/dropMode")
                    tmp_feed_drop_mode_obj.text = str(self.drop_mode)

                # add colorspace if any is set
                if self.feed_colorspace is not None:
                    self._add_colorspace(tmp_xml_feed, self.feed_colorspace)

                # then append/update feed to correct track in output
                if out_track_element:
                    self.log.debug("updating track element ..")
                    # update already present track
                    out_feeds = out_track_element.find('feeds')
                    out_feeds.set('currentVersion', self.feed_version_name)
                    out_feeds.append(tmp_xml_feed)

                    self.log.info(
                        "Appending new feed: {}".format(
                            self.feed_version_name))
                else:
                    self.log.debug("adding new track element ..")
                    # create new track as it doesn't exist yet
                    # set current version to feeds on tmp
                    tmp_xml_feeds = tmp_xml_track.find('feeds')
                    tmp_xml_feeds.set('currentVersion', self.feed_version_name)
                    out_tracks = out_xml.find("tracks")
                    out_tracks.append(tmp_xml_track)

                updated_any = True

        if updated_any:
            # Append vUID to versions
            out_xml_versions_obj = out_xml.find('versions')
            out_xml_versions_obj.set(
                'currentVersion', self.feed_version_name)
            new_version_obj = ET.Element(
                "version", {"type": "version", "uid": self.feed_version_name})
            out_xml_versions_obj.insert(0, new_version_obj)

            self._clear_handler(out_xml)

            # fist create backup
            self._create_openclip_backup_file(self.out_file)

            self.log.info("Adding feed version: {}".format(
                self.feed_version_name))

            self.write_clip_data_to_file(self.out_file, out_xml)

            self.log.debug("OpenClip Updated: {}".format(self.out_file))

    def _feed_exists(self, xml_data, path):
        # loop all available feed paths and check if
        # the path is not already in file
        for src_path in xml_data.iter('path'):
            if path == src_path.text:
                self.log.warning(
                    "Not appending file as it already is in .clip file")
                return True

    def _create_openclip_backup_file(self, file):
        bck_file = "{}.bak".format(file)
        # if backup does not exist
        if not os.path.isfile(bck_file):
            shutil.copy2(file, bck_file)
        else:
            # in case it exists and is already multiplied
            created = False
            for _i in range(1, 99):
                bck_file = "{name}.bak.{idx:0>2}".format(
                    name=file,
                    idx=_i)
                # create numbered backup file
                if not os.path.isfile(bck_file):
                    shutil.copy2(file, bck_file)
                    created = True
                    break
            # in case numbered does not exists
            if not created:
                bck_file = "{}.bak.last".format(file)
                shutil.copy2(file, bck_file)

    def _add_colorspace(self, feed_obj, profile_name):
        feed_storage_obj = feed_obj.find("storageFormat")
        feed_clr_obj = feed_storage_obj.find("colourSpace")
        if feed_clr_obj is not None:
            feed_clr_obj = ET.Element(
                "colourSpace", {"type": "string"})
            feed_clr_obj.text = profile_name
            feed_storage_obj.append(feed_clr_obj)

PublishableClip

Convert a segment to publishable instance

Parameters:

Name Type Description Default
segment PySegment

flame api object

required
kwargs optional

additional data needed for rename=True (presets)

required

Returns:

Type Description

flame.PySegment: flame api object

Source code in client/ayon_flame/api/plugin.py
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
class PublishableClip:
    """
    Convert a segment to publishable instance

    Args:
        segment (flame.PySegment): flame api object
        kwargs (optional): additional data needed for rename=True (presets)

    Returns:
        flame.PySegment: flame api object
    """
    vertical_clip_match = {}
    vertical_clip_used = {}
    marker_data = {}
    types = {
        "shot": "shot",
        "folder": "folder",
        "episode": "episode",
        "sequence": "sequence",
        "track": "sequence",
    }

    # parents search pattern
    parents_search_pattern = r"\{([a-z]*?)\}"

    # default templates for non-ui use
    rename_default = False
    hierarchy_default = "{_folder_}/{_sequence_}/{_track_}"
    clip_name_default = "shot_{_trackIndex_:0>3}_{_clipIndex_:0>4}"
    review_source_default = None
    base_product_variant_default = "<track_name>"
    product_type_default = "plate"
    count_from_default = 10
    count_steps_default = 10
    vertical_sync_default = False
    driving_layer_default = ""
    index_from_segment_default = False
    use_shot_name_default = False
    include_handles_default = False
    retimed_handles_default = True
    retimed_framerange_default = True

    def __init__(self,
            segment,
            pre_create_data=None,
            data=None,
            product_type=None,
            rename_index=None,
            log=None,
        ):
        self.rename_index = rename_index
        self.product_type = product_type
        self.log = log
        self.pre_create_data = pre_create_data or {}

        # get main parent objects
        self.current_segment = segment
        sequence_name = flib.get_current_sequence([segment]).name.get_value()
        self.sequence_name = str(sequence_name).replace(" ", "_")
        self.clip_data = flib.get_segment_attributes(segment)

        # segment (clip) main attributes
        self.cs_name = self.clip_data["segment_name"]
        self.cs_index = int(self.clip_data["segment"])
        self.shot_name = self.clip_data["shot_name"]

        # get track name and index
        self.track_index = int(self.clip_data["track"])
        track_name = self.clip_data["track_name"]
        self.track_name = (
            # make sure no space and other special characters are in track name
            # default track name is `*`
            str(track_name)
            .replace(" ", "_")
            .replace("*", f"noname{self.track_index}")
        )

        # add publish attribute to marker data
        self.marker_data.update({"publish": True})

        # adding input data if any
        if data:
            self.marker_data.update(data)

        # populate default data before we get other attributes
        self._populate_segment_default_data()

        # use all populated default data to create all important attributes
        self._populate_attributes()

        # create parents with correct types
        self._create_parents()

    @classmethod
    def restore_all_caches(cls):
        cls.vertical_clip_match = {}
        cls.vertical_clip_used = {}

    def convert(self):

        # solve segment data and add them to marker data
        self._convert_to_marker_data()

        # if track name is in review track name and also if driving track name
        # is not in review track name: skip tag creation
        if (self.track_name in self.reviewable_source) and (
                self.driving_layer not in self.reviewable_source):
            return

        # deal with clip name
        new_name = self.marker_data.pop("newClipName")
        hierarchy_filled = self.marker_data["hierarchy"]

        if self.rename and not self.use_shot_name:
            # rename segment
            self.current_segment.name = str(new_name)
            self.marker_data.update({
                "folderName": str(new_name),
                "folderPath": f"/{hierarchy_filled}/{new_name}"
            })

        elif self.use_shot_name:
            self.marker_data.update({
                "folderName": self.shot_name,
                "folderPath": f"/{hierarchy_filled}/{self.shot_name}",
                "hierarchyData": {
                    "shot": self.shot_name
                }
            })
        else:
            self.marker_data.update({
                "folderName": self.cs_name,
                "folderPath": f"/{hierarchy_filled}/{self.cs_name}",
                "hierarchyData": {
                    "shot": self.cs_name
                }
            })

        return self.current_segment

    def _populate_segment_default_data(self):
        """ Populate default formatting data from segment. """

        self.current_segment_default_data = {
            "_folder_": "shots",
            "_sequence_": self.sequence_name,
            "_track_": self.track_name,
            "_clip_": self.cs_name,
            "_trackIndex_": self.track_index,
            "_clipIndex_": self.cs_index
        }

    def _populate_attributes(self):
        """ Populate main object attributes. """
        # segment frame range and parent track name for vertical sync check
        self.clip_in = int(self.clip_data["record_in"])
        self.clip_out = int(self.clip_data["record_out"])

        # define ui inputs if non gui mode was used
        self.shot_num = self.cs_index
        self.log.debug(f"____ self.shot_num: {self.shot_num}")

        # Use pre-create data or default values if gui was not used
        self.rename = self.pre_create_data.get(
            "clipRename") or self.rename_default
        self.use_shot_name = self.pre_create_data.get(
            "useShotName") or self.use_shot_name_default
        self.clip_name = self.pre_create_data.get(
            "clipName") or self.clip_name_default
        self.hierarchy = self.pre_create_data.get(
            "hierarchy") or self.hierarchy_default
        self.hierarchy_data = self.pre_create_data.get(
            "hierarchyData") or self.current_segment_default_data.copy()
        self.index_from_segment = self.pre_create_data.get(
            "segmentIndex") or self.index_from_segment_default
        self.count_from = self.pre_create_data.get(
            "countFrom") or self.count_from_default
        self.count_steps = self.pre_create_data.get(
            "countSteps") or self.count_steps_default
        self.base_product_variant = self.pre_create_data.get(
            "clipVariant") or self.base_product_variant_default
        self.product_type = (
            self.pre_create_data.get("productType")
            or self.product_type_default
        )
        self.vertical_sync = self.pre_create_data.get(
            "vSyncOn") or self.vertical_sync_default
        self.driving_layer = self.pre_create_data.get(
            "vSyncTrack") or self.driving_layer_default
        self.review_source = self.pre_create_data.get(
            "reviewableSource") or self.review_source_default
        self.audio = self.pre_create_data.get("audio") or False
        self.include_handles = self.pre_create_data.get(
            "includeHandles") or self.include_handles_default
        self.retimed_handles = (
            self.pre_create_data.get("retimedHandles")
            or self.retimed_handles_default
        )
        self.retimed_framerange = (
            self.pre_create_data.get("retimedFramerange")
            or self.retimed_framerange_default
        )

        # build product name from layer name
        if self.base_product_variant == "<track_name>":
            self.variant = self.track_name
        else:
            self.variant = self.base_product_variant

        # create product for publishing
        self.product_name = (
            self.product_type + self.variant.capitalize()
        )

        self.hierarchy_data = {
            key: self.pre_create_data.get(key)
            for key in ["folder", "episode", "sequence", "track", "shot"]
        }

    def _replace_hash_to_expression(self, name, text):
        """ Replace hash with number in correct padding. """
        _spl = text.split("#")
        _len = (len(_spl) - 1)
        _repl = "{{{0}:0>{1}}}".format(name, _len)
        return text.replace(("#" * _len), _repl)

    def _convert_to_marker_data(self):
        """ Convert internal data to marker data.

        Populating the marker data into internal variable self.marker_data
        """
        # define vertical sync attributes
        hero_track = True
        self.reviewable_source = ""

        if (
            self.vertical_sync and
            self.track_name not in self.driving_layer
        ):
            # if it is not then define vertical sync as None
            hero_track = False

        # increasing steps by index of rename iteration
        if not self.index_from_segment:
            self.count_steps *= self.rename_index

        hierarchy_formatting_data = {}
        hierarchy_data = deepcopy(self.hierarchy_data)
        _data = self.current_segment_default_data.copy()

        if self.pre_create_data:

            # backward compatibility for reviewableSource (2024.12.02)
            if "reviewTrack" in self.pre_create_data:
                _value = self.marker_data.pop("reviewTrack")
                self.marker_data["reviewableSource"] = _value

            # driving layer is set as positive match
            if hero_track or self.vertical_sync:
                # mark review layer
                if self.review_source and (
                        self.review_source != self.review_source_default):
                    # if review layer is defined and not the same as default
                    self.reviewable_source  = self.review_source

                # shot num calculate
                if self.index_from_segment:
                    # use clip index from timeline
                    self.shot_num = self.count_steps * self.cs_index
                else:
                    if self.rename_index == 0:
                        self.shot_num = self.count_from
                    else:
                        self.shot_num = self.count_from + self.count_steps

            # clip name sequence number
            _data.update({"shot": self.shot_num})

            # solve # in test to pythonic expression
            for _k, _v in hierarchy_data.items():
                if "#" not in _v:
                    continue
                hierarchy_data[_k] = self._replace_hash_to_expression(_k, _v)

            # fill up pythonic expresisons in hierarchy data
            for k, _v in hierarchy_data.items():
                hierarchy_formatting_data[k] = str(_v).format(**_data)
        else:
            # if no gui mode then just pass default data
            hierarchy_formatting_data = hierarchy_data

        tag_instance_data = self._solve_tag_instance_data(
            hierarchy_formatting_data)

        tag_instance_data.update({"heroTrack": True})
        if hero_track and self.vertical_sync:
            self.vertical_clip_match.update({
                (self.clip_in, self.clip_out): tag_instance_data
            })

        if not hero_track and self.vertical_sync:
            # driving layer is set as negative match
            for (hero_in, hero_out), hero_data in self.vertical_clip_match.items():  # noqa
                """ Iterate over all clips in vertical sync match

                If clip frame range is outside of hero clip frame range
                then skip this clip and do not add to hierarchical shared
                metadata to them.
                """

                if self.clip_in < hero_in or self.clip_out > hero_out:
                    continue

                _distrib_data = deepcopy(hero_data)
                _distrib_data["heroTrack"] = False

                # form used clip unique key
                data_product_name = hero_data["productName"]
                new_clip_name = hero_data["newClipName"]

                # get used names list for duplicity check
                used_names_list = self.vertical_clip_used.setdefault(
                    f"{new_clip_name}{data_product_name}", []
                )
                self.log.debug(
                    f">> used_names_list: {used_names_list}"
                )
                clip_product_name = self.product_name
                variant = self.variant
                self.log.debug(
                    f">> clip_product_name: {clip_product_name}")

                # in case track name and product name is the same then add
                if self.variant == self.track_name:
                    clip_product_name = self.product_name

                # add track index in case duplicity of names in hero data
                # INFO: this is for case where hero clip product name
                #    is the same as current clip product name
                if clip_product_name in data_product_name:
                    clip_product_name = (
                        f"{clip_product_name}{self.track_index}")
                    variant = f"{variant}{self.track_index}"

                # in case track clip product name had been already used
                # then add product name with clip index
                if clip_product_name in used_names_list:
                    _clip_product_name = (
                        f"{clip_product_name}{self.cs_index}"
                    )
                    # just in case lets validate if new name is not used
                    # in case the track_index is the same as clip_index
                    if _clip_product_name in used_names_list:
                        _clip_product_name = (
                            f"{clip_product_name}"
                            f"{self.track_index}{self.cs_index}"
                        )
                    clip_product_name = _clip_product_name
                    variant = f"{variant}{self.cs_index}"

                self.log.debug(
                    f">> clip_product_name: {clip_product_name}")
                _distrib_data["productName"] = clip_product_name
                _distrib_data["variant"] = variant
                # assign data to return hierarchy data to tag
                tag_instance_data = _distrib_data

                # add used product name to used list to avoid duplicity
                used_names_list.append(clip_product_name)
                break

        # add data to return data dict
        self.marker_data.update(tag_instance_data)

        # add review track only to hero track
        if hero_track and self.reviewable_source:
            self.marker_data["reviewTrack"] = self.reviewable_source
        else:
            self.marker_data["reviewTrack"] = None

        # add only review related data if reviewable source is set
        if self.reviewable_source:
            review_switch = True
            reviewable_source = self.reviewable_source

            if self.vertical_sync and not hero_track:
                review_switch = False
                reviewable_source = False

            if review_switch:
                self.marker_data["review"] = True
            else:
                self.marker_data.pop("review", None)

            self.marker_data["reviewableSource"] = reviewable_source

    def _solve_tag_instance_data(self, hierarchy_formatting_data):
        """ Solve marker data from hierarchy data and templates. """
        # fill up clip name and hierarchy keys
        hierarchy_filled = self.hierarchy.format(**hierarchy_formatting_data)
        clip_name_filled = self.clip_name.format(**hierarchy_formatting_data)

        # remove shot from hierarchy data: is not needed anymore
        hierarchy_formatting_data.pop("shot")

        return {
            "newClipName": clip_name_filled,
            "hierarchy": hierarchy_filled,
            "parents": self.parents,
            "hierarchyData": hierarchy_formatting_data,
            "productName": self.product_name,
            "productType": self.product_type_default,
            "variant": self.variant,
        }

    def _convert_to_entity(self, src_type, template):
        """ Converting input key to key with type. """
        # convert to entity type
        folder_type = self.types.get(src_type, None)

        assert folder_type, "Missing folder type for `{}`".format(
            src_type
        )

        # first collect formatting data to use for formatting template
        formatting_data = {}
        for _k, _v in self.hierarchy_data.items():
            value = str(_v).format(
                **self.current_segment_default_data)
            formatting_data[_k] = value

        return {
            "folder_type": folder_type,
            "entity_name": template.format(
                **formatting_data
            )
        }

    def _create_parents(self):
        """ Create parents and return it in list. """
        self.parents = []

        pattern = re.compile(self.parents_search_pattern)

        par_split = [(pattern.findall(t).pop(), t)
                     for t in self.hierarchy.split("/")]

        for type, template in par_split:
            parent = self._convert_to_entity(type, template)
            self.parents.append(parent)

TimeEffectMetadata

Bases: object

Source code in client/ayon_flame/api/lib.py
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
class TimeEffectMetadata(object):
    log = log
    _data = {}
    _retime_modes = {
        0: "speed",
        1: "timewarp",
        2: "duration"
    }

    def __init__(self, segment, logger=None):
        if logger:
            self.log = logger

        self._setup_data, self._data = self._get_metadata(segment)

    @property
    def is_empty(self):
        """ Returns either the current object is empty or not.

        Returns:
            bool. Is the TimeEffectMetadata object empty?
        """
        return self._setup_data is None

    @property
    def data(self):
        """ Returns timewarp effect data

        Returns:
            dict: retime data
        """
        return self._data

    @property
    def setup_data(self):
        """ Returns timewarp effect setup data

        Returns:
            str. The XML formatted setup data.
        """
        return self._setup_data

    def _get_metadata(self, segment):
        effects = segment.effects or []
        for effect in effects:
            if effect.type == "Timewarp":
                with maintained_temp_file_path(".timewarp_node") as tmp_path:
                    self.log.info("Temp File: {}".format(tmp_path))
                    effect.save_setup(tmp_path)
                    return self._get_attributes_from_xml(tmp_path)

        return None, {}

    def _get_attributes_from_xml(self, tmp_path):
        with open(tmp_path, "r") as tw_setup_file:
            tw_setup_string = tw_setup_file.read()
            tw_setup_file.close()

        tw_setup_xml = ET.fromstring(tw_setup_string)
        tw_setup = self._dictify(tw_setup_xml)
        # pprint(tw_setup)
        try:
            tw_setup_state = tw_setup["Setup"]["State"][0]
            mode = int(
                tw_setup_state["TW_RetimerMode"][0]["_text"]
            )
            r_data = {
                "type": self._retime_modes[mode],
                "effectStart": int(
                    tw_setup["Setup"]["Base"][0]["Range"][0]["Start"]),
                "effectEnd": int(
                    tw_setup["Setup"]["Base"][0]["Range"][0]["End"])
            }

            if mode == 0:  # speed
                r_data[self._retime_modes[mode]] = float(
                    tw_setup_state["TW_Speed"]
                    [0]["Channel"][0]["Value"][0]["_text"]
                ) / 100
                r_data["numKeys"] = int(
                    tw_setup_state["TW_SpeedTiming"]
                    [0]["Channel"][0]["Size"][0]["_text"]
                )
            elif mode == 1:  # timewarp
                r_data[self._retime_modes[mode]] = self._get_anim_keys(
                    tw_setup_state["TW_Timing"]
                )
            elif mode == 2:  # duration
                r_data[self._retime_modes[mode]] = {
                    "start": {
                        "source": int(
                            tw_setup_state["TW_DurationTiming"][0]["Channel"]
                            [0]["KFrames"][0]["Key"][0]["Value"][0]["_text"]
                        ),
                        "timeline": int(
                            tw_setup_state["TW_DurationTiming"][0]["Channel"]
                            [0]["KFrames"][0]["Key"][0]["Frame"][0]["_text"]
                        )
                    },
                    "end": {
                        "source": int(
                            tw_setup_state["TW_DurationTiming"][0]["Channel"]
                            [0]["KFrames"][0]["Key"][1]["Value"][0]["_text"]
                        ),
                        "timeline": int(
                            tw_setup_state["TW_DurationTiming"][0]["Channel"]
                            [0]["KFrames"][0]["Key"][1]["Frame"][0]["_text"]
                        )
                    }
                }
        except Exception:
            lines = traceback.format_exception(*sys.exc_info())
            self.log.error("\n".join(lines))
            return None, {}

        return tw_setup_string, r_data

    def _get_anim_keys(self, setup_cat, index=None):
        return_data = {
            "extrapolation": (
                setup_cat[0]["Channel"][0]["Extrap"][0]["_text"]
            ),
            "animKeys": []
        }
        for key in setup_cat[0]["Channel"][0]["KFrames"][0]["Key"]:
            if index and int(key["Index"]) != index:
                continue
            key_data = {
                "source": float(key["Value"][0]["_text"]),
                "timeline": float(key["Frame"][0]["_text"]),
                "index": int(key["Index"]),
                "curveMode": key["CurveMode"][0]["_text"],
                "curveOrder": key["CurveOrder"][0]["_text"]
            }
            if key.get("TangentMode"):
                key_data["tangentMode"] = key["TangentMode"][0]["_text"]

            return_data["animKeys"].append(key_data)

        return return_data

    def _dictify(self, xml_, root=True):
        """ Convert xml object to dictionary

        Args:
            xml_ (xml.etree.ElementTree.Element): xml data
            root (bool, optional): is root available. Defaults to True.

        Returns:
            dict: dictionarized xml
        """

        if root:
            return {xml_.tag: self._dictify(xml_, False)}

        d = copy(xml_.attrib)
        if xml_.text:
            d["_text"] = xml_.text

        for x in xml_.findall("./*"):
            if x.tag not in d:
                d[x.tag] = []
            d[x.tag].append(self._dictify(x, False))
        return d

data property

Returns timewarp effect data

Returns:

Name Type Description
dict

retime data

is_empty property

Returns either the current object is empty or not.

Returns:

Type Description

bool. Is the TimeEffectMetadata object empty?

setup_data property

Returns timewarp effect setup data

Returns:

Type Description

str. The XML formatted setup data.

create_batch_group(name, frame_start, frame_duration, update_batch_group=None, **kwargs)

Create Batch Group in active project's Desktop

Parameters:

Name Type Description Default
name str

name of batch group to be created

required
frame_start int

start frame of batch

required
frame_end int

end frame of batch

required
update_batch_group PyBatch)[optional]

batch group to update

None
Return

PyBatch: active flame batch group

Source code in client/ayon_flame/api/batch_utils.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def create_batch_group(
    name,
    frame_start,
    frame_duration,
    update_batch_group=None,
    **kwargs
):
    """Create Batch Group in active project's Desktop

    Args:
        name (str): name of batch group to be created
        frame_start (int): start frame of batch
        frame_end (int): end frame of batch
        update_batch_group (PyBatch)[optional]: batch group to update

    Return:
        PyBatch: active flame batch group
    """
    # make sure some batch obj is present
    batch_group = update_batch_group or flame.batch

    schematic_reels = kwargs.get("shematic_reels") or ['LoadedReel1']
    shelf_reels = kwargs.get("shelf_reels") or ['ShelfReel1']

    handle_start = kwargs.get("handleStart") or 0
    handle_end = kwargs.get("handleEnd") or 0

    frame_start -= handle_start
    frame_duration += handle_start + handle_end

    if not update_batch_group:
        # Create batch group with name, start_frame value, duration value,
        # set of schematic reel names, set of shelf reel names
        batch_group = batch_group.create_batch_group(
            name,
            start_frame=frame_start,
            duration=frame_duration,
            reels=schematic_reels,
            shelf_reels=shelf_reels
        )
    else:
        batch_group.name = name
        batch_group.start_frame = frame_start
        batch_group.duration = frame_duration

        # add reels to batch group
        _add_reels_to_batch_group(
            batch_group, schematic_reels, shelf_reels)

        # TODO: also update write node if there is any
        # TODO: also update loaders to start from correct frameStart

    if kwargs.get("switch_batch_tab"):
        # use this command to switch to the batch tab
        batch_group.go_to()

    return batch_group

create_batch_group_conent(batch_nodes, batch_links, batch_group=None)

Creating batch group with links

Parameters:

Name Type Description Default
batch_nodes list of dict

each dict is node definition

required
batch_links list of dict

each dict is link definition

required
batch_group PyBatch

batch group. Defaults to None.

None
Return

dict: all batch nodes {name or id: PyNode}

Source code in client/ayon_flame/api/batch_utils.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def create_batch_group_conent(batch_nodes, batch_links, batch_group=None):
    """Creating batch group with links

    Args:
        batch_nodes (list of dict): each dict is node definition
        batch_links (list of dict): each dict is link definition
        batch_group (PyBatch, optional): batch group. Defaults to None.

    Return:
        dict: all batch nodes {name or id: PyNode}
    """
    # make sure some batch obj is present
    batch_group = batch_group or flame.batch
    all_batch_nodes = {
        b.name.get_value(): b
        for b in batch_group.nodes
    }
    for node in batch_nodes:
        # NOTE: node_props needs to be ideally OrederDict type
        node_id, node_type, node_props = (
            node["id"], node["type"], node["properties"])

        # get node name for checking if exists
        node_name = node_props.pop("name", None) or node_id

        if all_batch_nodes.get(node_name):
            # update existing batch node
            batch_node = all_batch_nodes[node_name]
        else:
            # create new batch node
            batch_node = batch_group.create_node(node_type)

            # set name
            batch_node.name.set_value(node_name)

        # set attributes found in node props
        for key, value in node_props.items():
            if not hasattr(batch_node, key):
                continue
            setattr(batch_node, key, value)

        # add created node for possible linking
        all_batch_nodes[node_id] = batch_node

    # link nodes to each other
    for link in batch_links:
        _from_n, _to_n = link["from_node"], link["to_node"]

        # check if all linking nodes are available
        if not all([
            all_batch_nodes.get(_from_n["id"]),
            all_batch_nodes.get(_to_n["id"])
        ]):
            continue

        # link nodes in defined link
        batch_group.connect_nodes(
            all_batch_nodes[_from_n["id"]], _from_n["connector"],
            all_batch_nodes[_to_n["id"]], _to_n["connector"]
        )

    # sort batch nodes
    batch_group.organize()

    return all_batch_nodes

create_segment_data_marker(segment)

Create AYON marker on a segment.

Attributes:

Name Type Description
segment PySegment

flame api object

Returns:

Type Description

flame.PyMarker: flame api object

Source code in client/ayon_flame/api/lib.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
def create_segment_data_marker(segment):
    """ Create AYON marker on a segment.

    Attributes:
        segment (flame.PySegment): flame api object

    Returns:
        flame.PyMarker: flame api object
    """
    # get duration of segment
    duration = segment.record_duration.relative_frame
    # calculate start frame of the new marker
    start_frame = int(segment.record_in.relative_frame) + int(duration / 2)
    # create marker
    marker = segment.create_marker(start_frame)
    # set marker name
    marker.name = MARKER_NAME
    # set duration
    marker.duration = MARKER_DURATION
    # set colour
    marker.colour = COLOR_MAP[MARKER_COLOR]  # Red

    return marker

export_clip(export_path, clip, preset_path, **kwargs)

Flame exported wrapper

Parameters:

Name Type Description Default
export_path str

exporting directory path

required
clip PyClip

flame api object

required
preset_path str

full export path to xml file

required
Kwargs

thumb_frame_number (int)[optional]: source frame number in_mark (int)[optional]: cut in mark out_mark (int)[optional]: cut out mark

Raises:

Type Description
KeyError

Missing input kwarg thumb_frame_number in case thumbnail in export_preset

FileExistsError

Missing export preset in shared folder

Source code in client/ayon_flame/api/render_utils.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def export_clip(export_path, clip, preset_path, **kwargs):
    """Flame exported wrapper

    Args:
        export_path (str): exporting directory path
        clip (PyClip): flame api object
        preset_path (str): full export path to xml file

    Kwargs:
        thumb_frame_number (int)[optional]: source frame number
        in_mark (int)[optional]: cut in mark
        out_mark (int)[optional]: cut out mark

    Raises:
        KeyError: Missing input kwarg `thumb_frame_number`
                  in case `thumbnail` in `export_preset`
        FileExistsError: Missing export preset in shared folder
    """
    import flame

    in_mark = out_mark = None

    # Set exporter
    exporter = flame.PyExporter()
    exporter.foreground = True
    exporter.export_between_marks = True

    if kwargs.get("thumb_frame_number"):
        thumb_frame_number = kwargs["thumb_frame_number"]
        # make sure it exists in kwargs
        if not thumb_frame_number:
            raise KeyError(
                "Missing key `thumb_frame_number` in input kwargs")

        in_mark = int(thumb_frame_number)
        out_mark = int(thumb_frame_number) + 1

    elif kwargs.get("in_mark") and kwargs.get("out_mark"):
        in_mark = int(kwargs["in_mark"])
        out_mark = int(kwargs["out_mark"])
    else:
        exporter.export_between_marks = False

    try:
        # set in and out marks if they are available
        if in_mark and out_mark:
            clip.in_mark = in_mark
            clip.out_mark = out_mark

        # export with exporter
        exporter.export(clip, preset_path, export_path)
    finally:
        print('Exported: {} at {}-{}'.format(
            clip.name.get_value(),
            clip.in_mark,
            clip.out_mark
        ))

get_frame_from_filename(filename)

Return sequence number from Flame path style

Parameters:

Name Type Description Default
filename str

file name

required

Returns:

Name Type Description
int

sequence frame number

Example

def get_frame_from_filename(path): ("plate.0001.exr") > 0001

Source code in client/ayon_flame/api/lib.py
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
def get_frame_from_filename(filename):
    """
    Return sequence number from Flame path style

    Args:
        filename (str): file name

    Returns:
        int: sequence frame number

    Example:
        def get_frame_from_filename(path):
            ("plate.0001.exr") > 0001

    """

    found = re.findall(FRAME_PATTERN, filename)

    return found.pop() if found else None

get_padding_from_filename(filename)

Return padding number from Flame path style

Parameters:

Name Type Description Default
filename str

file name

required

Returns:

Name Type Description
int

padding number

Example

get_padding_from_filename("plate.0001.exr") > 4

Source code in client/ayon_flame/api/lib.py
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
def get_padding_from_filename(filename):
    """
    Return padding number from Flame path style

    Args:
        filename (str): file name

    Returns:
        int: padding number

    Example:
        get_padding_from_filename("plate.0001.exr") > 4

    """
    found = get_frame_from_filename(filename)

    return len(found) if found else None

get_publish_attribute(segment)

Get Publish attribute from input Tag object

Attribute

segment (flame.PySegment)): flame api object

Returns:

Name Type Description
bool

True or False

Source code in client/ayon_flame/api/lib.py
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def get_publish_attribute(segment):
    """ Get Publish attribute from input Tag object

    Attribute:
        segment (flame.PySegment)): flame api object

    Returns:
        bool: True or False
    """
    tag_data = get_segment_data_marker(segment)

    if not tag_data:
        set_publish_attribute(segment, MARKER_PUBLISH_DEFAULT)
        return MARKER_PUBLISH_DEFAULT

    return tag_data["publish"]

get_reformatted_filename(filename, padded=True)

Return fixed python expression path

Parameters:

Name Type Description Default
filename str

file name

required

Returns:

Name Type Description
type

string with reformatted path

Example

get_reformatted_filename("plate.1001.exr") > plate.%04d.exr

Source code in client/ayon_flame/api/lib.py
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
def get_reformatted_filename(filename, padded=True):
    """
    Return fixed python expression path

    Args:
        filename (str): file name

    Returns:
        type: string with reformatted path

    Example:
        get_reformatted_filename("plate.1001.exr") > plate.%04d.exr

    """
    found = FRAME_PATTERN.search(filename)

    if not found:
        log.info("File name is not sequence: {}".format(filename))
        return filename

    padding = get_padding_from_filename(filename)

    replacement = "%0{}d".format(padding) if padded else "%d"
    start_idx, end_idx = found.span(1)

    return replacement.join(
        [filename[:start_idx], filename[end_idx:]]
    )

get_segment_data_marker(segment, with_marker=None)

Get AYON track item tag created by creator or loader plugin.

Attributes:

Name Type Description
segment PySegment

flame api object

with_marker bool)[optional]

if true it will return also marker object

Returns:

Name Type Description
dict

AYON tag data

Returns(with_marker=True): flame.PyMarker, dict

Source code in client/ayon_flame/api/lib.py
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
def get_segment_data_marker(segment, with_marker=None):
    """
    Get AYON track item tag created by creator or loader plugin.

    Attributes:
        segment (flame.PySegment): flame api object
        with_marker (bool)[optional]: if true it will return also marker object

    Returns:
        dict: AYON tag data

    Returns(with_marker=True):
        flame.PyMarker, dict
    """
    for marker in segment.markers:
        comment = marker.comment.get_value()
        color = marker.colour.get_value()
        name = marker.name.get_value()

        if (name == MARKER_NAME) and (
                color == COLOR_MAP[MARKER_COLOR]):
            if not with_marker:
                return json.loads(comment)
            else:
                return marker, json.loads(comment)

imprint(segment, data=None)

Adding AYON data to Flame timeline segment.

Also including publish attribute into tag.

Parameters:

Name Type Description Default
segment PySegment

flame api object

required
data dict

Any data which needst to be imprinted

None

Examples:

data = { 'asset': 'sq020sh0280', 'productType': 'render', 'productName': 'productMain' }

Source code in client/ayon_flame/api/pipeline.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def imprint(segment, data=None):
    """
    Adding AYON data to Flame timeline segment.

    Also including publish attribute into tag.

    Arguments:
        segment (flame.PySegment)): flame api object
        data (dict): Any data which needst to be imprinted

    Examples:
        data = {
            'asset': 'sq020sh0280',
            'productType': 'render',
            'productName': 'productMain'
        }
    """
    data = data or {}

    set_segment_data_marker(segment, data)

    # add publish attribute
    set_publish_attribute(segment, True)

list_instances()

List all created instances from current workfile.

Source code in client/ayon_flame/api/pipeline.py
151
152
153
154
def list_instances():
    """List all created instances from current workfile."""
    # TODO: list_instances
    pass

ls()

List available containers.

Source code in client/ayon_flame/api/pipeline.py
114
115
116
117
def ls():
    """List available containers.
    """
    return []

maintained_object_duplication(item)

Maintain input item duplication

Attributes:

Name Type Description
item any flame.PyObject

python api object

Yield

duplicate input PyObject type

Source code in client/ayon_flame/api/lib.py
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
@contextlib.contextmanager
def maintained_object_duplication(item):
    """Maintain input item duplication

    Attributes:
        item (any flame.PyObject): python api object

    Yield:
        duplicate input PyObject type
    """
    import flame
    # Duplicate the clip to avoid modifying the original clip
    duplicate = flame.duplicate(item)

    try:
        # do the operation on selected segments
        yield duplicate
    finally:
        # delete the item at the end
        flame.delete(duplicate)

maintained_segment_selection(sequence)

Maintain selection during context

Attributes:

Name Type Description
sequence PySequence

python api object

Yield

list of flame.PySegment

Example

with maintained_segment_selection(sequence) as selected_segments: ... for segment in selected_segments: ... segment.selected = False print(segment.selected) True

Source code in client/ayon_flame/api/lib.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
@contextlib.contextmanager
def maintained_segment_selection(sequence):
    """Maintain selection during context

    Attributes:
        sequence (flame.PySequence): python api object

    Yield:
        list of flame.PySegment

    Example:
        >>> with maintained_segment_selection(sequence) as selected_segments:
        ...     for segment in selected_segments:
        ...         segment.selected = False
        >>> print(segment.selected)
        True
    """
    selected_segments = get_sequence_segments(sequence, True)
    try:
        # do the operation on selected segments
        yield selected_segments
    finally:
        # reset all selected clips
        reset_segment_selection(sequence)
        # select only original selection of segments
        for segment in selected_segments:
            segment.selected = True

modify_preset_file(xml_path, staging_dir, data)

Modify xml preset with input data

Parameters:

Name Type Description Default
xml_path str

path for input xml preset

required
staging_dir str

staging dir path

required
data dict

data where key is xmlTag and value as string

required

Returns:

Name Type Description
str

description

Source code in client/ayon_flame/api/render_utils.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def modify_preset_file(xml_path, staging_dir, data):
    """Modify xml preset with input data

    Args:
        xml_path (str ): path for input xml preset
        staging_dir (str): staging dir path
        data (dict): data where key is xmlTag and value as string

    Returns:
        str: _description_
    """
    # create temp path
    dirname, basename = os.path.split(xml_path)
    temp_path = os.path.join(staging_dir, basename)

    # change xml following data keys
    with open(xml_path, "r") as datafile:
        _root = ET.parse(datafile)

        for key, value in data.items():
            try:
                if "/" in key:
                    if not key.startswith("./"):
                        key = ".//" + key

                    split_key_path = key.split("/")
                    element_key = split_key_path[-1]
                    parent_obj_path = "/".join(split_key_path[:-1])

                    parent_obj = _root.find(parent_obj_path)
                    element_obj = parent_obj.find(element_key)
                    if not element_obj:
                        append_element(parent_obj, element_key, value)
                else:
                    finds = _root.findall(".//{}".format(key))
                    if not finds:
                        raise AttributeError
                    for element in finds:
                        element.text = str(value)
            except AttributeError:
                log.warning(
                    "Cannot create attribute: {}: {}. Skipping".format(
                        key, value
                    ))
        _root.write(temp_path)

    return temp_path

remove_instance(instance)

Remove instance marker from track item.

Source code in client/ayon_flame/api/pipeline.py
145
146
147
148
def remove_instance(instance):
    """Remove instance marker from track item."""
    # TODO: remove_instance
    pass

reset_segment_selection(sequence)

Deselect all selected nodes

Source code in client/ayon_flame/api/lib.py
501
502
503
504
505
506
507
508
509
def reset_segment_selection(sequence):
    """Deselect all selected nodes
    """
    for ver in sequence.versions:
        for track in ver.tracks:
            if len(track.segments) == 0 and track.hidden:
                continue
            for segment in track.segments:
                segment.selected = False

set_publish_attribute(segment, value)

Set Publish attribute in input Tag object

Attribute

segment (flame.PySegment)): flame api object value (bool): True or False

Source code in client/ayon_flame/api/lib.py
390
391
392
393
394
395
396
397
398
399
400
401
def set_publish_attribute(segment, value):
    """ Set Publish attribute in input Tag object

    Attribute:
        segment (flame.PySegment)): flame api object
        value (bool): True or False
    """
    tag_data = get_segment_data_marker(segment)
    tag_data["publish"] = value

    # set data to the publish attribute
    set_segment_data_marker(segment, tag_data)

set_segment_data_marker(segment, data=None)

Set AYON track item tag to input segment.

Attributes:

Name Type Description
segment PySegment

flame api object

Returns:

Name Type Description
dict

json loaded data

Source code in client/ayon_flame/api/lib.py
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
def set_segment_data_marker(segment, data=None):
    """
    Set AYON track item tag to input segment.

    Attributes:
        segment (flame.PySegment): flame api object

    Returns:
        dict: json loaded data
    """
    data = data or dict()

    marker_data = get_segment_data_marker(segment, True)

    if marker_data:
        # get available AYON tag if any
        marker, tag_data = marker_data
        # update tag data with new data
        tag_data.update(data)
        # update marker with tag data
        marker.comment = json.dumps(tag_data)
    else:
        # update tag data with new data
        marker = create_segment_data_marker(segment)
        # add tag data to marker's comment
        marker.comment = json.dumps(data)

setup(env=None)

Wrapper installer started from flame/hooks/pre_flame_setup.py

Source code in client/ayon_flame/api/utils.py
119
120
121
122
123
124
125
126
127
128
def setup(env=None):
    """ Wrapper installer started from
    `flame/hooks/pre_flame_setup.py`
    """
    env = env or os.environ

    # synchronize resolve utility scripts
    _sync_utility_scripts(env)

    log.info("Flame AYON wrapper has been installed")

update_container(tl_segment, data=None)

Update container data to input timeline_item's AYON tag.

Source code in client/ayon_flame/api/pipeline.py
127
128
129
130
131
def update_container(tl_segment, data=None):
    """Update container data to input timeline_item's AYON tag.
    """
    # TODO: update_container
    pass