Skip to content

collect_workfile_data

CollectWorkfileData

Bases: ContextPlugin

Source code in client/ayon_tvpaint/plugins/publish/collect_workfile_data.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
class CollectWorkfileData(pyblish.api.ContextPlugin):
    label = "Collect Workfile Data"
    order = pyblish.api.CollectorOrder - 0.45
    hosts = ["tvpaint"]
    actions = [ResetTVPaintWorkfileMetadata]

    settings_category = "tvpaint"

    def process(self, context):
        current_project_id = execute_george("tv_projectcurrentid")
        execute_george("tv_projectselect {}".format(current_project_id))

        # Collect and store current context to have reference
        current_context = {
            "project_name": context.data["projectName"],
            "folder_path": context.data["folderPath"],
            "task_name": context.data["task"]
        }
        self.log.debug("Current context is: {}".format(current_context))

        # Collect context from workfile metadata
        self.log.info("Collecting workfile context")

        workfile_context = get_current_workfile_context()
        if "project" in workfile_context:
            workfile_context = {
                "project_name": workfile_context.get("project"),
                "folder_path": workfile_context.get("asset"),
                "task_name": workfile_context.get("task"),
            }
        # Store workfile context to pyblish context
        context.data["workfile_context"] = workfile_context
        if workfile_context:
            # Change current context with context from workfile
            key_map = (
                ("AYON_FOLDER_PATH", "folder_path"),
                ("AYON_TASK_NAME", "task_name")
            )
            for env_key, key in key_map:
                os.environ[env_key] = workfile_context[key]
            self.log.info("Context changed to: {}".format(workfile_context))

            folder_path = workfile_context["folder_path"]
            task_name = workfile_context["task_name"]

        else:
            folder_path = current_context["folder_path"]
            task_name = current_context["task_name"]
            # Handle older workfiles or workfiles without metadata
            self.log.warning((
                "Workfile does not contain information about context."
                " Using current Session context."
            ))

        # Store context folder path
        context.data["folderPath"] = folder_path
        context.data["task"] = task_name
        self.log.info(
            "Context is set to Folder: \"{}\" and Task: \"{}\"".format(
                folder_path, task_name
            )
        )

        # Collect instances
        self.log.info("Collecting instance data from workfile")
        instance_data = list_instances()
        context.data["workfileInstances"] = instance_data
        self.log.debug(
            "Instance data:\"{}".format(json.dumps(instance_data, indent=4))
        )

        # Collect information about layers
        self.log.info("Collecting layers data from workfile")
        layers_data = get_layers_data()
        layers_by_name = {}
        for layer in layers_data:
            layer_name = layer["name"]
            if layer_name not in layers_by_name:
                layers_by_name[layer_name] = []
            layers_by_name[layer_name].append(layer)
        context.data["layersData"] = layers_data
        context.data["layersByName"] = layers_by_name

        self.log.debug(
            "Layers data:\"{}".format(json.dumps(layers_data, indent=4))
        )

        # Collect information about groups
        self.log.info("Collecting groups data from workfile")
        group_data = get_groups_data()
        context.data["groupsData"] = group_data
        self.log.debug(
            "Group data:\"{}".format(json.dumps(group_data, indent=4))
        )

        self.log.info("Collecting scene data from workfile")
        workfile_info_parts = execute_george("tv_projectinfo").split(" ")

        # Project frame start - not used
        workfile_info_parts.pop(-1)
        field_order = workfile_info_parts.pop(-1)
        frame_rate = float(workfile_info_parts.pop(-1))
        pixel_apsect = float(workfile_info_parts.pop(-1))
        height = int(workfile_info_parts.pop(-1))
        width = int(workfile_info_parts.pop(-1))
        workfile_path = " ".join(workfile_info_parts).replace("\"", "")

        # Marks return as "{frame - 1} {state} ", example "0 set".
        result = execute_george("tv_markin")
        mark_in_frame, mark_in_state, _ = result.split(" ")

        result = execute_george("tv_markout")
        mark_out_frame, mark_out_state, _ = result.split(" ")

        current_scene_id = execute_george("tv_scenecurrentid")
        scene_index = 0
        while True:
            scene_id = execute_george(f"tv_sceneenumid {scene_index}")
            if scene_id == "none":
                raise PublishError(
                    "Current scene was not found in workfile."
                )

            if scene_id == current_scene_id:
                break
            scene_index += 1

        current_clip_id = execute_george("tv_clipcurrentid")
        clip_index = 0
        while True:
            clip_id = execute_george(
                f"tv_clipenumid {current_scene_id} {clip_index}"
            )
            if clip_id == "none":
                raise PublishError(
                    "Current clip was not found in scene."
                )

            if clip_id == current_clip_id:
                break
            clip_index += 1

        scene_data = {
            "currentFile": workfile_path,
            "sceneWidth": width,
            "sceneHeight": height,
            "scenePixelAspect": pixel_apsect,
            "sceneFps": frame_rate,
            "sceneFieldOrder": field_order,
            "sceneMarkIn": int(mark_in_frame),
            "sceneMarkInState": mark_in_state == "set",
            "sceneMarkOut": int(mark_out_frame),
            "sceneMarkOutState": mark_out_state == "set",
            "sceneStartFrame": int(execute_george("tv_startframe")),
            "sceneBgColor": self._get_bg_color(),
            "sceneSceneIdx": scene_index,
            "sceneClipIdx": clip_index,
        }
        self.log.debug(
            "Scene data: {}".format(json.dumps(scene_data, indent=4))
        )
        context.data.update(scene_data)

    def _get_bg_color(self):
        """Background color set on scene.

        Is important for review exporting where scene bg color is used as
        background.
        """
        output_file = tempfile.NamedTemporaryFile(
            mode="w", prefix="a_tvp_", suffix=".txt", delete=False
        )
        output_file.close()
        output_filepath = output_file.name.replace("\\", "/")
        george_script_lines = [
            # Variable containing full path to output file
            "output_path = \"{}\"".format(output_filepath),
            "tv_background",
            "bg_color = result",
            # Write data to output file
            (
                "tv_writetextfile"
                " \"strict\" \"append\" '\"'output_path'\"' bg_color"
            )
        ]

        george_script = "\n".join(george_script_lines)
        execute_george_through_file(george_script)

        with open(output_filepath, "r") as stream:
            data = stream.read()

        os.remove(output_filepath)
        data = data.strip()
        if not data:
            return None
        return data.split(" ")

ResetTVPaintWorkfileMetadata

Bases: Action

Fix invalid metadata in workfile.

Source code in client/ayon_tvpaint/plugins/publish/collect_workfile_data.py
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
class ResetTVPaintWorkfileMetadata(pyblish.api.Action):
    """Fix invalid metadata in workfile."""
    label = "Reset invalid workfile metadata"
    on = "failed"

    def process(self, context, plugin):
        metadata_keys = {
            SECTION_NAME_CONTEXT: {},
            SECTION_NAME_INSTANCES: [],
            SECTION_NAME_CONTAINERS: []
        }
        for metadata_key, default in metadata_keys.items():
            json_string = get_workfile_metadata_string(metadata_key)
            if not json_string:
                continue

            try:
                return json.loads(json_string)
            except Exception:
                self.log.warning(
                    (
                        "Couldn't parse metadata from key \"{}\"."
                        " Will reset to default value \"{}\"."
                        " Loaded value was: {}"
                    ).format(metadata_key, default, json_string),
                    exc_info=True
                )
                write_workfile_metadata(metadata_key, default)