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
27
28
29
30
31
32
33
34
35
@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
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
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["productBaseType"] = attach_instance.get(
                "productBaseType"
            )
            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
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
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
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
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

    """

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

    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:
        copyfile(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
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
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.

    # 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.")

    additional_data = {
        "renderProducts": instance.data["renderProducts"],
    }

    # Collect color management data if present
    colorspace_config = instance.data.get("colorspaceConfig")
    if colorspace_config:
        additional_data.update({
            "colorspaceConfig": colorspace_config,
            # Display/View are optional
            "display": instance.data.get("sourceDisplay"),
            "view": instance.data.get("sourceView")
        })

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

    # 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_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
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
1384
1385
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
1414
1415
1416
1417
1418
1419
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"]
    product_base_type = skeleton.get("productBaseType")
    if not product_base_type:
        product_base_type = product_type
    exp_files = instance.data["expectedFiles"]

    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)

        log.info("Creating data for: {}".format(product_name))
        new_instance["productName"] = product_name
        new_instance["productType"] = product_type
        new_instance["productBaseType"] = product_base_type
        # 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
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
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
    if families_transfer is None:
        families_transfer = []

    if instance_transfer is None:
        instance_transfer = {}

    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.warning(("Could not find root path for remapping \"{}\". "
                     "This may cause issues.").format(source))

    # This is a hack to keep the value of 'productType'.
    # Because this function does not use product base type from source
    #   instance and we don't know if product type of the instance was
    #   customized or not, only way how to guess custom product type is
    #   to check if is same as product base type.
    i_product_base_type = instance.data.get("productBaseType")
    i_product_type = instance.data.get("productType")
    product_type = None
    if (
        i_product_base_type
        and i_product_base_type != i_product_type
    ):
        product_type = i_product_type

    # This is the old way of defining product base type
    # - hard-coded product base type
    product_base_type = "render"
    if "prerender.farm" in instance.data["families"]:
        product_base_type = "prerender"

    if not product_type:
        product_type = product_base_type

    families = [product_base_type]

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

    instance_skeleton_data = {
        # TODO find out how to define product type
        # - Right now product base type is hardcoded, from where should be
        #   product type taken?
        "productType": product_type,
        "productBaseType": product_base_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", False),
        "reuseLastVersion": data.get("reuseLastVersion", False),
    }

    # Pass on the OCIO metadata of what the source display and view are
    # so that the farm can correctly set up color management.
    if "sceneDisplay" in data and "sceneView" in data:
        instance_skeleton_data["sceneDisplay"] = data["sceneDisplay"]
        instance_skeleton_data["sceneView"] = data["sceneView"]
    elif "colorspaceDisplay" in data and "colorspaceView" in data:
        # Backwards compatibility for sceneDisplay and sceneView
        instance_skeleton_data["colorspaceDisplay"] = data["colorspaceDisplay"]
        instance_skeleton_data["colorspaceView"] = data["colorspaceView"]
    if "sourceDisplay" in data and "sourceView" in data:
        instance_skeleton_data["sourceDisplay"] = data["sourceDisplay"]
        instance_skeleton_data["sourceView"] = data["sourceView"]

    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
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
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
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.warning(("Could not find root path for remapping \"{}\". "
                     "This may cause issues.").format(source))

    product_type = instance.data["productType"]
    product_base_type = instance.data.get("productBaseType")
    if not product_base_type:
        product_base_type = product_type
    # Make sure "render" is in the families to go through
    # validating expected and rendered files
    # during publishing job.
    families = ["render", product_base_type]

    instance_skeleton_data = {
        "productName": data["productName"],
        "productType": product_type,
        "productBaseType": product_base_type,
        "family": product_base_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
 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
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, *, folder_entity=None, product_base_type=None, project_entity=None, project_settings=None)

Get product name and group name from template.

This function is/was used only in ayon-houdini which uses/d kwargs

for all arguments. When houdini starts to use 'folder_entity' and 'product_base_type' this should change order of arguments.

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
project_name str

Project name.

required
task_entity Union[dict[str, Any], None]

Task entity.

required
host_name str

Host name.

required
product_type str

Product type.

required
variant str

Variant.

required
dynamic_data Optional[dict[str, Any]]

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

None
folder_entity Union[dict[str, Any], None]

Folder entity.

None
product_base_type str

Product base type.

None
project_entity Optional[dict[str, Any]]

Project entity.

None
project_settings Optional[dict[str, Any]]

Project settings.

None

Returns:

Name Type Description
tuple tuple[str, str]

product name and group name.

Source code in client/ayon_core/pipeline/farm/pyblish_functions.py
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
def get_product_name_and_group_from_template(
    project_name: str,
    task_entity: Union[dict[str, Any], None],
    product_type: str,
    variant: str,
    host_name: str,
    dynamic_data: Optional[dict[str, Any]] = None,
    *,
    folder_entity: Union[dict[str, Any], None] = None,
    product_base_type: str = None,
    project_entity: Optional[dict[str, Any]] = None,
    project_settings: Optional[dict[str, Any]] = None,
) -> tuple[str, str]:
    """Get product name and group name from template.

    NOTE: This function is/was used only in ayon-houdini which uses/d kwargs
        for all arguments. When houdini starts to use 'folder_entity' and
        'product_base_type' this should change order of arguments.

    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:
        project_name (str): Project name.
        task_entity (Union[dict[str, Any], None]): Task entity.
        host_name (str): Host name.
        product_type (str): Product type.
        variant (str): Variant.
        dynamic_data (Optional[dict[str, Any]]): Dynamic data
            (aov, renderlayer, camera, ...).
        folder_entity (Union[dict[str, Any], None]): Folder entity.
        product_base_type (str): Product base type.
        project_entity (Optional[dict[str, Any]]): Project entity.
        project_settings (Optional[dict[str, Any]]): Project settings.

    Returns:
        tuple: product name and group name.

    """
    if not folder_entity and task_entity:
        folder_entity = None
        if task_entity:
            folder_entity = ayon_api.get_folder_by_path(
                project_name, task_entity["folderId"]
            )

    if not product_base_type:
        log.warning(
            f"DEPRECATION WARNING: Product base type not provided,"
            f" using product type: {product_type}"
        )
        product_base_type = product_type

    if not project_entity:
        project_entity = ayon_api.get_project(project_name)

    if not project_settings:
        project_settings = get_project_settings(project_name)

    # remove 'aov' from data used to format group. See todo comment above
    # for possible solution.
    if dynamic_data is None:
        dynamic_data = {}
    _dynamic_data = deepcopy(dynamic_data)
    _dynamic_data.pop("aov", None)

    resulting_group_name = get_product_name(
        project_name=project_name,
        folder_entity=folder_entity,
        task_entity=task_entity,
        host_name=host_name,
        product_base_type=product_base_type,
        product_type=product_type,
        dynamic_data=_dynamic_data,
        variant=variant,
        project_entity=project_entity,
        project_settings=project_settings,
    )

    resulting_product_name = get_product_name(
        project_name=project_name,
        folder_entity=folder_entity,
        task_entity=task_entity,
        host_name=host_name,
        product_base_type=product_base_type,
        product_type=product_type,
        dynamic_data=dynamic_data,
        variant=variant,
        project_entity=project_entity,
        project_settings=project_settings,
    )
    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
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
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(
        project_name, 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
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
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
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
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.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
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
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
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)

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

    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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def 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