66 lines
2.4 KiB
Python
66 lines
2.4 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Convert to Percent Node
|
|
|
|
This node takes two numerical inputs (A and B), computes (A / B) * 100,
|
|
and outputs the result as a float formatted to 4 decimal places. If an error
|
|
occurs, an error message is stored. The node's title is always "Convert to Percent".
|
|
"""
|
|
|
|
from NodeGraphQt import BaseNode
|
|
from Qt import QtCore
|
|
|
|
class ConvertToPercentNode(BaseNode):
|
|
__identifier__ = 'io.github.nicole.convert'
|
|
NODE_NAME = 'Convert to Percent'
|
|
|
|
def __init__(self):
|
|
super(ConvertToPercentNode, self).__init__()
|
|
# Add two input ports for separate numerator and denominator.
|
|
self.add_input("Numerator")
|
|
self.add_input("Denominator")
|
|
# Add one output port.
|
|
self.add_output("Percent")
|
|
# Initialize internal value.
|
|
self.value = "No Input"
|
|
# Set the node title to a static string.
|
|
self.set_name(self.NODE_NAME)
|
|
# Initialize a values dictionary so that connected Display nodes can read output.
|
|
self.values = {}
|
|
|
|
def process_input(self):
|
|
numerator_input = self.input(0)
|
|
denominator_input = self.input(1)
|
|
|
|
numerator = self.get_connected_value(numerator_input)
|
|
denominator = self.get_connected_value(denominator_input)
|
|
|
|
try:
|
|
numerator = float(numerator)
|
|
denominator = float(denominator)
|
|
if denominator == 0:
|
|
raise ZeroDivisionError("Division by zero")
|
|
percent = (numerator / denominator) * 100
|
|
formatted_percent = f"{percent:.4f}"
|
|
self.value = formatted_percent
|
|
except Exception as e:
|
|
self.value = f"Error: {e}"
|
|
|
|
# Always keep the title static.
|
|
self.set_name(self.NODE_NAME)
|
|
# Store the computed value in the values dictionary under the output port key.
|
|
self.values["Percent"] = self.value
|
|
|
|
def get_connected_value(self, input_port):
|
|
"""
|
|
Helper function to retrieve the value from a connected port.
|
|
"""
|
|
if input_port and input_port.connected_ports():
|
|
connected_output = input_port.connected_ports()[0]
|
|
parent_node = connected_output.node()
|
|
port_name = connected_output.name()
|
|
if hasattr(parent_node, 'values') and isinstance(parent_node.values, dict):
|
|
return parent_node.values.get(port_name, "0")
|
|
return getattr(parent_node, 'value', "0")
|
|
return "0"
|