Skip to content

api

AYON Autodesk Flame api

ClipLoader

Bases: LoaderPlugin

A basic clip loader for Flame leveraging native OpenClip API.

Source code in client/ayon_flame/api/plugin.py
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
class ClipLoader(LoaderPlugin):
    """A basic clip loader for Flame leveraging native OpenClip API.
    """
    log = log

    product_base_types = {
        "render2d", "source", "plate", "render", "review"
    }
    representations = {"*"}
    extensions = set(
        ext.lstrip(".") for ext in IMAGE_EXTENSIONS.union(VIDEO_EXTENSIONS)
    )

    options = [
        BoolDef(
            "handles",
            label="Set handles",
            default=False,
            tooltip="Also set handles to clip as In/Out marks"
        )
    ]

    _mapping = None
    _host_settings = None

    @classmethod
    def apply_settings(cls, project_settings):

        plugin_type_settings = (
            project_settings
            .get("flame", {})
            .get("load", {})
        )

        if not plugin_type_settings:
            return

        plugin_name = cls.__name__

        plugin_settings = None
        # Look for plugin settings in host specific settings
        if plugin_name in plugin_type_settings:
            plugin_settings = plugin_type_settings[plugin_name]

        if not plugin_settings:
            return

        log.debug(">>> We have preset for {}".format(plugin_name))
        for option, value in plugin_settings.items():
            if option == "enabled" and value is False:
                log.debug("  - is disabled by preset")
            elif option == "representations":
                continue
            else:
                log.debug("  - setting `{}`: `{}`".format(option, value))
            setattr(cls, option, value)

    def get_colorspace(self, context):
        """Get colorspace name

        Look either to version data or representation data.

        Args:
            context (dict): version context data

        Returns:
            str: colorspace name or None
        """
        version_entity = context["version"]
        version_attributes = version_entity["attrib"]
        colorspace = version_attributes.get("colorSpace")

        if (
            not colorspace
            or colorspace == "Unknown"
        ):
            colorspace = context["representation"]["data"].get(
                "colorspace")

        return colorspace

    @classmethod
    def get_native_colorspace(cls, input_colorspace):
        """Return native colorspace name.

        Args:
            input_colorspace (str | None): colorspace name

        Returns:
            str: native colorspace name defined in mapping or None
        """
        # TODO: rewrite to support only pipeline's remapping
        if not cls._host_settings:
            cls._host_settings = get_current_project_settings()["flame"]

        # [Deprecated] way of remapping
        if not cls._mapping:
            mapping = (
                cls._host_settings["imageio"]["profilesMapping"]["inputs"])
            cls._mapping = {
                input["ocioName"]: input["flameName"]
                for input in mapping
            }

        native_name = cls._mapping.get(input_colorspace)

        if not native_name:
            native_name = get_remapped_colorspace_to_native(
                input_colorspace, "flame", cls._host_settings["imageio"])

        return native_name

    def _get_clip_name_format_data(self, context, _) -> dict[str, str]:
        """ Get formatting data for the clip name template.
        """
        format_data = deepcopy(context["representation"]["context"])
        folder_entity = context["folder"]
        product_entity = context["product"]
        format_data.update({
            "asset": folder_entity["name"],
            "folder": {
                "name": folder_entity["name"],
            },
            "subset": product_entity["name"],
            "family": product_entity["productType"],
            "product": {
                "name": product_entity["name"],
                "type": product_entity["productType"],
                "basetype": product_entity["productBaseType"],
            }
        })

        if not format_data.get("output"):
            format_data["output"] = format_data["representation"]

        return format_data

    def load(self, context, name, namespace, options):
        """
        From a specific clip representation, load it with all of
        its versions, connecting to Flame native OpenClip version support.
        """
        fproject = flame.project.current_project
        self.fpd = fproject.current_workspace.desktop

        # Build clip name from current clip,
        # using settings template and representation context.
        clip_name = StringTemplate(self.clip_name_template).format(
            self._get_clip_name_format_data(context, options)
        )

        # Flame OpenClip is a file-based format,
        # prepare clip file in work directory.
        workfile_dir = os.environ["AYON_WORKDIR"]
        openclip_dir = os.path.join(workfile_dir, clip_name)
        openclip_path = os.path.join(
            openclip_dir, clip_name + ".clip"
        )
        os.makedirs(openclip_dir, exist_ok=True)

        # Find all versions for the clip.
        project_name = context["project"]["name"]
        product_id =  context["version"]["productId"]
        all_versions = list(
            ayon_api.get_versions(
                project_name,
                product_ids=[product_id],
            )
        )

        # Find all representations per version.
        repres_by_version_id = {}
        for repre_entity in ayon_api.get_representations(
             project_name,
             representation_names={context["representation"]["name"]},
             version_ids=[version["id"] for version in all_versions],
         ):
             repre_version_id = repre_entity["versionId"]
             repres_by_version_id[repre_version_id] = repre_entity

        if not repres_by_version_id:
            raise RuntimeError(
                "Could not find any representations named '{}' for product "
                "'{}' in project '{}' while preparing OpenClip feeds. "
                "Current version id: '{}'. Checked {} version(s).".format(
                    context["representation"]["name"],
                    product_id,
                    project_name,
                    context["version"]["id"],
                    len(all_versions),
                )
            )
        # Prepare OpenClip object.
        clip_solver = OpenClipSolver(
            openclip_path,
            self.layer_rename_patterns
        )

        # Resolve each version as new OpenClip feed.
        for version_id, representation in repres_by_version_id.items():
            version = next(v for v in all_versions if v["id"] == version_id)
            version_context = deepcopy(context)
            version_context["version"] = version
            version_context["representation"] = representation
            version_name = version["name"]
            colorspace = self.get_colorspace(version_context)

            # in case output is not in context replace key to representation
            layer_rename_template = self.layer_rename_template
            if not representation["context"].get("output"):
                layer_rename_template = self.layer_rename_template.replace(
                    "output", "representation"
                )

            # convert colorspace with ocio to flame mapping
            # in imageio flame section
            colorspace = self.get_native_colorspace(colorspace)

            # prepare clip data from context ad send it to openClipLoader
            path = self.filepath_from_context(version_context)

            try:
                clip_solver.add_feed(
                    path,
                    version_name,
                    colorspace,
                    representation["context"],
                    layer_rename_template,
                )
            except RuntimeError:
                flame.messages.show_in_dialog(
                    "Unsupported Input",
                    f"Flame does not support incoming media path {path}",
                    "warning",
                    ["OK"],
                )
                return

        version_entity = context["version"]
        clip_solver.set_current_version(
            f"v{version_entity['version']:03}"
        )
        clip_solver.write()

        # prepare Reel group in actual desktop
        opc = self._get_clip(clip_name, openclip_path)
        opc.name = clip_name

        return opc

    def _get_clip(self, name, clip_path):
        reel = self._get_reel()
        # with maintained openclip as opc
        for cl in reel.clips:
            if cl.name.get_value().startswith(name):
                return cl

        created_clips = flame.import_clips(str(clip_path), reel)
        return created_clips.pop()

    def _get_reel(self):
        """ Retrieve/Create expected reel for current clip.
        """
        raise NotImplementedError(
            "To be implemented by public loader subclass."
        )

    def update(self, container, context):
        """ AYON native version management.
        """
        raise NotImplementedError(
            "Version management rely on Flame "
            "native implementation through OpenClip."
        )

    def remove(self, container):
        """ AYON native version management.
        """
        raise NotImplementedError(
            "Version management rely on Flame "
            "native implementation through OpenClip."
        )

get_colorspace(context)

Get colorspace name

Look either to version data or representation data.

Parameters:

Name Type Description Default
context dict

version context data

required

Returns:

Name Type Description
str

colorspace name or None

Source code in client/ayon_flame/api/plugin.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
def get_colorspace(self, context):
    """Get colorspace name

    Look either to version data or representation data.

    Args:
        context (dict): version context data

    Returns:
        str: colorspace name or None
    """
    version_entity = context["version"]
    version_attributes = version_entity["attrib"]
    colorspace = version_attributes.get("colorSpace")

    if (
        not colorspace
        or colorspace == "Unknown"
    ):
        colorspace = context["representation"]["data"].get(
            "colorspace")

    return colorspace

get_native_colorspace(input_colorspace) classmethod

Return native colorspace name.

Parameters:

Name Type Description Default
input_colorspace str | None

colorspace name

required

Returns:

Name Type Description
str

native colorspace name defined in mapping or None

Source code in client/ayon_flame/api/plugin.py
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
@classmethod
def get_native_colorspace(cls, input_colorspace):
    """Return native colorspace name.

    Args:
        input_colorspace (str | None): colorspace name

    Returns:
        str: native colorspace name defined in mapping or None
    """
    # TODO: rewrite to support only pipeline's remapping
    if not cls._host_settings:
        cls._host_settings = get_current_project_settings()["flame"]

    # [Deprecated] way of remapping
    if not cls._mapping:
        mapping = (
            cls._host_settings["imageio"]["profilesMapping"]["inputs"])
        cls._mapping = {
            input["ocioName"]: input["flameName"]
            for input in mapping
        }

    native_name = cls._mapping.get(input_colorspace)

    if not native_name:
        native_name = get_remapped_colorspace_to_native(
            input_colorspace, "flame", cls._host_settings["imageio"])

    return native_name

load(context, name, namespace, options)

From a specific clip representation, load it with all of its versions, connecting to Flame native OpenClip version support.

