Skip to content

extract_product_resources

ExtractProductResources

Bases: Extractor, ColormanagedPyblishPluginMixin

Extractor for transcoding files from Flame clip

Source code in client/ayon_flame/plugins/publish/extract_product_resources.py
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
class ExtractProductResources(
    publish.Extractor,
    publish.ColormanagedPyblishPluginMixin
):
    """
    Extractor for transcoding files from Flame clip
    """

    label = "Extract product resources"
    order = pyblish.api.ExtractorOrder
    families = ["clip"]
    hosts = ["flame"]

    settings_category = "flame"

    # hide publisher during exporting
    hide_ui_on_process = True

    # settings
    missing_media_link_export_preset: dict
    additional_representation_export: dict
    thumbnail_preset: dict

    def process(self, instance):
        # create staging dir path
        staging_dir = self.staging_dir(instance)

        # append staging dir for later cleanup
        instance.context.data["cleanupFullPaths"].append(staging_dir)

        clip_data = self.get_clip_data(instance)
        if not clip_data["clip_path"]:
            # render missing media and add `clip_data["clip_path"]`
            clip_data = self.missing_media_link_export_preset_process(
                instance, clip_data, staging_dir)

        self.thumbnail_preset_process(instance, clip_data, staging_dir)
        self.additional_representation_export_process(
            instance, clip_data, staging_dir)

        # pformat output instance representations
        self.log.info("Instance representations:")
        self.log.info(pformat(instance.data["representations"]))

    def get_clip_data(self, instance: pyblish.api.Instance) -> dict:
        """Extract and prepare all clip-related data for export processing.

        Args:
            instance (Instance): Instance object.

        Returns:
            Dict[str, Any]: A dictionary containing all extracted clip data
                with at least these keys:
                * `segment` (flame.Segment): The flame segment object.
                * `folder_path` (str): Path to the folder.
                * `segment_name` (str): Name of the segment.
                * `clip_path` (Optional[str]): Path to the clip
                    (None if not linked media).
                * `sequence_clip` (flame.Clip): The flame sequence clip object.
                * `s_track_name` (str): Parent track name of the segment.
                * `frame_start` (int): Configured workfile frame start.
                * `source_first_frame` (int): Media source first frame.
                * `clip_in` (int): Timeline in point of segment.
                * `clip_out` (int): Timeline out point of segment.
                * `retimed_handle_start` (int): Retimed handle start value.
                * `retimed_handle_end` (int): Retimed handle end value.
                * `retimed_source_duration` (int): Retimed source duration.
                * `retimed_speed` (float): Retimed speed factor.
                * `handle_start` (int): Handle start value.
                * `handle_end` (int): Handle end value.
                * `handles` (int): Maximum of handle_start and handle_end.
                * `include_handles` (bool): Whether to include handles.
                * `retimed_handles` (bool): Whether handles are retimed.
                * `source_start_handles` (int): Source start with handles.
                * `source_end_handles` (int): Source end with handles.
                * `frame_start_handle` (int): Frame start with handles applied.
                * `repre_frame_start` (int): Representation frame start.
                * `source_duration_handles` (int): Source duration including
                    handles.
                * `version_frame_start` (int): Version data frame start.

        """
        # flame objects
        item = instance.data["item"]
        if isinstance(item, flame.PySegment):
            segment = item
        elif isinstance(item, flame.PyClip):
            segment = ayfapi.lib.get_clip_segment(item)
        else:
            raise ValueError(f"Unsupported item: {item}.")

        folder_path = instance.data["folderPath"]
        segment_name = segment.name.get_value()
        # clip_path will be None if not linked media
        clip_path = instance.data["path"]
        sequence_clip = instance.context.data.get("flameSequence")

        # segment's parent track name
        s_track_name = segment.parent.name.get_value()

        # get configured workfile frame start/end (handles excluded)
        frame_start = instance.data["frameStart"]
        # get media source first frame
        source_first_frame = instance.data["sourceFirstFrame"]

        self.log.debug("_ frame_start: %s", frame_start)
        self.log.debug("_ source_first_frame: %s", source_first_frame)

        # get timeline in/out of segment
        clip_in = instance.data["clipIn"]
        clip_out = instance.data["clipOut"]

        # get handles value - take only the max from both
        handle_start = instance.data["handleStart"]
        handle_end = instance.data["handleEnd"]
        handles = max(handle_start, handle_end)

        retimed_data = {}
        if clip_path:
            # media source is linked to a clip, so we do have available
            # otio reference for media source frame range calculation

            # get retimed attributres
            retimed_data = self._get_retimed_attributes(instance)

            # get individual keys
            retimed_handle_start = retimed_data["handle_start"]
            retimed_handle_end = retimed_data["handle_end"]
            retimed_source_duration = retimed_data["source_duration"]
            retimed_speed = retimed_data["speed"]
            # get media source range with handles
            source_start_handles = instance.data["sourceStartH"]
            source_end_handles = instance.data["sourceEndH"]
        else:
            # media source is unlinked, so we do not have available
            # otio reference for media source frame range calculation
            segment_data = ayfapi.get_segment_attributes(segment)
            source_in = segment_data["source_in"]
            source_out = segment_data["source_out"]
            source_duration = source_out - source_in + 1
            record_duration = segment_data["record_duration"]
            # secondly check if any change of speed
            retimed_speed = 1
            if source_duration != record_duration:
                speed = float(source_duration) / float(record_duration)
                self.log.debug(f"_ calculated speed: {speed}")
                retimed_speed *= speed
            retimed_handle_start = handle_start * retimed_speed
            retimed_handle_end = handle_end * retimed_speed
            retimed_source_duration = source_duration * retimed_speed
            source_start_handles = source_in - handle_start
            source_end_handles = source_out - handle_end

        include_handles = instance.data.get("includeHandles")
        retimed_handles = instance.data.get("retimedHandles")

        # retime if needed
        if retimed_speed != 1.0:
            if retimed_handles:
                # handles are retimed
                source_start_handles = (
                    source_start_handles - retimed_handle_start)
                source_end_handles = (
                    source_start_handles
                    + (retimed_source_duration - 1)
                    + retimed_handle_start
                    + retimed_handle_end
                )

            else:
                # handles are not retimed
                source_end_handles = (
                    source_start_handles
                    + (retimed_source_duration - 1)
                    + handle_start
                    + handle_end
                )

        # get frame range with handles for representation range
        frame_start_handle = frame_start - handle_start
        repre_frame_start = frame_start_handle
        if include_handles:
            if retimed_speed == 1.0 or not retimed_handles:
                frame_start_handle = frame_start
            else:
                frame_start_handle = (
                    frame_start - handle_start) + retimed_handle_start

        self.log.debug("_ frame_start_handle: %s", frame_start_handle)
        self.log.debug("_ repre_frame_start: %s", repre_frame_start)

        # calculate duration with handles
        source_duration_handles = (
            source_end_handles - source_start_handles) + 1

        self.log.debug(
            "_ source_duration_handles: %s",
            source_duration_handles
        )

        if not instance.data.get("versionData"):
            instance.data["versionData"] = {}

        # set versiondata if any retime
        version_data = retimed_data.get("version_data")
        self.log.debug("_ version_data: %s", version_data)

        if version_data:
            instance.data["versionData"].update(version_data)

        # version data start frame
        version_frame_start = frame_start
        if include_handles:
            version_frame_start = frame_start_handle
        if retimed_speed != 1.0:
            if retimed_handles:
                instance.data["versionData"].update({
                    "frameStart": version_frame_start,
                    "frameEnd": (
                        (version_frame_start + source_duration_handles - 1)
                        - (retimed_handle_start + retimed_handle_end)
                    )
                })
            else:
                instance.data["versionData"].update({
                    "handleStart": handle_start,
                    "handleEnd": handle_end,
                    "frameStart": version_frame_start,
                    "frameEnd": (
                        (version_frame_start + source_duration_handles - 1)
                        - (handle_start + handle_end)
                    )
                })
        self.log.debug("_ version_data: {}".format(
            instance.data["versionData"]
        ))

        # Return all extracted data as a dictionary
        return {
            "segment": segment,
            "folder_path": folder_path,
            "segment_name": segment_name,
            "clip_path": clip_path,
            "sequence_clip": sequence_clip,
            "s_track_name": s_track_name,
            "frame_start": frame_start,
            "source_first_frame": source_first_frame,
            "clip_in": clip_in,
            "clip_out": clip_out,
            "retimed_handle_start": retimed_handle_start,
            "retimed_handle_end": retimed_handle_end,
            "retimed_source_duration": retimed_source_duration,
            "retimed_speed": retimed_speed,
            "handle_start": handle_start,
            "handle_end": handle_end,
            "handles": handles,
            "include_handles": include_handles,
            "retimed_handles": retimed_handles,
            "source_start_handles": source_start_handles,
            "source_end_handles": source_end_handles,
            "frame_start_handle": frame_start_handle,
            "repre_frame_start": repre_frame_start,
            "source_duration_handles": source_duration_handles,
            "version_frame_start": version_frame_start,
        }

    def missing_media_link_export_preset_process(
            self, instance, clip_data, staging_dir) -> dict:

        unique_name = "missing_media_link"
        extension = self.missing_media_link_export_preset["ext"]

        # Process preset export
        exporting_clip, export_dir_path, imageio_colorspace = \
            self._process_preset_export(
                instance,
                self.missing_media_link_export_preset,
                clip_data,
                unique_name,
                staging_dir,
            )

        repre_staging_dir, repre_files, _ = (
            self._process_exported_files(
                export_dir_path,
                extension,
                unique_name
            )
        )
        # Extract only needed data from clip_data dictionary
        source_duration_handles = clip_data["source_duration_handles"]
        repre_frame_start = clip_data["repre_frame_start"]

        # create representation data
        representation_data = self._create_representation_data(
            repr_name=extension,
            repre_files=repre_files,
            extension=extension,
            repre_staging_dir=repre_staging_dir,
            repre_tags=[],
            preset_config=self.missing_media_link_export_preset,
            repre_frame_start=repre_frame_start,
            source_duration_handles=source_duration_handles,
            instance=instance,
            imageio_colorspace=imageio_colorspace,
        )

        instance.data["representations"].append(representation_data)

        clip_data["clip_path"] = (
            Path(repre_staging_dir) / repre_files[0]).as_posix()
        clip_data["PyClip"] = exporting_clip

        return clip_data

    def thumbnail_preset_process(
            self, instance, clip_data, staging_dir):
        if (
            not self.thumbnail_preset["enabled"]
        ):
            self.log.debug("No thumbnail_preset is set")
            return
        unique_name = "thumbnail"
        # Process preset export
        exporting_clip, export_dir_path, imageio_colorspace = \
            self._process_preset_export(
                instance,
                self.thumbnail_preset,
                clip_data,
                unique_name,
                staging_dir,
            )

    def additional_representation_export_process(
            self, instance, clip_data, staging_dir):
        ad_repre_settings = self.additional_representation_export
        additional_export_presets: list[dict] = ad_repre_settings[
            "export_presets_mapping"]

        if (
            not ad_repre_settings["keep_original_representation"] and
            any(preset for preset in additional_export_presets
                if preset["enabled"])
        ):
            # remove previeous representation if not needed
            instance.data["representations"] = []

        # Extract only needed data from clip_data dictionary
        clip_path = clip_data["clip_path"]
        source_duration_handles = clip_data["source_duration_handles"]
        repre_frame_start = clip_data["repre_frame_start"]

        # loop all preset names and
        for preset_config in additional_export_presets:
            unique_name = preset_config["name"]
            enabled = preset_config["enabled"]
            extension = preset_config["ext"]

            if not enabled:
                continue

            # skipping based on clip name regex filtering
            if self._should_skip(preset_config, clip_path, unique_name):
                continue

            # Process preset export
            exporting_clip, export_dir_path, imageio_colorspace = \
                self._process_preset_export(
                    instance,
                    preset_config,
                    clip_data,
                    unique_name,
                    staging_dir
                )
            repre_staging_dir, repre_files, repr_name = (
                self._process_exported_files(
                    export_dir_path, extension, unique_name
                )
            )

            # get preset attributes for representation
            export_type = preset_config["export_type"]
            repre_tags = preset_config.get("representation_tags", [])

            # create representation data
            representation_data = self._create_representation_data(
                repr_name=repr_name,
                repre_files=repre_files,
                extension=extension,
                repre_staging_dir=repre_staging_dir,
                repre_tags=repre_tags,
                preset_config=preset_config,
                repre_frame_start=repre_frame_start,
                source_duration_handles=source_duration_handles,
                instance=instance,
                imageio_colorspace=imageio_colorspace,
            )

            instance.data["representations"].append(representation_data)

            # add review family if found in tags
            if "review" in repre_tags:
                instance.data["families"].append("review")

            self.log.info("Added representation: %s", representation_data)

            if export_type == "Sequence Publish":
                publish_clips = flame.find_by_name(
                    f"{exporting_clip.name.get_value()}_publish",
                    parent=exporting_clip.parent
                )
                for publish_clip in publish_clips:
                    flame.delete(publish_clip)
                # at the end remove the duplicated clip
                flame.delete(exporting_clip)

    def _get_retimed_attributes(self, instance):
        handle_start = instance.data["handleStart"]
        handle_end = instance.data["handleEnd"]

        # get basic variables
        otio_clip = instance.data["otioClip"]

        # get available range trimmed with processed retimes
        retimed_attributes = get_media_range_with_retimes(
            otio_clip, handle_start, handle_end)
        self.log.debug(
            ">> retimed_attributes: %s", retimed_attributes)

        r_media_in = int(retimed_attributes["mediaIn"])
        r_media_out = int(retimed_attributes["mediaOut"])
        version_data = retimed_attributes.get("versionData")

        return {
            "version_data": version_data,
            "handle_start": int(retimed_attributes["handleStart"]),
            "handle_end": int(retimed_attributes["handleEnd"]),
            "source_duration": (
                (r_media_out - r_media_in) + 1
            ),
            "speed": float(retimed_attributes["speed"])
        }

    def _process_preset_export(
        self,
        instance,
        preset_config,
        clip_data,
        unique_name,
        staging_dir
    ):
        """Process and export a single preset configuration.

        Args:
            instance: The publish instance
            preset_config: Configuration for the preset
            clip_data: Dictionary containing clip data
            unique_name: Unique name for the preset
            staging_dir: Staging directory path

        Returns:
            tuple: (export_dir_path, imageio_colorspace)

        Raises:
            ValueError: If the clip data is missing required keys
        """
        # Extract clip data
        clip_path = clip_data["clip_path"]
        clip_obj = clip_data.get("PyClip")
        segment = clip_data["segment"]
        sequence_clip = clip_data["sequence_clip"]
        segment_name = clip_data["segment_name"]
        s_track_name = clip_data["s_track_name"]
        clip_in = clip_data["clip_in"]
        clip_out = clip_data["clip_out"]
        handles = clip_data["handles"]
        source_start_handles = clip_data["source_start_handles"]
        source_first_frame = clip_data["source_first_frame"]
        source_duration_handles = clip_data["source_duration_handles"]
        folder_path = clip_data["folder_path"]
        repre_frame_start = clip_data["repre_frame_start"]

        modify_xml_data = {}

        # get all presets attributes
        extension = preset_config["ext"]
        preset_file = preset_config["xml_preset_file"]
        preset_dir = preset_config["xml_preset_dir"]
        export_type = preset_config["export_type"]
        parsed_comment_attrs = preset_config.get("parsed_comment_attrs", [])

        self.log.info(
            "Processing `%s` as `%s` to `%s` type...",
            preset_file, export_type, extension
        )

        exporting_clip = None
        name_pattern_xml = f"<name>_{unique_name}."

        if export_type == "Sequence Publish":
            # change export clip to sequence
            exporting_clip = flame.duplicate(sequence_clip)

            # only keep visible layer where instance segment is child
            self.hide_others(
                exporting_clip, segment_name, s_track_name)

            # change name pattern
            name_pattern_xml = (
                f"<segment name>_<shot name>_{unique_name}.")

            # only for h264 with baked retime
            in_mark = clip_in
            out_mark = clip_out + 1
            modify_xml_data.update({
                "exportHandles": True,
                "nbHandles": handles
            })
        else:
            in_mark = (source_start_handles - source_first_frame) + 1
            out_mark = in_mark + source_duration_handles

            exporting_clip = None
            if clip_path:
                if not clip_obj:
                    exporting_clip = self.import_clip(clip_path)
                else:
                    exporting_clip = clip_obj
                exporting_clip.name.set_value(f"{folder_path}_{segment_name}")

        # add xml tags modifications
        modify_xml_data.update({
            # enum position low start from 0
            "frameIndex": 0,
            "startFrame": repre_frame_start,
            "namePattern": name_pattern_xml
        })

        if parsed_comment_attrs:
            # add any xml overrides collected form segment.comment
            modify_xml_data.update(instance.data["xml_overrides"])

        self.log.debug("_ in_mark: %s", in_mark)
        self.log.debug("_ out_mark: %s", out_mark)

        export_kwargs = {}
        # validate xml preset file is filled
        if preset_file == "":
            raise ValueError(
                f"Check Settings for {unique_name} preset: "
                    "`XML preset file` is not filled"
            )

        # resolve xml preset dir if not filled
        if preset_dir == "":
            preset_dir = ayfapi.get_preset_path_by_xml_name(
                preset_file)

            if not preset_dir:
                raise ValueError(
                    f"Check Settings for {unique_name} preset: "
                        f"`XML preset file` {preset_file} is not found"
                )

        # create preset path
        preset_orig_xml_path = (Path(preset_dir) / preset_file).as_posix()

        # define kwargs based on preset type
        if "thumbnail" in unique_name:
            modify_xml_data.update({
                "video/posterFrame": True,
                "video/useFrameAsPoster": 1,
                "namePattern": "__thumbnail"
            })
            thumb_frame_number = int(in_mark + (
                (out_mark - in_mark + 1) / 2))

            self.log.debug("__ thumb_frame_number: %s", thumb_frame_number)

            export_kwargs["thumb_frame_number"] = thumb_frame_number
        else:
            export_kwargs.update({
                "in_mark": in_mark,
                "out_mark": out_mark
            })

        preset_path = ayfapi.modify_preset_file(
            preset_orig_xml_path, staging_dir, modify_xml_data)

        # get and make export dir paths
        export_dir_path = (Path(staging_dir) / unique_name).as_posix()
        Path(export_dir_path).mkdir(parents=True, exist_ok=True)

        if not exporting_clip:
            exporting_clip, export_dir_path = \
                self.convert_unlinked_segment_to_clip(
                    segment, extension, preset_path, export_dir_path)
        else:
            # export
            ayfapi.export_clip(
                export_dir_path, exporting_clip, preset_path, **export_kwargs)

        imageio_colorspace = self._get_imageio_colorspace(
            exporting_clip, instance
        )

        return exporting_clip, export_dir_path, imageio_colorspace

    def _get_imageio_colorspace(self, exporting_clip, instance):
        """Get the imageio colorspace from the exporting clip.

        Args:
            exporting_clip: The flame clip object
            instance: The publish instance

        Returns:
            str: The remapped colorspace name
        """
        flame_colour = exporting_clip.get_colour_space()
        self.log.debug(flame_colour)
        context = instance.context
        host_name = context.data["hostName"]
        project_settings = context.data["project_settings"]
        host_imageio_settings = project_settings["flame"]["imageio"]
        imageio_colorspace = get_remapped_colorspace_from_native(
            flame_colour,
            host_name,
            host_imageio_settings,
        )
        self.log.debug(imageio_colorspace)
        return imageio_colorspace

    def _process_exported_files(self, export_dir_path, extension, unique_name):
        """Process exported files and prepare representation data.

        Args:
            export_dir_path: Path to the export directory
            preset_config: Preset configuration dictionary
            unique_name: Unique name for the preset

        Returns:
            tuple: (repre_staging_dir, repre_files, repr_name, extension)

        Raises:
            ValueError: If export directory doesn't exist or contains no files
        """
        repre_staging_dir = export_dir_path
        export_dir_p = Path(export_dir_path)
        if not export_dir_p.exists():
            raise ValueError(
                f"Export directory does not exist: {export_dir_path}")

        rendered_files = list(export_dir_p.iterdir())

        if not rendered_files:
            raise ValueError(
                f"No files found in export directory: {export_dir_path}")

        # make sure no nested folders inside
        n_stage_dir, n_files = self._unfolds_nested_folders(
            export_dir_path, rendered_files, extension)

        # fix representation in case of nested folders
        if n_stage_dir:
            repre_staging_dir = n_stage_dir
        if n_files:
            rendered_files = n_files

        repr_name = unique_name
        # add files to representation but add
        # imagesequence as list
        if len(rendered_files) == 1:
            repre_files = rendered_files.pop().name
        else:
            repre_files = [f.name for f in rendered_files]

        # make sure only first segment is used if underscore in name
        # HACK: `ftrackreview_withLUT` will result only in `ftrackreview`
        if (
            "thumbnail" in unique_name
            or "ftrackreview" in unique_name
        ):
            self.log.debug("Unique name: %s", unique_name)
            repr_name = unique_name.split("_")[0]

        return repre_staging_dir, repre_files, repr_name

    def _create_representation_data(
        self,
        repr_name,
        repre_files,
        extension,
        repre_staging_dir,
        repre_tags,
        preset_config,
        repre_frame_start,
        source_duration_handles,
        instance,
        imageio_colorspace
    ):
        """Create representation data dictionary.

        Args:
            repr_name (str): Representation name
            repre_files (list): List of representation files
            extension (str): File extension
            repre_staging_dir (str): Staging directory path
            repre_tags (list): List of tags
            preset_config (dict): Preset configuration
            repre_frame_start (int): Start frame number
            source_duration_handles (int): Duration with handles
            instance: Pyblish instance
            imageio_colorspace (str): Colorspace name

        Returns:
            dict: Representation data dictionary
        """
        # create representation data
        representation_data = {
            "name": repr_name,
            "files": repre_files,
            "outputName": repr_name,
            "ext": extension,
            "stagingDir": repre_staging_dir,
            "tags": repre_tags,
            "load_to_batch_group": preset_config.get(
                "load_to_batch_group"),
            "batch_group_loader_name": preset_config.get(
                "batch_group_loader_name") or None
        }

        # add frame range
        representation_add_range = preset_config.get(
            "representation_add_range", False)
        if (
            representation_add_range
            and repre_frame_start is not None
            and source_duration_handles is not None
        ):
            representation_data.update({
                "frameStart": repre_frame_start,
                "frameEnd": (
                    repre_frame_start + source_duration_handles) - 1,
                "fps": instance.data["fps"]
            })

        self.set_representation_colorspace(
            representation_data,
            instance.context,
            colorspace=imageio_colorspace,
        )

        return representation_data

    def _should_skip(self, preset_config, clip_path, unique_name):
        # get activating attributes
        activated_preset = preset_config.get("enabled", False)
        filter_path_regex = preset_config.get("filter_path_regex")

        self.log.info(
            "Preset `%s` with filter `%s`", unique_name, filter_path_regex
        )

        # skip if not activated presets
        if not activated_preset:
            return True

        # exclude by regex filter if any
        if (
            filter_path_regex
            and not re.search(filter_path_regex, clip_path)
        ):
            return True

        return False

    def _unfolds_nested_folders(self, stage_dir, files_list, ext):
        """Unfolds nested folders

        Args:
            stage_dir (str): path string with directory
            files_list (list[Path]): list of file names
            ext (str): extension (jpg)[without dot]

        Raises:
            IOError: in case no files were collected form any directory

        Returns:
            str, list: new staging dir path, new list of file names
            or
            None, None: In case single file in `files_list`
        """
        # exclude single files which are having extension
        # the same as input ext attr
        if (
            # only one file in list
            len(files_list) == 1
            # file is having extension as input
            and ext in files_list[0].suffix
        ) or (
            # more then one file in list
            len(files_list) >= 1
            # extension is correct
            and ext in files_list[0].suffix
            # test file exists
            and (Path(stage_dir) / files_list[0].name).exists()
        ):
            return None, None

        new_stage_dir = None
        new_files_list: list[Path] = []
        for file in files_list:
            search_path = Path(stage_dir) / file.name
            if not search_path.is_dir():
                continue
            for root, _dirs, files in os.walk(search_path):
                for _file in files:
                    file_path = Path(_file)
                    _ext = file_path.suffix
                    if ext.lower() != _ext[1:].lower():
                        continue
                    new_file_p = Path(root) / file_path.name
                    new_files_list.append(new_file_p)
                    if not new_stage_dir:
                        new_stage_dir = root

        if not new_stage_dir:
            raise AssertionError(
                f"Files in `{files_list}` are not correct! Check `{stage_dir}`"
            )

        return new_stage_dir, new_files_list

    def hide_others(self, sequence_clip, segment_name, track_name):
        """Helper method used only if sequence clip is used

        Args:
            sequence_clip (flame.Clip): sequence clip
            segment_name (str): segment name
            track_name (str): track name
        """
        # create otio tracks and clips
        for ver in sequence_clip.versions:
            for track in ver.tracks:
                if len(track.segments) == 0 and track.hidden.get_value():
                    continue

                # hide tracks which are not parent track
                if track.name.get_value() != track_name:
                    track.hidden = True
                    continue

                # hidde all other segments
                for segment in track.segments:
                    if segment.name.get_value() != segment_name:
                        segment.hidden = True

    def import_clip(self, path):
        """Import clip from path
        """
        path_p = Path(path)
        dir_path = path_p.parent
        media_info = MediaInfoFile(path, logger=self.log)
        file_pattern = media_info.file_pattern
        self.log.debug("__ file_pattern: %s", file_pattern)

        # rejoin the pattern to dir path
        new_path = (dir_path / file_pattern).as_posix()

        clips = flame.import_clips(new_path)
        self.log.info("Clips [%s] imported from `%s`", clips, path)

        if not clips:
            self.log.warning("Path `%s` is not having any clips", path)
            return None
        if len(clips) > 1:
            self.log.warning(
                "Path `%s` is containing more that one clip", path
            )
        return clips[0]

    def convert_unlinked_segment_to_clip(
            self, segment, extension, preset_path, staging_dir):
        """
        Exports a segment to a temp file then import it back as a PyClip.
        Uses temporary reel duplication to handle unlinked media properly.
        """
        if isinstance(preset_path, str):
            preset_path = Path(preset_path)

        # Create a unique filename based on segment name
        subdir_name = f"{segment.name.get_value()}_temp_conversion_{extension}"
        export_path = Path(staging_dir) / subdir_name

        try:
            # Get or create a temporary library for rendering
            workspace = flame.projects.current_project.current_workspace
            desktop = workspace.desktop
            temp_library = None

            # Search for existing temp library
            for library in workspace.libraries:
                if library.name == "AYON_TEMP_EXPORT":
                    temp_library = library
                    self.log.info("Found temporary library: AYON_TEMP_EXPORT")
                    break

            else:
                # Create a temp library if it doesn't exist
                temp_library = workspace.create_library("AYON_TEMP_EXPORT")
                self.log.info("Created temporary library: AYON_TEMP_EXPORT")

            # Duplicate/copy the segment to create a clip
            segment.selected = True
            desktop.destination = temp_library

            # Use Flame's duplicate command to create a clip from the segment
            # This will render the segment as necessary
            segment.copy_to_media_panel(temp_library)

            # Get the newly created clip from the library
            new_clip = temp_library.clips[-1]
            self.log.debug(f"Created temporary clip: {new_clip.name}")

            # Configure and export using PyExporter
            exporter = flame.PyExporter()
            exporter.foreground = True
            exporter.export_between_marks = False  # Export full clip

            self.log.debug(f"Exporting clip to: {export_path.as_posix()}")
            exporter.export(
                sources=new_clip,
                output_directory=export_path.as_posix(),
                preset_path=preset_path.as_posix())

            #  Import the file back as a PyClip
            if export_path.exists():
                imported_clips = flame.import_clips(export_path.as_posix())

                # Optional: Clean up temp clip
                flame.delete(new_clip)
                self.log.debug("Cleaned up temporary clip")

                return imported_clips[0], export_path.as_posix()
            else:
                raise publish.PublishError(
                    f"Export failed - path does not exist: {export_path}")

        except publish.PublishError as e:
            raise publish.PublishError(f"Export/Import failed: {e}") from e

