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
| /**
* Create by TonyJiangWJ on Nov 15, 2023.
* Modified by SuperMonster003 as of Jan 18, 2026.
*/
!function sampleForPaddleOcr() {
let currentEngine = engines.myEngine();
let runningEngines = engines.all();
let currentSource = `${currentEngine.getSource()}`;
if (runningEngines.length > 1) {
runningEngines.forEach(compareEngine => {
let compareSource = `${compareEngine.getSource()}`;
if (currentEngine.getId() !== compareEngine.getId() && compareSource === currentSource) {
// Force stop scripts with the same name.
// zh-CN: 强制关闭同名的脚本.
compareEngine.forceStop();
}
});
}
if (!requestScreenCapture()) {
// Failed to request screenshot permission.
toastError('请求截图权限失败');
exit();
}
sleep(500);
// Use slim model for faster inference.
// zh-CN: 使用 slim 模型以获得更快速度.
let useSlim = true;
// CPU thread count.
// zh-CN: CPU 线程数量.
let cpuThreadNum = 4;
// Whether to request OpenCL.
// zh-CN: 是否请求 OpenCL.
let useOpenCL = false;
// Recognition results and screenshot information.
// zh-CN: 识别结果和截图信息.
let result = [];
let img = null;
let running = true;
let capturing = false;
// Get status bar height offset.
// zh-CN: 获取状态栏高度偏移.
let offset = /* -getStatusBarHeightCompat(); */ 0;
// Draw OCR results.
// zh-CN: 绘制 OCR 结果.
let window = floaty.rawWindow(
<canvas id="canvas" layout_weight="1"/>,
);
// Set float window position.
// zh-CN: 设置悬浮窗位置.
ui.post(() => {
window.setPosition(0, offset);
window.setSize(WIDTH, HEIGHT);
window.setTouchable(false);
window.exitOnClose();
});
// Operation buttons.
// zh-CN: 操作按钮.
let clickButtonWindow = floaty.rawWindow(
<vertical>
{/* Screenshot OCR */}
<button id="captureAndOcr" text="截图识别"/>
{/* Save OCR results */}
<button id="saveBtn" text="保存结果"/>
{/* Exit */}
<button id="closeBtn" text="退出"/>
</vertical>,
);
// OCR worker.
// zh-CN: OCR 工作线程.
function captureAndOcrAsync() {
if (capturing) {
// Busy, please wait.
toastLog('正在处理中, 请稍候.');
return;
}
capturing = true;
// Clear last result immediately to avoid drawing stale boxes after capture.
// zh-CN: 立即清空上一次结果, 避免截取完成后仍显示旧框.
result = [];
// Hide overlay windows before capturing to avoid them being captured into screenshot.
// zh-CN: 截图前隐藏悬浮窗, 避免悬浮窗内容被截图到.
ui.run(function () {
clickButtonWindow.setPosition(WIDTH, HEIGHT);
window.setPosition(WIDTH, HEIGHT);
});
threads.start(function () {
try {
// Wait for UI to apply window position changes (1-2 frames).
// zh-CN: 等待 UI 应用窗口位置变化 (1-2 帧).
sleep(150);
img && img.recycle();
img = images.captureScreen();
if (!img) {
// Failed to capture screenshot.
toastError('截图失败');
return;
}
let start = new Date();
result = ocr.paddle.detect(img, { useSlim, cpuThreadNum, useOpenCL });
// OCR cost time.
toastLog(`OCR 耗时 ${new Date() - start}ms`);
} catch (e) {
toastError(e);
exit();
} finally {
capturing = false;
// Restore overlay windows.
// zh-CN: 恢复悬浮窗位置.
ui.run(function () {
window.setPosition(0, offset);
window.setSize(WIDTH, HEIGHT);
window.setTouchable(false);
clickButtonWindow.setPosition(
cX(0.5) - ~~(clickButtonWindow.getWidth() / 2),
cY(0.65),
);
});
}
});
}
/**
* Save current OCR results to JSON file.
* zh-CN: 将当前 OCR 识别结果保存为 JSON 文件.
*/
function saveResultsToJson() {
if (!result || result.length === 0) {
toastLog('暂无识别结果,请先截图识别');
return;
}
let jsonItems = result.map((item, index) => {
let b = item.bounds;
return {
index: index + 1,
text: item.label || item.text || '',
confidence: typeof item.confidence === 'number' ? item.confidence : null,
bounds: {
left: b.left,
top: b.top,
right: b.right,
bottom: b.bottom,
centerX: b.centerX ? b.centerX() : (b.left + b.right) / 2,
centerY: b.centerY ? b.centerY() : (b.top + b.bottom) / 2,
width: b.width ? b.width() : (b.right - b.left),
height: b.height ? b.height() : (b.bottom - b.top),
}
};
});
let payload = {
timestamp: new Date().toISOString(),
resultCount: jsonItems.length,
results: jsonItems,
};
let fileName = 'ocr_result_' + new Date().getTime() + '.json';
let filePath = files.join(files.cwd(), fileName);
files.write(filePath, JSON.stringify(payload, null, 2));
toastLog('识别结果已保存: ' + filePath);
}
clickButtonWindow['captureAndOcr'].click(function () {
captureAndOcrAsync();
});
clickButtonWindow['saveBtn'].click(function () {
saveResultsToJson();
});
clickButtonWindow['closeBtn'].click(function () {
exit();
});
clickButtonWindow.exitOnClose();
let paint = new Paint();
paint.setStrokeWidth(1);
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setTextAlign(Paint.Align.LEFT);
paint.setAntiAlias(true);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setDither(true);
window.canvas.on('draw', function (canvas) {
if (!running || capturing) return;
// Clear canvas.
// zh-CN: 清空画布.
canvas.drawColor(0xFFFFFF, android.graphics.PorterDuff.Mode.CLEAR);
if (result && result.length > 0) {
for (let i = 0; i < result.length; i++) {
let ocrResult = result[i];
drawRectAndText(ocrResult.label, ocrResult.bounds, '#00ff00', canvas, paint);
}
}
});
// Keep script alive.
// zh-CN: 保持脚本运行.
keepAlive();
events.on('exit', () => {
// Mark stop to avoid canvas crash.
// zh-CN: 标记停止, 避免 canvas 导致闪退.
running = false;
// Remove all listeners.
// zh-CN: 撤销监听.
window.canvas.removeAllListeners();
// Recycle image.
// zh-CN: 回收图片.
img && img.recycle();
});
/**
* Draw text and rectangle.
* zh-CN: 绘制文本和方框.
*/
function drawRectAndText(desc, rect, colorStr, canvas, paint) {
let color = colors.parseColor(colorStr);
paint.setStrokeWidth(1);
paint.setStyle(Paint.Style.STROKE);
// Invert color.
// zh-CN: 反色.
paint.setARGB(255, 255 - (color >> 16 & 0xff), 255 - (color >> 8 & 0xff), 255 - (color & 0xff));
canvas.drawRect(rect, paint);
paint.setARGB(255, color >> 16 & 0xff, color >> 8 & 0xff, color & 0xff);
paint.setStrokeWidth(1);
paint.setTextSize(20);
paint.setStyle(Paint.Style.FILL);
canvas.drawText(desc, rect.left, rect.top, paint);
paint.setTextSize(10);
paint.setStrokeWidth(1);
paint.setARGB(255, 0, 0, 0);
}
/**
* Get status bar height.
* zh-CN: 获取状态栏高度.
*/
function getStatusBarHeightCompat() {
let result = 0;
let resId = context.getResources().getIdentifier('status_bar_height', 'dimen', 'android');
if (resId > 0) {
result = context.getResources().getDimensionPixelOffset(resId);
}
if (result <= 0) {
result = context.getResources().getDimensionPixelOffset(R.dimen.dimen_25dp);
}
return result;
}
// Run once at start.
// zh-CN: 启动后先执行一次.
captureAndOcrAsync();
}();
|