Skip to content

lib

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))

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_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

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)

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

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)