Source code in client/ayon_flame/api/plugin.py
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
def load(self, context, name, namespace, options):
    """
    From a specific clip representation, load it with all of
    its versions, connecting to Flame native OpenClip version support.
    """
    fproject = flame.project.current_project
    self.fpd = fproject.current_workspace.desktop

    # Build clip name from current clip,
    # using settings template and representation context.
    clip_name = StringTemplate(self.clip_name_template).format(
        self._get_clip_name_format_data(context, options)
    )

    # Flame OpenClip is a file-based format,
    # prepare clip file in work directory.
    workfile_dir = os.environ["AYON_WORKDIR"]
    openclip_dir = os.path.join(workfile_dir, clip_name)
    openclip_path = os.path.join(
        openclip_dir, clip_name + ".clip"
    )
    os.makedirs(openclip_dir, exist_ok=True)

    # Find all versions for the clip.
    project_name = context["project"]["name"]
    product_id =  context["version"]["productId"]
    all_versions = list(
        ayon_api.get_versions(
            project_name,
            product_ids=[product_id],
        )
    )

    # Find all representations per version.
    repres_by_version_id = {}
    for repre_entity in ayon_api.get_representations(
         project_name,
         representation_names={context["representation"]["name"]},
         version_ids=[version["id"] for version in all_versions],
     ):
         repre_version_id = repre_entity["versionId"]
         repres_by_version_id[repre_version_id] = repre_entity

    if not repres_by_version_id:
        raise RuntimeError(
            "Could not find any representations named '{}' for product "
            "'{}' in project '{}' while preparing OpenClip feeds. "
            "Current version id: '{}'. Checked {} version(s).".format(
                context["representation"]["name"],
                product_id,
                project_name,
                context["version"]["id"],
                len(all_versions),
            )
        )
    # Prepare OpenClip object.
    clip_solver = OpenClipSolver(
        openclip_path,
        self.layer_rename_patterns
    )

    # Resolve each version as new OpenClip feed.
    for version_id, representation in repres_by_version_id.items():
        version = next(v for v in all_versions if v["id"] == version_id)
        version_context = deepcopy(context)
        version_context["version"] = version
        version_context["representation"] = representation
        version_name = version["name"]
        colorspace = self.get_colorspace(version_context)

        # in case output is not in context replace key to representation
        layer_rename_template = self.layer_rename_template
        if not representation["context"].get("output"):
            layer_rename_template = self.layer_rename_template.replace(
                "output", "representation"
            )

        # convert colorspace with ocio to flame mapping
        # in imageio flame section
        colorspace = self.get_native_colorspace(colorspace)

        # prepare clip data from context ad send it to openClipLoader
        path = self.filepath_from_context(version_context)

        try:
            clip_solver.add_feed(
                path,
                version_name,
                colorspace,
                representation["context"],
                layer_rename_template,
            )
        except RuntimeError:
            flame.messages.show_in_dialog(
                "Unsupported Input",
                f"Flame does not support incoming media path {path}",
                "warning",
                ["OK"],
            )
            return

    version_entity = context["version"]
    clip_solver.set_current_version(
        f"v{version_entity['version']:03}"
    )
    clip_solver.write()

    # prepare Reel group in actual desktop
    opc = self._get_clip(clip_name, openclip_path)
    opc.name = clip_name

    return opc

remove(container)

AYON native version management.

Source code in client/ayon_flame/api/plugin.py
831
832
833
834
835
836
837
def remove(self, container):
    """ AYON native version management.
    """
    raise NotImplementedError(
        "Version management rely on Flame "
        "native implementation through OpenClip."
    )

update(container, context)

AYON native version management.

Source code in client/ayon_flame/api/plugin.py
823
824
825
826
827
828
829
def update(self, container, context):
    """ AYON native version management.
    """
    raise NotImplementedError(
        "Version management rely on Flame "
        "native implementation through OpenClip."
    )

FlameAppFramework

Bases: object

Takes care of preferences.

Source code in client/ayon_flame/api/lib.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
class FlameAppFramework(object):
    """ Takes care of preferences.
    """

    def __init__(self):
        self.name = self.__class__.__name__
        self.bundle_name = "AYONFlame"
        # self.prefs scope is limited to flame project and user
        self.prefs = {}
        self.prefs_user = {}
        self.prefs_global = {}
        self.log = log

        try:
            import flame
            self.flame = flame
            self.flame_project_name = self.flame.project.current_project.name
            self.flame_user_name = flame.users.current_user.name
        except Exception:
            self.flame = None
            self.flame_project_name = None
            self.flame_user_name = None

        import socket
        self.hostname = socket.gethostname()

        if sys.platform == "darwin":
            self.prefs_folder = os.path.join(
                os.path.expanduser("~"),
                "Library",
                "Caches",
                "AYON",
                self.bundle_name
            )
        elif sys.platform.startswith("linux"):
            self.prefs_folder = os.path.join(
                os.path.expanduser("~"),
                ".AYON",
                self.bundle_name)

        self.prefs_folder = os.path.join(
            self.prefs_folder,
            self.hostname,
        )

        self.log.info("[{}] waking up".format(self.__class__.__name__))

        try:
            self.load_prefs()
        except RuntimeError:
            self.save_prefs()

        # menu auto-refresh defaults
        if not self.prefs_global.get("menu_auto_refresh"):
            self.prefs_global["menu_auto_refresh"] = {
                "media_panel": True,
                "batch": True,
                "main_menu": True,
                "timeline_menu": True
            }

        self.apps = []

    def get_pref_file_paths(self):

        prefix = self.prefs_folder + os.path.sep + self.bundle_name
        prefs_file_path = "_".join([
            prefix, self.flame_user_name,
            self.flame_project_name]) + ".prefs"
        prefs_user_file_path = "_".join([
            prefix, self.flame_user_name]) + ".prefs"
        prefs_global_file_path = prefix + ".prefs"

        return (prefs_file_path, prefs_user_file_path, prefs_global_file_path)


    def _process_prefs(self, save: bool = False):
        # make sure the preference folder is available
        try:
            os.makedirs(self.prefs_folder, exist_ok=True)
        except Exception:
            self.log.error(
                "Unable to create folder %s",
                self.prefs_folder
            )
            return False

        # Read or write the prefs in each files.
        for attr, path in zip(
            (self.prefs, self.prefs_user, self.prefs_global),
            self.get_pref_file_paths(),
        ):
            with io_preferences_file(self, path, write=save) as prefs_file:
                if save:
                    pickle.dump(attr, prefs_file)
                else:
                    attr.clear()
                    attr.update(pickle.load(prefs_file))

                self.log.info(
                    "Preferences contents:\n%s",
                    pformat(attr),
                )

        return True

    def load_prefs(self) -> bool:
        return self._process_prefs(save=False)

    def save_prefs(self) -> bool:
        return self._process_prefs(save=True)

FlameCreator

Bases: Creator

Creator class wrapper

Source code in client/ayon_flame/api/plugin.py
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
class FlameCreator(Creator):
    """Creator class wrapper
    """
    skip_discovery = True
    settings_category = "flame"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.project = flib.get_current_project()

    def create(self, product_name, instance_data, pre_create_data):
        """Prepare data for new instance creation.

        Args:
            product_name(str): Product name of created instance.
            instance_data(dict): Base data for instance.
            pre_create_data(dict): Data based on pre creation attributes.
                Those may affect how creator works.
        """
        instance_data["flame_context"] = flib.CTX.context
        selected = pre_create_data.get("use_selection", False)
        self.selected = flib.get_clips_in_reels(
            self.project,
            selected=selected
        )

create(product_name, instance_data, pre_create_data)

Prepare data for new instance creation.

Parameters:

Name Type Description Default
product_name str

Product name of created instance.

required
instance_data dict

Base data for instance.

required
pre_create_data dict

Data based on pre creation attributes. Those may affect how creator works.

required
Source code in client/ayon_flame/api/plugin.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def create(self, product_name, instance_data, pre_create_data):
    """Prepare data for new instance creation.

    Args:
        product_name(str): Product name of created instance.
        instance_data(dict): Base data for instance.
        pre_create_data(dict): Data based on pre creation attributes.
            Those may affect how creator works.
    """
    instance_data["flame_context"] = flib.CTX.context
    selected = pre_create_data.get("use_selection", False)
    self.selected = flib.get_clips_in_reels(
        self.project,
        selected=selected
    )

FlameEditorialCreator

Bases: FlameCreator

Creator class wrapper for Editorial usage.

Source code in client/ayon_flame/api/plugin.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class FlameEditorialCreator(FlameCreator):
    """Creator class wrapper for Editorial usage.
    """
    skip_discovery = True

    def create(self, product_name, instance_data, pre_create_data):
        """Prepare data for new instance creation.

        Args:
            product_name(str): Product name of created instance.
            instance_data(dict): Base data for instance.
            pre_create_data(dict): Data based on pre creation attributes.
                Those may affect how creator works.
        """
        super().create(product_name, instance_data, pre_create_data)
        self.sequence = flib.get_current_sequence(flib.CTX.selection)
        selected = pre_create_data.get("use_selection", False)
        self.selected = flib.get_sequence_segments(
            self.sequence,
            selected=selected,
        )

create(product_name, instance_data, pre_create_data)

Prepare data for new instance creation.

Parameters:

Name Type Description Default
product_name str

Product name of created instance.

required
instance_data dict

Base data for instance.

required
pre_create_data dict

Data based on pre creation attributes. Those may affect how creator works.

required
Source code in client/ayon_flame/api/plugin.py
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def create(self, product_name, instance_data, pre_create_data):
    """Prepare data for new instance creation.

    Args:
        product_name(str): Product name of created instance.
        instance_data(dict): Base data for instance.
        pre_create_data(dict): Data based on pre creation attributes.
            Those may affect how creator works.
    """
    super().create(product_name, instance_data, pre_create_data)
    self.sequence = flib.get_current_sequence(flib.CTX.selection)
    selected = pre_create_data.get("use_selection", False)
    self.selected = flib.get_sequence_segments(
        self.sequence,
        selected=selected,
    )

FlameHost

Bases: HostBase, ILoadHost, IPublishHost

Source code in client/ayon_flame/api/pipeline.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class FlameHost(HostBase, ILoadHost, IPublishHost):
    name = "flame"

    def __init__(self):
        super().__init__()
        self._publish_context_data = {}

    def get_containers(self):
        return ls()

    def install(self):
        """Install all requirements for Flame host"""
        install()

    def get_context_data(self):
        return deepcopy(self._publish_context_data)

    def update_context_data(self, data, changes):
        self._publish_context_data = deepcopy(data)

install()

Install all requirements for Flame host

Source code in client/ayon_flame/api/pipeline.py
48
49
50
def install(self):
    """Install all requirements for Flame host"""
    install()

FlameMenuProjectConnect

Bases: _FlameMenuApp

Takes care of the preferences dialog as well.

Source code in client/ayon_flame/api/menu.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
class FlameMenuProjectConnect(_FlameMenuApp):
    """ Takes care of the preferences dialog as well.
    """

    def build_menu(self):
        if not self.flame:
            return []

        menu = deepcopy(self.menu)

        menu['actions'].append({
            "name": "1 - Load...",
            "execute": lambda x: self.tools_helper.show_loader()
        })
        menu['actions'].append({
            "name": "2 - Library...",
            "execute": lambda x: self.tools_helper.show_library_loader()
        })

        return menu

FlameMenuTimeline

Bases: _FlameMenuApp

Menu that appears in the timeline context.

