-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpack_nuke.py
More file actions
1628 lines (1409 loc) · 65.5 KB
/
pack_nuke.py
File metadata and controls
1628 lines (1409 loc) · 65.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
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
import csv
import datetime
import glob
import hashlib
import json
import logging
import os
import platform
import pprint
import re
import shutil
import subprocess
import sys
import time
import timeit
import nuke
class PackNukeScript:
def __init__(self, nuke_file, anatomy, settings, row_id, source_place, target_place):
self.anatomy = anatomy
self.settings = settings
self.row_id = row_id
# add more to anatomy
nuke_script_full = nuke_file.replace('\\', '/')
nuke_script = nuke_script_full.split('/')[-1][:-3]
more_tokens = {
"place_source": source_place,
"place_target": target_place,
"timestamp": self.settings['job']['timestamp'],
'job': self.settings['job']['path'], # add job full path
'job_name': self.settings['job']['name'],
'script_path': nuke_script_full,
'script_name': nuke_script
}
self.anatomy.update(more_tokens)
self.ocio = {}
self.media_items = []
self.font_items = []
self.gizmo_items = []
self.loaded_plugins = []
self.categories = {}
self.media_copy_list = []
# open Nuke script
nuke.scriptOpen(nuke_script_full)
def get_default_category(self) -> dict:
"""Get the default category if not specified by settings
Returns:
dict: Default category
"""
default_category = {
"default_category": {
"path": {
"root_template": "{job}/{folder[name]}/{category}",
"root_template_relink": "{job}/{folder[name]}/{category}",
"top_folder": "{node}",
"top_folder_relink": "{node}"
},
"filter_options": {
"skip_disconnected": True,
"skip_disabled": True,
"combine_filters": "AND"
},
"filters": [
{
"source": "File Name",
"search": ".*\.(\w{2,4})$",
"check": [],
"token_name": "extension",
"invert": False
}
]
}
}
return default_category
def file_sequence_to_glob(self, path):
"""Helper function to convert a full path with printf or hash file sequence notation to glob filter
foo\bar%04d.exr -> foo/bar.????.exr
foo\bar###.exr -> foo/bar.???.exr
foo/bar -> foo/bar
"""
path = path.replace('\\', '/')
path_only = path.split('/')[:-1]
name = path.split('/')[-1]
if '#' in name:
name.replace('#', '?')
path = path_only + '/' + name
elif '%' in name:
result = re.search(r'(.*)(%\d+d)(.*)', name)
printf_count = -1
try:
wildcards = '#' * int(result.group(2))
path = path_only + '/' + result.group(1) + wildcards + result.group(3)
except Exception as e:
# no printf used
pass
return path
def bytes_to_string(self, size_bytes) -> str:
"""Make human-readable file size
"""
size_bytes = float(size_bytes)
kb = float(1024)
mb = float(kb ** 2) # 1.048.576
gb = float(kb ** 3) # 1.073.741.824
tb = float(kb ** 4) # 1.099.511.627.776
if size_bytes < kb:
return '{0} {1}'.format(size_bytes, 'B')
elif kb <= size_bytes < mb:
return '{0:.2f} KB'.format(size_bytes / kb)
elif mb <= size_bytes < gb:
return '{0:.2f} MB'.format(size_bytes / mb)
elif gb <= size_bytes < tb:
return '{0:.2f} GB'.format(size_bytes / gb)
elif tb <= size_bytes:
return '{0:.2f} TB'.format(size_bytes / tb)
def eval_tcl(self, text) -> str:
val = ''
try:
val = nuke.tcl("[return \"" + text + "\"]")
except Exception as e:
# TCL not working for this string
pass
# only allow string type to be returned
if type(val) is not str:
val = text
return val
def prepend_project_directory(self, path, project_dir=None, evaluate_project_directory=True):
"""
prepend_project_directory: merge project directory with path.
:param path: Path to be merged with
:param project_dir: Project directory
:return:
"""
if not project_dir:
if evaluate_project_directory:
# Project directory can be TCL or Python expression, evaluate to path
project_dir = nuke.root()['project_directory'].evaluate()
else:
project_dir = nuke.root()['project_directory'].getValue()
full_path = path
if project_dir:
project_dir.replace('\\', '/')
project_dir.rstrip('/')
if project_dir == '':
project_dir = None
if path and project_dir:
path.replace('\\', '/')
if path.startswith('./'):
full_path = project_dir + path[1:]
elif path.startswith('/'):
full_path = project_dir + path
else:
full_path = project_dir + '/' + path
return full_path
def get_real_knob_paths(self, knob_path):
"""
Returns all paths one file knob could refer to.
Paths are absolute, no backslashes.
:param knob_path:
:return: list of absolute paths
"""
# container for all found paths in sequence
paths = []
# all versions of knob_path (stereo views, %v)
view_files = []
# project directory relative path
project_dir = False
# check if stereo files are used
if r'%v' in knob_path or r'%V' in knob_path:
# get all stereo views in the comp
view_return = nuke.root().knob('views').toScript()
for rtn in view_return.split('\n'):
# get each view name in the nuke comp
view = rtn.split(' ')[-2]
# replace in path and append to view_files
view_files.append(knob_path.replace(r'%v', view).replace(r'%V', view))
else:
# if if stereo files not used, do not replace anything
view_files = [knob_path]
# overwrite knob_path value with new value per view
# TODO per view file hashes
for knob_path in view_files:
# get TCL evaluated string
knob_path_tcl = self.eval_tcl(knob_path)
path_with_hashes = knob_path_tcl
# get parent directory
knob_path_parent_dir = os.path.dirname(knob_path_tcl)
# try appending project root folder, if the dir does not exist
if not os.path.exists(knob_path_parent_dir):
knob_path_project_dir = self.prepend_project_directory(knob_path_parent_dir)
if os.path.isdir(knob_path_project_dir):
project_dir = True
knob_path_parent_dir = knob_path_project_dir
knob_path_tcl = self.prepend_project_directory(knob_path_tcl)
# check if the parent dir exists
if os.path.exists(knob_path_parent_dir):
# if it does, get the filename
filename = knob_path_tcl.split('/')[-1]
# get number from printf notation as int
printf_count = -1
try:
# regex pattern for printf notation (only get first result of found printf notations)
regex = re.compile('%..d')
regex_file = regex.findall(filename)[0]
printf_count = int(regex_file[1:-1])
except Exception as e:
# no printf used
pass
# if printf notation is used for the sequence
if printf_count > 0:
# make wildcard string (e.g. '????') for glob with same length as #
wildcards = ''
for i in range(printf_count):
wildcards += '?'
wildcard_path = knob_path_tcl.replace(regex_file, wildcards)
# get all files in directory
files = glob.glob(wildcard_path)
for each_file in files:
paths.append(each_file.replace('\\', '/'))
path_with_hashes = wildcard_path.replace('?', '#')
# if hash notation is used for the sequence
elif '#' in filename:
# split by #
filename_split = filename.split('#')
# count amount of #
wildcard_count = len(filename_split) - 2
# make wildcard string (e.g. '????') for glob with same length as #
wildcards = ''
for i in range(wildcard_count + 1):
wildcards += '?'
# get full filename with wildcard replaced
filename = filename_split[-len(filename_split)] + wildcards + filename_split[-1]
# full file path
wildcard_path = os.path.join(knob_path_parent_dir, filename).replace('\\', '/')
# get all files that match wildcard pattern
files = glob.glob(wildcard_path)
for each_file in files:
paths.append(each_file.replace('\\', '/'))
path_with_hashes = wildcard_path.replace('?', '#')
# if not a sequence
else:
# append this file to paths, if it exists
if os.path.isfile(knob_path_tcl):
paths.append(knob_path_tcl)
# check if it is a relative (project directory) path
elif os.path.isfile(self.prepend_project_directory(knob_path_tcl)):
paths.append(self.prepend_project_directory(knob_path_tcl))
# return result
return paths, project_dir, path_with_hashes.replace('#', '?')
def read_comp_data(self):
"""
Gets all file knobs in Nuke file
Runs them through get_real_knob_paths()
Gets size of every file
Calculates media_item total size
Notes disabled nodes
Makes media_item
Merges duplicities
:return:
"""
def get_ocio():
"""
Gets OCIO config details
"""
all_files = []
total_size = 0
hash_for_all = ''
color_management = nuke.root().knob('colorManagement').value()
custom_path = ''
cfg = nuke.root().knob('OCIO_config').value()
if os.environ.get('OCIO') is not None:
# env has precedence
custom_path = os.path.abspath(os.environ.get('OCIO')).replace("\\", "/")
cfg = 'custom' # pretend it is not set by environment
else:
if cfg == 'custom':
# read custom
custom_path = os.path.abspath(nuke.root().knob('customOCIOConfigPath').evaluate()).replace("\\", "/")
if custom_path != '':
files = glob.glob(os.path.dirname(custom_path) + '/**', recursive=True)
files = [f.replace("\\", "/") for f in files if os.path.isfile(f)]
if files is not None and len(files) > 0:
# get total file size
all_hashes = ''
for each_file in files:
size = os.path.getsize(each_file)
total_size += size
my_hash = get_file_hash(each_file)
all_hashes += my_hash
all_files.append({'path': each_file, 'size': size, 'hash': my_hash})
hash_for_all = hashlib.blake2b(all_hashes.encode()).hexdigest()
self.ocio = {
'color_management': color_management,
'ocio_config': cfg,
'custom_path': custom_path,
'all_files': all_files,
'hash_for_all': hash_for_all,
'total_size': total_size
}
return self.ocio
def is_node_disconnected(node):
disconnected = False
# can have outputs and has no outputs
no_outs = False
no_ins = False
if node.dependent() == []:
no_outs = True
if node.dependencies() == []:
no_ins = True
if no_outs and no_ins:
disconnected = True
return disconnected
def is_node_gizmo(node):
# check if a node is a gizmo, and if so, return the full name
if type(node) == nuke.Gizmo:
return node.Class() if node.Class().endswith('.gizmo') else node.Class() + '.gizmo'
else:
return ''
def get_knob_value(node, knob_name):
"""Return the value of a knob or return None if it is missing"""
value = None
if not isinstance(node.knob(knob_name), type(None)):
value = node.knob(knob_name).value()
if value is None:
value = node.knob(knob_name).getValue()
return value
def get_loaded_plugins():
libs = ['.dll', '.so', '.dylib', '.pdb']
nuke_exe = nuke.env["ExecutablePath"].split('/')
nuke_exe_folder = '/'.join(nuke_exe[:-1])
custom_plugins = []
loaded_plugins = nuke.plugins()
for plugin in loaded_plugins:
if any(lib in plugin for lib in libs):
# skip loaded plugins in nuke/plugins folder
if nuke_exe_folder not in plugin:
custom_plugins.append(plugin)
return custom_plugins
def get_file_hash(path):
my_hash = None
if self.settings['hashes']['hashes_generate']:
one_file = open(path, 'rb')
try:
# read all file at once, memory hungry but faster
my_hash = hashlib.blake2b(one_file.read()).hexdigest()
finally:
one_file.close()
return my_hash
def store_gizmo_item(gizmo_name, gizmo_items, each_node, node_disabled, node_disconnected):
if gizmo_name != '':
gizmo_path_found = False
gizmo_path = ''
for each_plugin_path in nuke.pluginPath():
gizmo_path = os.path.join(each_plugin_path, gizmo_name).replace('\\', '/')
if os.path.isfile(gizmo_path):
gizmo_path_found = True
break
if gizmo_path_found:
if os.path.isfile(gizmo_path):
gizmo_item = {
'gizmo_name': gizmo_name,
'path': gizmo_path,
'node_name': each_node.fullName(),
'node_class': each_node.Class(),
'node_disabled': node_disabled,
'node_disconnected': node_disconnected,
'node': each_node,
'size': os.path.getsize(gizmo_path),
'file_hash': get_file_hash(gizmo_path),
'duplicate_of': None,
}
gizmo_items.append(gizmo_item)
return gizmo_items
def get_font_info(font_items):
"""
fill missing info from getFonts
if font path is known, get family, style, index
if font path is not known, get path
get file size and hash
"""
# see https://learn.foundry.com/nuke/content/comp_environment/effects/fonts_properties.html
# https://learn.foundry.com/nuke/developers/latest/pythondevguide/_autosummary/nuke.getFonts.html
# list of lists: [font_family, font_style, path, index]
all_fonts = nuke.getFonts()
if font_items and len(font_items) > 0:
# get all fonts as list of lists ["Open Sans", "Regular", "fontapath", somenumber]:
for found_font in font_items:
if found_font['path']:
# path is known, what is the font family & style?
for font in all_fonts:
if found_font['path'] == font[2]:
found_font['font_family'] = font[0]
found_font['font_style'] = font[1]
found_font['font_index'] = font[3]
break
else:
# need to find the path
to_match = found_font['font_family'] + found_font['font_style']
found_font['path'] = None
for font in all_fonts:
check = font[0] + font[1]
if to_match == check:
found_font['path'] = font[2]
found_font['font_index'] = font[3]
break
# now path is there, get size and hash
for found_font in font_items:
found_font['size'] = os.path.getsize(found_font['path'])
found_font['file_hash'] = get_file_hash(found_font['path'])
return font_items
def get_media_item(node, knob, path, disabled, disconnected):
# get real paths (file path list + project dir bool)
real_knob_paths, project_dir, path_with_question_marks = self.get_real_knob_paths(path)
# make new list for new paths with their per-file size included
all_files = []
# get total file size
total_size = 0
if real_knob_paths is None:
return None
all_hashes = ''
for each_file in real_knob_paths:
size = os.path.getsize(each_file)
total_size += size
my_hash = get_file_hash(each_file)
all_hashes += my_hash
all_files.append({'path': each_file, 'size': size, 'hash': my_hash})
hash_for_all = hashlib.blake2b(all_hashes.encode()).hexdigest()
# transform type in Nuke 15+, being colorspace/display
# the display value needs ocioDisplay, ocioView
_type = get_knob_value(node, 'transformType')
if _type is None:
_type = 'colorspace'
_cs = get_knob_value(node, 'colorspace')
# for default colorspace, do a wild guess by nuke defaults and file extension
if _cs is not None and _cs == 'default':
file_name = path_with_question_marks.split('/')[-1]
extension = file_name.split('.')[-1]
_cs = nuke.root()['floatLut'].value()
if extension != 'exr':
_cs = nuke.root()['int8Lut'].value()
_read_range = '-'
if node.Class() == 'Read':
_first = get_knob_value(node, 'first')
_last = get_knob_value(node, 'last')
if _first is not None and _last is not None:
_read_range = f'{int(str(_first).strip())}-{int(str(_last).strip())}'
item = {
'node': node,
'color_space': _cs,
'color_transformType': _type,
'color_display': get_knob_value(node, 'ocioDisplay'),
'color_view': get_knob_value(node, 'ocioView'),
'color_raw': get_knob_value(node, 'raw'),
'read_range': _read_range,
'knob': knob,
'node_class': node.Class(),
'node_name': node.fullName(),
'found_path': path,
'found_path_filter': path_with_question_marks,
'all_files': all_files,
'hash_for_all': hash_for_all,
'total_size': total_size,
'project_dir': project_dir,
'node_disabled': disabled,
'node_disconnected': disconnected,
'categories': [],
'category_files': {},
'tokens': {},
'duplicate_of': None,
'exist_on_target': False
}
return item
# OCIO first
log.info("Read OCIO")
get_ocio()
log.info(pprint.pformat(self.ocio, indent=4))
# progress bar total value
all_nodes = nuke.allNodes(recurseGroups=True)
progress_total = len(all_nodes)
# container for all loaded files
media_items = []
gizmo_items = []
font_items = []
# collect all knobs with files in them
i_node = 0
for each_node in all_nodes:
# is node disabled?
node_disabled = False
if each_node.knob('disable') and each_node['disable'].getValue():
node_disabled = True
# is node disconnected?
node_disconnected = is_node_disconnected(each_node)
# check if node is a gizmo
gizmo_name = is_node_gizmo(each_node)
if gizmo_name != '':
gizmo_items = store_gizmo_item(gizmo_name, gizmo_items, each_node, node_disabled, node_disconnected)
# Check all knobs in Node
for each_knob in each_node.knobs():
curr_knob = each_node[each_knob]
# File resource
if curr_knob.Class() == 'File_Knob':
# only add if a path has been entered
found_path = curr_knob.getValue()
if '[' in found_path:
found_path = curr_knob.evaluate()
if found_path != '':
if found_path.endswith('.ttf'):
one_font = {
'font_family': None,
'font_style': None,
'font_index': None,
'node': each_node,
'knob': curr_knob,
'knob_type': 'File_Knob',
'node_class': str(each_node.Class()),
'node_name': str(each_node.fullName()),
'node_disabled': node_disabled,
'node_disconnected': node_disconnected,
'path': found_path.replace('\\', '/'),
'duplicate_of': None,
'font_files': {}
}
font_items.append(one_font)
else:
# file knob that is not a font
media_item = get_media_item(each_node, curr_knob, found_path, node_disabled,
node_disconnected)
if media_item is not None:
media_items.append(media_item)
# Font resource
elif curr_knob.Class() == 'FreeType_Knob':
# returns ["Open Sans", "Regular"]
found_font_knob = curr_knob.getValue()
if found_font_knob and len(found_font_knob) == 2:
one_font = {
'font_family': found_font_knob[0],
'font_style': found_font_knob[1],
'font_index': None,
'node': each_node,
'knob': curr_knob,
'knob_type': 'FreeType_Knob',
'node_class': str(each_node.Class()),
'node_name': str(each_node.fullName()),
'node_disabled': node_disabled,
'node_disconnected': node_disconnected,
'path': None,
'duplicate_of': None,
'font_files': {}
}
font_items.append(one_font)
percent = int(round(float(i_node) / float(progress_total) * 100 / 2))
# print('Done {}% of Nodes'.format(percent))
i_node += 1
self.media_items = media_items
log.info(pprint.pformat(self.media_items, indent=4))
self.font_items = get_font_info(font_items)
self.gizmo_items = gizmo_items
self.loaded_plugins = get_loaded_plugins()
def make_report(self):
# save report (start)
report = []
for one in self.media_items:
if one['duplicate_of'] is None:
number_of_files = len(one['all_files'])
if number_of_files == 1:
hash = one['all_files'][0]['hash']
else:
hash = ''
file_name = one['found_path_filter'].split('/')[-1]
extension = file_name.split('.')[-1]
if one['color_space'] is not None and one['color_space'] is None:
color_info = one['color_space']
elif one['color_transformType'] is not None and one['color_transformType'] == 'display':
color_info = f"{one['color_display']}:{one['color_view']}"
else:
color_info = ''
if one['color_raw'] is not None and one['color_raw']:
color_info += ':raw'
item = {
'type': 'media',
'categories': ', '.join(one['categories']),
'info': color_info,
'node_class': one['node_class'],
'node_name': one['node_name'],
'file_name': file_name,
'extension': extension,
'size': one['total_size'],
'node_disabled': one['node_disabled'],
'node_disconnected': one['node_disconnected'],
'path': one['found_path'],
'file_hash': hash,
'file_number': number_of_files,
'hash_for_all': one['hash_for_all'],
'place_source': self.anatomy['place_source'],
'place_target': self.anatomy['place_target'],
'timestamp': self.anatomy['timestamp']
}
report.append(item)
for one in self.font_items:
if one['duplicate_of'] is None:
file_name = one['path'].split('/')[-1]
extension = file_name.split('.')[-1]
font_info = f"{one['font_family']}, {one['font_style']}, {one['font_index']}"
item = {
'type': 'fonts',
'info': font_info,
'node_class': one['node_class'],
'node_name': one['node_name'],
'file_name': file_name,
'extension': extension,
'size': one['size'],
'categories': 'font',
'node_disabled': one['node_disabled'],
'node_disconnected': one['node_disconnected'],
'path': one['path'],
'file_hash': one['file_hash'],
'file_number': 1,
'hash_for_all': '',
'place_source': self.anatomy['place_source'],
'place_target': self.anatomy['place_target'],
'timestamp': self.anatomy['timestamp']
}
report.append(item)
for one in self.gizmo_items:
if one['duplicate_of'] is None:
file_name = one['path'].split('/')[-1]
extension = file_name.split('.')[-1]
item = {
'type': 'gizmos',
'info': '',
'node_class': one['node_class'],
'node_name': one['node_name'],
'file_name': file_name,
'extension': extension,
'size': one['size'],
'categories': 'gizmo',
'node_disabled': one['node_disabled'],
'node_disconnected': one['node_disconnected'],
'path': one['path'],
'file_hash': one['file_hash'],
'file_number': 1,
'hash_for_all': '',
'place_source': self.anatomy['place_source'],
'place_target': self.anatomy['place_target'],
'timestamp': self.anatomy['timestamp']
}
report.append(item)
for one in self.loaded_plugins:
item = {
'type': 'plugin',
'info': one,
'node_class': '',
'node_name': '',
'file_name': '',
'extension': '',
'size': 0,
'categories': '',
'node_disabled': False,
'node_disconnected': False,
'path': '',
'file_hash': '',
'file_number': 0,
'hash_for_all': '',
'place_source': '',
'place_target': '',
'timestamp': self.anatomy['timestamp']
}
report.append(item)
# OCIO
t = ''
for k, v in self.ocio.items():
if k in ['color_management', 'ocio_config', 'custom_path']:
t += f"{k}:{v}; "
item = {
'type': 'color_management',
'info': t,
'node_class': '',
'node_name': '',
'file_name': '',
'extension': '',
'size': self.ocio['total_size'],
'categories': '',
'node_disabled': False,
'node_disconnected': False,
'path': '',
'file_hash': '',
'file_number': len(self.ocio['all_files']),
'hash_for_all': self.ocio['hash_for_all'],
'place_source': '',
'place_target': '',
'timestamp': self.anatomy['timestamp']
}
report.append(item)
self.report = report
# Write the report to _pack_nuke folder as csv
pth = self.settings['job']['path'] + '/_pack_nuke/' + self.row_id + '.csv'
with open(pth, 'w', newline='') as output_file:
dict_writer = csv.DictWriter(output_file, report[0].keys())
dict_writer.writeheader()
dict_writer.writerows(report)
def media_items_to_categories(self):
def is_media_item_matching(media_item, paths, filter_options, filter_list):
def match_regex(filter, source):
"""
Checks if the filter matches the source by regex
"""
try:
_re = re.compile(filter['search'])
except:
return None
result = re.search(filter['search'], source)
if filter['check']:
# we have something to check agains
if result.group(1) in filter['check']:
if not filter['invert']:
# print("Match_regex matched")
return result.group(1)
else:
# print("Match_regex not matched, 'cause of invert")
return None
else:
if not filter['invert']:
# print("Match_regex not matched.")
return None
else:
# print("Match_regex matched, 'cause of invert.")
return result.group(1)
else:
# not looking for match, just if regex found something
if not filter['invert']:
return result.group(1)
else:
return None
def match_node_class(my_filter, node_class):
"""
Filter check is ignored, only matches the class name
"""
if node_class is None:
return None
node_list = my_filter['search'].strip().split(' ')
if node_list is None or len(node_list) == 0:
return None
if node_class in node_list:
if not my_filter['invert']:
# print("Match_class matched")
return node_class
else:
# print("Match_class not matched, 'cause of invert")
return None
else:
if not my_filter['invert']:
# print("Match_class not matched")
return None
else:
# print("Match_class matched, 'cause of invert")
return node_class
if filter_options['skip_disconnected'] and media_item['node_disconnected']:
# should skip disconnected
# print("Media Item {} skipped: disconnected".format(media_item['node_name']))
return False, None
if filter_options['skip_disabled'] and media_item['node_disabled']:
# should skip disabled
# print("Media Item {} skipped: disabled".format(media_item['node_name']))
return False, None
if media_item['all_files'] and len(media_item['all_files']) > 0:
full_path = media_item['all_files'][0]['path']
_dir, file_name = os.path.split(full_path)
else:
# print("Media Item {} skipped: no file found".format(media_item['node_name']))
# no file, no match
return False, None
matches = 0
tokens = {}
for one_filter in filter_list:
match = None
if one_filter['source'] == 'File Name':
match = match_regex(one_filter, source=file_name)
elif one_filter['source'] == 'File Path':
match = match_regex(one_filter, source=full_path)
elif one_filter['source'] == 'Node Class':
match = match_node_class(one_filter, media_item['node_class'])
if match is not None:
tokens[one_filter['token_name']] = match
matches += 1
# print("Tokens {}, matches {}".format(tokens, matches))
if (filter_options['combine_filters'].lower() == 'and' and matches == len(filter_list)) or (
filter_options['combine_filters'].lower() == 'or' and matches > 0):
# media item is matching filter!
return True, tokens
else:
return False, tokens
self.categories = self.settings.get('categories')
default_category = self.get_default_category()
if not self.categories:
# no categories defined, take default
self.categories = default_category
for category_name, category in self.categories.items():
# get path options
paths = category.get('path')
if not paths:
paths = default_category['default_category']['path']
# get filter options
filter_options = category.get('filter_options')
if not filter_options:
filter_options = default_category['default_category']['filter_options']
# get filters
filter_list = category.get('filters')
if not filter_list:
filter_list = default_category['default_category']['filters']
for media_item in self.media_items:
# print("media_items_to_categories: checking {} {}".format(media_item['node_name'], category_name))
matching, more_tokens = is_media_item_matching(media_item, paths, filter_options, filter_list)
if matching:
# add category name to media item
cats = media_item.get('categories')
if cats is not None:
media_item['categories'].append(category_name)
else:
media_item['categories'] = [category_name]
# add tokens to media item
tokens = media_item.get('tokens')
if tokens is not None:
media_item['tokens'].update(more_tokens)
else:
media_item['tokens'] = more_tokens
else:
pass
# print("Media Item from node {} doesn't match the category name {}".format(media_item['node_name'], category_name))
def find_media_duplicities(self):
for media_item in self.media_items:
if media_item['duplicate_of'] is None:
for check_item in self.media_items:
if check_item == media_item:
continue
if media_item['all_files'] == check_item['all_files']:
check_item['duplicate_of'] = media_item
def find_font_duplicities(self):
for font_item in self.font_items:
if font_item['duplicate_of'] is None:
for check_item in self.font_items:
if check_item == font_item:
continue
if font_item['path'] == check_item['path']:
check_item['duplicate_of'] = font_item
def find_gizmo_duplicities(self):
for gizmo_item in self.gizmo_items:
if gizmo_item.get('duplicate_of') is None:
for check_item in self.gizmo_items:
if check_item == gizmo_item:
continue
if gizmo_item['path'] == check_item['path']:
check_item['duplicate_of'] = gizmo_item
def media_items_to_paths(self):
"""
Fills media_item['category_files'][category_name]
template and template_relink are paths with tokens filled
target and relink are list of paths for every file
"""
class Default(dict):
def __missing__(self, key):
return key
for media_item in self.media_items:
cats = media_item.get('categories')
all_tokens = {**self.anatomy, **media_item['tokens']}
# get nuke compatible file name from glob filter, ie foo.????.exr -> foo.%04d.exr
nuke_filter = os.path.basename(media_item['found_path_filter'])
#print(f" Filter before {nuke_filter}")
try:
glob_split = re.match('([^\?]+)(\?*)([^\?]+)', nuke_filter)
if glob_split.group(2):
nuke_filter = glob_split.group(1) + '%0' + str(len(glob_split.group(2))) + 'd' + glob_split.group(3)
#print(f" Filter after {nuke_filter} {glob_split.group(2)}")
except:
# no ? in file name, so it is a single file
pass
# get filename but skip file sequence counter, use glob filter
_ = os.path.basename(media_item['found_path_filter']).split('?')
clean_name = _[0].rstrip('._-')
if len(_) > 1:
clean_name += _[-1]
all_file_names = []
for one_file in media_item['all_files']: