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
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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196 | class IngestCSV(TrayPublishCreator):
"""CSV ingest creator class"""
icon = "fa.file"
label = "CSV Ingest"
product_type = "csv_ingest_file"
product_base_type = "csv_ingest_file"
identifier = "io.ayon.creators.traypublisher.csv_ingest"
default_variants = ["Main"]
description = "Ingest products' data from CSV file"
detailed_description = """
Ingest products' data from CSV file following column and representation
configuration in project settings.
"""
settings_category = "traypublisher"
# Position in the list of creators.
order = 10
presets = []
def get_instance_attr_defs(self):
return [
BoolDef(
"add_review_family",
default=True,
label="Review"
)
]
def get_pre_create_attr_defs(self):
"""Creating pre-create attributes at creator plugin.
Returns:
list: list of attribute object instances
"""
# Use same attributes as for instance attributes
preset_items = []
for preset in self.presets:
preset_items.append(
{"value": preset["name"], "label": preset["name"]})
if not preset_items:
preset_items.append(
{"value": None, "label": "< Missing preset >"})
return [
EnumDef(
"preset",
items=preset_items,
label="Preset",
),
FileDef(
"csv_filepath_data",
folders=False,
extensions=[".csv"],
allow_sequences=False,
single_item=True,
label="CSV File",
),
]
def create(
self,
product_name: str,
instance_data: dict[str, Any],
pre_create_data: dict[str, Any]
):
"""Create product from each row found in the CSV.
Args:
product_name (str): The subset name.
instance_data (dict): The instance data.
pre_create_data (dict):
"""
selected_preset = pre_create_data["preset"]
preset_data = next(
(
preset for preset in self.presets
if preset["name"] == selected_preset
),
None,
)
if not preset_data:
raise CreatorError(
f"Invalid preset '{selected_preset}'"
)
csv_filepath_data = pre_create_data.get("csv_filepath_data", {})
csv_dir = csv_filepath_data.get("directory", "")
if not os.path.exists(csv_dir):
raise CreatorError(
f"Directory '{csv_dir}' does not exist."
)
filename = csv_filepath_data.get("filenames", [])
self._process_csv_file(
preset_data, product_name, instance_data, csv_dir, filename[0]
)
def _pass_data_to_csv_instance(
self,
instance_data: dict[str, Any],
staging_dir: str,
filename: str
):
"""Pass CSV representation file to instance data"""
representation = {
"name": "csv",
"ext": "csv",
"files": filename,
"stagingDir": staging_dir,
"stagingDir_persistent": True,
}
instance_data.update({
"label": f"CSV: {filename}",
"representations": [representation],
"stagingDir": staging_dir,
"stagingDir_persistent": True,
})
def _process_csv_file(
self,
preset_data: dict[str, Any],
product_name: str,
instance_data: dict[str, Any],
csv_dir: str,
filename: str
):
"""Process CSV file.
Args:
preset_data (dict[str, Any]): The selected preset data.
product_name (str): The subset name.
instance_data (dict): The instance data.
csv_dir (str): The csv directory.
filename (str): The filename.
"""
# create new instance from the csv file via self function
self._pass_data_to_csv_instance(
instance_data,
csv_dir,
filename
)
csv_instance = CreatedInstance(
product_base_type=self.product_base_type,
product_type=self.product_type,
product_name=product_name,
data=instance_data,
creator=self
)
csv_instance["csvFileData"] = {
"filename": filename,
"staging_dir": csv_dir,
}
# create instances from csv data via self function
instances = self._create_instances_from_csv_data(
preset_data, csv_dir, filename)
for instance in instances:
self._store_new_instance(instance)
self._store_new_instance(csv_instance)
def _resolve_repre_path(
self, csv_dir: str, filepath: Union[str, None]
) -> Union[str, None]:
if not filepath:
return filepath
# Validate only existence of file directory as filename
# may contain frame specific char (e.g. '%04d' or '####').
filedir, filename = os.path.split(filepath)
if not filedir or filedir == ".":
# If filedir is empty or "." then use same directory as
# csv path
filepath = os.path.join(csv_dir, filepath)
elif not os.path.exists(filedir):
# If filepath does not exist, first try to find it in the
# same directory as the csv file is, but keep original
# value otherwise.
new_filedir = os.path.join(csv_dir, filedir)
if os.path.exists(new_filedir):
filepath = os.path.join(new_filedir, filename)
return filepath
def _get_folder_type_from_regex_settings(
self,
folder_name: str,
folder_creation_config: dict
) -> str:
""" Get the folder type that matches the regex settings.
Args:
folder_name (str): The folder name.
folder_creation_config (dict): The folder creation configuration.
Returns:
str. The folder type to use.
"""
for folder_setting in folder_creation_config["folder_type_regexes"]:
if re.match(folder_setting["regex"], folder_name):
folder_type = folder_setting["folder_type"]
return folder_type
return folder_creation_config["folder_create_type"]
def _compute_parents_data(
self,
project_name: str,
product_item: ProductItem,
preset_data: dict[str, Any]
) -> list:
""" Compute parent data when new hierarchy has to be created during the
publishing process.
Args:
project_name (str): The project name.
product_item (ProductItem): The product item to inspect.
preset_data (dict): The preset data with folder creation settings.
Returns:
list. The parent list if any
Raise:
ValueError: When provided folder_path parent do not exist.
"""
parent_folder_names = product_item.folder_path.lstrip("/").split("/")
# Rename name of folder itself
parent_folder_names.pop(-1)
if not parent_folder_names:
return []
parent_paths = []
parent_path = ""
for name in parent_folder_names:
path = f"{parent_path}/{name}"
parent_paths.append(path)
parent_path = path
folders_by_path = {
folder["path"]: folder
for folder in ayon_api.get_folders(
project_name,
folder_paths=parent_paths,
fields={"folderType", "path"}
)
}
parent_data = []
for path in parent_paths:
folder_entity = folders_by_path.get(path)
name = path.rsplit("/", 1)[-1]
# Folder exists, retrieve data from existing.
if folder_entity:
folder_type = folder_entity["folderType"]
# Define folder type from settings.
else:
folder_type = self._get_folder_type_from_regex_settings(
name, preset_data["folder_creation_config"])
item = {
"entity_name": name,
"folder_type": folder_type,
}
parent_data.append(item)
return parent_data
def _get_data_from_csv(
self, preset_data: dict[str, Any], csv_dir: str, filename: str
) -> dict[str, ProductItem]:
"""Generate instances from the csv file"""
# get current project name and code from context.data
project_name = self.create_context.get_current_project_name()
csv_path = os.path.join(csv_dir, filename)
# preset's variables
columns_config = preset_data["columns_config"]
representations_config = preset_data["representations_config"]
folder_creation_config = preset_data["folder_creation_config"]
# make sure csv file contains columns from following list
required_columns = [
column["name"]
for column in columns_config["columns"]
if column["required_column"]
]
# read csv file
with open(csv_path, "r") as csv_file:
csv_content = csv_file.read()
# read csv file with DictReader
csv_reader = csv.DictReader(
StringIO(csv_content),
delimiter=columns_config["csv_delimiter"]
)
# fix fieldnames
# sometimes someone can keep extra space at the start or end of
# the column name
all_columns = [
" ".join(column.rsplit())
for column in csv_reader.fieldnames
]
# return back fixed fieldnames
csv_reader.fieldnames = all_columns
# check if csv file contains all required columns
if any(column not in all_columns for column in required_columns):
raise CreatorError(
f"Missing required columns: {required_columns}"
)
product_items_by_name: dict[str, ProductItem] = {}
for row in csv_reader:
product_item_: ProductItem = ProductItem.from_csv_row(
columns_config, row
)
unique_name = product_item_.unique_name
if unique_name not in product_items_by_name:
product_items_by_name[unique_name] = product_item_
product_item: ProductItem = product_items_by_name[unique_name]
product_item.add_repre_item(
RepreItem.from_csv_row(
columns_config,
representations_config,
row
)
)
folder_paths: set[str] = {
product_item.folder_path
for product_item in product_items_by_name.values()
}
folder_ids_by_path: dict[str, str] = {
folder_entity["path"]: folder_entity["id"]
for folder_entity in ayon_api.get_folders(
project_name, folder_paths=folder_paths, fields={"id", "path"}
)
}
missing_paths: set[str] = folder_paths - set(folder_ids_by_path.keys())
task_names: set[str] = {
product_item.task_name
for product_item in product_items_by_name.values()
}
task_entities_by_folder_id = collections.defaultdict(list)
for task_entity in ayon_api.get_tasks(
project_name,
folder_ids=set(folder_ids_by_path.values()),
task_names=task_names,
fields={"folderId", "name", "taskType"}
):
folder_id = task_entity["folderId"]
task_entities_by_folder_id[folder_id].append(task_entity)
missing_tasks: set[str] = set()
if missing_paths and not folder_creation_config["enabled"]:
error_msg = (
"Folder creation is disabled but found missing folder(s): %r" %
",".join(missing_paths)
)
raise CreatorError(error_msg)
for product_item in product_items_by_name.values():
folder_path = product_item.folder_path
if folder_path in missing_paths:
product_item.has_promised_context = True
product_item.task_type = None
product_item.parents = self._compute_parents_data(
project_name,
product_item,
preset_data,
)
continue
task_name = product_item.task_name
folder_id = folder_ids_by_path[folder_path]
task_entities = task_entities_by_folder_id[folder_id]
task_entity = next(
(
task_entity
for task_entity in task_entities
if task_entity["name"] == task_name
),
None
)
if task_entity is None:
missing_tasks.add(f"{folder_path}/{task_name}")
else:
product_item.task_type = task_entity["taskType"]
if missing_tasks:
ending = "" if len(missing_tasks) == 1 else "s"
joined_paths = "\n".join(sorted(missing_tasks))
raise CreatorError(
f"Task{ending} not found.\n{joined_paths}"
)
for product_item in product_items_by_name.values():
repre_paths: set[str] = set()
duplicated_paths: set[str] = set()
for repre_item in product_item.repre_items:
# Resolve relative paths in csv file
repre_item.filepath = self._resolve_repre_path(
csv_dir, repre_item.filepath
)
repre_item.thumbnail_path = self._resolve_repre_path(
csv_dir, repre_item.thumbnail_path
)
filepath = repre_item.filepath
if filepath in repre_paths:
duplicated_paths.add(filepath)
repre_paths.add(filepath)
if duplicated_paths:
ending = "" if len(duplicated_paths) == 1 else "s"
joined_names = "\n".join(sorted(duplicated_paths))
raise CreatorError(
f"Duplicate filename{ending} in csv file.\n{joined_names}"
)
return product_items_by_name
def _add_thumbnail_repre(
self,
thumbnails: set[str],
instance: CreatedInstance,
repre_item: RepreItem,
multiple_thumbnails: bool = False,
) -> Union[str, None]:
"""Add thumbnail to instance.
Add thumbnail as representation and set 'thumbnailPath' if is not set
yet.
Args:
thumbnails (set[str]): set of all thumbnail paths that should
create representation.
instance (CreatedInstance): Instance from create plugin.
repre_item (RepreItem): Representation item.
multiple_thumbnails (bool): There are multiple representations
with thumbnail.
Returns:
Uniom[str, None]: Explicit output name for thumbnail
representation.
"""
if not thumbnails:
return None
thumbnail_path = repre_item.thumbnail_path
if not thumbnail_path or thumbnail_path not in thumbnails:
return None
thumbnails.remove(thumbnail_path)
thumb_dir, thumb_file = os.path.split(thumbnail_path)
thumb_basename, thumb_ext = os.path.splitext(thumb_file)
# NOTE 'explicit_output_name' and custom repre name was set only
# when 'multiple_thumbnails' is True and 'review' tag is present.
# That was changed to set 'explicit_output_name' is set when
# 'multiple_thumbnails' is True.
# is_reviewable = "review" in repre_item.tags
repre_name = "thumbnail"
explicit_output_name = None
if multiple_thumbnails:
repre_name = f"thumbnail_{thumb_basename}"
explicit_output_name = repre_item.name
thumbnail_repre_data = {
"name": repre_name,
"ext": thumb_ext.lstrip("."),
"files": thumb_file,
"stagingDir": thumb_dir,
"stagingDir_persistent": True,
"tags": ["thumbnail", "delete"],
}
if explicit_output_name:
thumbnail_repre_data["outputName"] = explicit_output_name
instance["prepared_data_for_repres"].append({
"type": "thumbnail",
"colorspace": None,
"representation": thumbnail_repre_data,
})
# also add thumbnailPath for ayon to integrate
if not instance.get("thumbnailPath"):
instance["thumbnailPath"] = thumbnail_path
return explicit_output_name
def _add_representation(
self,
preset_data: dict[str, Any],
instance: CreatedInstance,
repre_item: RepreItem,
explicit_output_name: Optional[str] = None
) -> None:
"""Get representation data
Args:
preset_data (dict[str, Any]): Preset data.
instance (CreatedInstance): Created instance.
repre_item (RepreItem): Representation item based on csv row.
explicit_output_name (Optional[str]): Explicit output name.
For grouping purposes with reviewable components.
Exception:
CreatorError: If representation not found.
"""
representations_config = preset_data["representations_config"]
# get extension of file
basename: str = os.path.basename(repre_item.filepath)
extension: str = os.path.splitext(basename)[-1].lower()
# validate filepath is having correct extension based on output
repre_config_data: Union[dict[str, Any], None] = None
for repre in representations_config["representations"]:
if repre["name"] == repre_item.name:
repre_config_data = repre
break
if not repre_config_data:
raise CreatorError(
f"Representation '{repre_item.name}' not found "
"in config representation data."
)
validate_extensions: list[str] = repre_config_data["extensions"]
if extension not in validate_extensions:
raise CreatorError(
f"File extension '{extension}' not valid for "
f"output '{validate_extensions}'."
)
is_sequence: bool = extension in IMAGE_EXTENSIONS
# convert ### string in file name to %03d
# this is for correct frame range validation
# example: file.###.exr -> file.%03d.exr
file_head = basename.split(".")[0]
if "#" in basename:
padding = len(basename.split("#")) - 1
seq_padding = f"%0{padding}d"
basename = basename.replace("#" * padding, seq_padding)
file_head = basename.split(seq_padding)[0]
is_sequence = True
elif "%" in basename:
pattern = re.compile(r"%\d+d|%d")
padding = pattern.findall(basename)
if not padding:
raise CreatorError(
f"File sequence padding not found in '{basename}'."
)
file_head = basename.split("%")[0]
is_sequence = True
else:
# in case it is still image
is_sequence = False
# make absolute path to file
dirname: str = os.path.dirname(repre_item.filepath)
# check if dirname exists
if not os.path.isdir(dirname):
raise CreatorError(
f"Directory '{dirname}' does not exist."
)
frame_start: Union[int, None] = None
frame_end: Union[int, None] = None
files: Union[str, list[str]] = basename
if is_sequence:
# get only filtered files form dirname
files_from_dir = [
filename
for filename in os.listdir(dirname)
if filename.startswith(file_head)
]
# collect all data from dirname
cols, _ = clique.assemble(files_from_dir)
if not cols:
raise CreatorError(
f"No collections found in directory '{dirname}'."
)
col = cols[0]
files = list(col)
frame_start = min(col.indexes)
frame_end = max(col.indexes)
tags: list[str] = deepcopy(repre_item.tags)
# if slate in repre_data is True then remove one frame from start
if repre_item.slate_exists:
tags.append("has_slate")
# get representation data
representation_data: dict[str, Any] = {
"name": repre_item.name,
"ext": extension[1:],
"files": files,
"stagingDir": dirname,
"stagingDir_persistent": True,
"tags": tags,
}
if extension in VIDEO_EXTENSIONS:
representation_data.update({
"fps": repre_item.fps,
"outputName": repre_item.name,
})
if explicit_output_name:
representation_data["outputName"] = explicit_output_name
if frame_start:
representation_data["frameStart"] = frame_start
if frame_end:
representation_data["frameEnd"] = frame_end
instance["prepared_data_for_repres"].append({
"type": "media",
"colorspace": repre_item.colorspace,
"representation": representation_data,
})
def _prepare_representations(
self,
preset_data: dict[str, Any],
product_item: ProductItem,
instance: CreatedInstance
) -> None:
"""Prepare representations for the given product item.
Args:
preset_data (dict[str, Any]): The preset data.
product_item (ProductItem): The product item.
instance (CreatedInstance): The created instance.
"""
# Collect thumbnail paths from all representation items
# to check if multiple thumbnails are present.
# Once representation is created for certain thumbnail it is removed
# from the set.
thumbnails: set[str] = {
repre_item.thumbnail_path
for repre_item in product_item.repre_items
if repre_item.thumbnail_path
}
multiple_thumbnails: bool = len(thumbnails) > 1
for repre_item in product_item.repre_items:
explicit_output_name = self._add_thumbnail_repre(
thumbnails,
instance,
repre_item,
multiple_thumbnails,
)
# get representation data
self._add_representation(
preset_data,
instance,
repre_item,
explicit_output_name
)
def _get_task_type_from_task_name(
self,
preset_data: dict[str, Any],
task_name: str
) -> str:
"""Retrieve task type from task name.
Args:
preset_data (dict[str, Any]): The preset data.
task_name (str): The task name.
Returns:
str. The task type computed from settings.
"""
folder_creation_config = preset_data["folder_creation_config"]
for task_setting in folder_creation_config["task_type_regexes"]:
if re.match(task_setting["regex"], task_name):
task_type = task_setting["task_type"]
break
else:
task_type = folder_creation_config["task_create_type"]
return task_type
def _create_instances_from_csv_data(
self,
preset_data: dict[str, Any],
csv_dir: str,
filename: str
) -> list[CreatedInstance]:
"""Create instances from csv data.
Args:
preset_data (dict[str, Any]): The preset data.
csv_dir (str): The directory of the CSV file.
filename (str): The name of the CSV file.
Returns:
list[CreatedInstance]. The created instances.
"""
# from special function get all data from csv file and convert them
# to new instances
product_items_by_name: dict[str, ProductItem] = (
self._get_data_from_csv(preset_data, csv_dir, filename)
)
instances = []
project_name: str = self.create_context.get_current_project_name()
# Pre-fetch all existing entities to find matching
folder_paths = {
product_item.folder_path
for product_item in product_items_by_name.values()
}
folder_entities_by_path: dict[str, dict[str, str]] = {
folder_entity["path"]: folder_entity
for folder_entity in ayon_api.get_folders(
project_name,
folder_paths=folder_paths,
)
}
folder_paths_by_id = {
f["id"]: f["path"]
for f in folder_entities_by_path.values()
}
task_entities = list(ayon_api.get_tasks(
project_name,
folder_ids=folder_paths_by_id,
fields={"name", "taskType", "folderId"},
))
task_entities_by_folder_path = collections.defaultdict(list)
for task_entity in task_entities:
folder_id = task_entity["folderId"]
folder_path = folder_paths_by_id[folder_id]
task_entities_by_folder_path[folder_path].append(task_entity)
for product_item in product_items_by_name.values():
folder_path: str = product_item.folder_path
hierarchy, folder_name = folder_path.rsplit("/", 1)
folder_entity = folder_entities_by_path.get(folder_path)
if folder_entity is not None:
folder_type = folder_entity["folderType"]
else:
# TODO find out how to define default folder type
# - was hardcoded in pyblish plugin 'CollectShotInstances'
folder_type: str = "Shot"
if product_item.has_promised_context:
folder_type = self._get_folder_type_from_regex_settings(
folder_name, preset_data["folder_creation_config"]
)
# Fake folder entity, this might break if more data
# is used in 'get_product_name'.
folder_entity = {
"name": folder_name,
"label": folder_name,
"path": folder_path,
"folderType": folder_type,
}
instance_tasks = None
task_name = None
task_entity = None
if product_item.task_name:
task_name_low = product_item.task_name.lower()
for f_task_entity in task_entities_by_folder_path[folder_path]:
if f_task_entity["name"].lower() == task_name_low:
task_entity = f_task_entity
break
if task_entity is not None:
task_name = task_entity["name"]
task_type = task_entity["taskType"]
else:
task_name = product_item.task_name
task_type = self._get_task_type_from_task_name(
preset_data, task_name)
# Fake task entity, this might break if more data
# is used in 'get_product_name'.
task_entity = {
"name": task_name,
"label": task_name,
"taskType": task_type,
}
if product_item.has_promised_context:
instance_tasks = {task_name: {"type": task_type}}
version: int = product_item.version
product_name: str = get_product_name(
project_name=project_name,
folder_entity=folder_entity,
task_entity=task_entity,
product_base_type=product_item.product_base_type,
product_type=product_item.product_type,
host_name=self.host_name,
variant=product_item.variant,
project_settings=(
self.create_context.get_current_project_settings()
),
project_entity=(
self.create_context.get_current_project_entity()
),
)
version_label: str = "[next]"
if version is not None:
version_label = f"{version:>03}"
label: str = f"{folder_path}_{product_name}_v{version_label}"
repre_items: list[RepreItem] = product_item.repre_items
first_repre_item: RepreItem = repre_items[0]
version_comment: Union[str, None] = next(
(
repre_item.comment
for repre_item in repre_items
if repre_item.comment
),
None
)
slate_exists: bool = any(
repre_item.slate_exists
for repre_item in repre_items
)
is_reviewable: bool = any(
True
for repre_item in repre_items
if "review" in repre_item.tags
)
families: list[str] = ["csv_ingest"]
if slate_exists:
# adding slate to families mainly for loaders to be able
# to filter out slates
families.append("slate")
if is_reviewable:
# review family needs to be added for ExtractReview plugin
families.append("review")
instance_data = {
"name": product_item.instance_name,
"label": label,
"folderPath": folder_path,
"task": task_name,
"folder_type": folder_type,
"families": families,
"variant": product_item.variant,
"source": "csv",
"frameStart": first_repre_item.frame_start,
"frameEnd": first_repre_item.frame_end,
"handleStart": first_repre_item.handle_start,
"handleEnd": first_repre_item.handle_end,
"fps": first_repre_item.fps,
"version": version,
"comment": version_comment,
"prepared_data_for_repres": [],
}
if instance_tasks:
instance_data["tasks"] = instance_tasks
if product_item.has_promised_context:
families.append("shot")
instance_data.update(
{
"newHierarchyIntegration": True,
"hierarchy": hierarchy,
"parents": product_item.parents,
"families": families,
"heroTrack": True,
}
)
if product_item.pixel_aspect:
instance_data["pixelAspect"] = product_item.pixel_aspect
if product_item.width and product_item.height:
instance_data.update(
{
"resolutionWidth": product_item.width,
"resolutionHeight": product_item.height,
}
)
elif product_item.width or product_item.height:
log.warning(
(
"Ignoring incomplete provided resolution"
" %rx%r for shot %s."
),
product_item.width,
product_item.height,
folder_name
)
# create new instance
new_instance: CreatedInstance = CreatedInstance(
product_base_type=product_item.product_base_type,
product_type=product_item.product_type,
product_name=product_name,
data=instance_data,
creator=self
)
self._prepare_representations(
preset_data, product_item, new_instance)
if product_item.has_promised_context:
new_instance.transient_data["has_promised_context"] = True
instances.append(new_instance)
return instances
|