Skip to content

pyblish_functions

TimeData

Bases: object

Structure used to handle time related data.

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
21
22
23
24
25
26
27
28
29
@attr.s
class TimeData(object):
    """Structure used to handle time related data."""
    start = attr.ib(type=int)
    end = attr.ib(type=int)
    fps = attr.ib()
    step = attr.ib(default=1, type=int)
    handle_start = attr.ib(default=0, type=int)
    handle_end = attr.ib(default=0, type=int)

attach_instances_to_product(attach_to, instances)

Attach instance to product.

If we are attaching to other products, create copy of existing instances, change data to match its product and replace existing instances with modified data.

Parameters:

Name Type Description Default
attach_to list

List of instances to attach to.

required
instances list

List of instances to attach.

required

Returns:

Name Type Description
list

List of attached instances.

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
def attach_instances_to_product(attach_to, instances):
    """Attach instance to product.

    If we are attaching to other products, create copy of existing
    instances, change data to match its product and replace
    existing instances with modified data.

    Args:
        attach_to (list): List of instances to attach to.
        instances (list): List of instances to attach.

    Returns:
          list: List of attached instances.

    """
    new_instances = []
    for attach_instance in attach_to:
        for i in instances:
            new_inst = copy.deepcopy(i)
            new_inst["version"] = attach_instance.get("version")
            new_inst["productName"] = attach_instance.get("productName")
            new_inst["productType"] = attach_instance.get("productType")
            new_inst["family"] = attach_instance.get("family")
            new_inst["append"] = True
            # don't set productGroup if we are attaching
            new_inst.pop("productGroup")
            new_instances.append(new_inst)
    return new_instances

convert_frames_str_to_list(frames)

Convert frames definition string to frames.

Handles formats as

convert_frames_str_to_list('1001') [1001] convert_frames_str_to_list('1002,1004') [1002, 1004] convert_frames_str_to_list('1003-1005') [1003, 1004, 1005] convert_frames_str_to_list('1001-1021x5') [1001, 1006, 1011, 1016, 1021]

Parameters:

Name Type Description Default
frames str

String with frames definition.

required

Returns:

Type Description
list[int]

list[int]: List of frames.

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
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
def convert_frames_str_to_list(frames: str) -> list[int]:
    """Convert frames definition string to frames.

    Handles formats as:
        >>> convert_frames_str_to_list('1001')
        [1001]
        >>> convert_frames_str_to_list('1002,1004')
        [1002, 1004]
        >>> convert_frames_str_to_list('1003-1005')
        [1003, 1004, 1005]
        >>> convert_frames_str_to_list('1001-1021x5')
        [1001, 1006, 1011, 1016, 1021]

    Args:
        frames (str): String with frames definition.

    Returns:
        list[int]: List of frames.

    """
    step_pattern = re.compile(r"(?:step|by|every|x|:)(\d+)$")

    output = []
    step = 1
    for frame in frames.split(","):
        if "-" in frame:
            frame_start, frame_end = frame.split("-")
            match = step_pattern.findall(frame_end)
            if match:
                step = int(match[0])
                frame_end = re.sub(step_pattern, "", frame_end)

            output.extend(
                range(int(frame_start), int(frame_end) + 1, step)
            )
        else:
            output.append(int(frame))
    output.sort()
    return output

copy_extend_frames(instance, representation)

Copy existing frames from latest version.

This will copy all existing frames from product's latest version back to render directory and rename them to what renderer is expecting.

Parameters:

Name Type Description Default
instance Instance

instance to get required data from

required
representation dict

presentation to operate on

