Skip to content

api

ClipLoader

Source code in client/ayon_hiero/api/plugin.py
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
class ClipLoader:

    active_bin = None
    data = dict()

    def __init__(self, cls, context, path, **options):
        """ Initialize object

        Arguments:
            cls (ayon_core.api.Loader): plugin object
            context (dict): loader plugin context
            options (dict)[optional]: possible keys:
                projectBinPath: "path/to/binItem"

        """
        self.__dict__.update(cls.__dict__)
        self.context = context
        self.active_project = lib.get_current_project()
        self.fname = path

        # try to get value from options or evaluate key value for `handles`
        self.with_handles = options.get("handles") or bool(
            options.get("handles") is True)
        # try to get value from options or evaluate key value for `load_how`
        self.sequencial_load = options.get("sequentially") or bool(
            "Sequentially in order" in options.get("load_how", ""))
        # try to get value from options or evaluate key value for `load_to`
        self.new_sequence = options.get("newSequence") or bool(
            "New timeline" in options.get("load_to", ""))
        self.clip_name_template = options.get(
            "clipNameTemplate") or "{asset}_{subset}_{representation}"
        assert self._populate_data(), str(
            "Cannot Load selected data, look into database "
            "or call your supervisor")

        # inject folder data to representation dict
        folder_entity = self.context["folder"]
        self.data["folderAttributes"] = folder_entity["attrib"]

        # add active components to class
        if self.new_sequence:
            if options.get("sequence"):
                # if multiselection is set then use options sequence
                self.active_sequence = options["sequence"]
            else:
                # create new sequence
                self.active_sequence = lib.get_current_sequence(new=True)
                self.active_sequence.setFramerate(
                    hiero.core.TimeBase.fromString(
                        str(self.data["folderAttributes"]["fps"])))
        else:
            self.active_sequence = lib.get_current_sequence()

        if options.get("track"):
            # if multiselection is set then use options track
            self.active_track = options["track"]
        else:
            self.active_track = lib.get_current_track(
                self.active_sequence, self.data["track_name"])

    def _populate_data(self):
        """ Gets context and convert it to self.data
        data structure:
            {
                "name": "assetName_productName_representationName"
                "path": "path/to/file/created/by/get_repr..",
                "binPath": "projectBinPath",
            }
        """
        # create name
        repr = self.context["representation"]
        repr_cntx = repr["context"]
        folder_path = self.context["folder"]["path"]
        product_name = self.context["product"]["name"]
        representation = repr["name"]
        self.data["clip_name"] = self.clip_name_template.format(**repr_cntx)
        self.data["track_name"] = "_".join([product_name, representation])
        self.data["versionAttributes"] = self.context["version"]["attrib"]
        # gets file path
        file = get_representation_path_from_context(self.context)
        if not file:
            repr_id = repr["id"]
            log.warning(
                "Representation id `{}` is failing to load".format(repr_id))
            return None
        self.data["path"] = file.replace("\\", "/")

        # convert to hashed path
        if repr_cntx.get("frame"):
            self._fix_path_hashes()

        # solve project bin structure path
        hierarchy = "Loader{}".format(folder_path)

        self.data["binPath"] = hierarchy

        return True

    def _fix_path_hashes(self):
        """ Convert file path where it is needed padding with hashes
        """
        file = self.data["path"]
        if "#" not in file:
            frame = self.context["representation"]["context"].get("frame")
            padding = len(frame)
            file = file.replace(frame, "#" * padding)
        self.data["path"] = file

    def _make_track_item(self, source_bin_item, audio=False):
        """ Create track item with """

        clip = source_bin_item.activeItem()

        # add to track as clip item
        if not audio:
            track_item = hiero.core.TrackItem(
                self.data["clip_name"], hiero.core.TrackItem.kVideo)
        else:
            track_item = hiero.core.TrackItem(
                self.data["clip_name"], hiero.core.TrackItem.kAudio)

        track_item.setSource(clip)
        track_item.setSourceIn(self.handle_start)
        track_item.setTimelineIn(self.timeline_in)
        track_item.setSourceOut((self.media_duration) - self.handle_end)
        track_item.setTimelineOut(self.timeline_out)
        track_item.setPlaybackSpeed(1)
        self.active_track.addTrackItem(track_item)

        return track_item

    def load(self):
        # create project bin for the media to be imported into
        self.active_bin = lib.create_bin(self.data["binPath"])

        # create mediaItem in active project bin
        # create clip media
        self.media = hiero.core.MediaSource(self.data["path"])
        self.media_duration = int(self.media.duration())

        # get handles
        version_attributes = self.data["versionAttributes"]
        self.handle_start = version_attributes.get("handleStart")
        self.handle_end = version_attributes.get("handleEnd")
        if self.handle_start is None:
            self.handle_start = self.data["folderAttributes"]["handleStart"]
        if self.handle_end is None:
            self.handle_end = self.data["folderAttributes"]["handleEnd"]

        self.handle_start = int(self.handle_start)
        self.handle_end = int(self.handle_end)

        if self.sequencial_load:
            last_track_item = lib.get_track_items(
                sequence_name=self.active_sequence.name(),
                track_name=self.active_track.name()
            )
            if len(last_track_item) == 0:
                last_timeline_out = 0
            else:
                last_track_item = last_track_item[-1]
                last_timeline_out = int(last_track_item.timelineOut()) + 1
            self.timeline_in = last_timeline_out
            self.timeline_out = last_timeline_out + int(
                self.data["folderAttributes"]["clipOut"]
                - self.data["folderAttributes"]["clipIn"])
        else:
            self.timeline_in = int(self.data["folderAttributes"]["clipIn"])
            self.timeline_out = int(self.data["folderAttributes"]["clipOut"])

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

        # check if slate is included
        slate_on = "slate" in self.context["version"]["data"].get(
            "families", [])
        log.debug("__ slate_on: {}".format(slate_on))

        # if slate is on then remove the slate frame from beginning
        if slate_on:
            self.media_duration -= 1
            self.handle_start += 1

        # create Clip from Media
        clip = hiero.core.Clip(self.media)
        clip.setName(self.data["clip_name"])

        # add Clip to bin if not there yet
        if self.data["clip_name"] not in [
                b.name() for b in self.active_bin.items()]:
            bin_item = hiero.core.BinItem(clip)
            self.active_bin.addItem(bin_item)

        # just make sure the clip is created
        # there were some cases were hiero was not creating it
        source_bin_item = None
        for item in self.active_bin.items():
            if self.data["clip_name"] == item.name():
                source_bin_item = item
        if not source_bin_item:
            log.warning("Problem with created Source clip: `{}`".format(
                self.data["clip_name"]))

        # include handles
        if self.with_handles:
            self.timeline_in -= self.handle_start
            self.timeline_out += self.handle_end
            self.handle_start = 0
            self.handle_end = 0

        # make track item from source in bin as item
        track_item = self._make_track_item(source_bin_item)

        log.info("Loading clips: `{}`".format(self.data["clip_name"]))
        return track_item