Source code in client/ayon_flame/api/menu.py
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
class FlameMenuTimeline(_FlameMenuApp):
    """ Menu that appears in the timeline context.
    """

    def build_menu(self):
        if not self.flame:
            return []

        menu = deepcopy(self.menu)

        menu['actions'].append(
            {
                "name": "1 - Create...",
                "execute": lambda x: callback_selection(
                    x,
                    host_tools.show_publisher(
                        tab="create", parent=_get_main_window()
                    ),
                    context="FlameMenuTimeline"
                ),
            }
        )
        menu["actions"].append(
            {
                "name": "2 - Publish...",
                "execute": lambda x: callback_selection(
                    x,
                    host_tools.show_publisher(
                        tab="publish", parent=_get_main_window()
                    ),
                    context="FlameMenuTimeline"
                ),
            }
        )
        menu['actions'].append({
            "name": "3 - Load...",
            "execute": lambda x: self.tools_helper.show_loader()
        })
        # TODO: enable once scene inventory is ready
        # menu['actions'].append({
        #     "name": "Manage...",
        #     "execute": lambda x: self.tools_helper.show_scene_inventory()
        # })
        menu['actions'].append({
            "name": "4 - Library...",
            "execute": lambda x: self.tools_helper.show_library_loader()
        })

        return menu

FlameMenuUniversal

Bases: _FlameMenuApp

Menu that appears in the universal context.

Source code in client/ayon_flame/api/menu.py
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
class FlameMenuUniversal(_FlameMenuApp):
    """ Menu that appears in the universal context.
    """

    def build_menu(self):
        if not self.flame:
            return []

        menu = deepcopy(self.menu)
        menu['actions'].append(
            {
                "name": "1 - Create...",
                "execute": lambda x: callback_selection(
                    x,
                    host_tools.show_publisher(
                        tab="create", parent=_get_main_window()
                    ),
                    context="FlameMenuUniversal"
                ),
            }
        )
        menu["actions"].append(
            {
                "name": "2 - Publish...",
                "execute": lambda x: callback_selection(
                    x,
                    host_tools.show_publisher(
                        tab="publish", parent=_get_main_window()
                    ),
                    context="FlameMenuUniversal"
                ),
            }
        )
        menu['actions'].append({
            "name": "3 - Load...",
            "execute": lambda x: callback_selection(
                x,
                self.tools_helper.show_loader,
                context="FlameMenuUniversal"
            )
        })
        menu['actions'].append({
            "name": "4 - Library...",
            "execute": lambda x: self.tools_helper.show_library_loader()
        })

        return menu

HiddenFlameCreator

Bases: HiddenCreator

HiddenCreator class wrapper

Source code in client/ayon_flame/api/plugin.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class HiddenFlameCreator(HiddenCreator):
    """HiddenCreator class wrapper
    """
    skip_discovery = True
    settings_category = "flame"

    def collect_instances(self):
        pass

    def update_instances(self, update_list):
        pass

    def remove_instances(self, instances):
        pass

MediaInfoFile

Bases: object

Class to get media info file clip data

Raises:

Type Description
IOError

MEDIA_SCRIPT_PATH path doesn't exists

TypeError

Not able to generate clip xml data file

ParseError

Missing clip in xml clip data

IOError

Not able to save xml clip data to file

Attributes:

Name Type Description
str

MEDIA_SCRIPT_PATH path to flame binary

logging.Logger

log logger

TODO: add method for getting metadata to dict

Source code in client/ayon_flame/api/lib.py
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
class MediaInfoFile(object):
    """Class to get media info file clip data

    Raises:
        IOError: MEDIA_SCRIPT_PATH path doesn't exists
        TypeError: Not able to generate clip xml data file
        ET.ParseError: Missing clip in xml clip data
        IOError: Not able to save xml clip data to file

    Attributes:
        str: `MEDIA_SCRIPT_PATH` path to flame binary
        logging.Logger: `log` logger

    TODO: add method for getting metadata to dict
    """
    MEDIA_SCRIPT_PATH = "/opt/Autodesk/mio/current/dl_get_media_info"

    log = log

    _clip_data = None
    _start_frame = None
    _fps = None
    _drop_mode = None
    _file_pattern = None

    def __init__(self, path, logger=None):

        # replace log if any
        if logger:
            self.log = logger

        # test if `dl_get_media_info` path exists
        self._validate_media_script_path()

        # derivate other feed variables
        feed_basename = os.path.basename(path)
        feed_dir = os.path.dirname(path)
        feed_ext = os.path.splitext(feed_basename)[1][1:].lower()

        with maintained_temp_file_path(".clip") as tmp_path:
            self.log.info("Temp File: {}".format(tmp_path))
            self._generate_media_info_file(tmp_path, feed_ext, feed_dir)

            # get collection containing feed_basename from path
            self.file_pattern = self._get_collection(
                feed_basename, feed_dir, feed_ext)

            if (
                not self.file_pattern
                and os.path.exists(os.path.join(feed_dir, feed_basename))
            ):
                self.file_pattern = feed_basename

            # get clip data and make them single if there is multiple
            # clips data
            xml_data = self._make_single_clip_media_info(
                tmp_path, feed_basename, self.file_pattern)
            self.log.debug("xml_data: {}".format(xml_data))
            self.log.debug("type: {}".format(type(xml_data)))

            # get all time related data and assign them
            self._get_time_info_from_origin(xml_data)
            self.log.debug("start_frame: {}".format(self.start_frame))
            self.log.debug("fps: {}".format(self.fps))
            self.log.debug("drop frame: {}".format(self.drop_mode))
            # get all resolution related data and assign them
            self._get_resolution_info_from_origin(xml_data)

            try:
                self.log.debug("width: {}".format(self.width))
                self.log.debug("height: {}".format(self.height))
                self.log.debug("pixel aspect: {}".format(self.pixel_aspect))

            except AttributeError:
                self.log.debug("audio: true")

            self.clip_data = xml_data

    def _get_typed_value(self, xml_obj):
        """ Get typed value from xml object

        Args:
            xml_obj (xml.etree.ElementTree.Element): xml object

        Returns:
            str: value
        """
        if hasattr(xml_obj, "type"):
            if xml_obj.type in ["int", "uint"]:
                return int(xml_obj.text)
            if xml_obj.type == "float":
                return float(xml_obj.text)
            if xml_obj.type == "string":
                return str(xml_obj.text)

        return xml_obj.text

    def _get_collection(self, feed_basename, feed_dir, feed_ext) -> str | None:
        """Get collection string.

        Args:
            feed_basename (str): file base name
            feed_dir (str): file's directory
            feed_ext (str): file extension

        Raises:
            AttributeError: feed_ext is not matching feed_basename

        Returns:
            str: collection basename with range of sequence
        """
        partialname = self._separate_file_head(feed_basename, feed_ext)

        # make sure partial input basename is having correct extensoon
        if not partialname:
            raise AttributeError(
                f"Wrong input attributes. Basename - {feed_basename}, "
                f"Ext - {feed_ext}"
            )

        # get all related files
        files = [
            f for f in os.listdir(feed_dir)
            if partialname == self._separate_file_head(f, feed_ext)
        ]

        # ignore reminders as we dont need them
        collections = clique.assemble(files)[0]

        # in case no collection found return None
        # it is probably just single file
        if not collections:
            return

        # we expect only one collection
        collection = collections[0]

        self.log.debug("__ collection: {}".format(collection))

        if collection.is_contiguous():
            return self._format_collection(collection)

        # add `[` in front to make sure it want capture
        # shot name with the same number
        number_from_path = self._separate_number(feed_basename, feed_ext)
        search_number_pattern = "[" + number_from_path
        # convert to multiple collections
        _continues_colls = collection.separate()
        for _coll in _continues_colls:
            coll_to_text = self._format_collection(
                _coll, len(number_from_path))
            self.log.debug("__ coll_to_text: {}".format(coll_to_text))
            if search_number_pattern in coll_to_text:
                return coll_to_text
        return None

    @staticmethod
    def _format_collection(collection, padding=None):
        padding = padding or collection.padding
        # if no holes then return collection
        head = collection.format("{head}")
        tail = collection.format("{tail}")
        range_template = "[{{:0{0}d}}-{{:0{0}d}}]".format(
            padding)
        ranges = range_template.format(
            min(collection.indexes),
            max(collection.indexes)
        )
        # if no holes then return collection
        return "{}{}{}".format(head, ranges, tail)

    def _separate_file_head(self, basename, extension):
        """ Get only head with out sequence and extension

        Args:
            basename (str): file base name
            extension (str): file extension

        Returns:
            str: file head
        """
        # in case sequence file
        found = re.findall(
            r"(.*)[._][\d]*(?=.{})".format(extension),
            basename,
        )
        if found:
            return found.pop()

        # in case single file
        name, ext = os.path.splitext(basename)

        if extension == ext[1:]:
            return name

    def _separate_number(self, basename, extension):
        """ Get only sequence number as string

        Args:
            basename (str): file base name
            extension (str): file extension

        Returns:
            str: number with padding
        """
        # in case sequence file
        found = re.findall(
            r"[._]([\d]*)(?=.{})".format(extension),
            basename,
        )
        if found:
            return found.pop()

    @property
    def clip_data(self):
        """Clip's xml clip data

        Returns:
            xml.etree.ElementTree: xml data
        """
        return self._clip_data

    @clip_data.setter
    def clip_data(self, data):
        self._clip_data = data

    @property
    def start_frame(self):
        """ Clip's starting frame found in timecode

        Returns:
            int: number of frames
        """
        return self._start_frame

    @start_frame.setter
    def start_frame(self, number):
        self._start_frame = int(number)

    @property
    def fps(self):
        """ Clip's frame rate

        Returns:
            float: frame rate
        """
        return self._fps

    @fps.setter
    def fps(self, fl_number):
        self._fps = float(fl_number)

    @property
    def drop_mode(self):
        """ Clip's drop frame mode

        Returns:
            str: drop frame flag
        """
        return self._drop_mode

    @drop_mode.setter
    def drop_mode(self, text):
        self._drop_mode = str(text)

    @property
    def file_pattern(self):
        """Clips file pattern.

        Returns:
            str: file pattern. ex. file.[1-2].exr
        """
        return self._file_pattern

    @file_pattern.setter
    def file_pattern(self, fpattern):
        self._file_pattern = fpattern

    def _validate_media_script_path(self):
        if not os.path.isfile(self.MEDIA_SCRIPT_PATH):
            raise IOError("Media Script does not exist: `{}`".format(
                self.MEDIA_SCRIPT_PATH))

    def _generate_media_info_file(self, fpath, feed_ext, feed_dir):
        """ Generate media info xml .clip file

        Args:
            fpath (str): .clip file path
            feed_ext (str): file extension to be filtered
            feed_dir (str): look up directory

        Raises:
            TypeError: Type error if it fails
        """
        # Create cmd arguments for gettig xml file info file
        cmd_args = [
            self.MEDIA_SCRIPT_PATH,
            "-e", feed_ext,
            "-o", fpath,
            feed_dir
        ]

        try:
            # execute creation of clip xml template data
            run_subprocess(cmd_args)
        except TypeError as error:
            raise TypeError(
                "Error creating `{}` due: {}".format(fpath, error))

    def _make_single_clip_media_info(self, fpath, feed_basename, path_pattern):
        """ Separate only relative clip object form .clip file

        Args:
            fpath (str): clip file path
            feed_basename (str): search basename
            path_pattern (str): search file pattern (file.[1-2].exr)

        Raises:
            ET.ParseError: if nothing found

        Returns:
            ET.Element: xml element data of matching clip
        """
        with open(fpath) as f:
            lines = f.readlines()
            _added_root = itertools.chain(
                "<root>", deepcopy(lines)[1:], "</root>")
            new_root = ET.fromstringlist(_added_root)

        # find the clip which is matching to my input name
        xml_clips = new_root.findall("clip")
        matching_clip = None
        for xml_clip in xml_clips:
            clip_name = xml_clip.find("name").text
            self.log.debug("__ clip_name: `{}`".format(clip_name))
            if clip_name not in feed_basename:
                continue

            # test path pattern
            for out_track in xml_clip.iter("track"):
                for out_feed in out_track.iter("feed"):
                    for span in out_feed.iter("span"):
                        # start frame
                        span_path = span.find("path")
                        self.log.debug(
                            "__ span_path.text: {}, path_pattern: {}".format(
                                span_path.text, path_pattern
                            )
                        )
                        if path_pattern in span_path.text:
                            matching_clip = xml_clip

        if matching_clip is None:
            # return warning there is missing clip
            raise ET.ParseError(
                "Missing clip in `{}`. Available clips {}".format(
                    feed_basename, [
                        xml_clip.find("name").text
                        for xml_clip in xml_clips
                    ]
                ))

        return matching_clip

    def _get_time_info_from_origin(self, xml_data):
        """Set time info to class attributes

        Args:
            xml_data (ET.Element): clip data
        """
        try:
            for out_track in xml_data.iter("track"):
                for out_feed in out_track.iter("feed"):
                    # start frame
                    out_feed_nb_ticks_obj = out_feed.find(
                        "startTimecode/nbTicks")
                    self.start_frame = self._get_typed_value(
                        out_feed_nb_ticks_obj)

                    # fps
                    out_feed_fps_obj = out_feed.find(
                        "startTimecode/rate")
                    self.fps = self._get_typed_value(out_feed_fps_obj)

                    # drop frame mode
                    out_feed_drop_mode_obj = out_feed.find(
                        "startTimecode/dropMode")
                    self.drop_mode = self._get_typed_value(
                        out_feed_drop_mode_obj)
                    break
        except Exception as msg:
            self.log.warning(msg)

    def _get_resolution_info_from_origin(self, xml_data):
        """Set resolution info to class attributes

        Args:
            xml_data (ET.Element): clip data
        """
        try:
            for out_track in xml_data.iter("track"):
                for out_feed in out_track.iter("feed"):
                    # width
                    out_feed_width_obj = out_feed.find("storageFormat/width")
                    self.width = int(self._get_typed_value(out_feed_width_obj))

                    # height
                    out_feed_height_obj = out_feed.find("storageFormat/height")
                    self.height = int(
                        self._get_typed_value(out_feed_height_obj))

                    # pixel aspect ratio
                    out_feed_pixel_aspect_obj = out_feed.find(
                        "storageFormat/pixelRatio")
                    self.pixel_aspect = float(
                        self._get_typed_value(out_feed_pixel_aspect_obj))
                    break
        except Exception as msg:
            self.log.warning(msg)

    @staticmethod
    def write_clip_data_to_file(fpath, xml_element_data):
        """ Write xml element of clip data to file

        Args:
            fpath (string): file path
            xml_element_data (xml.etree.ElementTree.Element): xml data

        Raises:
            IOError: If data could not be written to file
        """
        try:
            # save it as new file
            tree = ET.ElementTree(xml_element_data)
            tree.write(
                fpath, xml_declaration=True,
                method="xml", encoding="UTF-8"
            )
        except IOError as error:
            raise IOError(
                "Not able to write data to file: {}".format(error))

