-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodes.py
More file actions
242 lines (199 loc) · 9.19 KB
/
nodes.py
File metadata and controls
242 lines (199 loc) · 9.19 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
import sys
import os
import traceback
from .utils import tensor_to_cv2_img, get_paddle_hw_kwargs
# Attempt to import PaddleOCR
try:
from paddleocr import PaddleOCR
except ImportError:
PaddleOCR = None
class PaddleOCR_Node:
"""
Main PaddleOCR Custom Node.
"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"language": (["ch", "en", "japan", "korean", "chinese_cht", "french", "german"], {"default": "ch"}),
# Renamed from use_angle_cls
"vertical_direction": ("BOOLEAN", {"default": True}),
# Added ocr_version
"ocr_version": (["PP-OCRv5", "PP-OCRv4", "PP-OCRv3"], {"default": "PP-OCRv5"}),
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("text",)
FUNCTION = "apply_ocr"
CATEGORY = "PaddleOCR"
def apply_ocr(self, image, language, vertical_direction, ocr_version):
try:
if PaddleOCR is None:
raise ImportError("PaddleOCR library is not installed.")
print(f"DEBUG: Initializing PaddleOCR. Lang: {language}, Vertical: {vertical_direction}, Version: {ocr_version}")
# Instantiate PaddleOCR
# We pass 'use_textline_orientation' (which vertical_direction maps to)
# and 'ocr_version' to let the internal logic handle model selection.
# Get hardware kwargs (handles GPU/CPU/OneDNN automatically)
hw_kwargs = get_paddle_hw_kwargs()
print(f"DEBUG: Hardware Kwargs: {hw_kwargs}")
try:
ocr = PaddleOCR(
use_textline_orientation=vertical_direction,
lang=language,
ocr_version=ocr_version,
**hw_kwargs
)
except TypeError as e:
print(f"DEBUG: Initialization TypeError: {e}")
# Fallback for older/standard versions that might not support keys
# We try 'use_angle_cls' if 'use_textline_orientation' fails, etc.
# But since the user is using the Pipeline wrapper, the above SHOULD work.
try:
ocr = PaddleOCR(use_angle_cls=vertical_direction, lang=language, **hw_kwargs)
except:
ocr = PaddleOCR(lang=language, **hw_kwargs)
# process
cv_images = tensor_to_cv2_img(image)
full_text_results = []
for i, img_numpy in enumerate(cv_images):
# ocr() method
try:
result = ocr.ocr(img_numpy, use_textline_orientation=vertical_direction)
except TypeError:
# Fallback
result = ocr.ocr(img_numpy, cls=vertical_direction)
if not result:
continue
if result[0] is None:
continue
# Flatten
lines = result
# Handle batch or odd structure
if isinstance(result, list) and len(result) > 0 and isinstance(result[0], list) and isinstance(result[0][0], list):
lines = result[0]
for line in lines:
# Handle if line is dictionary (PaddleX Pipeline structure)
if isinstance(line, dict):
rec_texts = line.get('rec_texts', [])
if isinstance(rec_texts, list):
full_text_results.extend(rec_texts)
elif isinstance(rec_texts, str):
full_text_results.append(rec_texts)
else:
text = line.get('text', line.get('rec_text', ''))
if text:
full_text_results.append(text)
continue
# Standard structure
if isinstance(line, (list, tuple)) and len(line) > 1:
if isinstance(line[1], (list, tuple)):
text = line[1][0]
else:
text = line[0] if isinstance(line[0], str) else str(line)
full_text_results.append(text)
full_text_string = "\n".join(full_text_results)
return (full_text_string,)
except Exception as e:
print(f"CRITICAL ERROR in PaddleOCR_Node: {e}")
traceback.print_exc()
raise RuntimeError(f"PaddleOCR Failed: {e}\n{traceback.format_exc()}")
class PaddleOCR_TestNode:
"""
A simple test node that adds 1 to the input integer.
Useful for verifying basic custom node functionality.
"""
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"int_input": ("INT", {"default": 0, "min": 0, "max": 100000, "step": 1, "display": "number"}),
}
}
RETURN_TYPES = ("INT",)
RETURN_NAMES = ("int_output",)
FUNCTION = "test_add"
CATEGORY = "PaddleOCR"
def test_add(self, int_input):
return (int_input + 1,)
class PaddleOCR_Unified_Node:
"""
Reviewer: User (Designer)
Concept: Pure OCR Node (v5/v4/v3)
A single node acting as a facade for standard PaddleOCR capabilities.
"""
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"image": ("IMAGE",),
"ocr_version": (["PP-OCRv5", "PP-OCRv4", "PP-OCRv3"], {"default": "PP-OCRv5"}),
"language": (["ch", "en", "japan", "korean", "chinese_cht", "french", "german"], {"default": "ch"}),
"use_angle_cls": ("BOOLEAN", {"default": True, "label_on": "Enable Angle Classification", "label_off": "Disable"}),
},
"optional": {
"use_tensorrt": ("BOOLEAN", {"default": False, "label_on": "Enable TensorRT (Faster)", "label_off": "Disable TensorRT"}),
"precision": (["fp32", "fp16", "int8"], {"default": "fp32"}),
}
}
RETURN_TYPES = ("STRING", "JSON")
RETURN_NAMES = ("text", "json_output")
FUNCTION = "apply_unified_ocr"
CATEGORY = "PaddleOCR"
def apply_unified_ocr(self, image, ocr_version, language, use_angle_cls, use_tensorrt, precision):
hw_kwargs = get_paddle_hw_kwargs()
# Inject user overrides for high-end optimization
if use_tensorrt:
hw_kwargs["use_tensorrt"] = True
hw_kwargs["precision"] = precision
print(f"DEBUG: TensorRT Enabled with precision {precision}")
print(f"DEBUG: Unified Node (Pure OCR) - Ver: {ocr_version}, Lang: {language}, Angle: {use_angle_cls}, HW: {hw_kwargs}")
try:
cv_images = tensor_to_cv2_img(image)
results_txt = []
results_json = []
if PaddleOCR is None:
raise ImportError("PaddleOCR not installed.")
# Standard Init
ocr = PaddleOCR(ocr_version=ocr_version, lang=language, use_angle_cls=use_angle_cls, **hw_kwargs)
for img_numpy in cv_images:
result = ocr.ocr(img_numpy, cls=use_angle_cls)
# Result structure: [[[[x1,y1],[x2,y2]..], ("text", score)], ...]
page_txt = []
page_json = []
if result:
# Handle batch wrapper if needed
if isinstance(result, list) and len(result)>0 and isinstance(result[0], list) and isinstance(result[0][0], list):
lines = result[0]
else:
lines = result
for line in lines:
# line: [box, (text, score)]
if len(line) >= 2:
text_info = line[1]
text = text_info[0]
score = text_info[1]
box = line[0]
page_txt.append(text)
page_json.append({
"text": text,
"confidence": float(score),
"box": box
})
results_txt.append("\n".join(page_txt))
results_json.append(page_json)
# Final Aggregation
final_txt = "\n\n".join(results_txt)
# JSON needs to be serialize-safe
import json
try:
final_json_str = json.dumps(results_json, ensure_ascii=False, indent=2)
except:
final_json_str = str(results_json)
return (final_txt, final_json_str)
except Exception as e:
traceback.print_exc()
raise RuntimeError(f"Unified OCR Failed: {e}")