__init__(cls, context, path, **options)

Initialize object

Parameters:

Name Type Description Default
cls Loader

plugin object

required
context dict

loader plugin context

required
options dict)[optional]

possible keys: projectBinPath: "path/to/binItem"

{}
Source code in client/ayon_hiero/api/plugin.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
def __init__(self, cls, context, path, **options):
    """ Initialize object

    Arguments:
        cls (ayon_core.api.Loader): plugin object
        context (dict): loader plugin context
        options (dict)[optional]: possible keys:
            projectBinPath: "path/to/binItem"

    """
    self.__dict__.update(cls.__dict__)
    self.context = context
    self.active_project = lib.get_current_project()
    self.fname = path

    # try to get value from options or evaluate key value for `handles`
    self.with_handles = options.get("handles") or bool(
        options.get("handles") is True)
    # try to get value from options or evaluate key value for `load_how`
    self.sequencial_load = options.get("sequentially") or bool(
        "Sequentially in order" in options.get("load_how", ""))
    # try to get value from options or evaluate key value for `load_to`
    self.new_sequence = options.get("newSequence") or bool(
        "New timeline" in options.get("load_to", ""))
    self.clip_name_template = options.get(
        "clipNameTemplate") or "{asset}_{subset}_{representation}"
    assert self._populate_data(), str(
        "Cannot Load selected data, look into database "
        "or call your supervisor")

    # inject folder data to representation dict
    folder_entity = self.context["folder"]
    self.data["folderAttributes"] = folder_entity["attrib"]

    # add active components to class
    if self.new_sequence:
        if options.get("sequence"):
            # if multiselection is set then use options sequence
            self.active_sequence = options["sequence"]
        else:
            # create new sequence
            self.active_sequence = lib.get_current_sequence(new=True)
            self.active_sequence.setFramerate(
                hiero.core.TimeBase.fromString(
                    str(self.data["folderAttributes"]["fps"])))
    else:
        self.active_sequence = lib.get_current_sequence()

    if options.get("track"):
        # if multiselection is set then use options track
        self.active_track = options["track"]
    else:
        self.active_track = lib.get_current_track(
            self.active_sequence, self.data["track_name"])

CreatorWidget

Bases: QDialog