clip_data property writable

Clip's xml clip data

Returns:

Type Description

xml.etree.ElementTree: xml data

drop_mode property writable

Clip's drop frame mode

Returns:

Name Type Description
str

drop frame flag

file_pattern property writable

Clips file pattern.

Returns:

Name Type Description
str

file pattern. ex. file.[1-2].exr

fps property writable

Clip's frame rate

Returns:

Name Type Description
float

frame rate

start_frame property writable

Clip's starting frame found in timecode

Returns:

Name Type Description
int

number of frames

write_clip_data_to_file(fpath, xml_element_data) staticmethod

Write xml element of clip data to file

Parameters:

Name Type Description Default
fpath string

file path

required
xml_element_data Element

xml data

required

Raises:

Type Description
IOError

If data could not be written to file

Source code in client/ayon_flame/api/lib.py
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
@staticmethod
def write_clip_data_to_file(fpath, xml_element_data):
    """ Write xml element of clip data to file

    Args:
        fpath (string): file path
        xml_element_data (xml.etree.ElementTree.Element): xml data

    Raises:
        IOError: If data could not be written to file
    """
    try:
        # save it as new file
        tree = ET.ElementTree(xml_element_data)
        tree.write(
            fpath, xml_declaration=True,
            method="xml", encoding="UTF-8"
        )
    except IOError as error:
        raise IOError(
            "Not able to write data to file: {}".format(error))

PublishableClip

Convert a segment to publishable instance

Parameters:

Name Type Description Default
segment PySegment

flame api object

required
kwargs optional

additional data needed for rename=True (presets)

required

Returns:

Type Description

flame.PySegment: flame api object