required
Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
def copy_extend_frames(instance, representation):
    """Copy existing frames from latest version.

    This will copy all existing frames from product's latest version back
    to render directory and rename them to what renderer is expecting.

    Arguments:
        instance (pyblish.plugin.Instance): instance to get required
            data from
        representation (dict): presentation to operate on

    """
    import speedcopy

    R_FRAME_NUMBER = re.compile(
        r".+\.(?P<frame>[0-9]+)\..+")

    log = Logger.get_logger("farm_publishing")
    log.info("Preparing to copy ...")
    start = instance.data.get("frameStart")
    end = instance.data.get("frameEnd")
    project_name = instance.context.data["project"]
    anatomy = instance.context.data["anatomy"]

    folder_entity = ayon_api.get_folder_by_path(
        project_name, instance.data.get("folderPath")
    )

    # get latest version of product
    # this will stop if product wasn't published yet

    version_entity = ayon_api.get_last_version_by_product_name(
        project_name,
        instance.data.get("productName"),
        folder_entity["id"]
    )

    # get its files based on extension
    product_resources = get_resources(
        project_name, version_entity, representation.get("ext")
    )
    r_col, _ = clique.assemble(product_resources)

    # if override remove all frames we are expecting to be rendered,
    # so we'll copy only those missing from current render
    if instance.data.get("overrideExistingFrame"):
        for frame in range(start, end + 1):
            if frame not in r_col.indexes:
                continue
            r_col.indexes.remove(frame)

    # now we need to translate published names from representation
    # back. This is tricky, right now we'll just use same naming
    # and only switch frame numbers
    resource_files = []
    r_filename = os.path.basename(
        representation.get("files")[0])  # first file
    op = re.search(R_FRAME_NUMBER, r_filename)
    pre = r_filename[:op.start("frame")]
    post = r_filename[op.end("frame"):]
    assert op is not None, "padding string wasn't found"
    for frame in list(r_col):
        fn = re.search(R_FRAME_NUMBER, frame)
        # silencing linter as we need to compare to True, not to
        # type
        assert fn is not None, "padding string wasn't found"
        # list of tuples (source, destination)
        staging = representation.get("stagingDir")
        staging = anatomy.fill_root(staging)
        resource_files.append(
            (frame, os.path.join(
                staging, "{}{}{}".format(pre, fn["frame"], post)))
        )

    # test if destination dir exists and create it if not
    output_dir = os.path.dirname(representation.get("files")[0])
    if not os.path.isdir(output_dir):
        os.makedirs(output_dir)

    # copy files
    for source in resource_files:
        speedcopy.copy(source[0], source[1])
        log.info("  > {}".format(source[1]))

    log.info("Finished copying %i files" % len(resource_files))

create_instances_for_aov(instance, skeleton, aov_filter, skip_integration_repre_list, do_not_add_review, frames_to_render=None)

Create instances from AOVs.

This will create new pyblish.api.Instances by going over expected files defined on original instance.

Parameters:

Name Type Description Default
instance Instance

Original instance.

required
skeleton dict

Skeleton instance data.

required
aov_filter dict

AOV filter.

required
skip_integration_repre_list list

skip

required
do_not_add_review bool

Explicitly disable reviews

required
frames_to_render str | None

Frames to render.

None

Returns:

Type Description

list of pyblish.api.Instance: Instances created from expected files.

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
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
def create_instances_for_aov(
    instance,
    skeleton,
    aov_filter,
    skip_integration_repre_list,
    do_not_add_review,
    frames_to_render=None
):
    """Create instances from AOVs.

    This will create new pyblish.api.Instances by going over expected
    files defined on original instance.

    Args:
        instance (pyblish.api.Instance): Original instance.
        skeleton (dict): Skeleton instance data.
        aov_filter (dict): AOV filter.
        skip_integration_repre_list (list): skip
        do_not_add_review (bool): Explicitly disable reviews
        frames_to_render (str | None): Frames to render.

    Returns:
        list of pyblish.api.Instance: Instances created from
            expected files.

    """
    # we cannot attach AOVs to other products as we consider every
    # AOV product of its own.

    log = Logger.get_logger("farm_publishing")
    additional_color_data = {
        "renderProducts": instance.data["renderProducts"],
        "colorspaceConfig": instance.data["colorspaceConfig"],
        "display": instance.data["colorspaceDisplay"],
        "view": instance.data["colorspaceView"]
    }

    # Get templated path from absolute config path.
    anatomy = instance.context.data["anatomy"]
    colorspace_template = instance.data["colorspaceConfig"]
    try:
        additional_color_data["colorspaceTemplate"] = remap_source(
            colorspace_template, anatomy)
    except ValueError as e:
        log.warning(e)
        additional_color_data["colorspaceTemplate"] = colorspace_template

    # if there are product to attach to and more than one AOV,
    # we cannot proceed.
    if (
        len(instance.data.get("attachTo", [])) > 0
        and len(instance.data.get("expectedFiles")[0].keys()) != 1
    ):
        raise KnownPublishError(
            "attaching multiple AOVs or renderable cameras to "
            "product is not supported yet.")

    # create instances for every AOV we found in expected files.
    # NOTE: this is done for every AOV and every render camera (if
    #       there are multiple renderable cameras in scene)
    return _create_instances_for_aov(
        instance,
        skeleton,
        aov_filter,
        additional_color_data,
        skip_integration_repre_list,
        do_not_add_review,
        frames_to_render
    )

create_instances_for_cache(instance, skeleton)

Create instance for cache.