Source code in client/ayon_hiero/api/plugin.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
class CreatorWidget(QtWidgets.QDialog):

    # output items
    items = {}

    def __init__(self, name, info, ui_inputs, parent=None):
        super(CreatorWidget, self).__init__(parent)

        self.setObjectName(name)

        self.setWindowFlags(
            QtCore.Qt.Window
            | QtCore.Qt.CustomizeWindowHint
            | QtCore.Qt.WindowTitleHint
            | QtCore.Qt.WindowCloseButtonHint
            | QtCore.Qt.WindowStaysOnTopHint
        )
        self.setWindowTitle(name or "AYON Creator Input")
        self.resize(500, 700)

        # Where inputs and labels are set
        self.content_widget = [QtWidgets.QWidget(self)]
        top_layout = QtWidgets.QFormLayout(self.content_widget[0])
        top_layout.setObjectName("ContentLayout")
        top_layout.addWidget(Spacer(5, self))

        # first add widget tag line
        top_layout.addWidget(QtWidgets.QLabel(info))

        # main dynamic layout
        self.scroll_area = QtWidgets.QScrollArea(self, widgetResizable=True)
        self.scroll_area.setVerticalScrollBarPolicy(
            QtCore.Qt.ScrollBarAsNeeded)
        self.scroll_area.setVerticalScrollBarPolicy(
            QtCore.Qt.ScrollBarAlwaysOn)
        self.scroll_area.setHorizontalScrollBarPolicy(
            QtCore.Qt.ScrollBarAlwaysOff)
        self.scroll_area.setWidgetResizable(True)

        self.content_widget.append(self.scroll_area)

        scroll_widget = QtWidgets.QWidget(self)
        in_scroll_area = QtWidgets.QVBoxLayout(scroll_widget)
        self.content_layout = [in_scroll_area]

        # add preset data into input widget layout
        self.items = self.populate_widgets(ui_inputs)
        self.scroll_area.setWidget(scroll_widget)

        # Confirmation buttons
        btns_widget = QtWidgets.QWidget(self)
        btns_layout = QtWidgets.QHBoxLayout(btns_widget)

        cancel_btn = QtWidgets.QPushButton("Cancel")
        btns_layout.addWidget(cancel_btn)

        ok_btn = QtWidgets.QPushButton("Ok")
        btns_layout.addWidget(ok_btn)

        # Main layout of the dialog
        main_layout = QtWidgets.QVBoxLayout(self)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(0)

        # adding content widget
        for w in self.content_widget:
            main_layout.addWidget(w)

        main_layout.addWidget(btns_widget)

        ok_btn.clicked.connect(self._on_ok_clicked)
        cancel_btn.clicked.connect(self._on_cancel_clicked)

        stylesheet = load_stylesheet()
        self.setStyleSheet(stylesheet)

    def _on_ok_clicked(self):
        self.result = self.value(self.items)
        self.close()

    def _on_cancel_clicked(self):
        self.result = None
        self.close()

    def value(self, data, new_data=None):
        new_data = new_data or dict()
        for k, v in data.items():
            new_data[k] = {
                "target": None,
                "value": None
            }
            if v["type"] == "dict":
                new_data[k]["target"] = v["target"]
                new_data[k]["value"] = self.value(v["value"])
            if v["type"] == "section":
                new_data.pop(k)
                new_data = self.value(v["value"], new_data)
            elif getattr(v["value"], "currentText", None):
                new_data[k]["target"] = v["target"]
                new_data[k]["value"] = v["value"].currentText()
            elif getattr(v["value"], "isChecked", None):
                new_data[k]["target"] = v["target"]
                new_data[k]["value"] = v["value"].isChecked()
            elif getattr(v["value"], "value", None):
                new_data[k]["target"] = v["target"]
                new_data[k]["value"] = v["value"].value()
            elif getattr(v["value"], "text", None):
                new_data[k]["target"] = v["target"]
                new_data[k]["value"] = v["value"].text()

        return new_data

    def camel_case_split(self, text):
        matches = re.finditer(
            '.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', text)
        return " ".join([str(m.group(0)).capitalize() for m in matches])

    def create_row(self, layout, type, text, **kwargs):
        value_keys = ["setText", "setCheckState", "setValue", "setChecked"]

        # get type attribute from qwidgets
        attr = getattr(QtWidgets, type)

        # convert label text to normal capitalized text with spaces
        label_text = self.camel_case_split(text)

        # assign the new text to label widget
        label = QtWidgets.QLabel(label_text)
        label.setObjectName("LineLabel")

        # create attribute name text strip of spaces
        attr_name = text.replace(" ", "")

        # create attribute and assign default values
        setattr(
            self,
            attr_name,
            attr(parent=self))

        # assign the created attribute to variable
        item = getattr(self, attr_name)

        # set attributes to item which are not values
        for func, val in kwargs.items():
            if func in value_keys:
                continue

            if getattr(item, func):
                log.debug("Setting {} to {}".format(func, val))
                func_attr = getattr(item, func)
                if isinstance(val, tuple):
                    func_attr(*val)
                else:
                    func_attr(val)

        # set values to item
        for value_item in value_keys:
            if value_item not in kwargs:
                continue
            if getattr(item, value_item):
                getattr(item, value_item)(kwargs[value_item])

        # add to layout
        layout.addRow(label, item)

        return item

    def populate_widgets(self, data, content_layout=None):
        """
        Populate widget from input dict.

        Each plugin has its own set of widget rows defined in dictionary
        each row values should have following keys: `type`, `target`,
        `label`, `order`, `value` and optionally also `toolTip`.

        Args:
            data (dict): widget rows or organized groups defined
                         by types `dict` or `section`
            content_layout (QtWidgets.QFormLayout)[optional]: used when nesting

        Returns:
            dict: redefined data dict updated with created widgets

        """

        content_layout = content_layout or self.content_layout[-1]
        # fix order of process by defined order value
        ordered_keys = list(data.keys())
        for k, v in data.items():
            try:
                # try removing a key from index which should
                # be filled with new
                ordered_keys.pop(v["order"])
            except IndexError:
                pass
            # add key into correct order
            ordered_keys.insert(v["order"], k)

        # process ordered
        for k in ordered_keys:
            v = data[k]
            tool_tip = v.get("toolTip", "")
            if v["type"] == "dict":
                # adding spacer between sections
                self.content_layout.append(QtWidgets.QWidget(self))
                content_layout.addWidget(self.content_layout[-1])
                self.content_layout[-1].setObjectName("sectionHeadline")

                headline = QtWidgets.QVBoxLayout(self.content_layout[-1])
                headline.addWidget(Spacer(20, self))
                headline.addWidget(QtWidgets.QLabel(v["label"]))

                # adding nested layout with label
                self.content_layout.append(QtWidgets.QWidget(self))
                self.content_layout[-1].setObjectName("sectionContent")

                nested_content_layout = QtWidgets.QFormLayout(
                    self.content_layout[-1])
                nested_content_layout.setObjectName("NestedContentLayout")
                content_layout.addWidget(self.content_layout[-1])

                # add nested key as label
                data[k]["value"] = self.populate_widgets(
                    v["value"], nested_content_layout)

            if v["type"] == "section":
                # adding spacer between sections
                self.content_layout.append(QtWidgets.QWidget(self))
                content_layout.addWidget(self.content_layout[-1])
                self.content_layout[-1].setObjectName("sectionHeadline")

                headline = QtWidgets.QVBoxLayout(self.content_layout[-1])
                headline.addWidget(Spacer(20, self))
                headline.addWidget(QtWidgets.QLabel(v["label"]))

                # adding nested layout with label
                self.content_layout.append(QtWidgets.QWidget(self))
                self.content_layout[-1].setObjectName("sectionContent")

                nested_content_layout = QtWidgets.QFormLayout(
                    self.content_layout[-1])
                nested_content_layout.setObjectName("NestedContentLayout")
                content_layout.addWidget(self.content_layout[-1])

                # add nested key as label
                data[k]["value"] = self.populate_widgets(
                    v["value"], nested_content_layout)

            elif v["type"] == "QLineEdit":
                data[k]["value"] = self.create_row(
                    content_layout, "QLineEdit", v["label"],
                    setText=v["value"], setToolTip=tool_tip)
            elif v["type"] == "QComboBox":
                data[k]["value"] = self.create_row(
                    content_layout, "QComboBox", v["label"],
                    addItems=v["value"], setToolTip=tool_tip)
            elif v["type"] == "QCheckBox":
                data[k]["value"] = self.create_row(
                    content_layout, "QCheckBox", v["label"],
                    setChecked=v["value"], setToolTip=tool_tip)
            elif v["type"] == "QSpinBox":
                data[k]["value"] = self.create_row(
                    content_layout, "QSpinBox", v["label"],
                    setValue=v["value"],
                    setDisplayIntegerBase=10000,
                    setRange=(0, 99999), setMinimum=0,
                    setMaximum=100000, setToolTip=tool_tip)

        return data