Source code in client/ayon_flame/api/plugin.py
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
class PublishableClip:
    """
    Convert a segment to publishable instance

    Args:
        segment (flame.PySegment): flame api object
        kwargs (optional): additional data needed for rename=True (presets)

    Returns:
        flame.PySegment: flame api object
    """
    vertical_clip_match = {}
    vertical_clip_used = {}
    types = {
        "shot": "shot",
        "folder": "folder",
        "episode": "episode",
        "sequence": "sequence",
        "track": "sequence",
    }

    # parents search pattern
    parents_search_pattern = r"\{([a-z]*?)\}"

    # default templates for non-ui use
    rename_default = False
    hierarchy_default = "{_folder_}/{_sequence_}/{_track_}"
    clip_name_default = "shot_{_trackIndex_:0>3}_{_clipIndex_:0>4}"
    review_source_default = None
    base_product_variant_default = "<track_name>"
    product_base_type = "plate"
    product_type = product_base_type
    count_from_default = 10
    count_steps_default = 10
    vertical_sync_default = False
    driving_layer_default = ""
    index_from_segment_default = False
    use_shot_name_default = False
    include_handles_default = False
    retimed_handles_default = True
    retimed_framerange_default = True

    def __init__(
        self,
        segment: object,
        pre_create_data: dict[str, Any],
        data: dict[str, Any],
        rename_index: int,
        log: logging.Logger,
    ):
        self.rename_index = rename_index
        self.log = log
        self.pre_create_data = pre_create_data or {}
        self.marker_data = {}

        # get main parent objects
        self.current_segment = segment
        sequence_name = flib.get_current_sequence([segment]).name.get_value()
        self.sequence_name = str(sequence_name).replace(" ", "_")
        self.clip_data = flib.get_segment_attributes(segment)

        # segment (clip) main attributes
        self.cs_name = self.clip_data["segment_name"]
        self.cs_index = int(self.clip_data["segment"])
        self.shot_name = self.clip_data["shot_name"]

        # get track name and index
        self.track_index = int(self.clip_data["track"])
        track_name = self.clip_data["track_name"]
        self.track_name = (
            # make sure no space and other special characters are in track name
            # default track name is `*`
            str(track_name)
            .replace(" ", "_")
            .replace("*", f"noname{self.track_index}")
        )

        # add publish attribute to marker data
        self.marker_data.update({"active": True})

        # adding input data if any
        if data:
            self.marker_data.update(data)

        # populate default data before we get other attributes
        self._populate_segment_default_data()

        # use all populated default data to create all important attributes
        self._populate_attributes()

        # create parents with correct types
        self._create_parents()

    @classmethod
    def restore_all_caches(cls):
        cls.vertical_clip_match = {}
        cls.vertical_clip_used = {}

    def convert(self):

        # solve segment data and add them to marker data
        self._convert_to_marker_data()

        # if track name is in review track name and also if driving track name
        # is not in review track name: skip tag creation
        if (self.track_name in self.reviewable_source) and (
                self.driving_layer not in self.reviewable_source):
            return

        # deal with clip name
        new_name = self.marker_data.pop("newClipName")
        hierarchy_filled = self.marker_data["hierarchy"]

        if self.rename and not self.use_shot_name:
            # rename segment
            self.current_segment.name = str(new_name)
            self.marker_data.update({
                "folderName": str(new_name),
                "folderPath": f"/{hierarchy_filled}/{new_name}"
            })

        elif self.use_shot_name:
            if not self.shot_name:
                raise CreatorError(
                    f"Shot name is not set on segment: {self.cs_name}")
            self.marker_data.update({
                "folderName": self.shot_name,
                "folderPath": f"/{hierarchy_filled}/{self.shot_name}",
                "hierarchyData": {
                    "shot": self.shot_name
                }
            })
        else:
            self.marker_data.update({
                "folderName": self.cs_name,
                "folderPath": f"/{hierarchy_filled}/{self.cs_name}",
                "hierarchyData": {
                    "shot": self.cs_name
                }
            })

        return self.current_segment

    def _populate_segment_default_data(self):
        """ Populate default formatting data from segment. """

        self.current_segment_default_data = {
            "_folder_": "shots",
            "_sequence_": self.sequence_name,
            "_track_": self.track_name,
            "_clip_": self.cs_name,
            "_trackIndex_": self.track_index,
            "_clipIndex_": self.cs_index
        }

    def _populate_attributes(self):
        """ Populate main object attributes. """
        # segment frame range and parent track name for vertical sync check
        self.clip_in = int(self.clip_data["record_in"])
        self.clip_out = int(self.clip_data["record_out"])

        # define ui inputs if non gui mode was used
        self.shot_num = self.cs_index
        self.log.debug(f"____ self.shot_num: {self.shot_num}")

        # Use pre-create data or default values if gui was not used
        self.rename = self.pre_create_data.get(
            "clipRename") or self.rename_default
        self.use_shot_name = self.pre_create_data.get(
            "useShotName") or self.use_shot_name_default
        self.clip_name = self.pre_create_data.get(
            "clipName") or self.clip_name_default
        self.hierarchy = self.pre_create_data.get(
            "hierarchy") or self.hierarchy_default
        self.hierarchy_data = self.pre_create_data.get(
            "hierarchyData") or self.current_segment_default_data.copy()
        self.index_from_segment = self.pre_create_data.get(
            "segmentIndex") or self.index_from_segment_default
        self.count_from = self.pre_create_data.get(
            "countFrom") or self.count_from_default
        self.count_steps = self.pre_create_data.get(
            "countSteps") or self.count_steps_default
        self.base_product_variant = self.pre_create_data.get(
            "clipVariant") or self.base_product_variant_default
        self.product_type = (
            self.pre_create_data.get("plate_product_type")
            or self.product_base_type
        )
        self.vertical_sync = self.pre_create_data.get(
            "vSyncOn") or self.vertical_sync_default
        self.driving_layer = self.pre_create_data.get(
            "vSyncTrack") or self.driving_layer_default
        self.review_source = self.pre_create_data.get(
            "reviewableSource") or self.review_source_default
        self.audio = self.pre_create_data.get("export_audio") or False
        self.include_handles = self.pre_create_data.get(
            "includeHandles") or self.include_handles_default
        self.retimed_handles = (
            self.pre_create_data.get("retimedHandles")
            or self.retimed_handles_default
        )
        self.retimed_framerange = (
            self.pre_create_data.get("retimedFramerange")
            or self.retimed_framerange_default
        )

        # build product name from layer name
        if self.base_product_variant == "<track_name>":
            self.variant = self.track_name
        else:
            self.variant = self.base_product_variant

        # create product name for publishing
        # TODO: Use creator's `get_product_name` to correctly define name
        self.product_name = (
            f"{self.product_base_type}{self.variant.capitalize()}"
        )

        self.hierarchy_data = {
            key: self.pre_create_data.get(key)
            for key in ["folder", "episode", "sequence", "track", "shot"]
        }

    def _replace_hash_to_expression(self, name, text):
        """ Replace hash with number in correct padding. """
        _spl = text.split("#")
        _len = (len(_spl) - 1)
        _repl = "{{{0}:0>{1}}}".format(name, _len)
        return text.replace(("#" * _len), _repl)

    def _convert_to_marker_data(self):
        """ Convert internal data to marker data.

        Populating the marker data into internal variable self.marker_data
        """
        # define vertical sync attributes
        hero_track = True
        self.reviewable_source = ""

        if (
            self.vertical_sync and
            self.track_name not in self.driving_layer
        ):
            # if it is not then define vertical sync as None
            hero_track = False

        # increasing steps by index of rename iteration
        if not self.index_from_segment:
            self.count_steps *= self.rename_index

        hierarchy_formatting_data = {}
        hierarchy_data = deepcopy(self.hierarchy_data)
        _data = self.current_segment_default_data.copy()

        if self.pre_create_data:

            # backward compatibility for reviewableSource (2024.12.02)
            if "reviewTrack" in self.pre_create_data:
                _value = self.marker_data.pop("reviewTrack")
                self.marker_data["reviewableSource"] = _value

            # driving layer is set as positive match
            if hero_track or self.vertical_sync:
                # mark review layer
                if self.review_source and (
                        self.review_source != self.review_source_default):
                    # if review layer is defined and not the same as default
                    self.reviewable_source  = self.review_source

                # shot num calculate
                if self.index_from_segment:
                    # use clip index from timeline
                    self.shot_num = self.count_steps * self.cs_index
                else:
                    if self.rename_index == 0:
                        self.shot_num = self.count_from
                    else:
                        self.shot_num = self.count_from + self.count_steps

            # clip name sequence number
            _data.update({"shot": self.shot_num})

            # solve # in test to pythonic expression
            for _k, _v in hierarchy_data.items():
                if "#" not in _v:
                    continue
                hierarchy_data[_k] = self._replace_hash_to_expression(_k, _v)

            # fill up pythonic expresisons in hierarchy data
            for k, _v in hierarchy_data.items():
                hierarchy_formatting_data[k] = str(_v).format(**_data)
        else:
            # if no gui mode then just pass default data
            hierarchy_formatting_data = hierarchy_data

        tag_instance_data = self._solve_tag_instance_data(
            hierarchy_formatting_data)

        tag_instance_data.update({"heroTrack": True})
        if hero_track and self.vertical_sync:
            self.vertical_clip_match.update({
                (self.clip_in, self.clip_out): tag_instance_data
            })

        if not hero_track and self.vertical_sync:
            # driving layer is set as negative match
            for (hero_in, hero_out), hero_data in self.vertical_clip_match.items():  # noqa
                # Iterate over all clips in vertical sync match
                # If clip frame range is outside of hero clip frame range
                # then skip this clip and do not add to hierarchical shared
                # metadata to them.
                if self.clip_in < hero_in or self.clip_out > hero_out:
                    continue

                _distrib_data = deepcopy(hero_data)
                _distrib_data["heroTrack"] = False

                # form used clip unique key
                data_product_name = hero_data["productName"]
                new_clip_name = hero_data["newClipName"]

                # get used names list for duplicity check
                used_names_list = self.vertical_clip_used.setdefault(
                    f"{new_clip_name}{data_product_name}", []
                )
                self.log.debug(
                    f">> used_names_list: {used_names_list}"
                )
                clip_product_name = self.product_name
                variant = self.variant
                self.log.debug(
                    f">> clip_product_name: {clip_product_name}")

                # in case track name and product name is the same then add
                if self.variant == self.track_name:
                    clip_product_name = self.product_name

                # add track index in case duplicity of names in hero data
                # INFO: this is for case where hero clip product name
                #    is the same as current clip product name
                if clip_product_name in data_product_name:
                    clip_product_name = (
                        f"{clip_product_name}{self.track_index}")
                    variant = f"{variant}{self.track_index}"

                # in case track clip product name had been already used
                # then add product name with clip index
                if clip_product_name in used_names_list:
                    _clip_product_name = (
                        f"{clip_product_name}{self.cs_index}"
                    )
                    # just in case lets validate if new name is not used
                    # in case the track_index is the same as clip_index
                    if _clip_product_name in used_names_list:
                        _clip_product_name = (
                            f"{clip_product_name}"
                            f"{self.track_index}{self.cs_index}"
                        )
                    clip_product_name = _clip_product_name
                    variant = f"{variant}{self.cs_index}"

                self.log.debug(
                    f">> clip_product_name: {clip_product_name}")
                _distrib_data["productName"] = clip_product_name
                _distrib_data["variant"] = variant
                # assign data to return hierarchy data to tag
                tag_instance_data = _distrib_data

                # add used product name to used list to avoid duplicity
                used_names_list.append(clip_product_name)
                break

        # add data to return data dict
        self.marker_data.update(tag_instance_data)

        # add review track only to hero track
        if hero_track and self.reviewable_source:
            self.marker_data["reviewTrack"] = self.reviewable_source
        else:
            self.marker_data["reviewTrack"] = None

        # add only review related data if reviewable source is set
        if self.reviewable_source:
            review_switch = True
            reviewable_source = self.reviewable_source

            if self.vertical_sync and not hero_track:
                review_switch = False
                reviewable_source = False

            if review_switch:
                self.marker_data["review"] = True
            else:
                self.marker_data.pop("review", None)

            self.marker_data["reviewableSource"] = reviewable_source

    def _solve_tag_instance_data(self, hierarchy_formatting_data):
        """ Solve marker data from hierarchy data and templates. """
        # fill up clip name and hierarchy keys
        hierarchy_filled = self.hierarchy.format(**hierarchy_formatting_data)
        clip_name_filled = self.clip_name.format(**hierarchy_formatting_data)

        # remove shot from hierarchy data: is not needed anymore
        hierarchy_formatting_data.pop("shot")

        return {
            "newClipName": clip_name_filled,
            "hierarchy": hierarchy_filled,
            "parents": self.parents,
            "hierarchyData": hierarchy_formatting_data,
            "productName": self.product_name,
            "productType": self.product_type,
            "productBaseType": self.product_base_type,
            "variant": self.variant,
        }

    def _convert_to_entity(self, src_type, template):
        """ Converting input key to key with type. """
        # convert to entity type
        folder_type = self.types.get(src_type, None)

        assert folder_type, "Missing folder type for `{}`".format(
            src_type
        )

        # first collect formatting data to use for formatting template
        formatting_data = {}
        for _k, _v in self.hierarchy_data.items():
            value = str(_v).format(
                **self.current_segment_default_data)
            formatting_data[_k] = value

        return {
            "folder_type": folder_type,
            "entity_name": template.format(
                **formatting_data
            )
        }

    def _create_parents(self):
        """ Create parents and return it in list. """
        self.parents = []

        pattern = re.compile(self.parents_search_pattern)

        par_split = [(pattern.findall(t).pop(), t)
                     for t in self.hierarchy.split("/")]

        for type_, template in par_split:
            parent = self._convert_to_entity(type_, template)
            self.parents.append(parent)

TimeEffectMetadata

Bases: object

