284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
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
381
382
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
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 | class CreateShotClip(plugin.HieroCreator):
"""Publishable clip"""
identifier = "io.ayon.creators.hiero.clip"
label = "Create Publishable Clip"
product_type = "editorial"
icon = "film"
defaults = ["Main"]
detailed_description = """
Publishing clips/plate, audio for new shots to project
or updating already created from Hiero. Publishing will create
OTIO file.
"""
create_allow_thumbnail = False
def get_pre_create_attr_defs(self):
def header_label(text):
return f"<br><b>{text}</b>"
tokens_help = """\nUsable tokens:
{_clip_}: name of used clip
{_track_}: name of parent track layer
{_sequence_}: name of parent sequence (timeline)"""
current_sequence = lib.get_current_sequence()
if current_sequence is not None:
gui_tracks = [
{"value": tr.name(), "label": f"Track: {tr.name()}"}
for tr in current_sequence.videoTracks()
]
else:
gui_tracks = []
# Project settings might be applied to this creator via
# the inherited `Creator.apply_settings`
presets = self.presets
return [
BoolDef("use_selection",
label="Use only selected clip(s).",
tooltip=(
"When enabled it restricts create process "
"to selected clips."
),
default=True),
# renameHierarchy
UILabelDef(
label=header_label("Shot Hierarchy And Rename Settings")
),
TextDef(
"hierarchy",
label="Shot Parent Hierarchy",
tooltip="Parents folder for shot root folder, "
"Template filled with *Hierarchy Data* section",
default=presets.get("hierarchy", "{folder}/{sequence}"),
),
BoolDef(
"clipRename",
label="Rename clips",
tooltip="Renaming selected clips on fly",
default=presets.get("clipRename", False),
),
TextDef(
"clipName",
label="Clip Name Template",
tooltip="template for creating shot names, used for "
"renaming (use rename: on)",
default=presets.get("clipName", "{sequence}{shot}"),
),
NumberDef(
"countFrom",
label="Count sequence from",
tooltip="Set where the sequence number starts from",
default=presets.get("countFrom", 10),
),
NumberDef(
"countSteps",
label="Stepping number",
tooltip="What number is adding every new step",
default=presets.get("countSteps", 10),
),
# hierarchyData
UILabelDef(
label=header_label("Shot Template Keywords")
),
TextDef(
"folder",
label="{folder}",
tooltip="Name of folder used for root of generated shots.\n"
f"{tokens_help}",
default=presets.get("folder", "shots"),
),
TextDef(
"episode",
label="{episode}",
tooltip=f"Name of episode.\n{tokens_help}",
default=presets.get("episode", "ep01"),
),
TextDef(
"sequence",
label="{sequence}",
tooltip=f"Name of sequence of shots.\n{tokens_help}",
default=presets.get("sequence", "sq01"),
),
TextDef(
"track",
label="{track}",
tooltip=f"Name of timeline track.\n{tokens_help}",
default=presets.get("track", "{_track_}"),
),
TextDef(
"shot",
label="{shot}",
tooltip="Name of shot. '#' is converted to padded number."
f"\n{tokens_help}",
default=presets.get("shot", "sh###"),
),
# verticalSync
UILabelDef(
label=header_label("Vertical Synchronization Of Attributes")
),
BoolDef(
"vSyncOn",
label="Enable Vertical Sync",
tooltip="Switch on if you want clips above "
"each other to share its attributes",
default=presets.get("vSyncOn", True),
),
EnumDef(
"vSyncTrack",
label="Hero track",
tooltip="Select driving track name which should "
"be mastering all others",
items=(
gui_tracks or [
{"value": None, "label": "< nothing to select> "}
]
),
),
# publishSettings
UILabelDef(
label=header_label("Publish Settings")
),
EnumDef(
"clipVariant",
label="Product Variant",
tooltip="Chose variant which will be then used for "
"product name, if <track_name> "
"is selected, name of track layer will be used",
items=['<track_name>', 'main', 'bg', 'fg', 'bg', 'animatic'],
),
EnumDef(
"productType",
label="Product Type",
tooltip="How the product will be used",
items=['plate', 'take'],
),
EnumDef(
"reviewableSource",
label="Reviewable Source",
tooltip="Generate preview videos on fly, if "
"'< none >' is defined nothing will be generated.",
items=[
{"value": None, "label": "< none >"},
{"value": "clip_media", "label": "[ Clip's media ]"},
]
+ gui_tracks,
),
BoolDef(
"export_audio",
label="Include audio",
tooltip="Process subsets with corresponding audio",
default=False,
),
BoolDef(
"sourceResolution",
label="Source resolution",
tooltip="Is resolution taken from timeline or source?",
default=False,
),
# shotAttr
UILabelDef(
label=header_label("Shot Attributes"),
),
NumberDef(
"workfileFrameStart",
label="Workfiles Start Frame",
tooltip="Set workfile starting frame number",
default=presets.get("workfileFrameStart", 1001),
),
NumberDef(
"handleStart",
label="Handle start (head)",
tooltip="Handle at start of clip",
default=presets.get("handleStart", 0),
),
NumberDef(
"handleEnd",
label="Handle end (tail)",
tooltip="Handle at end of clip",
default=presets.get("handleEnd", 0),
),
]
def create(self, subset_name, instance_data, pre_create_data):
super(CreateShotClip, self).create(subset_name,
instance_data,
pre_create_data)
if len(self.selected) < 1:
return
self.log.info(self.selected)
self.log.debug(f"Selected: {self.selected}")
audio_clips = []
for audio_track in self.sequence.audioTracks():
audio_clips.extend(audio_track.items())
if not audio_clips and pre_create_data.get("export_audio"):
raise CreatorError(
"You must have audio in your active "
"timeline in order to export audio."
)
instance_data["task"] = None
# sort selected trackItems by
sorted_selected_track_items = list()
unsorted_selected_track_items = list()
v_sync_track = pre_create_data.get("vSyncTrack", "")
for _ti in self.selected:
if _ti.parent().name() in v_sync_track:
sorted_selected_track_items.append(_ti)
else:
unsorted_selected_track_items.append(_ti)
sorted_selected_track_items.extend(unsorted_selected_track_items)
shot_creator_id = "io.ayon.creators.hiero.shot"
audio_creator_id = "io.ayon.creators.hiero.audio"
plate_creator_id = "io.ayon.creators.hiero.plate"
# detect enabled creators for review, plate and audio
all_creators = {
shot_creator_id: True,
plate_creator_id: True,
audio_creator_id: True,
}
instances = []
all_shot_instances = {}
vertical_clip_match = {}
vertical_clip_used = {}
for idx, track_item in enumerate(sorted_selected_track_items):
_instance_data = copy.deepcopy(instance_data)
_instance_data["clip_index"] = track_item.guid()
# convert track item to timeline media pool item
publish_clip = plugin.PublishClip(
track_item,
vertical_clip_match,
vertical_clip_used,
pre_create_data=pre_create_data,
rename_index=idx,
data=_instance_data,
)
track_item = publish_clip.convert()
if track_item is None:
# Ignore input clips that do not convert into a track item
# from `PublishClip.convert`
continue
self.log.info(
"Processing track item data: {} (index: {})".format(
track_item, idx)
)
_instance_data.update(publish_clip.tag_data)
# Delete any existing instances previously generated for the clip.
prev_tag = lib.get_trackitem_ayon_tag(track_item)
if prev_tag:
prev_tag_data = tags.get_tag_data(prev_tag)
for creator_id, inst_data in prev_tag_data[_CONTENT_ID].items():
creator = self.create_context.creators[creator_id]
prev_instances = [
inst for inst_id, inst
in self.create_context.instances_by_id.items()
if inst_id == inst_data["instance_id"]
]
creator.remove_instances(prev_instances)
# Create new product(s) instances.
shot_folder_path = _instance_data["folderPath"]
shot_instances = all_shot_instances.setdefault(
shot_folder_path, {})
# desable shot creator if heroTrack is not enabled
all_creators[shot_creator_id] = _instance_data.get(
"heroTrack", False)
# desable audio creator if audio is not enabled
all_creators[audio_creator_id] = (
_instance_data.get("heroTrack", False) and
pre_create_data.get("export_audio", False)
)
enabled_creators = tuple(
cre for cre, enabled in all_creators.items() if enabled
)
clip_instances = {}
for creator_id in enabled_creators:
creator = self.create_context.creators[creator_id]
sub_instance_data = copy.deepcopy(_instance_data)
creator_attributes = sub_instance_data.setdefault(
"creator_attributes", {})
shot_folder_path = sub_instance_data["folderPath"]
# Shot creation
if creator_id == shot_creator_id:
track_item_duration = track_item.duration()
workfileFrameStart = \
sub_instance_data["workfileFrameStart"]
sub_instance_data.update(
{
"variant": "main",
"productType": "shot",
"productName": "shotMain",
"label": (
f"{sub_instance_data['folderPath']} shotMain"),
}
)
creator_attributes.update(
{
"workfileFrameStart": sub_instance_data[
"workfileFrameStart"
],
"handleStart": sub_instance_data["handleStart"],
"handleEnd": sub_instance_data["handleEnd"],
"frameStart": workfileFrameStart,
"frameEnd": (
workfileFrameStart + track_item_duration),
"clipIn": track_item.timelineIn(),
"clipOut": track_item.timelineOut(),
"clipDuration": track_item_duration,
"sourceIn": track_item.sourceIn(),
"sourceOut": track_item.sourceOut(),
}
)
# Plate, Audio
# insert parent instance data to allow
# metadata recollection as publish time.
elif creator_id == plate_creator_id:
parenting_data = shot_instances[shot_creator_id]
sub_instance_data.update({
"parent_instance_id": parenting_data["instance_id"],
"label": (
f"{sub_instance_data['folderPath']} "
f"{sub_instance_data['productName']}"
)
})
creator_attributes["parentInstance"] = parenting_data[
"label"]
if sub_instance_data.get("reviewableSource"):
creator_attributes.update({
"review": True,
"reviewableSource": sub_instance_data[
"reviewableSource"],
})
elif creator_id == audio_creator_id:
sub_instance_data["variant"] = "main"
sub_instance_data["productType"] = "audio"
sub_instance_data["productName"] = "audioMain"
parenting_data = shot_instances[shot_creator_id]
sub_instance_data.update(
{
"parent_instance_id": parenting_data["instance_id"],
"label": (
f"{sub_instance_data['folderPath']} "
f"{sub_instance_data['productName']}"
)
}
)
creator_attributes["parentInstance"] = parenting_data[
"label"]
if sub_instance_data.get("reviewableSource"):
creator_attributes["review"] = True
instance = creator.create(sub_instance_data, None)
instance.transient_data["track_item"] = track_item
self._add_instance_to_context(instance)
instance_data_to_store = instance.data_to_store()
shot_instances[creator_id] = instance_data_to_store
clip_instances[creator_id] = instance_data_to_store
lib.imprint(
track_item,
data={
_CONTENT_ID: clip_instances,
"clip_index": track_item.guid(),
}
)
instances.append(instance)
return instances
def _create_and_add_instance(self, data, creator_id,
track_item, instances):
"""
Args:
data (dict): The data to re-recreate the instance from.
creator_id (str): The creator id to use.
track_item (obj): The associated track item.
instances (list): Result instance container.
Returns:
CreatedInstance: The newly created instance.
"""
creator = self.create_context.creators[creator_id]
instance = creator.create(data, None)
instance.transient_data["track_item"] = track_item
self._add_instance_to_context(instance)
instances.append(instance)
return instance
def _collect_legacy_instance(self, track_item):
"""Collect a legacy instance from previous creator if any.#
Args:
track_item (obj): The Hiero track_item to inspect.
"""
tag = lib.get_trackitem_ayon_tag(
track_item,
tag_name=constants.LEGACY_OPENPYPE_TAG_NAME,
)
if not tag:
return
data = tag.metadata()
clip_instances = {}
instance_data = {
"clip_index": track_item.guid(),
"task": None,
"variant": track_item.parentTrack().name(),
"extract_audio": False,
}
for create_attr in self.get_pre_create_attr_defs():
if isinstance(create_attr.key, str):
instance_data[create_attr.key] = create_attr.default
required_key_mapping = {
"tag.audio": ("extract_audio", bool),
"tag.heroTrack": ("heroTrack", bool),
"tag.handleStart": ("handleStart", int),
"tag.handleEnd": ("handleEnd", int),
"tag.folderPath": ("folderPath", str),
"tag.reviewTrack": ("reviewableSource", str),
"tag.variant": ("variant", str),
"tag.workfileFrameStart": ("workfileFrameStart", int),
"tag.sourceResolution": ("sourceResolution", bool),
"tag.hierarchy": ("hierarchy", str),
"tag.hierarchyData": ("hierarchyData", json),
"tag.asset_name": ("folderName", str),
"tag.asset": ("productName", str),
"tag.active": ("active", bool),
"tag.productName": ("productName", str),
"tag.parents": ("parents", json),
}
for key, value in required_key_mapping.items():
if key not in data:
continue
try:
instance_key, type_cast = value
if type_cast is bool:
instance_data[instance_key] = data[key] == "True"
elif type_cast is json:
conformed_data = data[key].replace("'", "\"")
conformed_data = conformed_data.replace('u"', '"')
instance_data[instance_key] = json.loads(conformed_data)
else:
instance_data[instance_key] = type_cast(data[key])
except Exception as error:
self.log.warning(
"Cannot retrieve instance from legacy "
f"tag data: {error}."
)
if "folderPath" not in instance_data:
try:
instance_data["folderPath"] = (
"/" + instance_data["hierarchy"] + "/" +
instance_data["productName"]
)
except KeyError:
instance_data["folderPath"] = "unknown"
instance_data["active"] = False
if "tag.subset" in data:
instance_data["variant"] = data["tag.subset"].replace("plate", "")
for folder in instance_data.get("parents", []):
if "entity_name" in folder:
folder["folder_name"] = folder["entity_name"]
if "entity_type" in folder:
folder["folder_type"] = folder["entity_type"]
# Create parent shot instance.
sub_instance_data = instance_data.copy()
track_item_duration = track_item.duration()
workfileFrameStart = \
sub_instance_data["workfileFrameStart"]
sub_instance_data.update({
"label": (
f"{sub_instance_data['folderPath']} "
f"{sub_instance_data['productName']}"),
"variant": "main",
"creator_attributes": {
"workfileFrameStart": workfileFrameStart,
"handleStart": sub_instance_data["handleStart"],
"handleEnd": sub_instance_data["handleEnd"],
"frameStart": workfileFrameStart,
"frameEnd": (workfileFrameStart +
track_item_duration),
"clipIn": track_item.timelineIn(),
"clipOut": track_item.timelineOut(),
"clipDuration": track_item_duration,
"sourceIn": track_item.sourceIn(),
"sourceOut": track_item.sourceOut(),
}
})
shot_creator_id = "io.ayon.creators.hiero.shot"
creator = self.create_context.creators[shot_creator_id]
instance = creator.create(sub_instance_data, None)
instance.transient_data["track_item"] = track_item
self._add_instance_to_context(instance)
clip_instances[shot_creator_id] = instance.data_to_store()
parenting_data = instance
# Create plate/audio instance
if instance_data["extract_audio"]:
sub_creators = (
"io.ayon.creators.hiero.plate",
"io.ayon.creators.hiero.audio"
)
else:
sub_creators = ("io.ayon.creators.hiero.plate",)
for sub_creator_id in sub_creators:
sub_instance_data = instance_data.copy()
creator = self.create_context.creators[sub_creator_id]
sub_instance_data.update(
{
"parent_instance_id": parenting_data["instance_id"],
"label": (
f"{sub_instance_data['folderPath']} "
f"{sub_instance_data['productName']}"
),
"creator_attributes": {
"parentInstance": parenting_data["label"],
"reviewableSource": sub_instance_data[
"reviewableSource"],
"review": False,
}
}
)
instance = creator.create(sub_instance_data, None)
instance.transient_data["track_item"] = track_item
self._add_instance_to_context(instance)
clip_instances[sub_creator_id] = instance.data_to_store()
# Adjust clip tag to match new publisher
track_item.removeTag(tag)
lib.imprint(
track_item,
data={
_CONTENT_ID: clip_instances,
"clip_index": track_item.guid(),
}
)
def collect_instances(self):
"""Collect all created instances from current timeline."""
current_sequence = lib.get_current_sequence()
if current_sequence:
all_video_tracks = current_sequence.videoTracks()
else:
all_video_tracks = []
create_settings = self.project_settings["hiero"]["create"]
collect_settings = create_settings.get("CollectShotClip", {})
restrict_to_selection = collect_settings.get("collectSelectedInstance", False)
current_selection = [
item for item in lib.get_timeline_selection()
if isinstance(item, hiero.core.TrackItem) # get only clips
]
self.log.debug(
"Collect instances from timeline. "
f"restrict_to_selection setting: {restrict_to_selection} "
f"current_selection: {current_selection}"
)
instances = []
for video_track in all_video_tracks:
for track_item in video_track:
# Should we restrict collection to selected item ?
# This might be convenient for heavy timelines and
# can be handled via creator settings.
# When nothing is selected, collect everything.
if (restrict_to_selection and current_selection
and track_item not in current_selection):
continue
# attempt to get AYON tag data
tag = lib.get_trackitem_ayon_tag(track_item)
if not tag:
self._collect_legacy_instance(track_item)
continue
tag_data = tags.get_tag_data(tag)
for creator_id, data in tag_data.get(_CONTENT_ID, {}).items():
self._create_and_add_instance(
data, creator_id, track_item, instances)
if restrict_to_selection:
# Ensure that parent shot instance are enabled.
# This can happen when vertical_align is enabled
# but hero track is not part of the collected clips.
all_shot_ids = [inst.id for inst in instances if inst.data["productType"] == "shot"]
for inst in instances:
if inst.id in all_shot_ids:
continue
elif inst.data["active"] and inst.data["parent_instance_id"] not in all_shot_ids:
raise CreatorError(
"Incomplete selection: please select hero track"
f' for {inst.data["label"]} instance.'
)
return instances
def update_instances(self, update_list):
"""Never called, update is handled via _HieroInstanceCreator."""
pass
def remove_instances(self, instances):
"""Never called, update is handled via _HieroInstanceCreator."""
pass
|