This will create new instance for every AOV it can detect in expected files list.

Parameters:

Name Type Description Default
instance Instance

Original instance.

required
skeleton dict

Skeleton data for instance (those needed) later by collector.

required

Returns:

Type Description

list of instances

Throws

ValueError:

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
def create_instances_for_cache(instance, skeleton):
    """Create instance for cache.

    This will create new instance for every AOV it can detect in expected
    files list.

    Args:
        instance (pyblish.api.Instance): Original instance.
        skeleton (dict): Skeleton data for instance (those needed) later
            by collector.


    Returns:
        list of instances

    Throws:
        ValueError:

    """
    anatomy = instance.context.data["anatomy"]
    product_name = skeleton["productName"]
    product_type = skeleton["productType"]
    exp_files = instance.data["expectedFiles"]
    log = Logger.get_logger("farm_publishing")

    instances = []
    # go through AOVs in expected files
    for _, files in exp_files[0].items():
        cols, rem = clique.assemble(files)
        # we shouldn't have any reminders. And if we do, it should
        # be just one item for single frame renders.
        if not cols and rem:
            if len(rem) != 1:
                raise ValueError("Found multiple non related files "
                                 "to render, don't know what to do "
                                 "with them.")
            col = rem[0]
            ext = os.path.splitext(col)[1].lstrip(".")
        else:
            # but we really expect only one collection.
            # Nothing else make sense.
            if len(cols) != 1:
                raise ValueError("Only one image sequence type is expected.")  # noqa: E501
            ext = cols[0].tail.lstrip(".")
            col = list(cols[0])

        if isinstance(col, (list, tuple)):
            staging = os.path.dirname(col[0])
        else:
            staging = os.path.dirname(col)

        try:
            staging = remap_source(staging, anatomy)
        except ValueError as e:
            log.warning(e)

        new_instance = deepcopy(skeleton)

        new_instance["productName"] = product_name
        log.info("Creating data for: {}".format(product_name))
        new_instance["productType"] = product_type
        new_instance["families"] = skeleton["families"]
        # create representation
        if isinstance(col, (list, tuple)):
            files = [os.path.basename(f) for f in col]
        else:
            files = os.path.basename(col)

        rep = {
            "name": ext,
            "ext": ext,
            "files": files,
            "frameStart": int(skeleton["frameStartHandle"]),
            "frameEnd": int(skeleton["frameEndHandle"]),
            # If expectedFile are absolute, we need only filenames
            "stagingDir": staging,
            "fps": new_instance.get("fps"),
            "tags": [],
        }

        new_instance["representations"] = [rep]

        # if extending frames from existing version, copy files from there
        # into our destination directory
        if new_instance.get("extendFrames", False):
            copy_extend_frames(new_instance, rep)
        instances.append(new_instance)
        log.debug("instances:{}".format(instances))
    return instances

create_skeleton_instance(instance, families_transfer=None, instance_transfer=None)

Create skeleton instance from original instance data.

This will create dictionary containing skeleton - common - data used for publishing rendered instances. This skeleton instance is then extended with additional data and serialized to be processed by farm job.

Parameters:

Name Type Description Default
instance Instance

Original instance to be used as a source of data.

required
families_transfer list

List of family names to transfer from the original instance to the skeleton.

None
instance_transfer dict

Dict with keys as families and values as a list of property names to transfer to the new skeleton.

None

Returns:

Name Type Description
dict

