|
| 1 | +"""Base classes and mixins for Project Workflow nodes in Labelbox.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +import random |
| 5 | +import string |
| 6 | +from typing import Dict, List, Any, Optional |
| 7 | +from abc import abstractmethod |
| 8 | +from pydantic import BaseModel, Field, ConfigDict |
| 9 | + |
| 10 | +from labelbox.schema.workflow.enums import WorkflowDefinitionId, NodeOutput |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +def format_time_duration(seconds: int) -> str: |
| 16 | + """Convert seconds to human-readable time format. |
| 17 | +
|
| 18 | + Args: |
| 19 | + seconds: Time duration in seconds |
| 20 | +
|
| 21 | + Returns: |
| 22 | + Human-readable time string (e.g., "1h 30m", "5m 30s", "45s") |
| 23 | + """ |
| 24 | + if seconds >= 3600: # >= 1 hour |
| 25 | + hours = seconds // 3600 |
| 26 | + if seconds % 3600 == 0: |
| 27 | + return f"{hours}h" |
| 28 | + else: |
| 29 | + minutes = (seconds % 3600) // 60 |
| 30 | + if minutes == 0: |
| 31 | + return f"{hours}h" |
| 32 | + else: |
| 33 | + return f"{hours}h {minutes}m" |
| 34 | + elif seconds >= 60: # >= 1 minute |
| 35 | + minutes = seconds // 60 |
| 36 | + if seconds % 60 == 0: |
| 37 | + return f"{minutes}m" |
| 38 | + else: |
| 39 | + return f"{minutes}m {seconds % 60}s" |
| 40 | + else: |
| 41 | + return f"{seconds}s" |
| 42 | + |
| 43 | + |
| 44 | +def format_metadata_operator(operator: str) -> tuple[str, str]: |
| 45 | + """Format metadata operator for display and JSON. |
| 46 | +
|
| 47 | + Args: |
| 48 | + operator: Raw operator string |
| 49 | +
|
| 50 | + Returns: |
| 51 | + Tuple of (display_operator, json_operator) |
| 52 | + """ |
| 53 | + operator_mappings = { |
| 54 | + "contains": ("CONTAINS", "contains"), |
| 55 | + "contain": ("CONTAINS", "contains"), |
| 56 | + "does_not_contain": ("DOES NOT CONTAIN", "does_not_contain"), |
| 57 | + "startswith": ("STARTS WITH", "starts_with"), |
| 58 | + "starts_with": ("STARTS WITH", "starts_with"), |
| 59 | + "start": ("STARTS WITH", "starts_with"), |
| 60 | + "endswith": ("ENDS WITH", "ends_with"), |
| 61 | + "ends_with": ("ENDS WITH", "ends_with"), |
| 62 | + "end": ("ENDS WITH", "ends_with"), |
| 63 | + "is_any": ("IS ANY", "is_any"), |
| 64 | + "is_not_any": ("IS NOT ANY", "is_not_any"), |
| 65 | + } |
| 66 | + |
| 67 | + return operator_mappings.get(operator, (operator.upper(), operator)) |
| 68 | + |
| 69 | + |
| 70 | +def generate_filter_id() -> str: |
| 71 | + """Generate a unique filter ID for metadata filters.""" |
| 72 | + return "".join(random.choices(string.ascii_lowercase + string.digits, k=6)) |
| 73 | + |
| 74 | + |
| 75 | +class NodePosition(BaseModel): |
| 76 | + """Represents the position of a node in the workflow canvas.""" |
| 77 | + |
| 78 | + x: float = Field(default=0.0, description="X coordinate") |
| 79 | + y: float = Field(default=0.0, description="Y coordinate") |
| 80 | + |
| 81 | + |
| 82 | +class InstructionsMixin: |
| 83 | + """Mixin to handle instructions syncing with custom_fields.description.""" |
| 84 | + |
| 85 | + def sync_instructions_with_custom_fields(self): |
| 86 | + """Sync instructions with customFields.description.""" |
| 87 | + # First, try to load instructions from customFields.description if not already set |
| 88 | + instructions = getattr(self, "instructions", None) |
| 89 | + custom_fields = getattr(self, "custom_fields", None) |
| 90 | + |
| 91 | + if ( |
| 92 | + instructions is None |
| 93 | + and custom_fields |
| 94 | + and "description" in custom_fields |
| 95 | + ): |
| 96 | + # Use object.__setattr__ to bypass the frozen field restriction |
| 97 | + object.__setattr__( |
| 98 | + self, "instructions", custom_fields["description"] |
| 99 | + ) |
| 100 | + |
| 101 | + # Then sync instructions to customFields if instructions is set |
| 102 | + instructions = getattr(self, "instructions", None) |
| 103 | + if instructions is not None: |
| 104 | + custom_fields = getattr(self, "custom_fields", None) |
| 105 | + if custom_fields is None: |
| 106 | + object.__setattr__(self, "custom_fields", {}) |
| 107 | + custom_fields = getattr(self, "custom_fields") |
| 108 | + custom_fields["description"] = instructions |
| 109 | + return self |
| 110 | + |
| 111 | + |
| 112 | +class WorkflowSyncMixin: |
| 113 | + """Mixin to handle syncing node changes back to workflow config.""" |
| 114 | + |
| 115 | + def _sync_to_workflow(self) -> None: |
| 116 | + """Sync node properties to the workflow config.""" |
| 117 | + workflow = getattr(self, "raw_data", {}).get("_workflow") |
| 118 | + if workflow and hasattr(workflow, "config"): |
| 119 | + for node_data in workflow.config.get("nodes", []): |
| 120 | + if node_data.get("id") == getattr(self, "id", None): |
| 121 | + # Update label |
| 122 | + if hasattr(self, "label"): |
| 123 | + node_data["label"] = getattr(self, "label") |
| 124 | + # Update instructions via customFields |
| 125 | + instructions = getattr(self, "instructions", None) |
| 126 | + if instructions is not None: |
| 127 | + if "customFields" not in node_data: |
| 128 | + node_data["customFields"] = {} |
| 129 | + node_data["customFields"]["description"] = instructions |
| 130 | + # Update customFields |
| 131 | + custom_fields = getattr(self, "custom_fields", None) |
| 132 | + if custom_fields: |
| 133 | + node_data["customFields"] = custom_fields |
| 134 | + # Update filters if present |
| 135 | + filters = getattr(self, "filters", None) |
| 136 | + if filters: |
| 137 | + node_data["filters"] = filters |
| 138 | + # Update config if present |
| 139 | + node_config = getattr(self, "node_config", None) |
| 140 | + if node_config: |
| 141 | + node_data["config"] = node_config |
| 142 | + break |
| 143 | + |
| 144 | + def sync_property_change(self, property_name: str) -> None: |
| 145 | + """Handle property changes that need workflow syncing.""" |
| 146 | + if property_name == "instructions" and hasattr(self, "id"): |
| 147 | + # Also update custom_fields on the node object itself |
| 148 | + instructions = getattr(self, "instructions", None) |
| 149 | + if instructions is not None: |
| 150 | + custom_fields = getattr(self, "custom_fields", None) |
| 151 | + if custom_fields is None: |
| 152 | + object.__setattr__(self, "custom_fields", {}) |
| 153 | + custom_fields = getattr(self, "custom_fields") |
| 154 | + custom_fields["description"] = instructions |
| 155 | + self._sync_to_workflow() |
| 156 | + |
| 157 | + |
| 158 | +class BaseWorkflowNode(BaseModel, InstructionsMixin, WorkflowSyncMixin): |
| 159 | + """Base class for all workflow nodes with common functionality.""" |
| 160 | + |
| 161 | + id: str = Field(description="Unique identifier for the node") |
| 162 | + position: NodePosition = Field( |
| 163 | + default_factory=NodePosition, description="Node position on canvas" |
| 164 | + ) |
| 165 | + definition_id: WorkflowDefinitionId = Field( |
| 166 | + alias="definitionId", description="Type of workflow node" |
| 167 | + ) |
| 168 | + inputs: List[str] = Field( |
| 169 | + default_factory=lambda: [], description="List of input node IDs" |
| 170 | + ) |
| 171 | + output_if: Optional[str] = Field( |
| 172 | + default=None, description="ID of node connected to 'if' output" |
| 173 | + ) |
| 174 | + output_else: Optional[str] = Field( |
| 175 | + default=None, description="ID of node connected to 'else' output" |
| 176 | + ) |
| 177 | + raw_data: Dict[str, Any] = Field( |
| 178 | + default_factory=dict, description="Raw configuration data" |
| 179 | + ) |
| 180 | + |
| 181 | + model_config = ConfigDict( |
| 182 | + populate_by_name=True, |
| 183 | + arbitrary_types_allowed=True, |
| 184 | + extra="forbid", |
| 185 | + ) |
| 186 | + |
| 187 | + def __init__(self, **data): |
| 188 | + super().__init__(**data) |
| 189 | + # Sync instructions after initialization |
| 190 | + self.sync_instructions_with_custom_fields() |
| 191 | + |
| 192 | + @property |
| 193 | + @abstractmethod |
| 194 | + def supported_outputs(self) -> List[NodeOutput]: |
| 195 | + """Returns the list of supported output types for this node.""" |
| 196 | + pass |
| 197 | + |
| 198 | + @property |
| 199 | + def name(self) -> Optional[str]: |
| 200 | + """Get the node's name (label).""" |
| 201 | + return getattr(self, "label", None) or self.raw_data.get("label") |
| 202 | + |
| 203 | + @name.setter |
| 204 | + def name(self, value: str) -> None: |
| 205 | + """Set the node's name (updates label).""" |
| 206 | + if hasattr(self, "label"): |
| 207 | + object.__setattr__(self, "label", value) |
| 208 | + self._sync_to_workflow() |
| 209 | + |
| 210 | + def __setattr__(self, name: str, value) -> None: |
| 211 | + """Override setattr to sync property changes to workflow.""" |
| 212 | + super().__setattr__(name, value) |
| 213 | + # Sync changes to workflow for important properties |
| 214 | + if name in ["instructions", "label"] and hasattr(self, "id"): |
| 215 | + self.sync_property_change(name) |
0 commit comments