convert_unlinked_segment_to_clip(segment, extension, preset_path, staging_dir)

Exports a segment to a temp file then import it back as a PyClip. Uses temporary reel duplication to handle unlinked media properly.

Source code in client/ayon_flame/plugins/publish/extract_product_resources.py
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
def convert_unlinked_segment_to_clip(
        self, segment, extension, preset_path, staging_dir):
    """
    Exports a segment to a temp file then import it back as a PyClip.
    Uses temporary reel duplication to handle unlinked media properly.
    """
    if isinstance(preset_path, str):
        preset_path = Path(preset_path)

    # Create a unique filename based on segment name
    subdir_name = f"{segment.name.get_value()}_temp_conversion_{extension}"
    export_path = Path(staging_dir) / subdir_name

    try:
        # Get or create a temporary library for rendering
        workspace = flame.projects.current_project.current_workspace
        desktop = workspace.desktop
        temp_library = None

        # Search for existing temp library
        for library in workspace.libraries:
            if library.name == "AYON_TEMP_EXPORT":
                temp_library = library
                self.log.info("Found temporary library: AYON_TEMP_EXPORT")
                break

        else:
            # Create a temp library if it doesn't exist
            temp_library = workspace.create_library("AYON_TEMP_EXPORT")
            self.log.info("Created temporary library: AYON_TEMP_EXPORT")

        # Duplicate/copy the segment to create a clip
        segment.selected = True
        desktop.destination = temp_library

        # Use Flame's duplicate command to create a clip from the segment
        # This will render the segment as necessary
        segment.copy_to_media_panel(temp_library)

        # Get the newly created clip from the library
        new_clip = temp_library.clips[-1]
        self.log.debug(f"Created temporary clip: {new_clip.name}")

        # Configure and export using PyExporter
        exporter = flame.PyExporter()
        exporter.foreground = True
        exporter.export_between_marks = False  # Export full clip

        self.log.debug(f"Exporting clip to: {export_path.as_posix()}")
        exporter.export(
            sources=new_clip,
            output_directory=export_path.as_posix(),
            preset_path=preset_path.as_posix())

        #  Import the file back as a PyClip
        if export_path.exists():
            imported_clips = flame.import_clips(export_path.as_posix())

            # Optional: Clean up temp clip
            flame.delete(new_clip)
            self.log.debug("Cleaned up temporary clip")

            return imported_clips[0], export_path.as_posix()
        else:
            raise publish.PublishError(
                f"Export failed - path does not exist: {export_path}")

    except publish.PublishError as e:
        raise publish.PublishError(f"Export/Import failed: {e}") from e

