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

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
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
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())]
        setting_value = presets[key]
        assert setting_value in options, msg.format(setting_value, key)
        widget.setCurrentText(presets[key])

    # This code block is for setting up project colorspaces for files on disk.
    # Due to not having Python API access to set the project settings, the
    # Foundry recommended way is to modify the hrox files on disk with XML. See
    # this forum thread for more details;
    # https://community.foundry.com/discuss/topic/137771/change-a-project-s-default-color-transform-with-python  # noqa
    '''
    # backward compatibility layer
    # TODO: remove this after some time
    config_data = get_current_context_imageio_config_preset()

    if config_data:
        presets.update({
            "ocioConfigName": "custom"
        })

    # get path the the active projects
    project = get_current_project()
    current_file = project.path()

    msg = "The project needs to be saved to disk to apply colorspace settings."
    assert current_file, msg

    # save the workfile as subversion "comment:_colorspaceChange"
    split_current_file = os.path.splitext(current_file)
    copy_current_file = current_file

    if "_colorspaceChange" not in current_file:
        copy_current_file = (
            split_current_file[0]
            + "_colorspaceChange"
            + split_current_file[1]
        )

    try:
        # duplicate the file so the changes are applied only to the copy
        shutil.copyfile(current_file, copy_current_file)
    except shutil.Error:
        # in case the file already exists and it want to copy to the
        # same filewe need to do this trick
        # TEMP file name change
        copy_current_file_tmp = copy_current_file + "_tmp"
        # create TEMP file
        shutil.copyfile(current_file, copy_current_file_tmp)
        # remove original file
        os.remove(current_file)
        # copy TEMP back to original name
        shutil.copyfile(copy_current_file_tmp, copy_current_file)
        # remove the TEMP file as we dont need it
        os.remove(copy_current_file_tmp)

    # use the code from below for changing xml hrox Attributes
    presets.update({"name": os.path.basename(copy_current_file)})

    # read HROX in as QDomSocument
    doc = _read_doc_from_path(copy_current_file)

    # apply project colorspace properties
    _set_hrox_project_knobs(doc, **presets)

    # write QDomSocument back as HROX
    _write_doc_to_path(doc, copy_current_file)

    # open the file as current project
    hiero.core.openProject(copy_current_file)
    '''

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
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
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
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
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
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
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
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
86
87
88
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

None
new bool)[optional]

if we want to create new one

False

Returns:

Type Description

hiero.core.Sequence: the sequence object

Source code in client/ayon_hiero/api/lib.py
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
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

False

Returns:

Type Description

hiero.core.Track: the track object

Source code in client/ayon_hiero/api/lib.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
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
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
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.

Attributes:

Name Type Description
trackItem VideoTrack

hiero object

Returns:

Name Type Description
dict

data found on the AYON tag

Source code in client/ayon_hiero/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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def get_track_ayon_data(track, container_name=None):
    """
    Get track's AYON tag data.

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

    Returns:
        dict: data found on the AYON tag
    """
    return_data = {}
    # get pype data tag from track item
    tag = get_track_ayon_tag(track)

    if not tag:
        return None

    # get tag metadata attribute
    tag_data = deepcopy(dict(tag.metadata()))
    if tag_data.get("tag.json_metadata"):
        tag_data = json.loads(tag_data["tag.json_metadata"])

    ignore_names  = {"applieswhole", "note", "label"}
    for obj_name, obj_data in tag_data.items():
        obj_name = obj_name.replace("tag.", "")

        if obj_name in ignore_names:
            continue
        if isinstance(obj_data, dict):
            return_data[obj_name] = obj_data
        else:
            return_data[obj_name] = json.loads(obj_data)

    return (
        return_data[container_name]
        if container_name
        else return_data
    )

get_track_ayon_tag(track)

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

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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def get_track_ayon_tag(track):
    """
    Get AYON track item tag created by creator or loader plugin.

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

    Returns:
        hiero.core.Tag: hierarchy, orig clip attributes
    """
    # get all tags from track item
    _tags = track.tags()
    if not _tags:
        return None
    for tag in _tags:
        # return only correct tag defined by global name
        if AYON_TAG_NAME in tag.name():
            return tag

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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
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 tag.name() != AYON_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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
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.

Attributes:

Name Type Description
trackItem TrackItem

hiero object

Returns:

Name Type Description
dict

