Skip to content

lib

Host specific functions where host api is connected

PublishAction

Bases: QAction

Action with is showing as menu item

Source code in client/ayon_hiero/api/lib.py
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
class PublishAction(QtWidgets.QAction):
    """
    Action with is showing as menu item
    """

    def __init__(self):
        QtWidgets.QAction.__init__(self, "Publish", None)
        self.triggered.connect(self.publish)

        for interest in ["kShowContextMenu/kTimeline",
                         "kShowContextMenukBin",
                         "kShowContextMenu/kSpreadsheet"]:
            hiero.core.events.registerInterest(interest, self.eventHandler)

        self.setShortcut("Ctrl+Alt+P")

    def publish(self):
        from . import publish
        # Removing "submission" attribute from hiero module, to prevent tasks
        # from getting picked up when not using the "Export" dialog.
        if hasattr(hiero, "submission"):
            del hiero.submission
        publish(hiero.ui.mainWindow())

    def eventHandler(self, event):
        # Add the Menu to the right-click menu
        event.menu.addAction(self)

add_path_mapping()

This function reads the path mappings from the project settings and adds them to Hiero's path mapping table.

Source code in client/ayon_hiero/api/lib.py
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
def add_path_mapping() -> None:
    """This function reads the path mappings from the project
    settings and adds them to Hiero's path mapping table.
    """
    def _parse_remaps(remap_str: str) -> set[tuple[str, str, str]]:
        """Parse a remap string into a set of path mapping tuples."""
        tokens = remap_str.rstrip(";").split(";")
        return {tuple(tokens[i:i + 3]) for i in range(0, len(tokens) - 2, 3)}

    def _remaps_to_str(remaps: set[tuple[str, str, str]]) -> str:
        return "".join(";".join(r) + ";" for r in sorted(remaps))

    current_project_name = get_current_project_name()
    configured_path_mappings = _configured_path_mappings(current_project_name)
    preferences = nuke.toNode("preferences")
    remap_knob = preferences["platformPathRemaps"]
    if not configured_path_mappings:
        return

    # Clear previously remapping set by AYON.
    ayon_knob = preferences.knob("ayon_path_remapping")
    remaps = _parse_remaps(remap_knob.toScript())
    if ayon_knob is not None:
        # Remove previously set AYON remaps
        remaps -= _parse_remaps(ayon_knob.value())
    else:
        # Create the knob if it doesn't exist
        ayon_knob = nuke.String_Knob("ayon_path_remapping", "AYON Path Remapping")
        ayon_knob.setFlag(nuke.INVISIBLE)
        preferences.addKnob(ayon_knob)

    # Add configured path mappings
    # Convert to set of tuples once
    configured_set = {tuple(m) for m in configured_path_mappings}
    remaps |= configured_set

  # Add to Hiero if not already present
    hiero_remaps = hiero.core.pathRemappings()
    for path_tuple in configured_set:
        if list(path_tuple) not in hiero_remaps:
            hiero.core.addPathRemap(*path_tuple)

    # Update knobs
    remap_knob.fromScript(_remaps_to_str(remaps))
    ayon_knob.setValue(_remaps_to_str(configured_set))

    _persist_prefs_knobs(preferences, ["platformPathRemaps", "ayon_path_remapping"])

apply_colorspace_project()

Apply colorspaces from settings.

Due to not being able to set the project settings through the Python API, we need to do use some dubious code to find the widgets and set them. It is possible to set the project settings without traversing through the widgets but it involves reading the hrox files from disk with XML, so no in-memory support. See https://community.foundry.com/discuss/topic/137771/change-a-project-s-default-color-transform-with-python # noqa for more details.