populate_widgets(data, content_layout=None)

Populate widget from input dict.

Each plugin has its own set of widget rows defined in dictionary each row values should have following keys: type, target, label, order, value and optionally also toolTip.

Parameters:

Name Type Description Default
data dict

widget rows or organized groups defined by types dict or section

required
content_layout QtWidgets.QFormLayout)[optional]

used when nesting

None

Returns:

Name Type Description
dict

redefined data dict updated with created widgets

Source code in client/ayon_hiero/api/plugin.py
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def populate_widgets(self, data, content_layout=None):
    """
    Populate widget from input dict.

    Each plugin has its own set of widget rows defined in dictionary
    each row values should have following keys: `type`, `target`,
    `label`, `order`, `value` and optionally also `toolTip`.

    Args:
        data (dict): widget rows or organized groups defined
                     by types `dict` or `section`
        content_layout (QtWidgets.QFormLayout)[optional]: used when nesting

    Returns:
        dict: redefined data dict updated with created widgets

    """

    content_layout = content_layout or self.content_layout[-1]
    # fix order of process by defined order value
    ordered_keys = list(data.keys())
    for k, v in data.items():
        try:
            # try removing a key from index which should
            # be filled with new
            ordered_keys.pop(v["order"])
        except IndexError:
            pass
        # add key into correct order
        ordered_keys.insert(v["order"], k)

    # process ordered
    for k in ordered_keys:
        v = data[k]
        tool_tip = v.get("toolTip", "")
        if v["type"] == "dict":
            # adding spacer between sections
            self.content_layout.append(QtWidgets.QWidget(self))
            content_layout.addWidget(self.content_layout[-1])
            self.content_layout[-1].setObjectName("sectionHeadline")

            headline = QtWidgets.QVBoxLayout(self.content_layout[-1])
            headline.addWidget(Spacer(20, self))
            headline.addWidget(QtWidgets.QLabel(v["label"]))

            # adding nested layout with label
            self.content_layout.append(QtWidgets.QWidget(self))
            self.content_layout[-1].setObjectName("sectionContent")

            nested_content_layout = QtWidgets.QFormLayout(
                self.content_layout[-1])
            nested_content_layout.setObjectName("NestedContentLayout")
            content_layout.addWidget(self.content_layout[-1])

            # add nested key as label
            data[k]["value"] = self.populate_widgets(
                v["value"], nested_content_layout)

        if v["type"] == "section":
            # adding spacer between sections
            self.content_layout.append(QtWidgets.QWidget(self))
            content_layout.addWidget(self.content_layout[-1])
            self.content_layout[-1].setObjectName("sectionHeadline")

            headline = QtWidgets.QVBoxLayout(self.content_layout[-1])
            headline.addWidget(Spacer(20, self))
            headline.addWidget(QtWidgets.QLabel(v["label"]))

            # adding nested layout with label
            self.content_layout.append(QtWidgets.QWidget(self))
            self.content_layout[-1].setObjectName("sectionContent")

            nested_content_layout = QtWidgets.QFormLayout(
                self.content_layout[-1])
            nested_content_layout.setObjectName("NestedContentLayout")
            content_layout.addWidget(self.content_layout[-1])

            # add nested key as label
            data[k]["value"] = self.populate_widgets(
                v["value"], nested_content_layout)

        elif v["type"] == "QLineEdit":
            data[k]["value"] = self.create_row(
                content_layout, "QLineEdit", v["label"],
                setText=v["value"], setToolTip=tool_tip)
        elif v["type"] == "QComboBox":
            data[k]["value"] = self.create_row(
                content_layout, "QComboBox", v["label"],
                addItems=v["value"], setToolTip=tool_tip)
        elif v["type"] == "QCheckBox":
            data[k]["value"] = self.create_row(
                content_layout, "QCheckBox", v["label"],
                setChecked=v["value"], setToolTip=tool_tip)
        elif v["type"] == "QSpinBox":
            data[k]["value"] = self.create_row(
                content_layout, "QSpinBox", v["label"],
                setValue=v["value"],
                setDisplayIntegerBase=10000,
                setRange=(0, 99999), setMinimum=0,
                setMaximum=100000, setToolTip=tool_tip)

    return data

