Skip to content

lib

FlameAppFramework

Bases: object

Takes care of preferences.

Source code in client/ayon_flame/api/lib.py
 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
class FlameAppFramework(object):
    """ Takes care of preferences.
    """

    def __init__(self):
        self.name = self.__class__.__name__
        self.bundle_name = "AYONFlame"
        # self.prefs scope is limited to flame project and user
        self.prefs = {}
        self.prefs_user = {}
        self.prefs_global = {}
        self.log = log

        try:
            import flame
            self.flame = flame
            self.flame_project_name = self.flame.project.current_project.name
            self.flame_user_name = flame.users.current_user.name
        except Exception:
            self.flame = None
            self.flame_project_name = None
            self.flame_user_name = None

        import socket
        self.hostname = socket.gethostname()

        if sys.platform == "darwin":
            self.prefs_folder = os.path.join(
                os.path.expanduser("~"),
                "Library",
                "Caches",
                "AYON",
                self.bundle_name
            )
        elif sys.platform.startswith("linux"):
            self.prefs_folder = os.path.join(
                os.path.expanduser("~"),
                ".AYON",
                self.bundle_name)

        self.prefs_folder = os.path.join(
            self.prefs_folder,
            self.hostname,
        )

        self.log.info("[{}] waking up".format(self.__class__.__name__))

        try:
            self.load_prefs()
        except RuntimeError:
            self.save_prefs()

        # menu auto-refresh defaults
        if not self.prefs_global.get("menu_auto_refresh"):
            self.prefs_global["menu_auto_refresh"] = {
                "media_panel": True,
                "batch": True,
                "main_menu": True,
                "timeline_menu": True
            }

        self.apps = []

    def get_pref_file_paths(self):

        prefix = self.prefs_folder + os.path.sep + self.bundle_name
        prefs_file_path = "_".join([
            prefix, self.flame_user_name,
            self.flame_project_name]) + ".prefs"
        prefs_user_file_path = "_".join([
            prefix, self.flame_user_name]) + ".prefs"
        prefs_global_file_path = prefix + ".prefs"

        return (prefs_file_path, prefs_user_file_path, prefs_global_file_path)


    def _process_prefs(self, save: bool = False):
        # make sure the preference folder is available
        try:
            os.makedirs(self.prefs_folder, exist_ok=True)
        except Exception:
            self.log.error(
                "Unable to create folder %s",
                self.prefs_folder
            )
            return False

        # Read or write the prefs in each files.
        for attr, path in zip(
            (self.prefs, self.prefs_user, self.prefs_global),
            self.get_pref_file_paths(),
        ):
            with io_preferences_file(self, path, write=save) as prefs_file:
                if save:
                    pickle.dump(attr, prefs_file)
                else:
                    attr.clear()
                    attr.update(pickle.load(prefs_file))

                self.log.info(
                    "Preferences contents:\n%s",
                    pformat(attr),
                )

        return True

    def load_prefs(self) -> bool:
        return self._process_prefs(save=False)

    def save_prefs(self) -> bool:
        return self._process_prefs(save=True)

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
 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