Source code in client/ayon_hiero/api/lib.py
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
def apply_colorspace_project():
    """Apply colorspaces from settings.

    Due to not being able to set the project settings through the Python API,
    we need to do use some dubious code to find the widgets and set them. It is
    possible to set the project settings without traversing through the widgets
    but it involves reading the hrox files from disk with XML, so no in-memory
    support. See https://community.foundry.com/discuss/topic/137771/change-a-project-s-default-color-transform-with-python  # noqa
    for more details.
    """
    # get presets for hiero
    project_name = get_current_project_name()
    imageio = get_project_settings(project_name)["hiero"]["imageio"]
    presets = imageio.get("workfile")

    # Open Project Settings UI.
    for act in hiero.ui.registeredActions():
        if act.objectName() == "foundry.project.settings":
            act.trigger()

    # Find widgets from their sibling label.
    labels = {
        "Working Space:": "workingSpace",
        "Viewer:": "viewerLut",
        "Thumbnails:": "thumbnailLut",
        "Monitor Out:": "monitorOutLut",
        "8 Bit Files:": "eightBitLut",
        "16 Bit Files:": "sixteenBitLut",
        "Log Files:": "logLut",
        "Floating Point Files:": "floatLut",
    }
    widgets = {x: None for x in labels.values()}

    def _recursive_children(widget, labels, widgets):
        children = widget.children()
        for count, child in enumerate(children):
            if isinstance(child, QtWidgets.QLabel):
                if child.text() in labels.keys():
                    widgets[labels[child.text()]] = children[count + 1]
            _recursive_children(child, labels, widgets)

    app = QtWidgets.QApplication.instance()
    title = "Project Settings"
    for widget in app.topLevelWidgets():
        if isinstance(widget, QtWidgets.QMainWindow):
            if widget.windowTitle() != title:
                continue
            _recursive_children(widget, labels, widgets)
            widget.close()

    msg = "Setting value \"{}\" is not a valid option for \"{}\""
    for key, widget in widgets.items():
        options = [
            widget.itemText(i) for i in range(widget.count())
            if "Error:" not in widget.itemText(i)
        ]
        setting_value = presets[key]
        found = False
        for option in options:
            if setting_value in option:
                found = True
                break
        assert found, msg.format(setting_value, key)
        log.info(f"Setting {key} to {setting_value}")
        # Find the index of the setting value in the widget options
        for i in range(widget.count()):
            if setting_value in widget.itemText(i):
                widget.setCurrentIndex(i)
                break

check_inventory_versions(track_items=None)

Actual version color identifier of Loaded containers

Check all track items and filter only Loader nodes for its version. It will get all versions from database and check if the node is having actual version. If not then it will color it to red.

Source code in client/ayon_hiero/api/lib.py
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
def check_inventory_versions(track_items=None):
    """
    Actual version color identifier of Loaded containers

    Check all track items and filter only
    Loader nodes for its version. It will get all versions from database
    and check if the node is having actual version. If not then it will color
    it to red.
    """
    from . import parse_container

    track_items = track_items or get_track_items()
    # presets
    clip_color_last = "green"
    clip_color = "red"

    containers = []
    # Find all containers and collect it's node and representation ids
    for track_item in track_items:
        container = parse_container(track_item)
        if container:
            containers.append(container)

    # Skip if nothing was found
    if not containers:
        return

    project_name = get_current_project_name()
    filter_result = filter_containers(containers, project_name)
    for container in filter_result.latest:
        set_track_color(container["_item"], clip_color_last)

    for container in filter_result.outdated:
        set_track_color(container["_item"], clip_color)

create_bin(path=None, project=None)

Create bin in project. If the path is "bin1/bin2/bin3" it will create whole depth and return bin3