HieroHost

Bases: HostBase, IWorkfileHost, ILoadHost, IPublishHost

Source code in client/ayon_hiero/api/pipeline.py
 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
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
class HieroHost(
    HostBase, IWorkfileHost, ILoadHost, IPublishHost
):
    name = "hiero"

    def open_workfile(self, filepath):
        return open_file(filepath)

    def save_workfile(self, filepath=None):
        return save_file(filepath)

    def get_current_workfile(self):
        return current_file()

    def workfile_has_unsaved_changes(self):
        return has_unsaved_changes()

    def get_workfile_extensions(self):
        return file_extensions()

    def get_containers(self):
        return ls()

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

        # adding all events
        events.register_events()

        log.info("Registering Hiero plug-ins..")
        pyblish.register_host("hiero")
        pyblish.register_plugin_path(PUBLISH_PATH)
        register_loader_plugin_path(LOAD_PATH)
        register_creator_plugin_path(CREATE_PATH)

        # install menu
        menu.menu_install()
        menu.add_scripts_menu()

        # register hiero events
        events.register_hiero_events()

    def get_context_data(self):
        # TODO: implement to support persisting context attributes
        return {}

    def update_context_data(self, data, changes):
        # TODO: implement to support persisting context attributes
        pass

install()

Installing all requirements for hiero host

Source code in client/ayon_hiero/api/pipeline.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def install(self):
    """Installing all requirements for hiero host"""

    # adding all events
    events.register_events()

    log.info("Registering Hiero plug-ins..")
    pyblish.register_host("hiero")
    pyblish.register_plugin_path(PUBLISH_PATH)
    register_loader_plugin_path(LOAD_PATH)
    register_creator_plugin_path(CREATE_PATH)

    # install menu
    menu.menu_install()
    menu.add_scripts_menu()

    # register hiero events
    events.register_hiero_events()

PublishClip

Convert a track item to publishable instance

Parameters:

Name Type Description Default
track_item TrackItem

hiero track item object

required
kwargs optional

additional data needed for rename=True (presets)

required

Returns:

Type Description