data found on pype tag

Source code in client/ayon_hiero/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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
def get_trackitem_ayon_data(track_item):
    """
    Get track item's AYON tag data.

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

    Returns:
        dict: data found on pype tag
    """
    data = {}
    # get pype data tag from track item
    tag = get_trackitem_ayon_tag(track_item)

    if not tag:
        return None

    # get tag metadata attribute
    tag_data = deepcopy(dict(tag.metadata()))
    if tag_data.get("tag.json_metadata"):
        return json.loads(tag_data.get("tag.json_metadata"))

    # convert tag metadata to normal keys names and values to correct types
    for k, v in tag_data.items():
        key = k.replace("tag.", "")

        try:
            # capture exceptions which are related to strings only
            if re.match(r"^[\d]+$", v):
                value = int(v)
            elif re.match(r"^True$", v):
                value = True
            elif re.match(r"^False$", v):
                value = False
            elif re.match(r"^None$", v):
                value = None
            elif re.match(r"^[\w\d_]+$", v):
                value = v
            else:
                value = ast.literal_eval(v)
        except (ValueError, SyntaxError):
            value = v

        data[key] = value

    return data

get_trackitem_ayon_tag(track_item, tag_name=AYON_TAG_NAME)

Get pype 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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
def get_trackitem_ayon_tag(track_item, tag_name=AYON_TAG_NAME):
    """
    Get pype 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
    """
    # get all tags from track item
    _tags = track_item.tags()
    if not _tags:
        return None
    for tag in _tags:
        # return only correct tag defined by global name
        if tag_name in tag.name():
            return tag

imprint(track_item, data=None)

Adding Avalon data into a hiero track item tag.

Also including publish attribute into 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', 'productType': 'render', 'productName': 'productMain' }

Source code in client/ayon_hiero/api/lib.py
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
def imprint(track_item, data=None):
    """
    Adding `Avalon data` into a hiero track item tag.

    Also including publish attribute into 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',
            'productType': '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
644
645
646
647
648
649
650
651
652
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()

selection_changed_timeline(event)

Callback on timeline to check if asset in data is the same as clip name.

Parameters:

Name Type Description Default
event Event

timeline event

required
Source code in client/ayon_hiero/api/lib.py
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
def selection_changed_timeline(event):
    """Callback on timeline to check if asset in data is the same as clip name.

    Args:
        event (hiero.core.Event): timeline event
    """
    timeline_editor = event.sender
    selection = timeline_editor.selection()

    track_items = get_track_items(
        selection=selection,
        track_type="video",
        check_enabled=True,
        check_locked=True,
        check_tagged=True
    )

    # run checking function
    sync_clip_name_to_data_asset(track_items)

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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
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
    """
    data = data or {}

    # basic Tag's attribute
    tag_data = {
        "editable": "0",
        "note": "AYON data container",
        "icon": "AYON_icon.png",
        "metadata": dict(data.items())
    }
    # get available pype tag if any
    _tag = get_track_ayon_tag(track)

    if _tag:
        # it not tag then create one
        tag = tags.update_tag(_tag, tag_data)
    else:
        # if pype tag available then update with input data
        tag = tags.create_tag(
            "{}_{}".format(
                AYON_TAG_NAME,
                _get_tag_unique_hash()
            ),
            tag_data
        )
        # add it to the input track item
        track.addTag(tag)

    return tag

set_trackitem_ayon_tag(track_item, 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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
def set_trackitem_ayon_tag(track_item, data=None):
    """
    Set AYON track tag to input track object.

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

    Returns:
        hiero.core.Tag
    """
    data = data or {}

    # basic Tag's attribute
    tag_data = {
        "editable": "0",
        "note": "AYON data container",
        "icon": "AYON_icon.png",
        "metadata": dict(data.items())
    }
    # get available pype tag if any
    _tag = get_trackitem_ayon_tag(track_item)
    if _tag:
        # if pype tag available then update with input data
        tag = tags.update_tag(_tag, tag_data)
    else:
        # it not tag then create one
        tag = tags.create_tag(
            "{}_{}".format(
                AYON_TAG_NAME,
                _get_tag_unique_hash()
            ),
            tag_data
        )
        # add it to the input track item
        track_item.addTag(tag)

    return tag

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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
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()

    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
681
682
683
684
685
686
687
688
689
690
691
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")