Dictionary with skeleton instance data.

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
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
def create_skeleton_instance(
        instance, families_transfer=None, instance_transfer=None):
    """Create skeleton instance from original instance data.

    This will create dictionary containing skeleton
    - common - data used for publishing rendered instances.
    This skeleton instance is then extended with additional data
    and serialized to be processed by farm job.

    Args:
        instance (pyblish.api.Instance): Original instance to
            be used as a source of data.
        families_transfer (list): List of family names to transfer
            from the original instance to the skeleton.
        instance_transfer (dict): Dict with keys as families and
            values as a list of property names to transfer to the
            new skeleton.

    Returns:
        dict: Dictionary with skeleton instance data.

    """
    # list of family names to transfer to new family if present

    context = instance.context
    data = instance.data.copy()
    anatomy = instance.context.data["anatomy"]

    # get time related data from instance (or context)
    time_data = get_time_data_from_instance_or_context(instance)

    if data.get("extendFrames", False):
        time_data.start, time_data.end = extend_frames(
            data["folderPath"],
            data["productName"],
            time_data.start,
            time_data.end,
        )

    source = data.get("source") or context.data.get("currentFile")
    success, rootless_path = (
        anatomy.find_root_template_from_path(source)
    )
    if success:
        source = rootless_path
    else:
        # `rootless_path` is not set to `source` if none of roots match
        log = Logger.get_logger("farm_publishing")
        log.warning(("Could not find root path for remapping \"{}\". "
                     "This may cause issues.").format(source))

    product_type = ("render"
              if "prerender.farm" not in instance.data["families"]
              else "prerender")
    families = [product_type]

    # pass review to families if marked as review
    if data.get("review"):
        families.append("review")

    instance_skeleton_data = {
        "productType": product_type,
        "productName": data["productName"],
        "task": data["task"],
        "families": families,
        "folderPath": data["folderPath"],
        "frameStart": time_data.start,
        "frameEnd": time_data.end,
        "handleStart": time_data.handle_start,
        "handleEnd": time_data.handle_end,
        "frameStartHandle": time_data.start - time_data.handle_start,
        "frameEndHandle": time_data.end + time_data.handle_end,
        "comment": data.get("comment"),
        "fps": time_data.fps,
        "source": source,
        "extendFrames": data.get("extendFrames"),
        "overrideExistingFrame": data.get("overrideExistingFrame"),
        "pixelAspect": data.get("pixelAspect", 1),
        "resolutionWidth": data.get("resolutionWidth", 1920),
        "resolutionHeight": data.get("resolutionHeight", 1080),
        "multipartExr": data.get("multipartExr", False),
        "jobBatchName": data.get("jobBatchName", ""),
        "useSequenceForReview": data.get("useSequenceForReview", True),
        # map inputVersions `ObjectId` -> `str` so json supports it
        "inputVersions": list(map(str, data.get("inputVersions", []))),
        "colorspace": data.get("colorspace"),
        "hasExplicitFrames": data.get("hasExplicitFrames")
    }

    if data.get("renderlayer"):
        instance_skeleton_data["renderlayer"] = data["renderlayer"]

    # skip locking version if we are creating v01
    instance_version = data.get("version")  # take this if exists
    if instance_version != 1:
        instance_skeleton_data["version"] = instance_version

    # transfer specific families from original instance to new render
    for item in families_transfer:
        if item in instance.data.get("families", []):
            instance_skeleton_data["families"] += [item]

    # transfer specific properties from original instance based on
    # mapping dictionary `instance_transfer`
    for key, values in instance_transfer.items():
        if key in instance.data.get("families", []):
            for v in values:
                instance_skeleton_data[v] = instance.data.get(v)

    representations = get_transferable_representations(instance)
    instance_skeleton_data["representations"] = representations

    persistent = instance.data.get("stagingDir_persistent") is True
    instance_skeleton_data["stagingDir_persistent"] = persistent

    return instance_skeleton_data

create_skeleton_instance_cache(instance)

Create skeleton instance from original instance data.

This will create dictionary containing skeleton - common - data used for publishing rendered instances. This skeleton instance is then extended with additional data and serialized to be processed by farm job.

Parameters:

Name Type Description Default
instance Instance

Original instance to be used as a source of data.

required

Returns:

Name Type Description
dict

Dictionary with skeleton instance data.

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
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
def create_skeleton_instance_cache(instance):
    """Create skeleton instance from original instance data.

    This will create dictionary containing skeleton
    - common - data used for publishing rendered instances.
    This skeleton instance is then extended with additional data
    and serialized to be processed by farm job.

    Args:
        instance (pyblish.api.Instance): Original instance to
            be used as a source of data.

    Returns:
        dict: Dictionary with skeleton instance data.

    """
    # list of family names to transfer to new family if present

    context = instance.context
    data = instance.data.copy()
    anatomy = instance.context.data["anatomy"]

    # get time related data from instance (or context)
    time_data = get_time_data_from_instance_or_context(instance)

    if data.get("extendFrames", False):
        time_data.start, time_data.end = extend_frames(
            data["folderPath"],
            data["productName"],
            time_data.start,
            time_data.end,
        )

    source = data.get("source") or context.data.get("currentFile")
    success, rootless_path = (
        anatomy.find_root_template_from_path(source)
    )
    if success:
        source = rootless_path
    else:
        # `rootless_path` is not set to `source` if none of roots match
        log = Logger.get_logger("farm_publishing")
        log.warning(("Could not find root path for remapping \"{}\". "
                     "This may cause issues.").format(source))

    product_type = instance.data["productType"]
    # Make sure "render" is in the families to go through
    # validating expected and rendered files
    # during publishing job.
    families = ["render", product_type]

    instance_skeleton_data = {
        "productName": data["productName"],
        "productType": product_type,
        "family": product_type,
        "families": families,
        "folderPath": data["folderPath"],
        "frameStart": time_data.start,
        "frameEnd": time_data.end,
        "handleStart": time_data.handle_start,
        "handleEnd": time_data.handle_end,
        "frameStartHandle": time_data.start - time_data.handle_start,
        "frameEndHandle": time_data.end + time_data.handle_end,
        "comment": data.get("comment"),
        "fps": time_data.fps,
        "source": source,
        "extendFrames": data.get("extendFrames"),
        "overrideExistingFrame": data.get("overrideExistingFrame"),
        "jobBatchName": data.get("jobBatchName", ""),
        # map inputVersions `ObjectId` -> `str` so json supports it
        "inputVersions": list(map(str, data.get("inputVersions", []))),
    }

    # skip locking version if we are creating v01
    instance_version = data.get("version")  # take this if exists
    if instance_version != 1:
        instance_skeleton_data["version"] = instance_version

    representations = get_transferable_representations(instance)
    instance_skeleton_data["representations"] = representations

    persistent = instance.data.get("stagingDir_persistent") is True
    instance_skeleton_data["stagingDir_persistent"] = persistent

    return instance_skeleton_data