hiero.core.TrackItem: hiero track item object with AYON tag

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

    Args:
        track_item (hiero.core.TrackItem): hiero track item object
        kwargs (optional): additional data needed for rename=True (presets)

    Returns:
        hiero.core.TrackItem: hiero track item object with AYON tag
    """
    tag_data = {}

    types = {
        "shot": "shot",
        "folder": "folder",
        "episode": "episode",
        "sequence": "sequence",
        "track": "sequence",
    }

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

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

    # Define which keys of the pre create data should also be 'tag data'
    tag_keys = {
        # renameHierarchy
        "hierarchy",
        # hierarchyData
        "folder", "episode", "sequence", "track", "shot",
        # publish settings
        "audio", "sourceResolution",
        # shot attributes
        "workfileFrameStart", "handleStart", "handleEnd",
        # instance attributes data
        "reviewableSource",
    }

    def __init__(
            self,
            track_item,
            vertical_clip_match,
            vertical_clip_used,
            pre_create_data=None,
            data=None,
            rename_index=0):

        self.vertical_clip_match = vertical_clip_match
        self.vertical_clip_used = vertical_clip_used

        self.rename_index = rename_index

        # adding ui inputs if any
        self.pre_create_data = pre_create_data or {}

        # get main parent objects
        self.track_item = track_item
        sequence_name = lib.get_current_sequence().name()
        self.sequence_name = str(sequence_name).replace(" ", "_")

        # track item (clip) main attributes
        self.ti_name = track_item.name()
        self.ti_index = int(track_item.eventNumber())

        # get track name and index
        track_name = track_item.parent().name()
        self.track_name = str(track_name).replace(" ", "_")
        self.track_index = int(track_item.parent().trackIndex())

        # adding instance_data["productType"] into tag
        if data:
            self.tag_data.update(data)

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

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

        # create parents with correct types
        self._create_parents()

    def convert(self):

        # solve track item data and add them to tag data
        self._convert_to_tag_data()

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

        # deal with clip name
        new_name = self.tag_data.pop("newClipName")

        if self.rename:
            # rename track item
            self.track_item.setName(new_name)
            self.tag_data["folderName"] = new_name
        else:
            self.tag_data["folderName"] = self.ti_name
            self.tag_data["hierarchyData"]["shot"] = self.ti_name

        # AYON unique identifier
        folder_path = "/{}/{}".format(
            self.tag_data["hierarchy"],
            self.tag_data["folderName"]
        )
        self.tag_data["folderPath"] = folder_path

        return self.track_item

    def _populate_track_item_default_data(self):
        """ Populate default formatting data from track item. """

        self.track_item_default_data = {
            "_folder_": "shots",
            "_sequence_": self.sequence_name,
            "_track_": self.track_name,
            "_clip_": self.ti_name,
            "_trackIndex_": self.track_index,
            "_clipIndex_": self.ti_index
        }

    def _populate_attributes(self):
        """ Populate main object attributes. """
        # track item frame range and parent track name for vertical sync check
        self.clip_in = int(self.track_item.timelineIn())
        self.clip_out = int(self.track_item.timelineOut())

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

        # publisher ui attribute inputs or default values if gui was not used
        def get(key):
            """Shorthand access for code readability"""
            return self.pre_create_data.get(key)

        # ui_inputs data or default values if gui was not used
        self.rename = self.pre_create_data.get(
            "clipRename", self.rename_default)
        self.clip_name = get("clipName") or self.clip_name_default
        self.hierarchy = get("hierarchy") or self.hierarchy_default
        self.count_from = get("countFrom") or self.count_from_default
        self.count_steps = get("countSteps") or self.count_steps_default
        self.base_product_variant = (
            get("clipVariant") or self.base_product_variant_default)
        self.product_type = get("productType") or self.product_type_default
        self.vertical_sync = get("vSyncOn") or self.vertical_sync_default
        self.driving_layer = get("vSyncTrack") or self.driving_layer_default
        self.driving_layer = self.driving_layer.replace(" ", "_")
        self.review_source = (
            get("reviewableSource") or self.review_source_default)
        self.audio = get("audio") or False

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

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

        # create product for publishing
        self.product_name = f"{self.product_type}{self.variant.capitalize()}"

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

    def _convert_to_tag_data(self):
        """ Convert internal data to tag data.

        Populating the tag data into internal variable self.tag_data
        """
        # define vertical sync attributes
        hero_track = True
        self.reviewable_source = ""
        if (
            self.vertical_sync
            and self.track_name != self.driving_layer
        ):
            # check if track name is not in driving layer
            # if it is not then define vertical sync as None
            hero_track = False

        # increasing steps by index of rename iteration
        self.count_steps *= self.rename_index

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

        # in case we are running creators headless default
        # precreate data values are used
        if self.pre_create_data:

            # adding tag metadata from ui
            for _key, _value in self.pre_create_data.items():
                # backward compatibility for reviewableSource (2024.11.08)
                if (
                    _key == "reviewableSource"
                    and "reviewTrack" in self.tag_keys
                ):
                    self.tag_data.pop("reviewTrack")
                    self.tag_data["reviewableSource"] = _value
                if _key in self.tag_keys:
                    self.tag_data[_key] = _value

            # driving layer is set as positive match
            if hero_track or self.vertical_sync:
                # mark review layer
                if self.review_source and (
                        self.review_source != self.review_source_default):
                    # if review layer is defined and not the same as default
                    self.reviewable_source = self.review_source
                # shot num calculate
                if self.rename_index == 0:
                    self.shot_num = self.count_from
                else:
                    self.shot_num = self.count_from + self.count_steps

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

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

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

        tag_instance_data = self._solve_tag_instance_data(
            hierarchy_formatting_data
        )

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

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

                If clip frame range is outside of hero clip frame range
                then skip this clip and do not add to hierarchical shared
                metadata to them.
                """
                if self.clip_in < hero_in or self.clip_out > hero_out:
                    continue

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

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

                # get used names list for duplicity check
                used_names_list = self.vertical_clip_used.setdefault(
                    f"{new_clip_name}{data_product_name}", [])

                clip_product_name = self.product_name
                variant = self.variant

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

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

                # in case track clip product name had been already used
                # then add product name with clip index
                if clip_product_name in used_names_list:
                    clip_product_name = (
                        f"{clip_product_name}{self.rename_index}")
                    variant = f"{variant}{self.rename_index}"

                _distrib_data["productName"] = clip_product_name
                _distrib_data["variant"] = variant
                # assign data to return hierarchy data to tag
                tag_instance_data = _distrib_data

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

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

        # add uuid to tag data
        self.tag_data["uuid"] = str(uuid.uuid4())

        # add review track only to hero track
        if hero_track and self.reviewable_source:
            self.tag_data["reviewTrack"] = self.reviewable_source
        else:
            self.tag_data.update({"reviewTrack": None})

        # add only review related data if reviewable source is set
        if self.reviewable_source:
            review_switch = True
            reviewable_source = self.reviewable_source
            #
            if self.vertical_sync and not hero_track:
                review_switch = False
                reviewable_source = False

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

            if reviewable_source:
                self.tag_data["reviewableSource"] = reviewable_source
            else:
                self.tag_data.pop("reviewableSource", None)

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

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

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

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

        assert folder_type, "Missing folder type for `{}`".format(
            src_type
        )
        formatting_data = {}
        for _k, _v in self.hierarchy_data.items():
            value = _v.format(
                **self.track_item_default_data)
            formatting_data[_k] = value

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

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

        pattern = re.compile(self.parents_search_pattern)

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

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

SequenceLoader

Bases: LoaderPlugin

A basic SequenceLoader for Resolve

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