get_clip_data(instance)

Extract and prepare all clip-related data for export processing.

Parameters:

Name Type Description Default
instance Instance

Instance object.

required

Returns:

Type Description
dict

Dict[str, Any]: A dictionary containing all extracted clip data with at least these keys: * segment (flame.Segment): The flame segment object. * folder_path (str): Path to the folder. * segment_name (str): Name of the segment. * clip_path (Optional[str]): Path to the clip (None if not linked media). * sequence_clip (flame.Clip): The flame sequence clip object. * s_track_name (str): Parent track name of the segment. * frame_start (int): Configured workfile frame start. * source_first_frame (int): Media source first frame. * clip_in (int): Timeline in point of segment. * clip_out (int): Timeline out point of segment. * retimed_handle_start (int): Retimed handle start value. * retimed_handle_end (int): Retimed handle end value. * retimed_source_duration (int): Retimed source duration. * retimed_speed (float): Retimed speed factor. * handle_start (int): Handle start value. * handle_end (int): Handle end value. * handles (int): Maximum of handle_start and handle_end. * include_handles (bool): Whether to include handles. * retimed_handles (bool): Whether handles are retimed. * source_start_handles (int): Source start with handles. * source_end_handles (int): Source end with handles. * frame_start_handle (int): Frame start with handles applied. * repre_frame_start (int): Representation frame start. * source_duration_handles (int): Source duration including handles. * version_frame_start (int): Version data frame start.

