forked from Kazuhito00/Image-Processing-Node-Editor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_word_cloud.py
More file actions
405 lines (348 loc) · 16 KB
/
Copy pathnode_word_cloud.py
File metadata and controls
405 lines (348 loc) · 16 KB
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
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Word Cloud – visual node that renders a word cloud from VLM text output.
Takes the JSON output of the VLM node (``{"TEXT": "...", "type": "..."}``) and
produces a beautiful word-cloud image. The image is also forwarded as a JSON
output so it can be wired into a Concat node.
Colourmap options:
viridis, plasma, inferno, magma, cool, hot, rainbow, ocean
The node also exposes a ``max_words`` slider (10 – 200) to control density.
"""
import re
import io
import time
import cv2
import numpy as np
import dearpygui.dearpygui as dpg
from PIL import Image
from wordcloud import WordCloud, STOPWORDS
from node_editor.util import dpg_get_value, dpg_set_value
from node.basenode import Node as BaseNode
# ── Canvas dimensions ─────────────────────────────────────────────────────
CANVAS_W = 480
CANVAS_H = 320
# ── Colourmaps available ──────────────────────────────────────────────────
COLOURMAPS = [
'viridis', 'plasma', 'inferno', 'magma',
'cool', 'hot', 'rainbow', 'ocean',
]
DEFAULT_COLOURMAP = 'plasma'
DEFAULT_MAX_WORDS = 80
DEFAULT_DELTA_T = 30 # seconds – rolling time window for word accumulation
# ── Colour pairs (background, fallback text) per colourmap ───────────────
_BG_COLOUR = {
'viridis': (15, 15, 30),
'plasma': (10, 5, 25),
'inferno': (10, 5, 10),
'magma': (10, 8, 12),
'cool': (5, 20, 30),
'hot': (20, 5, 5),
'rainbow': (10, 10, 10),
'ocean': (5, 15, 25),
}
# ── Helper functions ──────────────────────────────────────────────────────
def _clean_text(text):
"""Remove Florence2 task tokens and normalise the text."""
# Remove <TOKEN> style markers
text = re.sub(r'<[A-Z_]+>', ' ', text)
# Remove stray punctuation runs, keep alphanumeric + apostrophe + hyphen
text = re.sub(r"[^a-zA-ZÀ-ÿ0-9' \-]", ' ', text)
return text.strip()
def _render_word_cloud(text, colourmap=DEFAULT_COLOURMAP, max_words=DEFAULT_MAX_WORDS,
width=CANVAS_W, height=CANVAS_H):
"""Render a word cloud from *text* and return a BGR uint8 numpy array.
Parameters
----------
text : str
Raw text (e.g. from VLM JSON "TEXT" field).
colourmap : str
Matplotlib colourmap name used to colour words.
max_words : int
Maximum number of words rendered.
width, height : int
Output image dimensions.
Returns
-------
numpy.ndarray
BGR uint8 image.
"""
bg_rgb = _BG_COLOUR.get(colourmap, (10, 10, 10))
bg_hex = '#{:02x}{:02x}{:02x}'.format(*bg_rgb)
cleaned = _clean_text(text)
if not cleaned:
# Nothing to display – return a dark placeholder.
# bg_rgb is stored as (R, G, B); np.full needs BGR order for OpenCV.
canvas = np.full((height, width, 3), bg_rgb[::-1], dtype=np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX
msg = 'Waiting for text...'
(tw, th), _ = cv2.getTextSize(msg, font, 0.7, 1)
cv2.putText(
canvas, msg,
((width - tw) // 2, (height + th) // 2),
font, 0.7, (180, 180, 180), 1, cv2.LINE_AA,
)
return canvas
wc = WordCloud(
width=width,
height=height,
background_color=bg_hex,
colormap=colourmap,
max_words=max_words,
stopwords=STOPWORDS,
prefer_horizontal=0.85,
min_font_size=10,
max_font_size=None,
relative_scaling=0.5,
collocations=False,
margin=6,
).generate(cleaned)
# Convert PIL Image (RGB) → numpy array → BGR
pil_img = wc.to_image()
bgr = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
return bgr
def _render_blank(width=CANVAS_W, height=CANVAS_H):
"""Return a dark placeholder canvas."""
return np.zeros((height, width, 3), dtype=np.uint8)
# ── DearPyGui Factory ─────────────────────────────────────────────────────
class FactoryNode:
node_label = 'Word Cloud'
node_tag = 'WordCloud'
def __init__(self):
pass
def add_node(
self, parent, node_id, pos=[0, 0],
callback=None, opencv_setting_dict=None,
):
node = WordCloudNode()
node.tag_node_name = '{}:{}'.format(node_id, node.node_tag)
tag_node_name = node.tag_node_name
# ── Input – JSON from VLM ─────────────────────────────────────
node.tag_node_input_json_name = (
tag_node_name + ':' + node.TYPE_JSON + ':InputJson'
)
node.tag_node_input_json_value_name = (
tag_node_name + ':' + node.TYPE_JSON + ':InputJsonValue'
)
# ── Outputs ───────────────────────────────────────────────────
node.tag_node_output_image_name = (
tag_node_name + ':' + node.TYPE_IMAGE + ':OutputImage'
)
node.tag_node_output_image_value_name = (
tag_node_name + ':' + node.TYPE_IMAGE + ':OutputImageValue'
)
node.tag_node_output_json_name = (
tag_node_name + ':' + node.TYPE_JSON + ':OutputJson'
)
node.tag_node_output_json_value_name = (
tag_node_name + ':' + node.TYPE_JSON + ':OutputJsonValue'
)
# ── Static widget tags ────────────────────────────────────────
tag_colourmap_name = tag_node_name + ':Colourmap'
tag_colourmap_value = tag_node_name + ':ColourmapValue'
tag_max_words_name = tag_node_name + ':MaxWords'
tag_max_words_value = tag_node_name + ':MaxWordsValue'
tag_delta_t_name = tag_node_name + ':DeltaT'
tag_delta_t_value = tag_node_name + ':DeltaTValue'
node._opencv_setting_dict = opencv_setting_dict or {}
# Initial blank texture
blank = _render_blank(CANVAS_W, CANVAS_H)
blank_tex = node.convert_cv_to_dpg(blank, CANVAS_W, CANVAS_H)
with dpg.texture_registry(show=False):
dpg.add_raw_texture(
CANVAS_W,
CANVAS_H,
blank_tex,
tag=node.tag_node_output_image_value_name,
format=dpg.mvFormat_Float_rgb,
)
with dpg.node(
tag=tag_node_name, parent=parent,
label=node.node_label, pos=pos,
):
# ── JSON input ────────────────────────────────────────────
with dpg.node_attribute(
tag=node.tag_node_input_json_name,
attribute_type=dpg.mvNode_Attr_Input,
):
dpg.add_text(
tag=node.tag_node_input_json_value_name,
default_value='VLM JSON',
)
# ── Colourmap combo ───────────────────────────────────────
with dpg.node_attribute(
tag=tag_colourmap_name,
attribute_type=dpg.mvNode_Attr_Static,
):
dpg.add_combo(
tag=tag_colourmap_value,
items=COLOURMAPS,
default_value=DEFAULT_COLOURMAP,
width=240,
label='Colourmap',
)
# ── Max words slider ──────────────────────────────────────
with dpg.node_attribute(
tag=tag_max_words_name,
attribute_type=dpg.mvNode_Attr_Static,
):
dpg.add_slider_int(
tag=tag_max_words_value,
default_value=DEFAULT_MAX_WORDS,
min_value=10,
max_value=200,
width=240,
label='Max words',
)
# ── Delta T slider (rolling time window in seconds) ───────
with dpg.node_attribute(
tag=tag_delta_t_name,
attribute_type=dpg.mvNode_Attr_Static,
):
dpg.add_slider_int(
tag=tag_delta_t_value,
default_value=DEFAULT_DELTA_T,
min_value=5,
max_value=300,
width=240,
label='ΔT (s)',
)
# ── Image output ──────────────────────────────────────────
with dpg.node_attribute(
tag=node.tag_node_output_image_name,
attribute_type=dpg.mvNode_Attr_Output,
):
dpg.add_image(node.tag_node_output_image_value_name)
# ── JSON output (text for Concat) ─────────────────────────
with dpg.node_attribute(
tag=node.tag_node_output_json_name,
attribute_type=dpg.mvNode_Attr_Output,
):
dpg.add_button(
tag=node.tag_node_output_json_value_name,
label='Text →',
width=240,
enabled=False,
)
return node
# ── Node logic ─────────────────────────────────────────────────────────────
class WordCloudNode(BaseNode):
_ver = '0.0.1'
def __init__(self):
super().__init__()
self.node_label = 'Word Cloud'
self.node_tag = 'WordCloud'
self._last_frame = None
self._last_colourmap = DEFAULT_COLOURMAP
self._last_max_words = DEFAULT_MAX_WORDS
self._last_delta_t = DEFAULT_DELTA_T
# Rolling buffer: list of (timestamp, text) pairs
self._text_buffer = []
# Track last text appended to buffer to avoid duplicate entries
self._last_appended_text = ''
# Combined text used for the last render (to detect changes)
self._last_combined_text = ''
def update(
self, node_id, connection_list, node_image_dict,
node_result_dict, node_audio_dict,
):
tag_node_name = '{}:{}'.format(node_id, self.node_tag)
output_tex_tag = '{}:{}:OutputImageValue'.format(
tag_node_name, self.TYPE_IMAGE,
)
tag_colourmap_value = tag_node_name + ':ColourmapValue'
tag_max_words_value = tag_node_name + ':MaxWordsValue'
# ── Retrieve connected JSON ───────────────────────────────────
input_json = {}
for connection_info in connection_list:
parts = connection_info[0].split(':')
if len(parts) < 3:
continue
connection_type = parts[2]
target = connection_info[1]
if connection_type == self.TYPE_JSON and 'InputJson' in target:
src_key = ':'.join(parts[:2])
input_json = node_result_dict.get(src_key, {})
break
# ── Extract text from JSON ────────────────────────────────────
text = ''
if isinstance(input_json, dict):
text = str(input_json.get('TEXT', ''))
elif isinstance(input_json, str):
text = input_json
# ── Read UI settings ──────────────────────────────────────────
colourmap = dpg_get_value(tag_colourmap_value) or DEFAULT_COLOURMAP
try:
max_words = int(dpg_get_value(tag_max_words_value))
except (ValueError, TypeError):
max_words = DEFAULT_MAX_WORDS
tag_delta_t_value = tag_node_name + ':DeltaTValue'
try:
delta_t = int(dpg_get_value(tag_delta_t_value))
if delta_t < 1:
delta_t = DEFAULT_DELTA_T
except (ValueError, TypeError):
delta_t = DEFAULT_DELTA_T
# ── Update rolling text buffer ────────────────────────────────
now = time.time()
# Append text to buffer when it changes (new observation)
if text and text != self._last_appended_text:
self._text_buffer.append((now, text))
self._last_appended_text = text
# Prune entries older than delta_t
cutoff = now - delta_t
self._text_buffer = [
(ts, txt) for ts, txt in self._text_buffer if ts >= cutoff
]
# Build combined text from the rolling window
combined = ' '.join(txt for _, txt in self._text_buffer)
# ── Regenerate only when something changed ────────────────────
changed = (
combined != self._last_combined_text
or colourmap != self._last_colourmap
or max_words != self._last_max_words
or delta_t != self._last_delta_t
)
if changed or self._last_frame is None:
self._last_combined_text = combined
self._last_colourmap = colourmap
self._last_max_words = max_words
self._last_delta_t = delta_t
self._last_frame = _render_word_cloud(combined, colourmap, max_words)
frame = self._last_frame
# ── Update texture ────────────────────────────────────────────
texture = self.convert_cv_to_dpg(frame, CANVAS_W, CANVAS_H)
try:
dpg_set_value(output_tex_tag, texture)
except (SystemError, AttributeError):
pass
# ── Build JSON output (for Concat / downstream nodes) ─────────
# Always return a dict so downstream nodes can rely on a consistent
# API contract regardless of whether text is available.
json_out = {'TEXT': combined}
return {'image': frame, 'json': json_out, 'audio': None}
def close(self, node_id):
pass
def get_setting_dict(self, node_id):
tag_node_name = '{}:{}'.format(node_id, self.node_tag)
pos = dpg.get_item_pos(tag_node_name)
tag_colourmap_value = tag_node_name + ':ColourmapValue'
tag_max_words_value = tag_node_name + ':MaxWordsValue'
tag_delta_t_value = tag_node_name + ':DeltaTValue'
return {
'ver': self._ver,
'pos': pos,
tag_colourmap_value: dpg_get_value(tag_colourmap_value),
tag_max_words_value: dpg_get_value(tag_max_words_value),
tag_delta_t_value: dpg_get_value(tag_delta_t_value),
}
def set_setting_dict(self, node_id, setting_dict):
tag_node_name = '{}:{}'.format(node_id, self.node_tag)
tag_colourmap_value = tag_node_name + ':ColourmapValue'
tag_max_words_value = tag_node_name + ':MaxWordsValue'
tag_delta_t_value = tag_node_name + ':DeltaTValue'
if tag_colourmap_value in setting_dict:
dpg_set_value(tag_colourmap_value, setting_dict[tag_colourmap_value])
if tag_max_words_value in setting_dict:
dpg_set_value(tag_max_words_value, int(setting_dict[tag_max_words_value]))
if tag_delta_t_value in setting_dict:
dpg_set_value(tag_delta_t_value, int(setting_dict[tag_delta_t_value]))