Source code in client/ayon_hiero/api/plugin.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
class SequenceLoader(LoaderPlugin):
    """A basic SequenceLoader for Resolve

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

    """

    options = [
        qargparse.Boolean(
            "handles",
            label="Include handles",
            default=0,
            help="Load with handles or without?"
        ),
        qargparse.Choice(
            "load_to",
            label="Where to load clips",
            items=[
                "Current timeline",
                "New timeline"
            ],
            default="Current timeline",
            help="Where do you want clips to be loaded?"
        ),
        qargparse.Choice(
            "load_how",
            label="How to load clips",
            items=[
                "Original timing",
                "Sequentially in order"
            ],
            default="Original timing",
            help="Would you like to place it at original timing?"
        )
    ]

    def load(
        self,
        context,
        name=None,
        namespace=None,
        options=None
    ):
        pass

    def update(self, container, context):
        """Update an existing `container`
        """
        pass

    def remove(self, container):
        """Remove an existing `container`
        """
        pass

remove(container)

Remove an existing container

Source code in client/ayon_hiero/api/plugin.py
377
378
379
380
def remove(self, container):
    """Remove an existing `container`
    """
    pass

update(container, context)

Update an existing container

Source code in client/ayon_hiero/api/plugin.py
372
373
374
375
def update(self, container, context):
    """Update an existing `container`
    """
    pass

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

containerise(track_item, name, namespace, context, loader=None, data=None)

Bundle Hiero's object into an assembly and imprint it with metadata

Containerisation enables a tracking of version, author and origin for loaded assets.

Parameters:

Name Type Description Default
track_item TrackItem

object to imprint as container

required
name str

Name of resulting assembly

required
namespace str

Namespace under which to host container

required
context dict

Asset information

required
loader str

Name of node used to produce this container.

None

Returns:

Name Type Description
track_item TrackItem

containerised object

Source code in client/ayon_hiero/api/pipeline.py
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
def containerise(track_item,
                 name,
                 namespace,
                 context,
                 loader=None,
                 data=None):
    """Bundle Hiero's object into an assembly and imprint it with metadata

    Containerisation enables a tracking of version, author and origin
    for loaded assets.

    Arguments:
        track_item (hiero.core.TrackItem): object to imprint as container
        name (str): Name of resulting assembly
        namespace (str): Namespace under which to host container
        context (dict): Asset information
        loader (str, optional): Name of node used to produce this container.

    Returns:
        track_item (hiero.core.TrackItem): containerised object

    """

    data_imprint = OrderedDict({
        "schema": "ayon:container-3.0",
        "id": AYON_CONTAINER_ID,
        "name": str(name),
        "namespace": str(namespace),
        "loader": str(loader),
        "representation": context["representation"]["id"],
    })

    if data:
        for k, v in data.items():
            data_imprint.update({k: v})

    log.debug("_ data_imprint: {}".format(data_imprint))
    lib.set_trackitem_ayon_tag(track_item, data_imprint)

    return track_item

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

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_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(*args)

Wrapping function for workfiles launcher

Source code in client/ayon_hiero/api/pipeline.py
286
287
288
289
290
291
292
def launch_workfiles_app(*args):
    ''' Wrapping function for workfiles launcher '''
    from .lib import get_main_window

    main_window = get_main_window()
    # show workfile gui
    host_tools.show_workfiles(parent=main_window)

ls()

List available containers.

This function is used by the Container Manager in Nuke. You'll need to implement a for-loop that then yields one Container at a time.

See the container.json schema for details on how it should look, and the Maya equivalent, which is in avalon.maya.pipeline

Source code in client/ayon_hiero/api/pipeline.py
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
def ls():
    """List available containers.

    This function is used by the Container Manager in Nuke. You'll
    need to implement a for-loop that then *yields* one Container at
    a time.

    See the `container.json` schema for details on how it should look,
    and the Maya equivalent, which is in `avalon.maya.pipeline`
    """

    # get all track items from current timeline
    all_items = lib.get_track_items()

    # append all video tracks
    for track in (lib.get_current_sequence() or []):
        if type(track) is not hiero.core.VideoTrack:
            continue
        all_items.append(track)

    for item in all_items:
        container_data = parse_container(item)

        if isinstance(container_data, list):
            for _c in container_data:
                yield _c
        elif container_data:
            yield container_data

maintained_selection()

Maintain selection during context

Example

with maintained_selection(): ... for track_item in track_items: ... < do some stuff >

Source code in client/ayon_hiero/api/pipeline.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
@contextlib.contextmanager
def maintained_selection():
    """Maintain selection during context

    Example:
        >>> with maintained_selection():
        ...     for track_item in track_items:
        ...         < do some stuff >
    """
    from .lib import (
        set_selected_track_items,
        get_selected_track_items
    )
    previous_selection = get_selected_track_items()
    reset_selection()
    try:
        # do the operation
        yield
    finally:
        reset_selection()
        set_selected_track_items(previous_selection)

open_file(filepath)

Manually fire the kBeforeProjectLoad event in order to work around a bug in Hiero. The Foundry has logged this bug as: Bug 40413 - Python API - kBeforeProjectLoad event type is not triggered when calling hiero.core.openProject() (only triggered through UI) It exists in all versions of Hiero through (at least) v1.9v1b12.

Once this bug is fixed, a version check will need to be added here in order to prevent accidentally firing this event twice. The following commented-out code is just an example, and will need to be updated when the bug is fixed to catch the correct versions.

