generated from specklesystems/speckle_automate_python_example
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
80 lines (60 loc) · 2.74 KB
/
main.py
1
2
3
4
5
6
7
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import random
from pydantic import Field
from speckle_automate import AutomationContext, AutomateBase, execute_automate_function
from Utilities.helpers import flatten_base
class FunctionInputs(AutomateBase):
"""These are function author defined values.
Automate will make sure to supply them matching the types specified here.
Please use the pydantic model schema to define your inputs:
https://docs.pydantic.dev/latest/usage/models/
"""
comment_phrase: str = Field(
title="Comment Phrase",
description="This phrase will be added to a random model element.",
)
def automate_function(
automate_context: AutomationContext,
function_inputs: FunctionInputs,
) -> None:
"""This is an example Speckle Automate function.
Args:
automate_context: A context helper object, that carries relevant information
about the runtime context of this function.
It gives access to the Speckle project data, that triggered this run.
It also has convenience methods attach result data to the Speckle model.
function_inputs: An instance object matching the defined schema.
"""
# the context provides a convenient way, to receive the triggering version
version_root_object = automate_context.receive_version()
flat_list_of_objects = flatten_base(version_root_object)
# filter the list to only include objects that are displayable.
# this is a simple example, that checks if the object has a displayValue
displayable_objects = [
speckle_object
for speckle_object in flat_list_of_objects
if (
getattr(speckle_object, "displayValue", None)
or getattr(speckle_object, "@displayValue", None)
)
and getattr(speckle_object, "id", None) is not None
]
if len(displayable_objects) == 0:
automate_context.mark_run_failed(
"Automation failed: No displayable objects found."
)
else:
# select a random object from the list
random_object = random.choice(displayable_objects)
automate_context.attach_info_to_objects(
category="Selected Object",
object_ids=[random_object.id],
message=function_inputs.comment_phrase,
)
automate_context.mark_run_success("Added a comment to a random object.")
# set the automation context view, to the original model / version view
automate_context.set_context_view()
# make sure to call the function with the executor
if __name__ == "__main__":
# NOTE: always pass in the automate function by its reference, do not invoke it!
# pass in the function reference with the inputs schema to the executor
execute_automate_function(automate_function, FunctionInputs)