Source code in client/ayon_flame/plugins/publish/extract_product_resources.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def get_clip_data(self, instance: pyblish.api.Instance) -> dict:
    """Extract and prepare all clip-related data for export processing.

    Args:
        instance (Instance): Instance object.

    Returns:
        Dict[str, Any]: A dictionary containing all extracted clip data
            with at least these keys:
            * `segment` (flame.Segment): The flame segment object.
            * `folder_path` (str): Path to the folder.
            * `segment_name` (str): Name of the segment.
            * `clip_path` (Optional[str]): Path to the clip
                (None if not linked media).
            * `sequence_clip` (flame.Clip): The flame sequence clip object.
            * `s_track_name` (str): Parent track name of the segment.
            * `frame_start` (int): Configured workfile frame start.
            * `source_first_frame` (int): Media source first frame.
            * `clip_in` (int): Timeline in point of segment.
            * `clip_out` (int): Timeline out point of segment.
            * `retimed_handle_start` (int): Retimed handle start value.
            * `retimed_handle_end` (int): Retimed handle end value.
            * `retimed_source_duration` (int): Retimed source duration.
            * `retimed_speed` (float): Retimed speed factor.
            * `handle_start` (int): Handle start value.
            * `handle_end` (int): Handle end value.
            * `handles` (int): Maximum of handle_start and handle_end.
            * `include_handles` (bool): Whether to include handles.
            * `retimed_handles` (bool): Whether handles are retimed.
            * `source_start_handles` (int): Source start with handles.
            * `source_end_handles` (int): Source end with handles.
            * `frame_start_handle` (int): Frame start with handles applied.
            * `repre_frame_start` (int): Representation frame start.
            * `source_duration_handles` (int): Source duration including
                handles.
            * `version_frame_start` (int): Version data frame start.

    """
    # flame objects
    item = instance.data["item"]
    if isinstance(item, flame.PySegment):
        segment = item
    elif isinstance(item, flame.PyClip):
        segment = ayfapi.lib.get_clip_segment(item)
    else:
        raise ValueError(f"Unsupported item: {item}.")

    folder_path = instance.data["folderPath"]
    segment_name = segment.name.get_value()
    # clip_path will be None if not linked media
    clip_path = instance.data["path"]
    sequence_clip = instance.context.data.get("flameSequence")

    # segment's parent track name
    s_track_name = segment.parent.name.get_value()

    # get configured workfile frame start/end (handles excluded)
    frame_start = instance.data["frameStart"]
    # get media source first frame
    source_first_frame = instance.data["sourceFirstFrame"]

    self.log.debug("_ frame_start: %s", frame_start)
    self.log.debug("_ source_first_frame: %s", source_first_frame)

    # get timeline in/out of segment
    clip_in = instance.data["clipIn"]
    clip_out = instance.data["clipOut"]

    # get handles value - take only the max from both
    handle_start = instance.data["handleStart"]
    handle_end = instance.data["handleEnd"]
    handles = max(handle_start, handle_end)

    retimed_data = {}
    if clip_path:
        # media source is linked to a clip, so we do have available
        # otio reference for media source frame range calculation

        # get retimed attributres
        retimed_data = self._get_retimed_attributes(instance)

        # get individual keys
        retimed_handle_start = retimed_data["handle_start"]
        retimed_handle_end = retimed_data["handle_end"]
        retimed_source_duration = retimed_data["source_duration"]
        retimed_speed = retimed_data["speed"]
        # get media source range with handles
        source_start_handles = instance.data["sourceStartH"]
        source_end_handles = instance.data["sourceEndH"]
    else:
        # media source is unlinked, so we do not have available
        # otio reference for media source frame range calculation
        segment_data = ayfapi.get_segment_attributes(segment)
        source_in = segment_data["source_in"]
        source_out = segment_data["source_out"]
        source_duration = source_out - source_in + 1
        record_duration = segment_data["record_duration"]
        # secondly check if any change of speed
        retimed_speed = 1
        if source_duration != record_duration:
            speed = float(source_duration) / float(record_duration)
            self.log.debug(f"_ calculated speed: {speed}")
            retimed_speed *= speed
        retimed_handle_start = handle_start * retimed_speed
        retimed_handle_end = handle_end * retimed_speed
        retimed_source_duration = source_duration * retimed_speed
        source_start_handles = source_in - handle_start
        source_end_handles = source_out - handle_end

    include_handles = instance.data.get("includeHandles")
    retimed_handles = instance.data.get("retimedHandles")

    # retime if needed
    if retimed_speed != 1.0:
        if retimed_handles:
            # handles are retimed
            source_start_handles = (
                source_start_handles - retimed_handle_start)
            source_end_handles = (
                source_start_handles
                + (retimed_source_duration - 1)
                + retimed_handle_start
                + retimed_handle_end
            )

        else:
            # handles are not retimed
            source_end_handles = (
                source_start_handles
                + (retimed_source_duration - 1)
                + handle_start
                + handle_end
            )

    # get frame range with handles for representation range
    frame_start_handle = frame_start - handle_start
    repre_frame_start = frame_start_handle
    if include_handles:
        if retimed_speed == 1.0 or not retimed_handles:
            frame_start_handle = frame_start
        else:
            frame_start_handle = (
                frame_start - handle_start) + retimed_handle_start

    self.log.debug("_ frame_start_handle: %s", frame_start_handle)
    self.log.debug("_ repre_frame_start: %s", repre_frame_start)

    # calculate duration with handles
    source_duration_handles = (
        source_end_handles - source_start_handles) + 1

    self.log.debug(
        "_ source_duration_handles: %s",
        source_duration_handles
    )

    if not instance.data.get("versionData"):
        instance.data["versionData"] = {}

    # set versiondata if any retime
    version_data = retimed_data.get("version_data")
    self.log.debug("_ version_data: %s", version_data)

    if version_data:
        instance.data["versionData"].update(version_data)

    # version data start frame
    version_frame_start = frame_start
    if include_handles:
        version_frame_start = frame_start_handle
    if retimed_speed != 1.0:
        if retimed_handles:
            instance.data["versionData"].update({
                "frameStart": version_frame_start,
                "frameEnd": (
                    (version_frame_start + source_duration_handles - 1)
                    - (retimed_handle_start + retimed_handle_end)
                )
            })
        else:
            instance.data["versionData"].update({
                "handleStart": handle_start,
                "handleEnd": handle_end,
                "frameStart": version_frame_start,
                "frameEnd": (
                    (version_frame_start + source_duration_handles - 1)
                    - (handle_start + handle_end)
                )
            })
    self.log.debug("_ version_data: {}".format(
        instance.data["versionData"]
    ))

    # Return all extracted data as a dictionary
    return {
        "segment": segment,
        "folder_path": folder_path,
        "segment_name": segment_name,
        "clip_path": clip_path,
        "sequence_clip": sequence_clip,
        "s_track_name": s_track_name,
        "frame_start": frame_start,
        "source_first_frame": source_first_frame,
        "clip_in": clip_in,
        "clip_out": clip_out,
        "retimed_handle_start": retimed_handle_start,
        "retimed_handle_end": retimed_handle_end,
        "retimed_source_duration": retimed_source_duration,
        "retimed_speed": retimed_speed,
        "handle_start": handle_start,
        "handle_end": handle_end,
        "handles": handles,
        "include_handles": include_handles,
        "retimed_handles": retimed_handles,
        "source_start_handles": source_start_handles,
        "source_end_handles": source_end_handles,
        "frame_start_handle": frame_start_handle,
        "repre_frame_start": repre_frame_start,
        "source_duration_handles": source_duration_handles,
        "version_frame_start": version_frame_start,
    }