extend_frames(folder_path, product_name, start, end)

Get latest version of asset nad update frame range.

Based on minimum and maximum values.

Parameters:

Name Type Description Default
folder_path str

Folder path.

required
product_name str

Product name.

required
start int

Start frame.

required
end int

End frame.

required

Returns:

Type Description
(int, int)

update frame start/end

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
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
def extend_frames(folder_path, product_name, start, end):
    """Get latest version of asset nad update frame range.

    Based on minimum and maximum values.

    Arguments:
        folder_path (str): Folder path.
        product_name (str): Product name.
        start (int): Start frame.
        end (int): End frame.

    Returns:
        (int, int): update frame start/end

    """
    # Frame comparison
    prev_start = None
    prev_end = None

    project_name = get_current_project_name()
    folder_entity = ayon_api.get_folder_by_path(
        project_name, folder_path, fields={"id"}
    )
    version_entity = ayon_api.get_last_version_by_product_name(
        project_name,
        product_name,
        folder_entity["id"]
    )

    # Set prev start / end frames for comparison
    if not prev_start and not prev_end:
        prev_start = version_entity["attrib"]["frameStart"]
        prev_end = version_entity["attrib"]["frameEnd"]

    updated_start = min(start, prev_start)
    updated_end = max(end, prev_end)

    return updated_start, updated_end

get_product_name_and_group_from_template(project_name, task_entity, product_type, variant, host_name, dynamic_data=None)

Get product name and group name from template.

This will get product name and group name from template based on data provided. It is doing similar work as func::_get_legacy_product_name_and_group but using templates.

To get group name, template is called without any dynamic data, so (depending on the template itself) it should be product name without aov.

Todo

Maybe we should introduce templates for the groups themselves.

Parameters:

Name Type Description Default
task_entity dict

Task entity.

required
project_name str

Project name.

required
host_name str

Host name.

required
product_type str

Product type.

required
variant str

Variant.

required
dynamic_data dict

Dynamic data (aov, renderlayer, camera, ...).

None

Returns:

Name Type Description
tuple

product name and group name.

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
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
def get_product_name_and_group_from_template(
        project_name,
        task_entity,
        product_type,
        variant,
        host_name,
        dynamic_data=None):
    """Get product name and group name from template.

    This will get product name and group name from template based on
    data provided. It is doing similar work as
    `func::_get_legacy_product_name_and_group` but using templates.

    To get group name, template is called without any dynamic data, so
    (depending on the template itself) it should be product name without
    aov.

    Todo:
        Maybe we should introduce templates for the groups themselves.

    Args:
        task_entity (dict): Task entity.
        project_name (str): Project name.
        host_name (str): Host name.
        product_type (str): Product type.
        variant (str): Variant.
        dynamic_data (dict): Dynamic data (aov, renderlayer, camera, ...).

    Returns:
        tuple: product name and group name.

    """
    # remove 'aov' from data used to format group. See todo comment above
    # for possible solution.
    _dynamic_data = deepcopy(dynamic_data) or {}
    _dynamic_data.pop("aov", None)
    resulting_group_name = get_product_name(
        project_name=project_name,
        task_name=task_entity["name"],
        task_type=task_entity["taskType"],
        host_name=host_name,
        product_type=product_type,
        dynamic_data=_dynamic_data,
        variant=variant,
    )

    resulting_product_name = get_product_name(
        project_name=project_name,
        task_name=task_entity["name"],
        task_type=task_entity["taskType"],
        host_name=host_name,
        product_type=product_type,
        dynamic_data=dynamic_data,
        variant=variant,
    )
    return resulting_product_name, resulting_group_name

