Skip to content

Commit f826058

Browse files
committed
fix(sentence): serialize RecognizeResult for JSON compatibility
Fixes #327
1 parent a3fe116 commit f826058

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

custom_components/nodered/sentence.py

+36-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import logging
44
from typing import Any
55

6+
from hassil.expression import Sentence
67
from hassil.recognize import RecognizeResult
78
from homeassistant.components.conversation.default_agent import (
89
DATA_DEFAULT_ENTITY,
@@ -71,14 +72,17 @@ async def handle_trigger(
7172
device_id was added in 2024.4.0
7273
"""
7374

75+
# RecognizeResult in 2024.12 is not serializable, so we need to convert it to a serializable format
76+
serialized = convert_recognize_result_to_dict(result)
77+
7478
_LOGGER.debug(f"Sentence trigger: {sentence}")
7579
connection.send_message(
7680
event_message(
7781
message_id,
7882
{
7983
"data": {
8084
"sentence": sentence,
81-
"result": result,
85+
"result": serialized,
8286
"deviceId": device_id,
8387
"responseId": message_id,
8488
}
@@ -174,3 +178,34 @@ async def websocket_sentence_response(
174178
connection.send_message(
175179
error_message(message_id, "sentence_response_not_found", message),
176180
)
181+
182+
183+
def convert_recognize_result_to_dict(result: Any) -> dict:
184+
"""
185+
Serializes a RecognizeResult object into a JSON-serializable dictionary.
186+
"""
187+
188+
def serialize(obj):
189+
if isinstance(obj, Sentence):
190+
# Custom serialization for Sentence
191+
return {
192+
"text": obj.text,
193+
"pattern": obj.pattern.pattern if obj.pattern else None,
194+
}
195+
elif hasattr(obj, "__dict__"):
196+
# For objects with attributes, serialize attributes
197+
return {key: serialize(value) for key, value in vars(obj).items()}
198+
elif isinstance(obj, list):
199+
# Recursively handle lists
200+
return [serialize(item) for item in obj]
201+
elif isinstance(obj, dict):
202+
# Recursively handle dictionaries
203+
return {key: serialize(value) for key, value in obj.items()}
204+
elif isinstance(obj, (int, float, str, type(None))):
205+
# Primitive types are already serializable
206+
return obj
207+
else:
208+
# Fallback for non-serializable types
209+
return str(obj)
210+
211+
return serialize(result)

0 commit comments

Comments
 (0)