1202
1203
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
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

        # path could be a Windows-style path if an older project was imported
        # into a database created by an older server version prior to
        # migration. All current paths are stored in POSIX format, and all
        # legacy project data has been migrated accordingly.
        if not os.path.exists(path):
            t_path = path.replace("\\", "/")
            if os.path.exists(t_path):
                path = t_path
            else:
                raise FileNotFoundError(f"Path does not exist: {path}")

        # 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._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) -> str | None:
        """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)

        # make sure partial input basename is having correct extensoon
        if not partialname:
            raise AttributeError(
                f"Wrong input attributes. Basename - {feed_basename}, "
                f"Ext - {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
        return None

    @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 = ET.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
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
@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 = ET.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
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
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
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_xml = ET.fromstring(tw_setup_string)
        tw_setup = self._dictify(tw_setup_xml)

        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 as error:
            self.log.error(error, exc_info=True)
            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_clip_data_marker(clip)

Create AYON marker on a clip.

Attributes:

Name Type Description
clip PyClip

flame api object

Returns:

Type Description

flame.PyMarker: flame api object

Source code in client/ayon_flame/api/lib.py
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
def create_clip_data_marker(clip):
    """Create AYON marker on a clip.

    Attributes:
        clip (flame.PyClip): flame api object

    Returns:
        flame.PyMarker: flame api object
    """
    # get duration of segment
    duration = clip.duration.frame
    # calculate start frame of the new marker
    start_frame = int(clip.start_frame) + int(duration / 2)
    # create marker
    marker = clip.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

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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
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_clip_data_marker(clip, with_marker=None)

Get data marker from inside of reel clip.

Wrapper for get_segment_data_marker. Clip has actually also markers but it is different object type.

Attributes:

Name Type Description
clip PyClip

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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
def get_clip_data_marker(clip, with_marker=None):
    """Get data marker from inside of reel clip.

    Wrapper for get_segment_data_marker. Clip has actually also markers
    but it is different object type.

    Attributes:
        clip (flame.PyClip): 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
    """
    segment = get_clip_segment(clip)
    return get_segment_data_marker(
        segment,
        with_marker=with_marker
    )

get_clip_segment(flame_clip)

Get the segment associated to a clip.

Parameters:

Name Type Description Default
flame_clip PyClip

flame api object

required

Returns:

Name Type Description
segment Segment

Segment associated to the clip.

Source code in client/ayon_flame/api/lib.py
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
def get_clip_segment(flame_clip):
    """Get the segment associated to a clip.

    Args:
        flame_clip (flame.PyClip): flame api object

    Returns:
        segment (Segment): Segment associated to the clip.
    """
    name = flame_clip.name.get_value()
    version = flame_clip.versions[0]
    track = version.tracks[0]
    segments = track.segments

    if len(segments) < 1:
        raise ValueError("Clip `{}` has no segments!".format(name))

    if len(segments) > 1:
        raise ValueError("Clip `{}` has too many segments!".format(name))

    return segments[0]

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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
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_ocio_colorspace(colour_space, imageio_settings)

Return OCIO colorspace name from Flame clip colour space.

Flame >= 2026 colour spaces are already OCIO names, Flame < 2026 SynColor names are remapped from imageio settings.

Parameters:

Name Type Description Default
colour_space str

Flame clip colour space name

required
imageio_settings dict

Flame imageio settings

required

Returns:

Type Description

str or None: OCIO colorspace name, None if not found.

Source code in client/ayon_flame/api/lib.py
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
def get_ocio_colorspace(colour_space, imageio_settings):
    """Return OCIO colorspace name from Flame clip colour space.

    Flame >= 2026 colour spaces are already OCIO names,
    Flame < 2026 SynColor names are remapped from imageio settings.

    Args:
        colour_space (str): Flame clip colour space name
        imageio_settings (dict): Flame imageio settings

    Returns:
        str or None: OCIO colorspace name, None if not found.
    """
    import flame

    if not colour_space:
        return None

    if int(flame.get_version_major()) >= 2026:
        return colour_space

    return get_remapped_colorspace_from_native(
        colour_space,
        "flame",
        imageio_settings
    )

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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
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_project_ocio_config(project_name)

Get Flame project OCIO config from WireTap project metadata.

Parameters:

Name Type Description Default
project_name str

Name of the Flame project

required

Returns:

Type Description
Optional[str]

str or None: OCIO config path if set.

Source code in client/ayon_flame/api/lib.py
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
def get_project_ocio_config(project_name) -> Optional[str]:
    """Get Flame project OCIO config from WireTap project metadata.

    Args:
        project_name (str): Name of the Flame project

    Returns:
        str or None: OCIO config path if set.
    """
    from adsk.libwiretapPythonClientAPI import (
        WireTapClient,
        WireTapServerHandle,
        WireTapNodeHandle,
        WireTapStr
    )
    client = WireTapClient()
    if not client.init():
        raise RuntimeError("Could not initialize Wiretap Client")

    host_name = os.getenv("FLAME_WIRETAP_HOSTNAME") or "localhost"
    server = WireTapServerHandle(f"{host_name}:IFFFS")
    node = WireTapNodeHandle(server, f"/projects/{project_name}")

    metadata = WireTapStr()
    if not node.getMetaData("XML", "", 1, metadata):
        raise RuntimeError(
            f"Could not retrieve project '{project_name}' metadata: "
            f"{node.lastError()}"
        )

    project_xml = ET.fromstring(metadata.c_str())
    return project_xml.findtext("OCIOConfigFile") or 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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
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["active"]

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
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
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_attributes(segment, validation_aggregator=None)

Get attributes of a segment.

Parameters:

Name Type Description Default
segment Segment

Segment to get attributes from.

required
validation_aggregator ValidationAggregator
Output object to store attributes for passing into
publishing validation. Defaults to None.
None

Returns:

Name Type Description
dict

Dictionary of attributes.

Source code in client/ayon_flame/api/lib.py
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
629
630
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
def get_segment_attributes(
    segment, validation_aggregator: ValidationAggregator = None):
    """Get attributes of a segment.

    Args:
        segment (Segment): Segment to get attributes from.
        validation_aggregator (ValidationAggregator, optional):
                Output object to store attributes for passing into
                publishing validation. Defaults to None.

    Returns:
        dict: Dictionary of attributes.
    """
    if segment.type == "Gap":
        return None

    if not validation_aggregator:
        validation_aggregator = ValidationAggregator()

    segment_name = segment.name.get_value()

    # Add timeline segment to tree
    clip_data = {
        "shot_name": segment.shot_name.get_value(),
        "segment_comment": segment.comment.get_value(),
        "tape_name": segment.tape_name,
        "source_name": segment.source_name,
        "PySegment": segment,
        "segment_name": "",
        "fpath": "",
    }
    # make sure even segments without proper name are handled as missing
    # this way they will be detected by Publisher Validator
    if not segment_name:
        clip_data["segment_name"] = "Missing: Segment's Name"
        if segment not in validation_aggregator.failed_segments:
            validation_aggregator.failed_segments.append(segment)
    else:
        clip_data["segment_name"] = segment_name

    # make sure even segments without file path are handled as missing
    # this way they will be detected by Publisher Validator
    if segment.file_path and segment_name:
        clip_data["fpath"] = segment.file_path
    else:
        clip_data["segment_name"] = "Missing: Segment's File Path"
        if segment not in validation_aggregator.failed_segments:
            validation_aggregator.failed_segments.append(segment)

    # head and tail with forward compatibility
    for key in ("head", "tail"):
        value = getattr(segment, key)
        if value:
            clip_data[f"segment_{key}"] = (
                0 if isinstance(value, str)
                else int(value)
            )

    # add all available shot tokens
    shot_tokens = _get_shot_tokens_values(segment, [
        "<colour space>", "<width>", "<height>", "<depth>", "<segment>",
        "<track>", "<track name>"
    ])
    clip_data.update(shot_tokens)

    # populate shot source metadata
    segment_attrs = [
        "record_duration", "record_in", "record_out",
        "source_in", "source_out", "source_frame_rate", "source_height",
        "source_width", "source_ratio", "start_frame", "head", "tail",
    ]
    segment_attrs_data = {}
    for attr_name in segment_attrs:
        if not hasattr(segment, attr_name):
            continue
        attr = getattr(segment, attr_name)
        segment_attrs_data[attr_name] = str(attr).replace("+", ":")

        if attr_name in ["record_in", "record_out"]:
            clip_data[attr_name] = attr.relative_frame
        else:
            if hasattr(attr, "frame"):
                clip_data[attr_name] = attr.frame

    clip_data["segment_timecodes"] = segment_attrs_data
    return clip_data

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
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
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() or "{}"
        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)
    return None

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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
@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 assert(segment.selected)

Source code in client/ayon_flame/api/lib.py
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
@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
        >>> assert(segment.selected)
    """
    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