get_resources(project_name, version_entity, extension=None)

Get the files from the specific version.

This will return all get all files from representation.

Todo

This is really weird function, and it's use is highly controversial. First, it will not probably work ar all in final release of AYON, second, the logic isn't sound. It should try to find representation matching the current one - because it is used to pull out files from previous version to be included in this one.

.. deprecated:: 3.15.5 This won't work in AYON and even the logic must be refactored.

Parameters:

Name Type Description Default
project_name str

Name of the project.

required
version_entity dict

Version entity.

required
extension str

extension used to filter representations.

None

Returns:

Name Type Description
list

of files

Source code in client/ayon_core/pipeline/farm/pyblish_functions.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
def get_resources(project_name, version_entity, extension=None):
    """Get the files from the specific version.

    This will return all get all files from representation.

    Todo:
        This is really weird function, and it's use is
        highly controversial. First, it will not probably work
        ar all in final release of AYON, second, the logic isn't sound.
        It should try to find representation matching the current one -
        because it is used to pull out files from previous version to
        be included in this one.

    .. deprecated:: 3.15.5
       This won't work in AYON and even the logic must be refactored.

    Args:
        project_name (str): Name of the project.
        version_entity (dict): Version entity.
        extension (str): extension used to filter
            representations.

    Returns:
        list: of files

    """
    warnings.warn((
        "This won't work in AYON and even "
        "the logic must be refactored."), DeprecationWarning)
    extensions = []
    if extension:
        extensions = [extension]

    # there is a `context_filter` argument that won't probably work in
    # final release of AYON. SO we'll rather not use it
    repre_entities = list(ayon_api.get_representations(
        project_name, version_ids={version_entity["id"]}
    ))

    filtered = []
    for repre_entity in repre_entities:
        if repre_entity["context"]["ext"] in extensions:
            filtered.append(repre_entity)

    representation = filtered[0]
    directory = get_representation_path(representation)
    print("Source: ", directory)
    resources = sorted(
        [
            os.path.normpath(os.path.join(directory, file_name))
            for file_name in os.listdir(directory)
        ]
    )

    return resources

get_time_data_from_instance_or_context(instance)

Get time data from instance (or context).

If time data is not found on instance, data from context will be used.

Parameters:

Name Type Description Default
instance Instance

Source instance.

required

Returns:

Name Type Description
TimeData

dataclass holding time information.

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
 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
def get_time_data_from_instance_or_context(instance):
    """Get time data from instance (or context).

    If time data is not found on instance, data from context will be used.

    Args:
        instance (pyblish.api.Instance): Source instance.

    Returns:
        TimeData: dataclass holding time information.

    """
    context = instance.context
    return TimeData(
        start=instance.data.get("frameStart", context.data.get("frameStart")),
        end=instance.data.get("frameEnd", context.data.get("frameEnd")),
        fps=instance.data.get("fps", context.data.get("fps")),
        step=instance.data.get("byFrameStep", instance.data.get("step", 1)),
        handle_start=instance.data.get(
            "handleStart", context.data.get("handleStart")
        ),
        handle_end=instance.data.get(
            "handleEnd", context.data.get("handleEnd")
        )
    )

get_transferable_representations(instance)

Transfer representations from original instance.

This will get all representations on the original instance that are flagged with publish_on_farm and return them to be included on skeleton instance if needed.

Parameters:

Name Type Description Default
instance Instance

Original instance to be processed.

required
Return

list of dicts: List of transferable representations.

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
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
def get_transferable_representations(instance):
    """Transfer representations from original instance.

    This will get all representations on the original instance that
    are flagged with `publish_on_farm` and return them to be included
    on skeleton instance if needed.

    Args:
        instance (pyblish.api.Instance): Original instance to be processed.

    Return:
        list of dicts: List of transferable representations.

    """
    anatomy = instance.context.data["anatomy"]
    to_transfer = []

    for representation in instance.data.get("representations", []):
        if "publish_on_farm" not in representation.get("tags", []):
            continue

        trans_rep = representation.copy()

        # remove publish_on_farm from representations tags
        trans_rep["tags"].remove("publish_on_farm")

        staging_dir = trans_rep.get("stagingDir")

        if staging_dir:
            try:
                trans_rep["stagingDir"] = remap_source(staging_dir, anatomy)
            except ValueError:
                log = Logger.get_logger("farm_publishing")
                log.warning(
                    ("Could not find root path for remapping \"{}\". "
                     "This may cause issues on farm.").format(staging_dir))

        to_transfer.append(trans_rep)
    return to_transfer