Source code in client/ayon_hiero/api/lib.py
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
def create_bin(path=None, project=None):
    '''
    Create bin in project.
    If the path is "bin1/bin2/bin3" it will create whole depth
    and return `bin3`

    '''
    # get the first loaded project
    project = project or get_current_project()

    path = path or DEFAULT_BIN_NAME

    path = path.replace("\\", "/").split("/")

    root_bin = project.clipsBin()

    done_bin_lst = []
    for i, b in enumerate(path):
        if i == 0 and len(path) > 1:
            if b in [bin.name() for bin in root_bin.bins()]:
                bin = [bin for bin in root_bin.bins() if b in bin.name()][0]
                done_bin_lst.append(bin)
            else:
                create_bin = hiero.core.Bin(b)
                root_bin.addItem(create_bin)
                done_bin_lst.append(create_bin)

        elif i >= 1 and i < len(path) - 1:
            if b in [bin.name() for bin in done_bin_lst[i - 1].bins()]:
                bin = [
                    bin for bin in done_bin_lst[i - 1].bins()
                    if b in bin.name()
                ][0]
                done_bin_lst.append(bin)
            else:
                create_bin = hiero.core.Bin(b)
                done_bin_lst[i - 1].addItem(create_bin)
                done_bin_lst.append(create_bin)

        elif i == len(path) - 1:
            if b in [bin.name() for bin in done_bin_lst[i - 1].bins()]:
                bin = [
                    bin for bin in done_bin_lst[i - 1].bins()
                    if b in bin.name()
                ][0]
                done_bin_lst.append(bin)
            else:
                create_bin = hiero.core.Bin(b)
                done_bin_lst[i - 1].addItem(create_bin)
                done_bin_lst.append(create_bin)

    return done_bin_lst[-1]

create_nuke_workfile_clips(nuke_workfiles, seq=None)

nuke_workfiles is list of dictionaries like: [{ 'path': 'P:/Jakub_testy_pipeline/test_v01.nk', 'name': 'test', 'handleStart': 15, # added asymmetrically to handles 'handleEnd': 10, # added asymmetrically to handles "clipIn": 16, "frameStart": 991, "frameEnd": 1023, 'task': 'Comp-tracking', 'work_dir': 'VFX_PR', 'shot': '00010' }]

Source code in client/ayon_hiero/api/lib.py
 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
def create_nuke_workfile_clips(nuke_workfiles, seq=None):
    '''
    nuke_workfiles is list of dictionaries like:
    [{
        'path': 'P:/Jakub_testy_pipeline/test_v01.nk',
        'name': 'test',
        'handleStart': 15, # added asymmetrically to handles
        'handleEnd': 10, # added asymmetrically to handles
        "clipIn": 16,
        "frameStart": 991,
        "frameEnd": 1023,
        'task': 'Comp-tracking',
        'work_dir': 'VFX_PR',
        'shot': '00010'
    }]
    '''

    proj = hiero.core.projects()[-1]
    root = proj.clipsBin()

    if not seq:
        seq = hiero.core.Sequence('NewSequences')
        root.addItem(hiero.core.BinItem(seq))
    # todo will need to define this better
    # track = seq[1]  # lazy example to get a destination#  track
    clips_lst = []
    for nk in nuke_workfiles:
        task_path = '/'.join([nk['work_dir'], nk['shot'], nk['task']])
        bin = create_bin(task_path, proj)

        if nk['task'] not in seq.videoTracks():
            track = hiero.core.VideoTrack(nk['task'])
            seq.addTrack(track)
        else:
            track = seq.tracks(nk['task'])

        # create clip media
        media = hiero.core.MediaSource(nk['path'])
        media_in = int(media.startTime() or 0)
        media_duration = int(media.duration() or 0)

        handle_start = nk.get("handleStart")
        handle_end = nk.get("handleEnd")

        if media_in:
            source_in = media_in + handle_start
        else:
            source_in = nk["frameStart"] + handle_start

        if media_duration:
            source_out = (media_in + media_duration - 1) - handle_end
        else:
            source_out = nk["frameEnd"] - handle_end

        source = hiero.core.Clip(media)

        name = os.path.basename(os.path.splitext(nk['path'])[0])
        split_name = split_by_client_version(name)[0] or name

        # add to bin as clip item
        items_in_bin = [b.name() for b in bin.items()]
        if split_name not in items_in_bin:
            binItem = hiero.core.BinItem(source)
            bin.addItem(binItem)

        new_source = [
            item for item in bin.items() if split_name in item.name()
        ][0].items()[0].item()

        # add to track as clip item
        trackItem = hiero.core.TrackItem(
            split_name, hiero.core.TrackItem.kVideo)
        trackItem.setSource(new_source)
        trackItem.setSourceIn(source_in)
        trackItem.setSourceOut(source_out)
        trackItem.setTimelineIn(nk["clipIn"])
        trackItem.setTimelineOut(nk["clipIn"] + (source_out - source_in))
        track.addTrackItem(trackItem)
        clips_lst.append(trackItem)

    return clips_lst

deprecated(new_destination)

Mark functions as deprecated.

It will result in a warning being emitted when the function is used.

Source code in client/ayon_hiero/api/lib.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def deprecated(new_destination):
    """Mark functions as deprecated.

    It will result in a warning being emitted when the function is used.
    """

    func = None
    if callable(new_destination):
        func = new_destination
        new_destination = None

    def _decorator(decorated_func):
        if new_destination is None:
            warning_message = (
                " Please check content of deprecated function to figure out"
                " possible replacement."
            )
        else:
            warning_message = " Please replace your usage with '{}'.".format(
                new_destination
            )

        @functools.wraps(decorated_func)
        def wrapper(*args, **kwargs):
            warnings.simplefilter("always", DeprecatedWarning)
            warnings.warn(
                (
                    "Call to deprecated function '{}'"
                    "\nFunction was moved or removed.{}"
                ).format(decorated_func.__name__, warning_message),
                category=DeprecatedWarning,
                stacklevel=4
            )
            return decorated_func(*args, **kwargs)
        return wrapper

    if func is None:
        return _decorator
    return _decorator(func)

get_current_sequence(name=None, new=False)

Get current sequence in context of active project.

Parameters:

Name Type Description Default
name (str)[optional]

name of sequence we want to return

required
new (bool)[optional]

if we want to create new one

required

Returns:

Type Description

hiero.core.Sequence: the sequence object

Source code in client/ayon_hiero/api/lib.py
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
def get_current_sequence(name=None, new=False):
    """
    Get current sequence in context of active project.

    Args:
        name (str)[optional]: name of sequence we want to return
        new (bool)[optional]: if we want to create new one

    Returns:
        hiero.core.Sequence: the sequence object
    """
    sequence = None
    project = get_current_project()
    root_bin = project.clipsBin()

    if new:
        # create new
        name = name or DEFAULT_SEQUENCE_NAME
        sequence = hiero.core.Sequence(name)
        root_bin.addItem(hiero.core.BinItem(sequence))
    elif name:
        # look for sequence by name
        sequences = project.sequences()
        for _sequence in sequences:
            if _sequence.name() == name:
                sequence = _sequence
        if not sequence:
            # if nothing found create new with input name
            sequence = get_current_sequence(name, True)
    else:
        # if name is none and new is False then return current open sequence
        sequence = hiero.ui.activeSequence()

    return sequence

get_current_track(sequence, name, audio=False)

Get current track in context of active project.

Creates new if none is found.

Parameters:

Name Type Description Default
sequence Sequence

hiero sequence object

required
name str

name of track we want to return

required
audio (bool)[optional]

switch to AudioTrack

required

Returns:

Type Description

hiero.core.Track: the track object

Source code in client/ayon_hiero/api/lib.py
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
def get_current_track(sequence, name, audio=False):
    """
    Get current track in context of active project.

    Creates new if none is found.

    Args:
        sequence (hiero.core.Sequence): hiero sequence object
        name (str): name of track we want to return
        audio (bool)[optional]: switch to AudioTrack

    Returns:
        hiero.core.Track: the track object
    """
    tracks = sequence.videoTracks()

    if audio:
        tracks = sequence.audioTracks()

    # get track by name
    track = None
    for _track in tracks:
        if _track.name() == name:
            track = _track

    if not track:
        if not audio:
            track = hiero.core.VideoTrack(name)
        else:
            track = hiero.core.AudioTrack(name)

        sequence.addTrack(track)

    return track

get_main_window()

Acquire Nuke's main window

Source code in client/ayon_hiero/api/lib.py
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
def get_main_window():
    """Acquire Nuke's main window"""
    if _CTX.parent_gui is None:
        top_widgets = QtWidgets.QApplication.topLevelWidgets()
        name = "Foundry::UI::DockMainWindow"
        main_window = next(widget for widget in top_widgets if
                           widget.inherits("QMainWindow") and
                           widget.metaObject().className() == name)
        _CTX.parent_gui = main_window
    return _CTX.parent_gui

get_sequence_pattern_and_padding(file)

Return sequence pattern and padding from file

Attributes:

Name Type Description
file string

basename form path

Example

Can find file.0001.ext, file.%02d.ext, file.####.ext

Return

string: any matching sequence pattern int: padding of sequence numbering

Source code in client/ayon_hiero/api/lib.py
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
def get_sequence_pattern_and_padding(file):
    """ Return sequence pattern and padding from file

    Attributes:
        file (string): basename form path

    Example:
        Can find file.0001.ext, file.%02d.ext, file.####.ext

    Return:
        string: any matching sequence pattern
        int: padding of sequence numbering
    """
    foundall = re.findall(
        r"(#+)|(%\d+d)|(?<=[^a-zA-Z0-9])(\d+)(?=\.\w+$)", file)
    if not foundall:
        return None, None
    found = sorted(list(set(foundall[0])))[-1]

    padding = int(
        re.findall(r"\d+", found)[-1]) if "%" in found else len(found)
    return found, padding

get_track_ayon_data(track, container_name=None)

Get track's AYON tag data.

Data of legacy (OpenPype) tag are returned if the track does not have AYON tag.

Attributes:

Name Type Description
track VideoTrack

hiero object

Returns:

Name Type Description
dict

data found on the AYON tag

Source code in client/ayon_hiero/api/lib.py
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
def get_track_ayon_data(track, container_name=None):
    """
    Get track's AYON tag data.

    Data of legacy (OpenPype) tag are returned if the track does not
    have AYON tag.

    Attributes:
        track (hiero.core.VideoTrack): hiero object

    Returns:
        dict: data found on the AYON tag
    """
    tag = _get_ayon_tag(track, legacy=True)
    if not tag:
        return None

    return_data = {}
    for obj_name, obj_data in tags.get_tag_data(tag, legacy=True).items():
        if isinstance(obj_data, str):
            # legacy tag stored each container as json string
            try:
                obj_data = json.loads(obj_data)
            except json.JSONDecodeError:
                continue

        if isinstance(obj_data, dict):
            return_data[obj_name] = obj_data

    return (
        return_data[container_name]
        if container_name
        else return_data
    )

get_track_ayon_tag(track, tag_name=AYON_TAG_NAME)

Get AYON track tag created by loader plugin.

Attributes:

Name Type Description
track VideoTrack

hiero object

tag_name str

The tag name.

Returns:

Type Description

hiero.core.Tag: hierarchy, orig clip attributes

Source code in client/ayon_hiero/api/lib.py
454
455
456
457
458
459
460
461
462
463
464
465
def get_track_ayon_tag(track, tag_name=AYON_TAG_NAME):
    """
    Get AYON track tag created by loader plugin.

    Attributes:
        track (hiero.core.VideoTrack): hiero object
        tag_name (str): The tag name.

    Returns:
        hiero.core.Tag: hierarchy, orig clip attributes
    """
    return _get_ayon_tag(track, tag_name)

get_track_item_tags(track_item)

Get track item tags excluding AYON tag

Attributes:

Name Type Description
trackItem TrackItem

hiero object

Returns:

Type Description

hiero.core.Tag: hierarchy, orig clip attributes

Source code in client/ayon_hiero/api/lib.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def get_track_item_tags(track_item):
    """
    Get track item tags excluding AYON tag

    Attributes:
        trackItem (hiero.core.TrackItem): hiero object

    Returns:
        hiero.core.Tag: hierarchy, orig clip attributes
    """
    returning_tag_data = []
    # get all tags from track item
    _tags = track_item.tags()
    if not _tags:
        return []

    # collect all tags which are not AYON tag
    returning_tag_data.extend(
        tag for tag in _tags
        if AYON_TAG_NAME not in tag.name()
    )

    return returning_tag_data

get_track_items(selection=False, sequence_name=None, track_item_name=None, track_name=None, track_type=None, check_enabled=True, check_locked=True, check_tagged=False)

Get all available current timeline track items.

Attribute

selection (list)[optional]: list of selected track items sequence_name (str)[optional]: return only clips from input sequence track_item_name (str)[optional]: return only item with input name track_name (str)[optional]: return only items from track name track_type (str)[optional]: return only items of given type (audio or video) default is video check_enabled (bool)[optional]: ignore disabled if True check_locked (bool)[optional]: ignore locked if True

Return

list or hiero.core.TrackItem: list of track items or single track item

Source code in client/ayon_hiero/api/lib.py
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
def get_track_items(
        selection=False,
        sequence_name=None,
        track_item_name=None,
        track_name=None,
        track_type=None,
        check_enabled=True,
        check_locked=True,
        check_tagged=False):
    """Get all available current timeline track items.

    Attribute:
        selection (list)[optional]: list of selected track items
        sequence_name (str)[optional]: return only clips from input sequence
        track_item_name (str)[optional]: return only item with input name
        track_name (str)[optional]: return only items from track name
        track_type (str)[optional]: return only items of given type
                                    (`audio` or `video`) default is `video`
        check_enabled (bool)[optional]: ignore disabled if True
        check_locked (bool)[optional]: ignore locked if True

    Return:
        list or hiero.core.TrackItem: list of track items or single track item
    """
    track_type = track_type or "video"
    selection = selection or []
    return_list = []

    # get selected track items or all in active sequence
    if selection:
        try:
            for track_item in selection:
                log.info("___ track_item: {}".format(track_item))
                # make sure only trackitems are selected
                if not isinstance(track_item, hiero.core.TrackItem):
                    continue

                if _validate_all_atrributes(
                    track_item,
                    track_item_name,
                    track_name,
                    track_type,
                    check_enabled,
                    check_tagged
                ):
                    log.info("___ valid trackitem: {}".format(track_item))
                    return_list.append(track_item)
        except AttributeError:
            pass

    # collect all available active sequence track items
    if not return_list:
        sequence = get_current_sequence(name=sequence_name)
        tracks = []
        if sequence is not None:
            # get all available tracks from sequence
            tracks.extend(sequence.audioTracks())
            tracks.extend(sequence.videoTracks())

        # loop all tracks
        for track in tracks:
            if check_locked and track.isLocked():
                continue
            if check_enabled and not track.isEnabled():
                continue
            # and all items in track
            for track_item in track.items():
                # make sure no subtrackitem is also track items
                if not isinstance(track_item, hiero.core.TrackItem):
                    continue

                if _validate_all_atrributes(
                    track_item,
                    track_item_name,
                    track_name,
                    track_type,
                    check_enabled,
                    check_tagged
                ):
                    return_list.append(track_item)

    return return_list

get_trackitem_ayon_data(track_item)

Get track item's AYON tag data.

Data of legacy (OpenPype) tag are returned if the track item does not have AYON tag.

Attributes:

Name Type Description
trackItem TrackItem

hiero object

Returns:

Name Type Description
dict

data found on the AYON tag

Source code in client/ayon_hiero/api/lib.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
def get_trackitem_ayon_data(track_item):
    """
    Get track item's AYON tag data.

    Data of legacy (OpenPype) tag are returned if the track item does not
    have AYON tag.

    Attributes:
        trackItem (hiero.core.TrackItem): hiero object

    Returns:
        dict: data found on the AYON tag
    """
    tag = _get_ayon_tag(track_item, legacy=True)
    if not tag:
        return None

    return tags.get_tag_data(tag, legacy=True)

get_trackitem_ayon_tag(track_item, tag_name=AYON_TAG_NAME)

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

Attributes:

Name Type Description
trackItem TrackItem

hiero object

tag_name str

The tag name.

Returns:

Type Description

hiero.core.Tag: hierarchy, orig clip attributes

Source code in client/ayon_hiero/api/lib.py
504
505
506
507
508
509
510
511
512
513
514
515
def get_trackitem_ayon_tag(track_item, tag_name=AYON_TAG_NAME):
    """
    Get AYON track item tag created by creator or loader plugin.

    Attributes:
        trackItem (hiero.core.TrackItem): hiero object
        tag_name (str): The tag name.

    Returns:
        hiero.core.Tag: hierarchy, orig clip attributes
    """
    return _get_ayon_tag(track_item, tag_name)

imprint(track_item, data=None)

Adding AYON data into a hiero track item tag.

Parameters:

Name Type Description Default
track_item TrackItem

hiero track item object

required
data dict

Any data which needs to be imprinted

None

Examples:

data = { 'folderPath': '/shots/sq020sh0280', 'productBaseType': 'render', 'productName': 'productMain' }

Source code in client/ayon_hiero/api/lib.py
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
def imprint(track_item, data=None):
    """
    Adding AYON data into a hiero track item tag.

    Arguments:
        track_item (hiero.core.TrackItem): hiero track item object
        data (dict): Any data which needs to be imprinted

    Examples:
        data = {
            'folderPath': '/shots/sq020sh0280',
            'productBaseType': 'render',
            'productName': 'productMain'
        }
    """
    data = data or {}

    set_trackitem_ayon_tag(track_item, data)

launch_workfiles_app(event)

Event for launching workfiles after hiero start

Parameters:

Name Type Description Default
event obj

required but unused

required
Source code in client/ayon_hiero/api/lib.py
623
624
625
626
627
628
629
630
631
def launch_workfiles_app(event):
    """
    Event for launching workfiles after hiero start

    Args:
        event (obj): required but unused
    """
    from . import launch_workfiles_app
    launch_workfiles_app()

remove_legacy_tags(item)

Remove legacy (OpenPype) tags from track or track item.

Parameters:

Name Type Description Default
item Union[TrackItem, VideoTrack]

hiero object

required
Source code in client/ayon_hiero/api/lib.py
429
430
431
432
433
434
435
436
437
438
def remove_legacy_tags(item):
    """Remove legacy (OpenPype) tags from track or track item.

    Args:
        item (Union[hiero.core.TrackItem, hiero.core.VideoTrack]): hiero
            object
    """
    for tag in item.tags():
        if LEGACY_OPENPYPE_TAG_NAME in tag.name():
            item.removeTag(tag)

set_favorites()

Add context-related favorites to Nuke's file browser.

Favorites are derived from AYON_WORKDIR (or the currently opened workfile path) and split into: - project directory - folder directory - work directory

Important limitations: - Project root detection assumes project_name is present in the path. If the project name is missing, or appears in an unexpected position, derived project paths may be incorrect. - Folder root detection assumes folder_name is present and uniquely identifiable in the path. If the folder name is missing or repeated, derived folder paths may be incorrect.

In short, path derivation is template-dependent and works best when the current context tokens are explicitly represented in the work directory.

Source code in client/ayon_hiero/api/lib.py
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
def set_favorites() -> None:
    """Add context-related favorites to Nuke's file browser.

    Favorites are derived from ``AYON_WORKDIR`` (or the currently opened
    workfile path) and split into:
    - project directory
    - folder directory
    - work directory

    Important limitations:
    - Project root detection assumes ``project_name`` is present in the path.
        If the project name is missing, or appears in an unexpected position,
        derived project paths may be incorrect.
    - Folder root detection assumes ``folder_name`` is present and uniquely
        identifiable in the path. If the folder name is missing or repeated,
        derived folder paths may be incorrect.

    In short, path derivation is template-dependent and works best when the
    current context tokens are explicitly represented in the work directory.
    """
    work_dir = os.getenv("AYON_WORKDIR")

    # Use workdir from current workfile
    host = registered_host()
    current_file = host.get_current_workfile()
    if current_file:
        work_dir = os.path.dirname(current_file)
    # Escape backslashes on windows
    if platform.system().lower() == "windows":
        work_dir = work_dir.replace("\\", "/")

    context = host.get_current_context()
    project_name = context["project_name"]
    folder_path = context["folder_path"]
    folder_name = folder_path.split("/")[-1]

    # Split workdir to parts by project name
    projects_root = work_dir.split(project_name)[0]
    project_dir = f"{projects_root}{project_name}/"

    folder_root = work_dir.split(folder_name)[0]
    folder_dir = f"{folder_root}{folder_name}/"

    icon_path = resources.get_resource("icons", "folder-favorite.png")
    for name, path in (
        ("Shot dir", folder_dir),
        ("Work dir", work_dir),
        ("Project dir", project_dir),
    ):
        # This only adds the favorite directory to the "Import File(s)"
        # and "Import Folder(s)" menus. It does not impact "Import EDL"
        # nor "Import OTIO" as those are handled natively by Hiero with
        # no public API.
        nuke.addFavoriteDir(
            name=name,
            directory=path,
            type=nuke.IMAGE | nuke.SCRIPT,
            icon=icon_path,
        )

set_track_ayon_tag(track, data=None)

Set AYON track tag to input track object.

Attributes:

Name Type Description
track VideoTrack

hiero object

Returns:

Type Description

hiero.core.Tag

Source code in client/ayon_hiero/api/lib.py
441
442
443
444
445
446
447
448
449
450
451
def set_track_ayon_tag(track, data=None):
    """
    Set AYON track tag to input track object.

    Attributes:
        track (hiero.core.VideoTrack): hiero object

    Returns:
        hiero.core.Tag
    """
    return _set_ayon_tag(track, data)

set_trackitem_ayon_tag(track_item, data=None)

Set AYON track item tag to input track item object.

Attributes:

Name Type Description
track_item TrackItem

hiero object

Returns:

Type Description

hiero.core.Tag

Source code in client/ayon_hiero/api/lib.py
518
519
520
521
522
523
524
525
526
527
528
def set_trackitem_ayon_tag(track_item, data=None):
    """
    Set AYON track item tag to input track item object.

    Attributes:
        track_item (hiero.core.TrackItem): hiero object

    Returns:
        hiero.core.Tag
    """
    return _set_ayon_tag(track_item, data)

setup(console=False, port=None, menu=True)

Setup integration

Registers Pyblish for Hiero plug-ins and appends an item to the File-menu

Parameters:

Name Type Description Default
console bool

Display console with GUI

False
port int

Port from which to start looking for an available port to connect with Pyblish QML, default provided by Pyblish Integration.

None
menu bool

Display file menu in Hiero.

True
Source code in client/ayon_hiero/api/lib.py
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
def setup(console=False, port=None, menu=True):
    """Setup integration

    Registers Pyblish for Hiero plug-ins and appends an item to the File-menu

    Arguments:
        console (bool): Display console with GUI
        port (int, optional): Port from which to start looking for an
            available port to connect with Pyblish QML, default
            provided by Pyblish Integration.
        menu (bool, optional): Display file menu in Hiero.
    """

    if _CTX.has_been_setup:
        teardown()

    add_submission()
    # Add path mappings for the current session
    add_path_mapping()

    if menu:
        add_to_filemenu()
        _CTX.has_menu = True

    _CTX.has_been_setup = True
    log.debug("pyblish: Loaded successfully.")

teardown()

Remove integration

Source code in client/ayon_hiero/api/lib.py
834
835
836
837
838
839
840
841
842
843
844
def teardown():
    """Remove integration"""
    if not _CTX.has_been_setup:
        return

    if _CTX.has_menu:
        remove_from_filemenu()
        _CTX.has_menu = False

    _CTX.has_been_setup = False
    log.debug("pyblish: Integration torn down successfully")