Source code in client/ayon_hiero/api/workio.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def open_file(filepath):
    """Manually fire the kBeforeProjectLoad event in order to work around a bug in Hiero.
    The Foundry has logged this bug as:
      Bug 40413 - Python API - kBeforeProjectLoad event type is not triggered
      when calling hiero.core.openProject() (only triggered through UI)
    It exists in all versions of Hiero through (at least) v1.9v1b12.

    Once this bug is fixed, a version check will need to be added here in order to
    prevent accidentally firing this event twice. The following commented-out code
    is just an example, and will need to be updated when the bug is fixed to catch the
    correct versions."""
    # if (hiero.core.env['VersionMajor'] < 1 or
    #     hiero.core.env['VersionMajor'] == 1 and hiero.core.env['VersionMinor'] < 10:
    hiero.core.events.sendEvent("kBeforeProjectLoad", None)

    project = hiero.core.projects()[-1]

    # Close previous project if its different to the current project.
    filepath = filepath.replace(os.path.sep, "/")
    if project.path().replace(os.path.sep, "/") != filepath:
        # open project file
        hiero.core.openProject(filepath)
        project.close()

    return True

parse_container(item, validate=True)

Return container data from track_item's pype tag.

Parameters:

Name Type Description Default
item TrackItem or VideoTrack

A containerised track item.

required
validate bool)[optional]

validating with avalon scheme

True

Returns:

Name Type Description
dict

The container schema data for input containerized track item.

Source code in client/ayon_hiero/api/pipeline.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def parse_container(item, validate=True):
    """Return container data from track_item's pype tag.

    Args:
        item (hiero.core.TrackItem or hiero.core.VideoTrack):
            A containerised track item.
        validate (bool)[optional]: validating with avalon scheme

    Returns:
        dict: The container schema data for input containerized track item.

    """
    def data_to_container(item, data):
        if (
            not data
            or data.get("id") not in {
                AYON_CONTAINER_ID, AVALON_CONTAINER_ID
            }
        ):
            return

        if validate and data and data.get("schema"):
            schema.validate(data)

        if not isinstance(data, dict):
            return

        # If not all required data return the empty container
        required = ['schema', 'id', 'name',
                    'namespace', 'loader', 'representation']

        if any(key not in data for key in required):
            return

        container = {key: data[key] for key in required}

        container["objectName"] = item.name()

        # Store reference to the node object
        container["_item"] = item

        return container

    # convert tag metadata to normal keys names
    if type(item) is hiero.core.VideoTrack:
        return_list = []
        _data = lib.get_track_ayon_data(item)

        if not _data:
            return
        # convert the data to list and validate them
        for _, obj_data in _data.items():
            container = data_to_container(item, obj_data)
            return_list.append(container)
        return return_list
    else:
        _data = lib.get_trackitem_ayon_data(item)
        return data_to_container(item, _data)

publish(parent)

Shorthand to publish from within host

Source code in client/ayon_hiero/api/pipeline.py
295
296
297
def publish(parent):
    """Shorthand to publish from within host"""
    return host_tools.show_publish(parent)

reload_config()

Attempt to reload pipeline at run-time.

CAUTION: This is primarily for development and debugging purposes.

Source code in client/ayon_hiero/api/pipeline.py
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
def reload_config():
    """Attempt to reload pipeline at run-time.

    CAUTION: This is primarily for development and debugging purposes.

    """
    import importlib

    for module in (
        "ayon_hiero.lib",
        "ayon_hiero.menu",
        "ayon_hiero.tags"
    ):
        log.info("Reloading module: {}...".format(module))
        try:
            module = importlib.import_module(module)
            import imp
            imp.reload(module)
        except Exception as e:
            log.warning("Cannot reload module: {}".format(e))
            importlib.reload(module)

reset_selection()

Deselect all selected nodes

Source code in client/ayon_hiero/api/pipeline.py
323
324
325
326
327
def reset_selection():
    """Deselect all selected nodes
    """
    from .lib import set_selected_track_items
    set_selected_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

update_container(item, data=None)

Update container data to input track_item or track's AYON tag.

Parameters:

Name Type Description Default
item TrackItem or VideoTrack

A containerised track item.

required
data dict)[optional]

dictionery with data to be updated

None

Returns:

Name Type Description
bool

True if container was updated correctly

Source code in client/ayon_hiero/api/pipeline.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def update_container(item, data=None):
    """Update container data to input track_item or track's
    AYON tag.

    Args:
        item (hiero.core.TrackItem or hiero.core.VideoTrack):
            A containerised track item.
        data (dict)[optional]: dictionery with data to be updated

    Returns:
        bool: True if container was updated correctly

    """

    data = data or {}
    data = deepcopy(data)

    if type(item) is hiero.core.VideoTrack:
        # form object data for test
        object_name = data["objectName"]

        # get all available containers
        containers = lib.get_track_ayon_data(item)
        container = lib.get_track_ayon_data(item, object_name)

        containers = deepcopy(containers)
        container = deepcopy(container)

        # update data in container
        updated_container = _update_container_data(container, data)
        # merge updated container back to containers
        containers.update({object_name: updated_container})

        return bool(lib.set_track_ayon_tag(item, containers))
    else:
        container = lib.get_trackitem_ayon_data(item)
        updated_container = _update_container_data(container, data)

        log.info("Updating container: `{}`".format(item.name()))
        return bool(lib.set_trackitem_ayon_tag(item, updated_container))