prepare_cache_representations(skeleton_data, exp_files, anatomy)

Create representations for file sequences.

This will return representations of expected files if they are not in hierarchy of aovs. There should be only one sequence of files for most cases, but if not - we create representation from each of them.

Parameters:

Name Type Description Default
skeleton_data dict

instance data for which we are setting representations

required
exp_files list

list of expected files

required

Returns: list of representations

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
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
1197
1198
1199
1200
1201
1202
1203
1204
1205
def prepare_cache_representations(skeleton_data, exp_files, anatomy):
    """Create representations for file sequences.

    This will return representations of expected files if they are not
    in hierarchy of aovs. There should be only one sequence of files for
    most cases, but if not - we create representation from each of them.

    Arguments:
        skeleton_data (dict): instance data for which we are
                         setting representations
        exp_files (list): list of expected files
        anatomy (Anatomy)
    Returns:
        list of representations

    """
    representations = []
    collections, remainders = clique.assemble(exp_files)

    log = Logger.get_logger("farm_publishing")

    # create representation for every collected sequence
    for collection in collections:
        ext = collection.tail.lstrip(".")

        staging = os.path.dirname(list(collection)[0])
        success, rootless_staging_dir = (
            anatomy.find_root_template_from_path(staging)
        )
        if success:
            staging = rootless_staging_dir
        else:
            log.warning((
                "Could not find root path for remapping \"{}\"."
                " This may cause issues on farm."
            ).format(staging))

        frame_start = int(skeleton_data.get("frameStartHandle"))
        rep = {
            "name": ext,
            "ext": ext,
            "files": [os.path.basename(f) for f in list(collection)],
            "frameStart": frame_start,
            "frameEnd": int(skeleton_data.get("frameEndHandle")),
            # If expectedFile are absolute, we need only filenames
            "stagingDir": staging,
            "fps": skeleton_data.get("fps")
        }

        representations.append(rep)

    return representations

prepare_representations(skeleton_data, exp_files, anatomy, aov_filter, skip_integration_repre_list, do_not_add_review, context, color_managed_plugin, frames_to_render=None)

Create representations for file sequences.

This will return representations of expected files if they are not in hierarchy of aovs. There should be only one sequence of files for most cases, but if not - we create representation from each of them.

Parameters:

Name Type Description Default
skeleton_data dict

instance data for which we are setting representations

required
exp_files list

list of expected files

required
anatomy Anatomy
required
aov_filter dict

add review for specific aov names

required
skip_integration_repre_list list

exclude specific extensions,

required
do_not_add_review bool

explicitly skip review

required
frames_to_render str | None

implicit or explicit range of frames to render this value is sent to Deadline in JobInfo.Frames

None