Source code in client/ayon_flame/api/lib.py
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
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
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
class TimeEffectMetadata(object):
    log = log
    _data = {}
    _retime_modes = {
        0: "speed",
        1: "timewarp",
        2: "duration"
    }

    def __init__(self, segment, logger=None):
        if logger:
            self.log = logger

        self._setup_data, self._data = self._get_metadata(segment)

    @property
    def is_empty(self):
        """ Returns either the current object is empty or not.

        Returns:
            bool. Is the TimeEffectMetadata object empty?
        """
        return self._setup_data is None

    @property
    def data(self):
        """ Returns timewarp effect data

        Returns:
            dict: retime data
        """
        return self._data

    @property
    def setup_data(self):
        """ Returns timewarp effect setup data

        Returns:
            str. The XML formatted setup data.
        """
        return self._setup_data

    def _get_metadata(self, segment):
        effects = segment.effects or []
        for effect in effects:
            if effect.type == "Timewarp":
                with maintained_temp_file_path(".timewarp_node") as tmp_path:
                    self.log.info("Temp File: {}".format(tmp_path))
                    effect.save_setup(tmp_path)
                    return self._get_attributes_from_xml(tmp_path)

        return None, {}

    def _get_attributes_from_xml(self, tmp_path):
        with open(tmp_path, "r") as tw_setup_file:
            tw_setup_string = tw_setup_file.read()

        tw_setup_xml = ET.fromstring(tw_setup_string)
        tw_setup = self._dictify(tw_setup_xml)

        try:
            tw_setup_state = tw_setup["Setup"]["State"][0]
            mode = int(
                tw_setup_state["TW_RetimerMode"][0]["_text"]
            )
            r_data = {
                "type": self._retime_modes[mode],
                "effectStart": int(
                    tw_setup["Setup"]["Base"][0]["Range"][0]["Start"]),
                "effectEnd": int(
                    tw_setup["Setup"]["Base"][0]["Range"][0]["End"])
            }

            if mode == 0:  # speed
                r_data[self._retime_modes[mode]] = float(
                    tw_setup_state["TW_Speed"]
                    [0]["Channel"][0]["Value"][0]["_text"]
                ) / 100
                r_data["numKeys"] = int(
                    tw_setup_state["TW_SpeedTiming"]
                    [0]["Channel"][0]["Size"][0]["_text"]
                )
            elif mode == 1:  # timewarp
                r_data[self._retime_modes[mode]] = self._get_anim_keys(
                    tw_setup_state["TW_Timing"]
                )
            elif mode == 2:  # duration
                r_data[self._retime_modes[mode]] = {
                    "start": {
                        "source": int(
                            tw_setup_state["TW_DurationTiming"][0]["Channel"]
                            [0]["KFrames"][0]["Key"][0]["Value"][0]["_text"]
                        ),
                        "timeline": int(
                            tw_setup_state["TW_DurationTiming"][0]["Channel"]
                            [0]["KFrames"][0]["Key"][0]["Frame"][0]["_text"]
                        )
                    },
                    "end": {
                        "source": int(
                            tw_setup_state["TW_DurationTiming"][0]["Channel"]
                            [0]["KFrames"][0]["Key"][1]["Value"][0]["_text"]
                        ),
                        "timeline": int(
                            tw_setup_state["TW_DurationTiming"][0]["Channel"]
                            [0]["KFrames"][0]["Key"][1]["Frame"][0]["_text"]
                        )
                    }
                }
        except Exception as error:
            self.log.error(error, exc_info=True)
            return None, {}

        return tw_setup_string, r_data

    def _get_anim_keys(self, setup_cat, index=None):
        return_data = {
            "extrapolation": (
                setup_cat[0]["Channel"][0]["Extrap"][0]["_text"]
            ),
            "animKeys": []
        }
        for key in setup_cat[0]["Channel"][0]["KFrames"][0]["Key"]:
            if index and int(key["Index"]) != index:
                continue
            key_data = {
                "source": float(key["Value"][0]["_text"]),
                "timeline": float(key["Frame"][0]["_text"]),
                "index": int(key["Index"]),
                "curveMode": key["CurveMode"][0]["_text"],
                "curveOrder": key["CurveOrder"][0]["_text"]
            }
            if key.get("TangentMode"):
                key_data["tangentMode"] = key["TangentMode"][0]["_text"]

            return_data["animKeys"].append(key_data)

        return return_data

    def _dictify(self, xml_, root=True):
        """ Convert xml object to dictionary

        Args:
            xml_ (xml.etree.ElementTree.Element): xml data
            root (bool, optional): is root available. Defaults to True.

        Returns:
            dict: dictionarized xml
        """

        if root:
            return {xml_.tag: self._dictify(xml_, False)}

        d = copy(xml_.attrib)
        if xml_.text:
            d["_text"] = xml_.text

        for x in xml_.findall("./*"):
            if x.tag not in d:
                d[x.tag] = []
            d[x.tag].append(self._dictify(x, False))
        return d

data property

Returns timewarp effect data

Returns:

Name Type Description
dict

retime data

is_empty property

Returns either the current object is empty or not.

Returns:

Type Description

bool. Is the TimeEffectMetadata object empty?

setup_data property

Returns timewarp effect setup data

Returns:

Type Description

str. The XML formatted setup data.

add_reels_to_batch(batch, reels=None, shelf_reels=None)

Add reels and shelf reels to batch.

Source code in client/ayon_flame/api/batch_utils.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def add_reels_to_batch(
    batch: flame.PyBatch,
    reels: Optional[List[str]] = None,
    shelf_reels: Optional[List[str]] = None,
):
    """ Add reels and shelf reels to batch.
    """
    if reels:
        existing_reel_names = [
            reel.name.get_value()
            for reel in batch.reels
        ]
        for new_reel in reels:
            if new_reel not in existing_reel_names:
                batch.create_reel(new_reel)

    if shelf_reels:
        existing_shelf_reel_names = [
            reel.name.get_value()
            for reel in batch.shelf_reels
        ]
        for new_sr in shelf_reels:
            if new_sr not in existing_shelf_reel_names:
                batch.create_shelf_reel(new_sr)

clear_node_metadata(node)

Remove AYON instance data from a node's note attribute.

Source code in client/ayon_flame/api/batch_utils.py
46
47
48
def clear_node_metadata(node: flame.PyNode):
    """ Remove AYON instance data from a node's note attribute."""
    node.note = ""

containerise(flame_clip_segment, name, namespace, context, loader=None, data=None)

Containerise a flame clip segment.

Source code in client/ayon_flame/api/pipeline.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def containerise(flame_clip_segment,
                 name,
                 namespace,
                 context,
                 loader=None,
                 data=None):
    """ Containerise a flame clip segment.
    """
    data_imprint = {
        "schema": "ayon:container-3.0",
        "id": AYON_CONTAINER_ID,
        "name": str(name),
        "namespace": str(namespace),
        "loader": str(loader),
        "representation": context["representation"]["id"],
    }

    if data:
        data_imprint.update(data)

    # timeline item imprinted data
    set_segment_data_marker(flame_clip_segment, data_imprint)

    return True

create_batch(name, frame_start, frame_duration, handle_start=0, handle_end=0)

Create Batch Group in active project's Desktop

Source code in client/ayon_flame/api/batch_utils.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def create_batch(
    name,
    frame_start: int,
    frame_duration: int,
    handle_start: int = 0,
    handle_end: int = 0,
) -> flame.PyBatch:
    """ Create Batch Group in active project's Desktop
    """
    frame_start -= handle_start
    frame_duration += handle_start + handle_end

    return flame.batch.create_batch_group(
        name,
        start_frame=frame_start,
        duration=frame_duration,
    )

create_segment_data_marker(segment)

Create AYON marker on a segment.

Attributes:

Name Type Description
segment PySegment

flame api object

Returns:

Type Description

flame.PyMarker: flame api object

Source code in client/ayon_flame/api/lib.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def create_segment_data_marker(segment):
    """Create AYON marker on a segment.

    Attributes:
        segment (flame.PySegment): flame api object

    Returns:
        flame.PyMarker: flame api object
    """
    # get duration of segment
    duration = segment.record_duration.relative_frame
    # calculate start frame of the new marker
    start_frame = int(segment.record_in.relative_frame) + int(duration / 2)
    # create marker
    marker = segment.create_marker(start_frame)
    # set marker name
    marker.name = MARKER_NAME
    # set duration
    marker.duration = MARKER_DURATION
    # set colour
    marker.colour = COLOR_MAP[MARKER_COLOR]  # Red

    return marker

export_clip(export_path, clip, preset_path, **kwargs)

Flame exported wrapper

Parameters:

Name Type Description Default
export_path str

exporting directory path

required
clip PyClip

flame api object

required
preset_path str

full export path to xml file

required
Kwargs

thumb_frame_number (int)[optional]: source frame number in_mark (int)[optional]: cut in mark out_mark (int)[optional]: cut out mark

Raises:

Type Description
KeyError

Missing input kwarg thumb_frame_number in case thumbnail in export_preset

FileExistsError

Missing export preset in shared folder

Source code in client/ayon_flame/api/render_utils.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def export_clip(export_path, clip, preset_path, **kwargs):
    """Flame exported wrapper

    Args:
        export_path (str): exporting directory path
        clip (PyClip): flame api object
        preset_path (str): full export path to xml file

    Kwargs:
        thumb_frame_number (int)[optional]: source frame number
        in_mark (int)[optional]: cut in mark
        out_mark (int)[optional]: cut out mark

    Raises:
        KeyError: Missing input kwarg `thumb_frame_number`
                  in case `thumbnail` in `export_preset`
        FileExistsError: Missing export preset in shared folder
    """
    import flame

    in_mark = out_mark = None

    # Set exporter
    exporter = flame.PyExporter()
    exporter.foreground = True
    exporter.export_between_marks = True

    if kwargs.get("thumb_frame_number"):
        thumb_frame_number = kwargs["thumb_frame_number"]
        in_mark = int(thumb_frame_number)
        out_mark = int(thumb_frame_number) + 1

    elif kwargs.get("in_mark") and kwargs.get("out_mark"):
        in_mark = int(kwargs["in_mark"])
        out_mark = int(kwargs["out_mark"])
    else:
        exporter.export_between_marks = False

    try:
        # set in and out marks if they are available
        if in_mark and out_mark:
            clip.in_mark = in_mark
            clip.out_mark = out_mark

        # export with exporter
        exporter.export(clip, preset_path, export_path)
    finally:
        log.debug('Exported: {} at {}-{}'.format(
            clip.name.get_value(),
            clip.in_mark,
            clip.out_mark
        ))

get_batch_from_workspace(name, workspace=None)

Get batch group from name and workspace.

Source code in client/ayon_flame/api/batch_utils.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def get_batch_from_workspace(
    name: str,
    workspace: Optional[flame.PyWorkspace] = None
) -> Optional[flame.PyBatch]:
    """ Get batch group from name and workspace.
    """
    if workspace is None:
        project = flame.project.current_project
        workspace = project.current_workspace

    desktop = workspace.desktop
    for batchgroup in desktop.batch_groups:
        if batchgroup.name.get_value() == name:
            return batchgroup

    return None

get_clip_data_marker(clip, with_marker=None)

Get data marker from inside of reel clip.

Wrapper for get_segment_data_marker. Clip has actually also markers but it is different object type.

Attributes:

Name Type Description
clip PyClip

flame api object

with_marker bool)[optional]

if true it will return also marker object

Returns:

Name Type Description
dict

AYON tag data

Returns(with_marker=True): flame.PyMarker, dict

Source code in client/ayon_flame/api/lib.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def get_clip_data_marker(clip, with_marker=None):
    """Get data marker from inside of reel clip.

    Wrapper for get_segment_data_marker. Clip has actually also markers
    but it is different object type.

    Attributes:
        clip (flame.PyClip): flame api object
        with_marker (bool)[optional]: if true it will return also marker object

    Returns:
        dict: AYON tag data

    Returns(with_marker=True):
        flame.PyMarker, dict
    """
    segment = get_clip_segment(clip)
    return get_segment_data_marker(
        segment,
        with_marker=with_marker
    )