hide_others(sequence_clip, segment_name, track_name)

Helper method used only if sequence clip is used

Parameters:

Name Type Description Default
sequence_clip Clip

sequence clip

required
segment_name str

segment name

required
track_name str

track name

required
Source code in client/ayon_flame/plugins/publish/extract_product_resources.py
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
def hide_others(self, sequence_clip, segment_name, track_name):
    """Helper method used only if sequence clip is used

    Args:
        sequence_clip (flame.Clip): sequence clip
        segment_name (str): segment name
        track_name (str): track name
    """
    # create otio tracks and clips
    for ver in sequence_clip.versions:
        for track in ver.tracks:
            if len(track.segments) == 0 and track.hidden.get_value():
                continue

            # hide tracks which are not parent track
            if track.name.get_value() != track_name:
                track.hidden = True
                continue

            # hidde all other segments
            for segment in track.segments:
                if segment.name.get_value() != segment_name:
                    segment.hidden = True

import_clip(path)

Import clip from path

Source code in client/ayon_flame/plugins/publish/extract_product_resources.py
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
def import_clip(self, path):
    """Import clip from path
    """
    path_p = Path(path)
    dir_path = path_p.parent
    media_info = MediaInfoFile(path, logger=self.log)
    file_pattern = media_info.file_pattern
    self.log.debug("__ file_pattern: %s", file_pattern)

    # rejoin the pattern to dir path
    new_path = (dir_path / file_pattern).as_posix()

    clips = flame.import_clips(new_path)
    self.log.info("Clips [%s] imported from `%s`", clips, path)

    if not clips:
        self.log.warning("Path `%s` is not having any clips", path)
        return None
    if len(clips) > 1:
        self.log.warning(
            "Path `%s` is containing more that one clip", path
        )
    return clips[0]