Returns: list of representations

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
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
def prepare_representations(
    skeleton_data,
    exp_files,
    anatomy,
    aov_filter,
    skip_integration_repre_list,
    do_not_add_review,
    context,
    color_managed_plugin,
    frames_to_render=None
):
    """Create representations for file sequences.

    This will return representations of expected files if they are not
    in hierarchy of aovs. There should be only one sequence of files for
    most cases, but if not - we create representation from each of them.

    Arguments:
        skeleton_data (dict): instance data for which we are
                         setting representations
        exp_files (list): list of expected files
        anatomy (Anatomy):
        aov_filter (dict): add review for specific aov names
        skip_integration_repre_list (list): exclude specific extensions,
        do_not_add_review (bool): explicitly skip review
        color_managed_plugin (publish.ColormanagedPyblishPluginMixin)
        frames_to_render (str | None): implicit or explicit range of frames
            to render this value is sent to Deadline in JobInfo.Frames
    Returns:
        list of representations

    """
    representations = []
    host_name = os.environ.get("AYON_HOST_NAME", "")
    collections, remainders = clique.assemble(exp_files)

    log = Logger.get_logger("farm_publishing")

    if frames_to_render is not None:
        frames_to_render = convert_frames_str_to_list(frames_to_render)
    else:
        # Backwards compatibility for older logic
        frame_start = int(skeleton_data.get("frameStartHandle"))
        frame_end = int(skeleton_data.get("frameEndHandle"))
        frames_to_render = list(range(frame_start, frame_end + 1))

    # create representation for every collected sequence
    for collection in collections:
        ext = collection.tail.lstrip(".")
        preview = False
        # TODO 'useSequenceForReview' is temporary solution which does
        #   not work for 100% of cases. We must be able to tell what
        #   expected files contains more explicitly and from what
        #   should be review made.
        # - "review" tag is never added when is set to 'False'
        if skeleton_data["useSequenceForReview"]:
            # toggle preview on if multipart is on
            if skeleton_data.get("multipartExr", False):
                log.debug(
                    "Adding preview tag because its multipartExr"
                )
                preview = True
            else:
                render_file_name = list(collection)[0]
                # if filtered aov name is found in filename, toggle it for
                # preview video rendering
                preview = match_aov_pattern(
                    host_name, aov_filter, render_file_name
                )

        staging = os.path.dirname(list(collection)[0])
        success, rootless_staging_dir = (
            anatomy.find_root_template_from_path(staging)
        )
        if success:
            staging = rootless_staging_dir
        else:
            log.warning((
                "Could not find root path for remapping \"{}\"."
                " This may cause issues on farm."
            ).format(staging))

        frame_start = frames_to_render[0]
        frame_end = frames_to_render[-1]
        if skeleton_data.get("slate"):
            frame_start -= 1
            frames_to_render.insert(0, frame_start)

        filenames = [
            os.path.basename(filepath)
            for filepath in _get_real_files_to_render(
                collection, frames_to_render
            )
        ]
        # explicitly disable review by user
        preview = preview and not do_not_add_review
        rep = {
            "name": ext,
            "ext": ext,
            "files": filenames,
            "stagingDir": staging,
            "frameStart": frame_start,
            "frameEnd": frame_end,
            "fps": skeleton_data.get("fps"),
            "tags": ["review"] if preview else [],
        }

        # poor man exclusion
        if ext in skip_integration_repre_list:
            rep["tags"].append("delete")

        if skeleton_data.get("multipartExr", False):
            rep["tags"].append("multipartExr")

        # support conversion from tiled to scanline
        if skeleton_data.get("convertToScanline"):
            log.info("Adding scanline conversion.")
            rep["tags"].append("toScanline")

        representations.append(rep)

        if preview:
            skeleton_data["families"] = _add_review_families(
                skeleton_data["families"])

    # add remainders as representations
    for remainder in remainders:
        ext = remainder.split(".")[-1]

        staging = os.path.dirname(remainder)
        success, rootless_staging_dir = (
            anatomy.find_root_template_from_path(staging)
        )
        if success:
            staging = rootless_staging_dir
        else:
            log.warning((
                "Could not find root path for remapping \"{}\"."
                " This may cause issues on farm."
            ).format(staging))

        rep = {
            "name": ext,
            "ext": ext,
            "files": os.path.basename(remainder),
            "stagingDir": staging,
        }

        preview = match_aov_pattern(
            host_name, aov_filter, remainder
        )
        preview = preview and not do_not_add_review
        if preview:
            rep.update({
                "fps": skeleton_data.get("fps"),
                "tags": ["review"]
            })
            skeleton_data["families"] = \
                _add_review_families(skeleton_data["families"])

        already_there = False
        for repre in skeleton_data.get("representations", []):
            # might be added explicitly before by publish_on_farm
            already_there = repre.get("files") == rep["files"]
            if already_there:
                log.debug("repre {} already_there".format(repre))
                break

        if not already_there:
            representations.append(rep)

    for rep in representations:
        # inject colorspace data
        color_managed_plugin.set_representation_colorspace(
            rep, context,
            colorspace=skeleton_data["colorspace"]
        )

    return representations

remap_source(path, anatomy)

Try to remap path to rootless path.

Parameters:

Name Type Description Default
path str

Path to be remapped to rootless.

required
anatomy Anatomy

Anatomy object to handle remapping itself.

required

Returns:

Name Type Description
str

Remapped path.

Throws

ValueError: if the root cannot be found.

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def remap_source(path, anatomy):
    """Try to remap path to rootless path.

    Args:
        path (str): Path to be remapped to rootless.
        anatomy (Anatomy): Anatomy object to handle remapping
            itself.

    Returns:
        str: Remapped path.

    Throws:
        ValueError: if the root cannot be found.

    """
    success, rootless_path = (
        anatomy.find_root_template_from_path(path)
    )
    if success:
        source = rootless_path
    else:
        raise ValueError(
            "Root from template path cannot be found: {}".format(path))
    return source