parse_frame_rate(frame_rate)

Convert a Flame frame rate attribute into a float.

Source code in client/ayon_flame/api/lib.py
186
187
188
def parse_frame_rate(frame_rate) -> float:
    """Convert a Flame frame rate attribute into a float."""
    return float(str(frame_rate).split(" ", 1)[0])

reset_segment_selection(sequence)

Deselect all selected nodes

Source code in client/ayon_flame/api/lib.py
550
551
552
553
554
555
556
557
558
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_clip_data_marker(clip, data=None)

Set AYON track item tag to input clip.

Attributes:

Name Type Description
clip PyClip

flame api object

data dict

json serializable data

Source code in client/ayon_flame/api/lib.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
def set_clip_data_marker(clip, data=None):
    """Set AYON track item tag to input clip.

    Attributes:
        clip (flame.PyClip): flame api object
        data (dict): json serializable data
    """
    data = data or dict()
    segment = get_clip_segment(clip)

    segment_data = data.get("clip_data", {}).pop("PySegment", None)
    if segment_data and segment_data != segment:
        raise ValueError(
            "Ambiguous clip to set marker data to."
            f"Provided clip refers to {segment}, while "
            f"data points toward {segment_data}."
        )

    set_segment_data_marker(segment, data=data)

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
417
418
419
420
421
422
423
424
425
426
427
428
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["active"] = value

    # set data to the active 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

Source code in client/ayon_flame/api/lib.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def set_segment_data_marker(segment, data=None):
    """Set AYON track item tag to input segment.

    Attributes:
        segment (flame.PySegment): flame api object
    """
    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)