get_clip_segment(flame_clip)

Get the segment associated to a clip.

Parameters:

Name Type Description Default
flame_clip PyClip

flame api object

required

Returns:

Name Type Description
segment Segment

Segment associated to the clip.

Source code in client/ayon_flame/api/lib.py
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def get_clip_segment(flame_clip):
    """Get the segment associated to a clip.

    Args:
        flame_clip (flame.PyClip): flame api object

    Returns:
        segment (Segment): Segment associated to the clip.
    """
    name = flame_clip.name.get_value()
    version = flame_clip.versions[0]
    track = version.tracks[0]
    segments = track.segments

    if len(segments) < 1:
        raise ValueError("Clip `{}` has no segments!".format(name))

    if len(segments) > 1:
        raise ValueError("Clip `{}` has too many segments!".format(name))

    return segments[0]

get_frame_from_filename(filename)

Return sequence number from Flame path style

Parameters:

Name Type Description Default
filename str

file name

required

Returns:

Name Type Description
int

sequence frame number

Example

def get_frame_from_filename(path): ("plate.0001.exr") > 0001

Source code in client/ayon_flame/api/lib.py
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
def get_frame_from_filename(filename):
    """
    Return sequence number from Flame path style

    Args:
        filename (str): file name

    Returns:
        int: sequence frame number

    Example:
        def get_frame_from_filename(path):
            ("plate.0001.exr") > 0001

    """

    found = re.findall(FRAME_PATTERN, filename)

    return found.pop() if found else None

get_padding_from_filename(filename)

Return padding number from Flame path style

Parameters:

Name Type Description Default
filename str

file name

required

Returns:

Name Type Description
int

padding number

Example

get_padding_from_filename("plate.0001.exr") > 4

Source code in client/ayon_flame/api/lib.py
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
def get_padding_from_filename(filename):
    """
    Return padding number from Flame path style

    Args:
        filename (str): file name

    Returns:
        int: padding number

    Example:
        get_padding_from_filename("plate.0001.exr") > 4

    """
    found = get_frame_from_filename(filename)

    return len(found) if found else None

get_publish_attribute(segment)

Get Publish attribute from input Tag object

Attribute

segment (flame.PySegment)): flame api object

Returns:

Name Type Description
bool

True or False

Source code in client/ayon_flame/api/lib.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
def get_publish_attribute(segment):
    """ Get Publish attribute from input Tag object

    Attribute:
        segment (flame.PySegment)): flame api object

    Returns:
        bool: True or False
    """
    tag_data = get_segment_data_marker(segment)

    if not tag_data:
        set_publish_attribute(segment, MARKER_PUBLISH_DEFAULT)
        return MARKER_PUBLISH_DEFAULT

    return tag_data["active"]

get_reformatted_filename(filename, padded=True)

Return fixed python expression path

Parameters:

Name Type Description Default
filename str

file name

required

Returns:

Name Type Description
type

string with reformatted path

Example

get_reformatted_filename("plate.1001.exr") > plate.%04d.exr

Source code in client/ayon_flame/api/lib.py
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
def get_reformatted_filename(filename, padded=True):
    """
    Return fixed python expression path

    Args:
        filename (str): file name

    Returns:
        type: string with reformatted path

    Example:
        get_reformatted_filename("plate.1001.exr") > plate.%04d.exr

    """
    found = FRAME_PATTERN.search(filename)

    if not found:
        log.info("File name is not sequence: {}".format(filename))
        return filename

    padding = get_padding_from_filename(filename)

    replacement = "%0{}d".format(padding) if padded else "%d"
    start_idx, end_idx = found.span(1)

    return replacement.join(
        [filename[:start_idx], filename[end_idx:]]
    )

get_segment_attributes(segment, validation_aggregator=None)

Get attributes of a segment.

Parameters:

Name Type Description Default
segment Segment

Segment to get attributes from.

required
validation_aggregator ValidationAggregator
Output object to store attributes for passing into
publishing validation. Defaults to None.
None

Returns:

Name Type Description
dict

Dictionary of attributes.

Source code in client/ayon_flame/api/lib.py
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
def get_segment_attributes(
    segment, validation_aggregator: ValidationAggregator = None):
    """Get attributes of a segment.

    Args:
        segment (Segment): Segment to get attributes from.
        validation_aggregator (ValidationAggregator, optional):
                Output object to store attributes for passing into
                publishing validation. Defaults to None.

    Returns:
        dict: Dictionary of attributes.
    """
    if segment.type == "Gap":
        return None

    if not validation_aggregator:
        validation_aggregator = ValidationAggregator()

    segment_name = segment.name.get_value()

    # Add timeline segment to tree
    clip_data = {
        "shot_name": segment.shot_name.get_value(),
        "segment_comment": segment.comment.get_value(),
        "tape_name": segment.tape_name,
        "source_name": segment.source_name,
        "PySegment": segment,
        "segment_name": "",
        "fpath": "",
    }
    # make sure even segments without proper name are handled as missing
    # this way they will be detected by Publisher Validator
    if not segment_name:
        clip_data["segment_name"] = "Missing: Segment's Name"
        if segment not in validation_aggregator.failed_segments:
            validation_aggregator.failed_segments.append(segment)
    else:
        clip_data["segment_name"] = segment_name

    # make sure even segments without file path are handled as missing
    # this way they will be detected by Publisher Validator
    if segment.file_path and segment_name:
        clip_data["fpath"] = segment.file_path
    else:
        clip_data["segment_name"] = "Missing: Segment's File Path"
        if segment not in validation_aggregator.failed_segments:
            validation_aggregator.failed_segments.append(segment)

    # head and tail with forward compatibility
    for key in ("head", "tail"):
        value = getattr(segment, key)
        if value:
            clip_data[f"segment_{key}"] = (
                0 if isinstance(value, str)
                else int(value)
            )

    # add all available shot tokens
    shot_tokens = _get_shot_tokens_values(segment, [
        "<colour space>", "<width>", "<height>", "<depth>", "<segment>",
        "<track>", "<track name>"
    ])
    clip_data.update(shot_tokens)

    # populate shot source metadata
    segment_attrs = [
        "record_duration", "record_in", "record_out",
        "source_in", "source_out", "source_frame_rate", "source_height",
        "source_width", "source_ratio", "start_frame", "head", "tail",
    ]
    segment_attrs_data = {}
    for attr_name in segment_attrs:
        if not hasattr(segment, attr_name):
            continue
        attr = getattr(segment, attr_name)
        segment_attrs_data[attr_name] = str(attr).replace("+", ":")

        if attr_name in ["record_in", "record_out"]:
            clip_data[attr_name] = attr.relative_frame
        else:
            if hasattr(attr, "frame"):
                clip_data[attr_name] = attr.frame

    clip_data["segment_timecodes"] = segment_attrs_data
    return clip_data

get_segment_data_marker(segment, with_marker=None)

Get AYON track item tag created by creator or loader plugin.

Attributes:

Name Type Description
segment PySegment

flame api object

with_marker bool)[optional]

if true it will return also marker object

Returns:

Name Type Description
dict

AYON tag data

Returns(with_marker=True): flame.PyMarker, dict

Source code in client/ayon_flame/api/lib.py
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
def get_segment_data_marker(segment, with_marker=None):
    """Get AYON track item tag created by creator or loader plugin.

    Attributes:
        segment (flame.PySegment): flame api object
        with_marker (bool)[optional]: if true it will return also marker object

    Returns:
        dict: AYON tag data

    Returns(with_marker=True):
        flame.PyMarker, dict
    """
    for marker in segment.markers:
        comment = marker.comment.get_value() or "{}"
        color = marker.colour.get_value()
        name = marker.name.get_value()

        if (
            name == MARKER_NAME
            and color == COLOR_MAP[MARKER_COLOR]
        ):
            if not with_marker:
                return json.loads(comment)
            else:
                return marker, json.loads(comment)
    return None

imprint(item, data=None)

Adding AYON data to Flame timeline segment.

Also including publish attribute into tag.

Parameters:

Name Type Description Default
item PySegment | PyClip

flame api object

required
data dict

Any data which needs to be imprinted

None

Examples:

data = { 'asset': 'sq020sh0280', 'productType': 'render', 'productName': 'productMain' }

Source code in client/ayon_flame/api/pipeline.py
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
def imprint(item, data=None):
    """
    Adding AYON data to Flame timeline segment.

    Also including publish attribute into tag.

    Arguments:
        item (flame.PySegment | flame.PyClip): flame api object
        data (dict): Any data which needs to be imprinted

    Examples:
        data = {
            'asset': 'sq020sh0280',
            'productType': 'render',
            'productName': 'productMain'
        }
    """
    data = data or {}

    if isinstance(item, flame.PySegment):
        set_segment_data_marker(item, data)
    elif isinstance(item, flame.PyClip):
        set_clip_data_marker(item, data)
    else:
        raise TypeError("Unsupported item type: {}".format(type(item)))

list_instances()

List all created instances from current workfile.

Source code in client/ayon_flame/api/pipeline.py
128
129
130
def list_instances():
    """List all created instances from current workfile."""
    log.debug("TODO: list_instances")

load_batch_from_consolidated_json(filepath, name=None, temporary_folder=None)

Load a batch from a consolidated json file.

Source code in client/ayon_flame/api/batch_utils.py
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
def load_batch_from_consolidated_json(
    filepath: str,
    name: Optional[str] = None,
    temporary_folder: Optional[str] = None,
) -> Optional[flame.PyBatch]:
    """ Load a batch from a consolidated json file.
    """
    with open(filepath, "r", encoding="utf-8") as file_:
        data = json.load(file_)

    tmp = tempfile.TemporaryDirectory() if not temporary_folder else None
    tmp_dir = pathlib.Path(tmp.name if tmp else temporary_folder)

    try:
        batch_file = None
        for relative_file, content in data.items():
            file_path = tmp_dir / relative_file
            file_path.parent.mkdir(parents=True, exist_ok=True)
            if content.startswith("__b64__:"):
                file_path.write_bytes(base64.b64decode(content[8:]))
            else:
                file_path.write_text(content, encoding="utf-8")

            if relative_file.endswith(".batch"):
                batch_file = relative_file

        if batch_file is None:
            raise ValueError(
                f"No valid batch found in consolidated json: {filepath}"
            )

        flame.batch.load_setup(str(tmp_dir / batch_file))

        # Restore the batch group name from the provided name
        # or use the .batch filename stem otherwise.
        batch_name = name or pathlib.Path(batch_file).stem
        flame.batch.name = batch_name

        return flame.batch

    finally:
        if tmp is not None:
            tmp.cleanup()

ls()

List available containers.

Source code in client/ayon_flame/api/pipeline.py
105
106
107
108
def ls():
    """List available containers.
    """
    return []  # TODO implement this from metadata

maintained_object_duplication(item)

Maintain input item duplication

Attributes:

Name Type Description
item any flame.PyObject

python api object

Yield

duplicate input PyObject type

Source code in client/ayon_flame/api/lib.py
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
@contextlib.contextmanager
def maintained_object_duplication(item):
    """Maintain input item duplication

    Attributes:
        item (any flame.PyObject): python api object

    Yield:
        duplicate input PyObject type
    """
    import flame
    # Duplicate the clip to avoid modifying the original clip
    duplicate = flame.duplicate(item)

    try:
        # do the operation on selected segments
        yield duplicate
    finally:
        # delete the item at the end
        flame.delete(duplicate)

maintained_segment_selection(sequence)

Maintain selection during context

Attributes:

Name Type Description
sequence PySequence

python api object

Yield

list of flame.PySegment

Example

with maintained_segment_selection(sequence) as selected_segments: ... for segment in selected_segments: ... segment.selected = False assert(segment.selected)

Source code in client/ayon_flame/api/lib.py
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
@contextlib.contextmanager
def maintained_segment_selection(sequence):
    """Maintain selection during context

    Attributes:
        sequence (flame.PySequence): python api object

    Yield:
        list of flame.PySegment

    Example:
        >>> with maintained_segment_selection(sequence) as selected_segments:
        ...     for segment in selected_segments:
        ...         segment.selected = False
        >>> assert(segment.selected)
    """
    selected_segments = get_sequence_segments(sequence, True)
    try:
        # do the operation on selected segments
        yield selected_segments
    finally:
        # reset all selected clips
        reset_segment_selection(sequence)
        # select only original selection of segments
        for segment in selected_segments:
            segment.selected = True

modify_preset_file(xml_path, staging_dir, data)

Modify xml preset with input data

Parameters:

Name Type Description Default
xml_path str

path for input xml preset

required
staging_dir str

staging dir path

required
data dict

data where key is xmlTag and value as string

required

Returns:

Name Type Description
str

path to modified preset file

Source code in client/ayon_flame/api/render_utils.py
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
def modify_preset_file(xml_path, staging_dir, data):
    """Modify xml preset with input data

    Args:
        xml_path (str ): path for input xml preset
        staging_dir (str): staging dir path
        data (dict): data where key is xmlTag and value as string

    Returns:
        str: path to modified preset file
    """
    # create temp path
    _, basename = os.path.split(xml_path)
    temp_path = os.path.join(staging_dir, basename)

    # change xml following data keys
    with open(xml_path, "r") as datafile:
        _root = ET.parse(datafile)

        for key, value in data.items():
            try:
                if "/" in key:
                    if not key.startswith("./"):
                        key = ".//" + key

                    split_key_path = key.split("/")
                    element_key = split_key_path[-1]
                    parent_obj_path = "/".join(split_key_path[:-1])

                    parent_obj = _root.find(parent_obj_path)
                    element_obj = parent_obj.find(element_key)
                    if not element_obj:
                        append_element(parent_obj, element_key, value)
                else:
                    finds = _root.findall(".//{}".format(key))
                    if not finds:
                        raise AttributeError
                    for element in finds:
                        element.text = str(value)
            except AttributeError:
                log.warning(
                    "Cannot create attribute: {}: {}. Skipping".format(
                        key, value
                    ))
        _root.write(temp_path)

    return temp_path

read_node_metadata(node)

Read AYON instance data from a node's note attribute.

Source code in client/ayon_flame/api/batch_utils.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def read_node_metadata(node: flame.PyNode) -> Optional[Dict[str, Any]]:
    """ Read AYON instance data from a node's note attribute.
    """
    try:
        raw = node.note.get_value()
    except Exception:
        return None

    if not raw:
        return None

    try:
        data = json.loads(raw)
    except json.JSONDecodeError:
        return None

    return data if data.get(AYON_NOTE_MARKER) else None

remove_instance(instance)

Remove instance marker from track item.

Source code in client/ayon_flame/api/pipeline.py
123
124
125
def remove_instance(instance):
    """Remove instance marker from track item."""
    log.debug("TODO: remove_instance")

reset_segment_selection(sequence)

Deselect all selected nodes

Source code in client/ayon_flame/api/lib.py
479
480
481
482
483
484
485
486
487
def reset_segment_selection(sequence):
    """Deselect all selected nodes
    """
    for ver in sequence.versions:
        for track in ver.tracks:
            if len(track.segments) == 0 and track.hidden:
                continue
            for segment in track.segments:
                segment.selected = False

save_batch_as_consolidated_json(batch, filepath, temporary_folder=None)

Export batch as a consolidated json file.

Source code in client/ayon_flame/api/batch_utils.py
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
def save_batch_as_consolidated_json(
    batch: flame.PyBatch,
    filepath: str,
    temporary_folder: Optional[str] = None,  # where flame run native export
) -> str:
    """ Export batch as a consolidated json file.
    """
    tmp = tempfile.TemporaryDirectory() if temporary_folder is None else None
    tmp_dir = pathlib.Path(tmp.name if tmp else temporary_folder)

    try:
        batch_name = batch.name.get_value()
        bgroup_file = tmp_dir / f"{batch_name}.batch"
        batch.save_setup(str(bgroup_file))

        if not tmp_dir.is_dir():
            raise RuntimeError(
                f"Unable to save batchgroup to folder: {tmp_dir}."
            )

        # Concatenate all intermediary files as 1 single consolidated JSON.
        # Binary files (e.g. .mx presets are not utf-8) are base64-encoded
        # using a "__b64__:" prefix so we can deserialize them.
        json_output = {}
        for file_path in tmp_dir.rglob("*"):
            if file_path.is_file():
                relative_path = file_path.relative_to(tmp_dir)
                try:
                    content = file_path.read_text(encoding="utf-8")
                except (UnicodeDecodeError, ValueError):
                    content = "__b64__:" + base64.b64encode(
                        file_path.read_bytes()
                    ).decode("ascii")
                json_output[str(relative_path)] = content

        with open(filepath, "w") as file_handler:
            json.dump(json_output, file_handler, indent=4)

    finally:
        # Delete temporary directory if created.
        if tmp is not None:
            tmp.cleanup()

    return filepath

set_clip_data_marker(clip, data=None)

Set AYON track item tag to input clip.

Attributes:

Name Type Description
clip PyClip

flame api object

data dict

json serializable data

Source code in client/ayon_flame/api/lib.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
def set_clip_data_marker(clip, data=None):
    """Set AYON track item tag to input clip.

    Attributes:
        clip (flame.PyClip): flame api object
        data (dict): json serializable data
    """
    data = data or dict()
    segment = get_clip_segment(clip)

    segment_data = data.get("clip_data", {}).pop("PySegment", None)
    if segment_data and segment_data != segment:
        raise ValueError(
            "Ambiguous clip to set marker data to."
            f"Provided clip refers to {segment}, while "
            f"data points toward {segment_data}."
        )

    set_segment_data_marker(segment, data=data)

set_publish_attribute(segment, value)

Set Publish attribute in input Tag object

Attribute

segment (flame.PySegment)): flame api object value (bool): True or False

Source code in client/ayon_flame/api/lib.py
346
347
348
349
350
351
352
353
354
355
356
357
def set_publish_attribute(segment, value):
    """ Set Publish attribute in input Tag object

    Attribute:
        segment (flame.PySegment)): flame api object
        value (bool): True or False
    """
    tag_data = get_segment_data_marker(segment)
    tag_data["active"] = value

    # set data to the active attribute
    set_segment_data_marker(segment, tag_data)

set_segment_data_marker(segment, data=None)

Set AYON track item tag to input segment.

Attributes:

Name Type Description
segment PySegment

flame api object

Source code in client/ayon_flame/api/lib.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def set_segment_data_marker(segment, data=None):
    """Set AYON track item tag to input segment.

    Attributes:
        segment (flame.PySegment): flame api object
    """
    data = data or dict()

    marker_data = get_segment_data_marker(segment, True)

    if marker_data:
        # get available AYON tag if any
        marker, tag_data = marker_data
        # update tag data with new data
        tag_data.update(data)
        # update marker with tag data
        marker.comment = json.dumps(tag_data)
    else:
        # update tag data with new data
        marker = create_segment_data_marker(segment)
        # add tag data to marker's comment
        marker.comment = json.dumps(data)

setup(env=None)

Wrapper installer started from flame/hooks/pre_flame_setup.py

Source code in client/ayon_flame/api/utils.py
116
117
118
119
120
121
122
123
124
125
def setup(env=None):
    """ Wrapper installer started from
    `flame/hooks/pre_flame_setup.py`
    """
    env = env or os.environ

    # synchronize resolve utility scripts
    _sync_utility_scripts(env)

    log.info("Flame AYON wrapper has been installed")

update_batch(batch, name=None, frame_start=None, frame_duration=None, handle_start=0, handle_end=0)

Update provided batch with new values.

Source code in client/ayon_flame/api/batch_utils.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def update_batch(
    batch: flame.PyBatch,
    name: Optional[str] = None,
    frame_start: Optional[int] = None,
    frame_duration: Optional[int] = None,
    handle_start: int = 0,
    handle_end: int = 0,
) -> flame.PyBatch:
    """ Update provided batch with new values.
    """
    if name:
        batch.name = name
    if frame_start is not None:
        batch.start_frame = frame_start - handle_start
    if frame_duration is not None:
        frame_duration += handle_start + handle_end
        batch.duration = frame_duration

    return batch

update_container(tl_segment, data=None)

Update container data to input timeline_item's AYON tag.

Source code in client/ayon_flame/api/pipeline.py
117
118
119
120
def update_container(tl_segment, data=None):
    """Update container data to input timeline_item's AYON tag.
    """
    log.debug("TODO: update_container")

write_node_metadata(node, data)

Write AYON instance data into a node's note attribute.

Source code in client/ayon_flame/api/batch_utils.py
38
39
40
41
42
43
def write_node_metadata(node: flame.PyNode, data: Dict[str, Any]):
    """ Write AYON instance data into a node's note attribute."""
    payload = dict(data)
    payload[AYON_NOTE_MARKER] = True
    node.note = json.dumps(payload)
    node.note_collapsed = True