6.7.0 - Alpha16 - 打包应用支持自带离线 Paddle OCR 引擎, 避免依赖插件安装
This commit is contained in:
1 parent
52be56318f
commit
a46d78b704
54 files changed
+2745
-253
No files matched your search
@@ -253,8 +253,11 @@ dependencies /* Unclassified */ {
|
|||||||
// R8
|
// R8
|
||||||
implementation(libs.r8)
|
implementation(libs.r8)
|
||||||
|
|
||||||
// Plugin API: Paddle OCR
|
// Plugin API: Paddle OCR API
|
||||||
implementation(project(":plugin-api:paddle-ocr"))
|
implementation(project(":plugin-api:paddle-ocr-api"))
|
||||||
|
|
||||||
|
// Plugin API: Paddle OCR Engine
|
||||||
|
implementation(project(":plugin-api:paddle-ocr-engine"))
|
||||||
}
|
}
|
||||||
|
|
||||||
dependencies /* MIME */ {
|
dependencies /* MIME */ {
|
||||||
|
|||||||
File renamed without changes.
+16
@@ -2,6 +2,22 @@
|
|||||||
* @author TonyJiangWJ
|
* @author TonyJiangWJ
|
||||||
*/
|
*/
|
||||||
!function originalClassesForPaddleOcr() {
|
!function originalClassesForPaddleOcr() {
|
||||||
|
|
||||||
|
let hintForAutoJs670AndAbove = '自 AutoJs6 6.7.0 起, Paddle OCR 已进行功能插件化, 因此无法再使用内置原始类.\n\n' +
|
||||||
|
'如需了解插件 API 使用示例, 可参考 "PaddleOCR (内置 API).js" 示例代码.';
|
||||||
|
|
||||||
|
dialogs.build({
|
||||||
|
title: R.string.text_prompt,
|
||||||
|
content: hintForAutoJs670AndAbove,
|
||||||
|
positiveText: R.string.text_exit,
|
||||||
|
stubborn: true,
|
||||||
|
}).on('positive', (d) => {
|
||||||
|
d.dismiss();
|
||||||
|
exit();
|
||||||
|
}).show();
|
||||||
|
|
||||||
|
exit();
|
||||||
|
|
||||||
const Predictor = com.baidu.paddle.lite.ocr.Predictor;
|
const Predictor = com.baidu.paddle.lite.ocr.Predictor;
|
||||||
|
|
||||||
console.show();
|
console.show();
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
/**
|
||||||
|
* 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="截图识别"/>
|
||||||
|
{/* 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),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
clickButtonWindow['captureAndOcr'].click(function () {
|
||||||
|
captureAndOcrAsync();
|
||||||
|
});
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
}();
|
||||||
@@ -1,198 +0,0 @@
|
|||||||
/**
|
|
||||||
* create by TonyJiangWJ
|
|
||||||
*/
|
|
||||||
!function sampleForPaddleOcr() {
|
|
||||||
|
|
||||||
const Predictor = com.baidu.paddle.lite.ocr.Predictor;
|
|
||||||
|
|
||||||
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) {
|
|
||||||
// 强制关闭同名的脚本
|
|
||||||
compareEngine.forceStop();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!requestScreenCapture()) {
|
|
||||||
toastLog('请求截图权限失败');
|
|
||||||
exit();
|
|
||||||
}
|
|
||||||
|
|
||||||
sleep(1000);
|
|
||||||
|
|
||||||
// 指定是否用精简版模型 速度较快
|
|
||||||
let useSlim = true;
|
|
||||||
|
|
||||||
// 创建检测器
|
|
||||||
let predictor = new Predictor();
|
|
||||||
|
|
||||||
// predictor.cpuThreadNum = 4 // 可以自定义使用 CPU 的线程数
|
|
||||||
// predictor.checkModelLoaded = false // 可以自定义是否需要校验模型是否成功加载 默认开启 使用内置 Base64 图片进行校验 识别测试文本来校验模型是否加载成功
|
|
||||||
|
|
||||||
// 初始化模型 首次运行时会比较耗时
|
|
||||||
let loading = threads.disposable();
|
|
||||||
|
|
||||||
// 建议在新线程中初始化模型
|
|
||||||
threads.start(function () {
|
|
||||||
loading.setAndNotify(predictor.init(context, useSlim));
|
|
||||||
// loading.setAndNotify(predictor.init(context)) 为默认不使用精简版
|
|
||||||
// 内置默认 modelPath 为 models/ocr_v3_for_cpu, 初始化自定义模型请写绝对路径否则无法获取到
|
|
||||||
// 内置默认 labelPath 为 labels/ppocr_keys_v1.txt
|
|
||||||
// let modelPath = files.path('./models/customize') // 指定自定义模型路径
|
|
||||||
// let labelPath = files.path('./models/customize') // 指定自定义 label 路径
|
|
||||||
// 使用自定义模型时 det rec cls 三个模型文件名称需要手动指定
|
|
||||||
// predictor.detModelFilename = 'det_opt.nb'
|
|
||||||
// predictor.recModelFilename = 'rec_opt.nb'
|
|
||||||
// predictor.clsModelFilename = 'cls_opt.nb'
|
|
||||||
// loading.setAndNotify(predictor.init(context, modelPath, labelPath))
|
|
||||||
});
|
|
||||||
let loadSuccess = loading.blockedGet();
|
|
||||||
if (!loadSuccess) {
|
|
||||||
toastLog('初始化 ocr 失败');
|
|
||||||
exit();
|
|
||||||
}
|
|
||||||
|
|
||||||
// 识别结果和截图信息
|
|
||||||
let result = [];
|
|
||||||
let img = null;
|
|
||||||
let running = true;
|
|
||||||
let capturing = true;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 截图并识别 OCR 文本信息
|
|
||||||
*/
|
|
||||||
function captureAndOcr() {
|
|
||||||
capturing = true;
|
|
||||||
img && img.recycle();
|
|
||||||
img = captureScreen();
|
|
||||||
if (!img) {
|
|
||||||
toastLog('截图失败');
|
|
||||||
}
|
|
||||||
let start = new Date();
|
|
||||||
result = predictor.runOcr(img.getBitmap());
|
|
||||||
toastLog(`耗时 ${new Date() - start}ms`);
|
|
||||||
capturing = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
captureAndOcr();
|
|
||||||
|
|
||||||
// 获取状态栏高度
|
|
||||||
let offset = -getStatusBarHeightCompat();
|
|
||||||
|
|
||||||
// 绘制识别结果
|
|
||||||
let window = floaty.rawWindow(
|
|
||||||
<canvas id="canvas" layout_weight="1"/>,
|
|
||||||
);
|
|
||||||
|
|
||||||
// 设置悬浮窗位置
|
|
||||||
ui.post(() => {
|
|
||||||
window.setPosition(0, offset);
|
|
||||||
window.setSize(device.width, device.height);
|
|
||||||
window.setTouchable(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
// 操作按钮
|
|
||||||
let clickButtonWindow = floaty.rawWindow(
|
|
||||||
<vertical>
|
|
||||||
<button id="captureAndOcr" text="截图识别"/>
|
|
||||||
<button id="closeBtn" text="退出"/>
|
|
||||||
</vertical>,
|
|
||||||
);
|
|
||||||
ui.run(function () {
|
|
||||||
clickButtonWindow.setPosition(device.width / 2 - ~~(clickButtonWindow.getWidth() / 2), device.height * 0.65);
|
|
||||||
});
|
|
||||||
|
|
||||||
// 点击识别
|
|
||||||
clickButtonWindow['captureAndOcr'].click(function () {
|
|
||||||
result = [];
|
|
||||||
ui.run(function () {
|
|
||||||
clickButtonWindow.setPosition(device.width, device.height);
|
|
||||||
});
|
|
||||||
setTimeout(() => {
|
|
||||||
captureAndOcr();
|
|
||||||
ui.run(function () {
|
|
||||||
clickButtonWindow.setPosition(device.width / 2 - ~~(clickButtonWindow.getWidth() / 2), device.height * 0.65);
|
|
||||||
});
|
|
||||||
}, 500);
|
|
||||||
});
|
|
||||||
|
|
||||||
// 点击关闭
|
|
||||||
clickButtonWindow['closeBtn'].click(function () {
|
|
||||||
exit();
|
|
||||||
});
|
|
||||||
|
|
||||||
let Typeface = android.graphics.Typeface;
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
// 清空内容
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
setInterval(() => {
|
|
||||||
/* Empty body. */
|
|
||||||
}, 10000);
|
|
||||||
events.on('exit', () => {
|
|
||||||
// 标记停止 避免 canvas 导致闪退
|
|
||||||
running = false;
|
|
||||||
// 撤销监听
|
|
||||||
window.canvas.removeAllListeners();
|
|
||||||
// 回收图片
|
|
||||||
img && img.recycle();
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 绘制文本和方框
|
|
||||||
*/
|
|
||||||
function drawRectAndText(desc, rect, colorStr, canvas, paint) {
|
|
||||||
let color = colors.parseColor(colorStr);
|
|
||||||
|
|
||||||
paint.setStrokeWidth(1);
|
|
||||||
paint.setStyle(Paint.Style.STROKE);
|
|
||||||
// 反色
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 获取状态栏高度
|
|
||||||
*/
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}();
|
|
||||||
@@ -1,17 +1,25 @@
|
|||||||
package org.autojs.autojs.apkbuilder
|
package org.autojs.autojs.apkbuilder
|
||||||
|
|
||||||
|
import android.content.ComponentName
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.ServiceConnection
|
||||||
|
import android.content.pm.ApplicationInfo
|
||||||
|
import android.content.pm.PackageManager
|
||||||
import android.content.pm.PackageManager.ApplicationInfoFlags
|
import android.content.pm.PackageManager.ApplicationInfoFlags
|
||||||
import android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES
|
import android.content.pm.PackageManager.GET_SHARED_LIBRARY_FILES
|
||||||
|
import android.content.pm.ServiceInfo
|
||||||
import android.content.res.AssetManager
|
import android.content.res.AssetManager
|
||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import android.os.IBinder
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
import com.mcal.apksigner.ApkSigner
|
import com.mcal.apksigner.ApkSigner
|
||||||
import com.reandroid.arsc.chunk.TableBlock
|
import com.reandroid.arsc.chunk.TableBlock
|
||||||
import org.autojs.autojs.AbstractAutoJs.Companion.isInrt
|
import org.autojs.autojs.AbstractAutoJs.Companion.isInrt
|
||||||
import org.autojs.autojs.apkbuilder.keystore.AESUtils
|
import org.autojs.autojs.apkbuilder.keystore.AESUtils
|
||||||
import org.autojs.autojs.app.GlobalAppContext
|
import org.autojs.autojs.app.GlobalAppContext
|
||||||
|
import org.autojs.autojs.core.plugin.center.PluginEnableStore
|
||||||
import org.autojs.autojs.engine.encryption.AdvancedEncryptionStandard
|
import org.autojs.autojs.engine.encryption.AdvancedEncryptionStandard
|
||||||
import org.autojs.autojs.pio.PFiles
|
import org.autojs.autojs.pio.PFiles
|
||||||
import org.autojs.autojs.project.BuildInfo
|
import org.autojs.autojs.project.BuildInfo
|
||||||
@@ -23,6 +31,7 @@ import org.autojs.autojs.script.JavaScriptFileSource
|
|||||||
import org.autojs.autojs.util.FileUtils.TYPE.JAVASCRIPT
|
import org.autojs.autojs.util.FileUtils.TYPE.JAVASCRIPT
|
||||||
import org.autojs.autojs.util.MD5Utils
|
import org.autojs.autojs.util.MD5Utils
|
||||||
import org.autojs.autojs6.R
|
import org.autojs.autojs6.R
|
||||||
|
import org.autojs.plugin.paddle.ocr.api.IOcrPlugin
|
||||||
import pxb.android.StringItem
|
import pxb.android.StringItem
|
||||||
import pxb.android.axml.AxmlWriter
|
import pxb.android.axml.AxmlWriter
|
||||||
import zhao.arsceditor.ResDecoder.ARSCDecoder
|
import zhao.arsceditor.ResDecoder.ARSCDecoder
|
||||||
@@ -33,10 +42,15 @@ import java.io.FileNotFoundException
|
|||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
import java.io.InputStream
|
import java.io.InputStream
|
||||||
|
import java.util.concurrent.CountDownLatch
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
import java.util.zip.ZipEntry
|
||||||
|
import java.util.zip.ZipFile
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Created by Stardust on Oct 24, 2017.
|
* Created by Stardust on Oct 24, 2017.
|
||||||
* Modified by SuperMonster003 as of Jul 8, 2022.
|
* Modified by JetBrains AI Assistant (GPT-5.2) as of Jan 17, 2026.
|
||||||
|
* Modified by SuperMonster003 as of Jan 18, 2026.
|
||||||
*/
|
*/
|
||||||
open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File, private val buildPath: String) {
|
open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File, private val buildPath: String) {
|
||||||
|
|
||||||
@@ -52,9 +66,9 @@ open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File
|
|||||||
|
|
||||||
private val mAssetManager: AssetManager by lazy { globalContext.assets }
|
private val mAssetManager: AssetManager by lazy { globalContext.assets }
|
||||||
|
|
||||||
private var mLibsIncludes = Libs.defaultLibsToInclude.toMutableList()
|
private var mLibsIncludes = Lib.defaultLibsToInclude.toMutableList()
|
||||||
private var mAssetsFileIncludes = Libs.defaultAssetFilesToInclude.toMutableList()
|
private var mAssetsFileIncludes = Lib.defaultAssetFilesToInclude.toMutableList()
|
||||||
private var mAssetsDirExcludes = Libs.defaultAssetDirsToExclude.toMutableList()
|
private var mAssetsDirExcludes = Lib.defaultAssetDirsToExclude.toMutableList()
|
||||||
|
|
||||||
private var mSplashThemeId: Int = 0
|
private var mSplashThemeId: Int = 0
|
||||||
private var mNoSplashThemeId: Int = 0
|
private var mNoSplashThemeId: Int = 0
|
||||||
@@ -231,11 +245,11 @@ open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File
|
|||||||
|
|
||||||
mKey = MD5Utils.md5(projectConfig.run { packageName + versionName + mainScriptFileName })
|
mKey = MD5Utils.md5(projectConfig.run { packageName + versionName + mainScriptFileName })
|
||||||
mInitVector = MD5Utils.md5(projectConfig.run { buildInfo.buildId + name }).take(16)
|
mInitVector = MD5Utils.md5(projectConfig.run { buildInfo.buildId + name }).take(16)
|
||||||
Libs.entries.forEach { entry ->
|
Lib.entries.forEach { entry ->
|
||||||
if (config.libs.contains(entry.label)) {
|
if (config.libs.contains(entry.label)) {
|
||||||
mLibsIncludes += entry.libsToInclude.toSet()
|
mLibsIncludes += entry.libsToInclude.toSet()
|
||||||
mAssetsFileIncludes += entry.assetFilesToInclude.toSet()
|
mAssetsFileIncludes += entry.assetFilesToInclude.toSet()
|
||||||
mAssetsDirExcludes -= entry.assetDirsToExclude.toSet()
|
mAssetsDirExcludes -= entry.assetDirsToInclude.toSet()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -418,6 +432,10 @@ open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File
|
|||||||
"armeabi-v7a" to "arm",
|
"armeabi-v7a" to "arm",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Try extracting native libraries from installed plugin APKs if needed.
|
||||||
|
// zh-CN: 如有需要, 尝试从已安装插件 APK 中解压 native 库文件.
|
||||||
|
ensureAndExtractPluginLibrariesIfNeeded(config, potentialAbiAliasList)
|
||||||
|
|
||||||
config.abis.forEach { abiCanonicalName ->
|
config.abis.forEach { abiCanonicalName ->
|
||||||
copyLibrariesByAbi(abiCanonicalName, abiCanonicalName)
|
copyLibrariesByAbi(abiCanonicalName, abiCanonicalName)
|
||||||
potentialAbiAliasList[abiCanonicalName]?.let { abiAliasName ->
|
potentialAbiAliasList[abiCanonicalName]?.let { abiAliasName ->
|
||||||
@@ -426,6 +444,322 @@ open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun ensureAndExtractPluginLibrariesIfNeeded(
|
||||||
|
config: ProjectConfig,
|
||||||
|
potentialAbiAliasList: Map<String, String>,
|
||||||
|
) {
|
||||||
|
Lib.entries.mapNotNull {
|
||||||
|
if (it.isPlugin && config.libs.contains(it.label)) it.toPluginPair() else null
|
||||||
|
}.forEach { (lib, plugin) ->
|
||||||
|
// Select plugin service by variant.
|
||||||
|
// zh-CN: 通过 variant 选择插件服务.
|
||||||
|
val (serviceInfo, selectedVariant) = selectPluginServiceOrThrow(
|
||||||
|
lib = lib,
|
||||||
|
action = plugin.action,
|
||||||
|
)
|
||||||
|
|
||||||
|
Log.i(TAG, "Selected ${lib.label} plugin: variant=${selectedVariant.variant}, pkg=${serviceInfo.packageName}")
|
||||||
|
|
||||||
|
// Extract libraries from installed plugin APK (variant-aware).
|
||||||
|
// zh-CN: 从已安装插件 APK 中解压 so 文件, 并按变体裁剪.
|
||||||
|
extractLibrariesFromPluginApkOrThrow(
|
||||||
|
config = config,
|
||||||
|
requiredLibNames = selectedVariant.libsToInclude,
|
||||||
|
serviceInfo = serviceInfo,
|
||||||
|
potentialAbiAliasList = potentialAbiAliasList,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Extract assets (models/labels) from installed plugin APK (variant-aware).
|
||||||
|
// zh-CN: 从已安装插件 APK 中解压 assets 资源 (models/labels), 并按变体裁剪.
|
||||||
|
extractAssetsFromPluginApkOrThrow(
|
||||||
|
serviceInfo = serviceInfo,
|
||||||
|
pluginLibVariant = selectedVariant,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun selectPluginServiceOrThrow(
|
||||||
|
lib: Lib,
|
||||||
|
action: String,
|
||||||
|
): Pair<ServiceInfo, PluginLibVariant> {
|
||||||
|
val pm = globalContext.packageManager
|
||||||
|
val moduleLabel = lib.label
|
||||||
|
val pluginPair = lib.toPluginPair()
|
||||||
|
val plugin = pluginPair.second
|
||||||
|
val services = findServicesByAction(pm, action)
|
||||||
|
if (services.isEmpty()) {
|
||||||
|
throw IllegalStateException(
|
||||||
|
globalContext.getString(R.string.error_missing_required_plugin_for_module_label, moduleLabel)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only consider enabled plugins in packaging phase.
|
||||||
|
// zh-CN: 打包阶段仅考虑已启用的插件.
|
||||||
|
val enabledServices = services.filter { si ->
|
||||||
|
PluginEnableStore.isEnabled(globalContext, si.packageName, defaultEnabled = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (enabledServices.isEmpty()) {
|
||||||
|
throw IllegalStateException(
|
||||||
|
globalContext.getString(R.string.error_no_enabled_plugin_for_module_label, moduleLabel)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val infos = enabledServices.mapNotNull { si ->
|
||||||
|
val info = runCatching { queryPluginInfoBlocking(globalContext, si, pluginPair) }.getOrNull()
|
||||||
|
info?.let { si to it }
|
||||||
|
}
|
||||||
|
|
||||||
|
val variantList = plugin.variants.map { it.variant?.lowercase() }
|
||||||
|
|
||||||
|
infos.filter { (_, pi) ->
|
||||||
|
pi.variant?.lowercase() in variantList
|
||||||
|
}.maxByOrNull { (_, pi) -> pi.variant?.replace(Regex("\\D"), "")?.toIntOrNull() ?: 0 }?.let {
|
||||||
|
return it
|
||||||
|
}
|
||||||
|
|
||||||
|
infos.firstOrNull()?.let { return it }
|
||||||
|
|
||||||
|
throw IllegalStateException(
|
||||||
|
globalContext.getString(R.string.error_no_available_enabled_plugin_variants_found, moduleLabel, variantList.joinToString("/"))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun queryPluginInfoBlocking(context: Context, serviceInfo: ServiceInfo, pluginPair: Pair<Lib, PluginLib>): PluginLibVariant {
|
||||||
|
// Bind service and call getInfo() synchronously (packaging-time only).
|
||||||
|
// zh-CN: 同步绑定服务并调用 getInfo() (仅打包阶段使用).
|
||||||
|
val latch = CountDownLatch(1)
|
||||||
|
var selectedVariant: String? = null
|
||||||
|
var error: Throwable? = null
|
||||||
|
|
||||||
|
val (lib, plugin) = pluginPair
|
||||||
|
|
||||||
|
val intent = Intent(plugin.action).apply {
|
||||||
|
component = ComponentName(serviceInfo.packageName, serviceInfo.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
val conn = object : ServiceConnection {
|
||||||
|
override fun onServiceConnected(name: ComponentName, binder: IBinder) {
|
||||||
|
try {
|
||||||
|
selectedVariant = plugin.onServiceConnected(binder)
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
error = t
|
||||||
|
} finally {
|
||||||
|
latch.countDown()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onServiceDisconnected(name: ComponentName) {
|
||||||
|
// Ignored.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val bound = runCatching {
|
||||||
|
context.bindService(intent, conn, Context.BIND_AUTO_CREATE)
|
||||||
|
}.getOrDefault(false)
|
||||||
|
|
||||||
|
if (!bound) {
|
||||||
|
throw IllegalStateException(
|
||||||
|
globalContext.getString(R.string.error_failed_to_bind_plugin_service, lib.label)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
val ok = latch.await(15, TimeUnit.SECONDS)
|
||||||
|
if (!ok) {
|
||||||
|
throw IllegalStateException(
|
||||||
|
globalContext.getString(R.string.error_timeout_while_querying_plugin_info, lib.label)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
error?.let { throw it }
|
||||||
|
selectedVariant ?: throw IllegalStateException(
|
||||||
|
globalContext.getString(R.string.error_plugin_returned_empty_info, lib.label)
|
||||||
|
)
|
||||||
|
return plugin.variants.firstOrNull {
|
||||||
|
it.variant.equals(selectedVariant, ignoreCase = true)
|
||||||
|
} ?: throw IllegalStateException(
|
||||||
|
globalContext.getString(R.string.error_plugin_returned_invalid_variant, lib.label, selectedVariant)
|
||||||
|
)
|
||||||
|
} finally {
|
||||||
|
runCatching { context.unbindService(conn) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun extractAssetsFromPluginApkOrThrow(
|
||||||
|
serviceInfo: ServiceInfo,
|
||||||
|
pluginLibVariant: PluginLibVariant,
|
||||||
|
) {
|
||||||
|
val pm = globalContext.packageManager
|
||||||
|
|
||||||
|
val appInfo = getApplicationInfoCompat(pm, serviceInfo.packageName)
|
||||||
|
val apkPaths = buildList {
|
||||||
|
add(appInfo.sourceDir)
|
||||||
|
appInfo.splitSourceDirs?.forEach { add(it) }
|
||||||
|
}.distinct()
|
||||||
|
|
||||||
|
val (requiredPrefixes, optionalPrefixes) = pluginLibVariant.assetsToInclude
|
||||||
|
|
||||||
|
// Extract required prefixes.
|
||||||
|
// zh-CN: 解压必需前缀.
|
||||||
|
val missingRequired = mutableListOf<String>()
|
||||||
|
requiredPrefixes.forEach { prefix ->
|
||||||
|
val ok = extractAssetsByPrefixFromApks(
|
||||||
|
apkPaths = apkPaths,
|
||||||
|
assetPrefix = prefix,
|
||||||
|
)
|
||||||
|
if (!ok) missingRequired += prefix
|
||||||
|
}
|
||||||
|
|
||||||
|
if (missingRequired.isNotEmpty()) {
|
||||||
|
val detail = missingRequired.joinToString(", ")
|
||||||
|
throw IllegalStateException(
|
||||||
|
globalContext.getString(R.string.error_plugin_apk_does_not_contain_required_assets_for_variant, pluginLibVariant.variant, detail)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract optional prefixes (best-effort).
|
||||||
|
// zh-CN: 解压可选前缀 (尽力而为).
|
||||||
|
optionalPrefixes.forEach { prefix ->
|
||||||
|
extractAssetsByPrefixFromApks(
|
||||||
|
apkPaths = apkPaths,
|
||||||
|
assetPrefix = prefix,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun extractAssetsByPrefixFromApks(
|
||||||
|
apkPaths: List<String>,
|
||||||
|
assetPrefix: String,
|
||||||
|
): Boolean {
|
||||||
|
var extractedAny = false
|
||||||
|
apkPaths.forEach { apkPath ->
|
||||||
|
runCatching {
|
||||||
|
ZipFile(apkPath).use { zip ->
|
||||||
|
val entries = zip.entries()
|
||||||
|
while (entries.hasMoreElements()) {
|
||||||
|
val entry: ZipEntry = entries.nextElement()
|
||||||
|
val name = entry.name
|
||||||
|
if (!name.startsWith(assetPrefix)) continue
|
||||||
|
if (entry.isDirectory) continue
|
||||||
|
|
||||||
|
val relative = name.removePrefix("assets/")
|
||||||
|
val outFile = File(buildPath, "assets/$relative").apply {
|
||||||
|
parentFile?.let { parent -> if (!parent.exists()) parent.mkdirs() }
|
||||||
|
}
|
||||||
|
|
||||||
|
zip.getInputStream(entry).use { input ->
|
||||||
|
FileOutputStream(outFile, false).use { output ->
|
||||||
|
input.copyTo(output, bufferSize = 16 * 1024)
|
||||||
|
output.fd.sync()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extractedAny = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
// Ignore and try next apk path.
|
||||||
|
// zh-CN: 忽略异常并尝试下一个 apk 路径.
|
||||||
|
it.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return extractedAny
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun extractLibrariesFromPluginApkOrThrow(
|
||||||
|
config: ProjectConfig,
|
||||||
|
requiredLibNames: List<String>,
|
||||||
|
serviceInfo: ServiceInfo,
|
||||||
|
potentialAbiAliasList: Map<String, String>,
|
||||||
|
) {
|
||||||
|
val pm = globalContext.packageManager
|
||||||
|
|
||||||
|
val appInfo = getApplicationInfoCompat(pm, serviceInfo.packageName)
|
||||||
|
val apkPaths = buildList {
|
||||||
|
add(appInfo.sourceDir)
|
||||||
|
appInfo.splitSourceDirs?.forEach { add(it) }
|
||||||
|
}.distinct()
|
||||||
|
|
||||||
|
val missingPairs = mutableListOf<Pair<String, String>>() // (abi, soName)
|
||||||
|
|
||||||
|
config.abis.forEach { abiCanonicalName ->
|
||||||
|
val abiCandidates = buildList {
|
||||||
|
add(abiCanonicalName)
|
||||||
|
potentialAbiAliasList[abiCanonicalName]?.let { add(it) }
|
||||||
|
}.distinct()
|
||||||
|
|
||||||
|
requiredLibNames.forEach { soName ->
|
||||||
|
val ok = extractFirstMatchedSoFromApks(
|
||||||
|
apkPaths = apkPaths,
|
||||||
|
abiCandidates = abiCandidates,
|
||||||
|
soName = soName,
|
||||||
|
abiDestName = abiCanonicalName,
|
||||||
|
)
|
||||||
|
if (!ok) missingPairs += abiCanonicalName to soName
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (missingPairs.isNotEmpty()) {
|
||||||
|
val detail = missingPairs.joinToString(", ") { (abi, so) -> "$abi/$so" }
|
||||||
|
throw IllegalStateException(
|
||||||
|
globalContext.getString(R.string.error_plugin_apk_does_not_contain_required_native_libraries, detail)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun findServicesByAction(pm: PackageManager, action: String): List<ServiceInfo> {
|
||||||
|
val resolveList = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
pm.queryIntentServices(Intent(action), PackageManager.ResolveInfoFlags.of(0))
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
pm.queryIntentServices(Intent(action), 0)
|
||||||
|
}
|
||||||
|
return resolveList.mapNotNull { it.serviceInfo }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun extractFirstMatchedSoFromApks(
|
||||||
|
apkPaths: List<String>,
|
||||||
|
abiCandidates: List<String>,
|
||||||
|
soName: String,
|
||||||
|
abiDestName: String,
|
||||||
|
): Boolean {
|
||||||
|
apkPaths.forEach { apkPath ->
|
||||||
|
runCatching {
|
||||||
|
ZipFile(apkPath).use { zip ->
|
||||||
|
abiCandidates.forEach { abiInApk ->
|
||||||
|
val entryName = "lib/$abiInApk/$soName"
|
||||||
|
val entry = zip.getEntry(entryName) ?: return@forEach
|
||||||
|
val outFile = File(buildPath, "lib/$abiDestName/$soName").apply {
|
||||||
|
parentFile?.let { parent -> if (!parent.exists()) parent.mkdirs() }
|
||||||
|
}
|
||||||
|
zip.getInputStream(entry).use { input ->
|
||||||
|
FileOutputStream(outFile, false).use { output ->
|
||||||
|
input.copyTo(output, bufferSize = 16 * 1024)
|
||||||
|
output.fd.sync()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Log.i(TAG, "Extracted so from plugin apk: $apkPath!/$entryName -> ${outFile.path}")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.onFailure {
|
||||||
|
// Ignore and try next apk path.
|
||||||
|
// zh-CN: 忽略异常并尝试下一个 apk 路径.
|
||||||
|
it.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getApplicationInfoCompat(pm: PackageManager, packageName: String): ApplicationInfo {
|
||||||
|
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
pm.getApplicationInfo(packageName, ApplicationInfoFlags.of(0))
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
pm.getApplicationInfo(packageName, 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun copyLibrariesByAbi(abiSrcName: String, abiDestName: String) {
|
private fun copyLibrariesByAbi(abiSrcName: String, abiDestName: String) {
|
||||||
|
|
||||||
// @Reference to LZX284 (https://github.com/LZX284) by SuperMonster003 on Dec 11, 2023.
|
// @Reference to LZX284 (https://github.com/LZX284) by SuperMonster003 on Dec 11, 2023.
|
||||||
@@ -466,12 +800,15 @@ open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Suppress("SpellCheckingInspection")
|
@Suppress("SpellCheckingInspection")
|
||||||
enum class Libs(
|
enum class Lib(
|
||||||
@JvmField val label: String,
|
@JvmField val label: String,
|
||||||
@JvmField val aliases: List<String> = emptyList(),
|
@JvmField val aliases: List<String> = emptyList(),
|
||||||
@JvmField val enumerable: Boolean = true,
|
@JvmField val enumerable: Boolean = true,
|
||||||
|
internal val plugin: PluginLib? = null,
|
||||||
internal val libsToInclude: List<String> = emptyList(),
|
internal val libsToInclude: List<String> = emptyList(),
|
||||||
internal val assetFilesToInclude: List<String> = emptyList(),
|
internal val assetFilesToInclude: List<String> = emptyList(),
|
||||||
|
// Select, then include into packaging APK. (选择后, 会被打包进 APK 中.)
|
||||||
|
internal val assetDirsToInclude: List<String> = emptyList(),
|
||||||
internal val assetDirsToExclude: List<String> = emptyList(),
|
internal val assetDirsToExclude: List<String> = emptyList(),
|
||||||
) {
|
) {
|
||||||
|
|
||||||
@@ -499,7 +836,7 @@ open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File
|
|||||||
libsToInclude = listOf(
|
libsToInclude = listOf(
|
||||||
"libmlkit_google_ocr_pipeline.so",
|
"libmlkit_google_ocr_pipeline.so",
|
||||||
),
|
),
|
||||||
assetDirsToExclude = listOf(
|
assetDirsToInclude = listOf(
|
||||||
"mlkit-google-ocr-models",
|
"mlkit-google-ocr-models",
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -507,14 +844,51 @@ open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File
|
|||||||
PADDLE_OCR(
|
PADDLE_OCR(
|
||||||
label = "Paddle OCR",
|
label = "Paddle OCR",
|
||||||
aliases = listOf("paddle", "paddleocr", "paddle-ocr", "paddle_ocr"),
|
aliases = listOf("paddle", "paddleocr", "paddle-ocr", "paddle_ocr"),
|
||||||
libsToInclude = listOf(
|
libsToInclude = emptyList(),
|
||||||
"libc++_shared.so",
|
assetDirsToInclude = emptyList(),
|
||||||
"libpaddle_light_api_shared.so",
|
|
||||||
"libNative.so",
|
|
||||||
),
|
|
||||||
assetDirsToExclude = listOf(
|
assetDirsToExclude = listOf(
|
||||||
"models",
|
"models",
|
||||||
)
|
),
|
||||||
|
plugin = PluginLib(
|
||||||
|
action = "org.autojs.plugin.PADDLE_OCR",
|
||||||
|
onServiceConnected = { binder: IBinder ->
|
||||||
|
IOcrPlugin.Stub.asInterface(binder).info.variant
|
||||||
|
},
|
||||||
|
variants = listOf(
|
||||||
|
PluginLibVariant(
|
||||||
|
variant = "v3",
|
||||||
|
assetsToInclude = listOf(
|
||||||
|
"assets/labels/ppocr_keys_v1.txt",
|
||||||
|
"assets/models/ocr_v3_for_cpu/",
|
||||||
|
) to listOf(
|
||||||
|
"assets/models/ocr_v3_for_cpu(slim)/",
|
||||||
|
),
|
||||||
|
libsToInclude = listOf(
|
||||||
|
"libc++_shared.so",
|
||||||
|
"libpaddle_light_api_shared.so",
|
||||||
|
"libNative.so",
|
||||||
|
"libopencv_java4.so",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
PluginLibVariant(
|
||||||
|
variant = "v5",
|
||||||
|
assetsToInclude = listOf(
|
||||||
|
"assets/labels/ppocr_keys_ocrv5.txt",
|
||||||
|
"assets/models/pp-ocrv5-arm/",
|
||||||
|
"assets/models/pp-ocrv5-arm-int8/",
|
||||||
|
"assets/models/pp-ocrv5-arm-opencl/",
|
||||||
|
"assets/models/pp-ocrv5-arm-opencl-int8/",
|
||||||
|
) to emptyList(),
|
||||||
|
libsToInclude = listOf(
|
||||||
|
"libc++_shared.so",
|
||||||
|
"libpaddle_light_api_shared.so",
|
||||||
|
"libNative.so",
|
||||||
|
"libopencv_java4.so",
|
||||||
|
"libopencl_probe.so",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
|
|
||||||
RAPID_OCR(
|
RAPID_OCR(
|
||||||
@@ -524,7 +898,7 @@ open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File
|
|||||||
"libRapidOcr.so",
|
"libRapidOcr.so",
|
||||||
"libonnxruntime.so",
|
"libonnxruntime.so",
|
||||||
),
|
),
|
||||||
assetDirsToExclude = listOf(
|
assetDirsToInclude = listOf(
|
||||||
"labels",
|
"labels",
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -535,7 +909,7 @@ open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File
|
|||||||
libsToInclude = listOf(
|
libsToInclude = listOf(
|
||||||
"libChineseConverter.so",
|
"libChineseConverter.so",
|
||||||
),
|
),
|
||||||
assetDirsToExclude = listOf(
|
assetDirsToInclude = listOf(
|
||||||
"openccdata",
|
"openccdata",
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -557,7 +931,7 @@ open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File
|
|||||||
libsToInclude = listOf(
|
libsToInclude = listOf(
|
||||||
"libbarhopper_v3.so",
|
"libbarhopper_v3.so",
|
||||||
),
|
),
|
||||||
assetDirsToExclude = listOf(
|
assetDirsToInclude = listOf(
|
||||||
"mlkit_barcode_models",
|
"mlkit_barcode_models",
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -582,6 +956,11 @@ open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File
|
|||||||
|
|
||||||
;
|
;
|
||||||
|
|
||||||
|
val isPlugin: Boolean
|
||||||
|
get() = plugin != null
|
||||||
|
|
||||||
|
fun toPluginPair(): Pair<Lib, PluginLib> = this to plugin!!
|
||||||
|
|
||||||
fun ensureLibFiles(moduleName: String = label) {
|
fun ensureLibFiles(moduleName: String = label) {
|
||||||
if (!isInrt) return
|
if (!isInrt) return
|
||||||
val nativeLibraryDir = File(globalContext.applicationInfo.nativeLibraryDir)
|
val nativeLibraryDir = File(globalContext.applicationInfo.nativeLibraryDir)
|
||||||
@@ -604,10 +983,23 @@ open class ApkBuilder(apkInputStream: InputStream?, private val outApkFile: File
|
|||||||
|
|
||||||
val defaultAssetDirsToExclude = listOf(
|
val defaultAssetDirsToExclude = listOf(
|
||||||
"doc", "docs", "editor", "indices", "js-beautify", "sample", "stored-locales",
|
"doc", "docs", "editor", "indices", "js-beautify", "sample", "stored-locales",
|
||||||
) + Libs.entries.flatMap { it.assetDirsToExclude }
|
) + entries.flatMap { it.assetDirsToInclude } + entries.flatMap { it.assetDirsToExclude }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
data class PluginLib(
|
||||||
|
val action: String,
|
||||||
|
val onServiceConnected: (IBinder) -> String,
|
||||||
|
val variants: List<PluginLibVariant>,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class PluginLibVariant(
|
||||||
|
val variant: String? = null,
|
||||||
|
/** <Required List> to <Optional List>. */
|
||||||
|
val assetsToInclude: Pair<List<String>, List<String>> = emptyList<String>() to emptyList(),
|
||||||
|
val libsToInclude: List<String> = emptyList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ import kotlinx.coroutines.Dispatchers
|
|||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import org.autojs.autojs.core.plugin.ocr.PaddleOcrPluginHost
|
import org.autojs.autojs.core.plugin.ocr.PaddleOcrPluginHost
|
||||||
import org.autojs.autojs6.R
|
import org.autojs.autojs6.R
|
||||||
import org.autojs.plugin.paddle.ocr.PluginInfo
|
import org.autojs.plugin.paddle.ocr.api.PluginInfo
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -21,10 +21,10 @@ import kotlinx.coroutines.launch
|
|||||||
import kotlinx.coroutines.suspendCancellableCoroutine
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import org.autojs.autojs.core.plugin.center.PluginEnableStore
|
import org.autojs.autojs.core.plugin.center.PluginEnableStore
|
||||||
import org.autojs.plugin.paddle.ocr.IOcrPlugin
|
import org.autojs.plugin.paddle.ocr.api.IOcrPlugin
|
||||||
import org.autojs.plugin.paddle.ocr.OcrOptions
|
import org.autojs.plugin.paddle.ocr.api.OcrOptions
|
||||||
import org.autojs.plugin.paddle.ocr.OcrResult
|
import org.autojs.plugin.paddle.ocr.api.OcrResult
|
||||||
import org.autojs.plugin.paddle.ocr.PluginInfo
|
import org.autojs.plugin.paddle.ocr.api.PluginInfo
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.FileOutputStream
|
import java.io.FileOutputStream
|
||||||
|
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ class OcrMLKit(private val scriptRuntime: ScriptRuntime) : Augmentable(scriptRun
|
|||||||
// ! Reserved param `options`.
|
// ! Reserved param `options`.
|
||||||
// ! zh-CN: 预留参数 `options`.
|
// ! zh-CN: 预留参数 `options`.
|
||||||
fun recognizeTextImpl(scriptRuntime: ScriptRuntime, image: ImageWrapper, options: NativeObject): List<String> {
|
fun recognizeTextImpl(scriptRuntime: ScriptRuntime, image: ImageWrapper, options: NativeObject): List<String> {
|
||||||
ApkBuilder.Libs.MLKIT_OCR.ensureLibFiles(OcrMode.MLKIT.value)
|
ApkBuilder.Lib.MLKIT_OCR.ensureLibFiles(OcrMode.MLKIT.value)
|
||||||
return scriptRuntime.ocrMLKit.recognizeText(image)
|
return scriptRuntime.ocrMLKit.recognizeText(image)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ class OcrMLKit(private val scriptRuntime: ScriptRuntime) : Augmentable(scriptRun
|
|||||||
// ! Reserved param `options`.
|
// ! Reserved param `options`.
|
||||||
// ! zh-CN: 预留参数 `options`.
|
// ! zh-CN: 预留参数 `options`.
|
||||||
fun detectImpl(scriptRuntime: ScriptRuntime, image: ImageWrapper, options: NativeObject): List<OcrResult> {
|
fun detectImpl(scriptRuntime: ScriptRuntime, image: ImageWrapper, options: NativeObject): List<OcrResult> {
|
||||||
ApkBuilder.Libs.MLKIT_OCR.ensureLibFiles(OcrMode.MLKIT.value)
|
ApkBuilder.Lib.MLKIT_OCR.ensureLibFiles(OcrMode.MLKIT.value)
|
||||||
return scriptRuntime.ocrMLKit.detect(image)
|
return scriptRuntime.ocrMLKit.detect(image)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package org.autojs.autojs.runtime.api.augment.ocr
|
package org.autojs.autojs.runtime.api.augment.ocr
|
||||||
|
|
||||||
import kotlinx.coroutines.runBlocking
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import org.autojs.autojs.AbstractAutoJs.Companion.isInrt
|
||||||
import org.autojs.autojs.annotation.RhinoRuntimeFunctionInterface
|
import org.autojs.autojs.annotation.RhinoRuntimeFunctionInterface
|
||||||
import org.autojs.autojs.apkbuilder.ApkBuilder
|
import org.autojs.autojs.apkbuilder.ApkBuilder
|
||||||
import org.autojs.autojs.core.image.ImageWrapper
|
import org.autojs.autojs.core.image.ImageWrapper
|
||||||
@@ -15,7 +16,7 @@ import org.autojs.autojs.runtime.exception.WrappedIllegalArgumentException
|
|||||||
import org.autojs.autojs.util.RhinoUtils.coerceBoolean
|
import org.autojs.autojs.util.RhinoUtils.coerceBoolean
|
||||||
import org.autojs.autojs.util.RhinoUtils.coerceIntNumber
|
import org.autojs.autojs.util.RhinoUtils.coerceIntNumber
|
||||||
import org.autojs.autojs6.R
|
import org.autojs.autojs6.R
|
||||||
import org.autojs.plugin.paddle.ocr.OcrOptions
|
import org.autojs.plugin.paddle.ocr.api.OcrOptions
|
||||||
import org.mozilla.javascript.NativeArray
|
import org.mozilla.javascript.NativeArray
|
||||||
import org.mozilla.javascript.NativeObject
|
import org.mozilla.javascript.NativeObject
|
||||||
|
|
||||||
@@ -50,33 +51,47 @@ class OcrPaddle(private val scriptRuntime: ScriptRuntime) : Augmentable(scriptRu
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun recognizeTextImpl(scriptRuntime: ScriptRuntime, image: ImageWrapper, options: NativeObject): List<String> {
|
fun recognizeTextImpl(scriptRuntime: ScriptRuntime, image: ImageWrapper, options: NativeObject): List<String> {
|
||||||
ApkBuilder.Libs.PADDLE_OCR.ensureLibFiles(OcrMode.PADDLE.value)
|
ApkBuilder.Lib.PADDLE_OCR.ensureLibFiles(OcrMode.PADDLE.value)
|
||||||
val (cpuThreadNum, useSlim, useOpenCL) = getOcrOptions(options)
|
val (cpuThreadNum, useSlim, useOpenCL) = getOcrOptions(options)
|
||||||
val ocrOptions = OcrOptions().apply {
|
val ocrOptions = OcrOptions().apply {
|
||||||
this.cpuThreadNum = cpuThreadNum
|
this.cpuThreadNum = cpuThreadNum
|
||||||
this.useSlim = useSlim
|
this.useSlim = useSlim
|
||||||
this.useOpenCL = useOpenCL
|
this.useOpenCL = useOpenCL
|
||||||
}
|
}
|
||||||
return runBlocking(scriptRuntime.coroutineContext) {
|
return if (!isInrt) {
|
||||||
val target = PaddleOcrPluginHost.select(globalContext)
|
runBlocking(scriptRuntime.coroutineContext) {
|
||||||
?: throw WrappedIllegalArgumentException(globalContext.getString(R.string.error_no_paddle_ocr_plugins_available))
|
val target = PaddleOcrPluginHost.select(globalContext)
|
||||||
PaddleOcrPluginHost.recognizeText(globalContext, target, image.bitmap, ocrOptions)
|
?: throw WrappedIllegalArgumentException(globalContext.getString(R.string.error_no_paddle_ocr_plugins_available))
|
||||||
|
PaddleOcrPluginHost.recognizeText(globalContext, target, image.bitmap, ocrOptions)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Use embedded engine in packaged (INRT) app.
|
||||||
|
// zh-CN: 打包应用 (INRT) 使用内置引擎 (本地推理), 不依赖插件.
|
||||||
|
PaddleOcrEmbeddedEngine.recognizeText(globalContext, image.bitmap, ocrOptions)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun detectImpl(scriptRuntime: ScriptRuntime, image: ImageWrapper, options: NativeObject): List<OcrResult> {
|
fun detectImpl(scriptRuntime: ScriptRuntime, image: ImageWrapper, options: NativeObject): List<OcrResult> {
|
||||||
ApkBuilder.Libs.PADDLE_OCR.ensureLibFiles(OcrMode.PADDLE.value)
|
ApkBuilder.Lib.PADDLE_OCR.ensureLibFiles(OcrMode.PADDLE.value)
|
||||||
val (cpuThreadNum, useSlim, useOpenCL) = getOcrOptions(options)
|
val (cpuThreadNum, useSlim, useOpenCL) = getOcrOptions(options)
|
||||||
val ocrOptions = OcrOptions().apply {
|
val ocrOptions = OcrOptions().apply {
|
||||||
this.cpuThreadNum = cpuThreadNum
|
this.cpuThreadNum = cpuThreadNum
|
||||||
this.useSlim = useSlim
|
this.useSlim = useSlim
|
||||||
this.useOpenCL = useOpenCL
|
this.useOpenCL = useOpenCL
|
||||||
}
|
}
|
||||||
return runBlocking(scriptRuntime.coroutineContext) {
|
return if (!isInrt) {
|
||||||
val target = PaddleOcrPluginHost.select(globalContext)
|
runBlocking(scriptRuntime.coroutineContext) {
|
||||||
?: throw WrappedIllegalArgumentException(globalContext.getString(R.string.error_no_paddle_ocr_plugins_available))
|
val target = PaddleOcrPluginHost.select(globalContext)
|
||||||
PaddleOcrPluginHost.detect(globalContext, target, image.bitmap, ocrOptions)
|
?: throw WrappedIllegalArgumentException(globalContext.getString(R.string.error_no_paddle_ocr_plugins_available))
|
||||||
}.map { OcrResult(it.text, it.confidence, it.bounds) }
|
PaddleOcrPluginHost.detect(globalContext, target, image.bitmap, ocrOptions)
|
||||||
|
}.map { OcrResult(it.text, it.confidence, it.bounds) }
|
||||||
|
} else {
|
||||||
|
// Use embedded engine in packaged (INRT) app.
|
||||||
|
// zh-CN: 打包应用 (INRT) 使用内置引擎 (本地推理), 不依赖插件.
|
||||||
|
PaddleOcrEmbeddedEngine.detect(globalContext, image.bitmap, ocrOptions).map {
|
||||||
|
OcrResult(it.text, it.confidence, it.bounds)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun getOcrOptions(options: NativeObject): OcrOptions {
|
private fun getOcrOptions(options: NativeObject): OcrOptions {
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ class OcrRapid(private val scriptRuntime: ScriptRuntime) : Augmentable(scriptRun
|
|||||||
// ! Reserved param `options`.
|
// ! Reserved param `options`.
|
||||||
// ! zh-CN: 预留参数 `options`.
|
// ! zh-CN: 预留参数 `options`.
|
||||||
fun recognizeTextImpl(scriptRuntime: ScriptRuntime, image: ImageWrapper, @Suppress("UNUSED_PARAMETER") options: NativeObject): List<String> {
|
fun recognizeTextImpl(scriptRuntime: ScriptRuntime, image: ImageWrapper, @Suppress("UNUSED_PARAMETER") options: NativeObject): List<String> {
|
||||||
ApkBuilder.Libs.RAPID_OCR.ensureLibFiles(OcrMode.RAPID.value)
|
ApkBuilder.Lib.RAPID_OCR.ensureLibFiles(OcrMode.RAPID.value)
|
||||||
return scriptRuntime.ocrRapid.recognizeText(image)
|
return scriptRuntime.ocrRapid.recognizeText(image)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,7 +48,7 @@ class OcrRapid(private val scriptRuntime: ScriptRuntime) : Augmentable(scriptRun
|
|||||||
// ! Reserved param `options`.
|
// ! Reserved param `options`.
|
||||||
// ! zh-CN: 预留参数 `options`.
|
// ! zh-CN: 预留参数 `options`.
|
||||||
fun detectImpl(scriptRuntime: ScriptRuntime, image: ImageWrapper, @Suppress("UNUSED_PARAMETER") options: NativeObject): List<OcrResult> {
|
fun detectImpl(scriptRuntime: ScriptRuntime, image: ImageWrapper, @Suppress("UNUSED_PARAMETER") options: NativeObject): List<OcrResult> {
|
||||||
ApkBuilder.Libs.RAPID_OCR.ensureLibFiles(OcrMode.RAPID.value)
|
ApkBuilder.Lib.RAPID_OCR.ensureLibFiles(OcrMode.RAPID.value)
|
||||||
return scriptRuntime.ocrRapid.detect(image)
|
return scriptRuntime.ocrRapid.detect(image)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+82
@@ -0,0 +1,82 @@
|
|||||||
|
package org.autojs.autojs.runtime.api.augment.ocr
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.res.AssetManager
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import com.baidu.paddle.lite.ocr.PaddleOcrEngine
|
||||||
|
import com.baidu.paddle.lite.ocr.VariantSpec
|
||||||
|
import org.autojs.autojs6.R
|
||||||
|
import org.autojs.plugin.paddle.ocr.api.OcrOptions
|
||||||
|
import org.autojs.plugin.paddle.ocr.api.OcrResult
|
||||||
|
|
||||||
|
internal object PaddleOcrEmbeddedEngine {
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var engine: PaddleOcrEngine? = null
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var resolvedVariant: VariantSpec? = null
|
||||||
|
|
||||||
|
private fun getEngine(context: Context): PaddleOcrEngine {
|
||||||
|
// Lazily initialize embedded engine.
|
||||||
|
// zh-CN: 懒初始化内置引擎.
|
||||||
|
val cached = engine
|
||||||
|
if (cached != null) return cached
|
||||||
|
return synchronized(this) {
|
||||||
|
engine ?: run {
|
||||||
|
val appCtx = context.applicationContext
|
||||||
|
val variant = resolveVariantOrThrow(appCtx, appCtx.assets).also { resolvedVariant = it }
|
||||||
|
PaddleOcrEngine(
|
||||||
|
appContext = appCtx,
|
||||||
|
variant = variant,
|
||||||
|
).also { engine = it }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resolveVariantOrThrow(context: Context, assets: AssetManager): VariantSpec {
|
||||||
|
// Mirror the packaging-time selection rule:
|
||||||
|
// - If neither exists -> throw.
|
||||||
|
// - If both exist -> v5 first.
|
||||||
|
// - If only one exists -> choose it.
|
||||||
|
// zh-CN:
|
||||||
|
// 复刻打包阶段的选择规则:
|
||||||
|
// - 两者都不存在 -> 抛异常.
|
||||||
|
// - 两者都存在 -> v5 优先.
|
||||||
|
// - 仅存在一个 -> 选择唯一项.
|
||||||
|
val hasV5 = assets.hasAsset("labels/ppocr_keys_ocrv5.txt") &&
|
||||||
|
assets.hasAsset("models/pp-ocrv5-arm/PP-OCRv5_mobile_det.nb")
|
||||||
|
|
||||||
|
val hasV3 = assets.hasAsset("labels/ppocr_keys_v1.txt") &&
|
||||||
|
assets.hasAsset("models/ocr_v3_for_cpu/det_opt.nb")
|
||||||
|
|
||||||
|
return when {
|
||||||
|
hasV5 -> VariantSpec.v5()
|
||||||
|
hasV3 -> VariantSpec.v3()
|
||||||
|
else -> throw IllegalStateException(
|
||||||
|
context.getString(R.string.error_no_embedded_paddle_ocr_assets_found)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun AssetManager.hasAsset(path: String): Boolean {
|
||||||
|
return try {
|
||||||
|
open(path).use { true }
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun recognizeText(context: Context, bitmap: Bitmap, options: OcrOptions): List<String> {
|
||||||
|
// Run OCR with embedded engine.
|
||||||
|
// zh-CN: 使用内置引擎执行 OCR.
|
||||||
|
return getEngine(context).recognizeText(bitmap, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun detect(context: Context, bitmap: Bitmap, options: OcrOptions): List<OcrResult> {
|
||||||
|
// Run OCR detection with embedded engine.
|
||||||
|
// zh-CN: 使用内置引擎执行 OCR 检测.
|
||||||
|
return getEngine(context).detect(bitmap, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -240,7 +240,7 @@ public class BuildActivity extends BaseActivity implements ApkBuilder.ProgressCa
|
|||||||
private KeyStoreViewModel mKeyStoreViewModel;
|
private KeyStoreViewModel mKeyStoreViewModel;
|
||||||
|
|
||||||
static {
|
static {
|
||||||
for (ApkBuilder.Libs entry : ApkBuilder.Libs.getEntries()) {
|
for (ApkBuilder.Lib entry : ApkBuilder.Lib.getEntries()) {
|
||||||
if (entry.enumerable) {
|
if (entry.enumerable) {
|
||||||
SUPPORTED_LIBS.add(entry.label);
|
SUPPORTED_LIBS.add(entry.label);
|
||||||
LIB_ALIASES.put(entry.label, entry.aliases);
|
LIB_ALIASES.put(entry.label, entry.aliases);
|
||||||
|
|||||||
@@ -1181,5 +1181,15 @@
|
|||||||
<string name="text_sort_by_name">فرز حسب الاسم</string>
|
<string name="text_sort_by_name">فرز حسب الاسم</string>
|
||||||
<string name="text_sort_by_last_update_time">فرز حسب آخر تحديث</string>
|
<string name="text_sort_by_last_update_time">فرز حسب آخر تحديث</string>
|
||||||
<string name="text_sort_by_package_size">فرز حسب حجم الحزمة</string>
|
<string name="text_sort_by_package_size">فرز حسب حجم الحزمة</string>
|
||||||
|
<string name="error_missing_required_plugin_for_module_label">المكوّن الإضافي المطلوب لـ \"%1$s\" مفقود. يُرجى تثبيت المكوّن الإضافي ثم إعادة المحاولة.</string>
|
||||||
|
<string name="error_no_enabled_plugin_for_module_label">لا يوجد مكوّن إضافي مفعّل لـ \"%1$s\". يُرجى تفعيل مكوّن إضافي ثم إعادة المحاولة.</string>
|
||||||
|
<string name="error_no_available_enabled_plugin_variants_found">لم يتم العثور على أي متغيرات مفعّلة ومتاحة للمكوّن الإضافي %1$s (%2$s).</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_assets_for_variant">ملف APK للمكوّن الإضافي لا يحتوي على الموارد المطلوبة لـ variant=\"%1$s\": %2$s.</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_native_libraries">ملف APK للمكوّن الإضافي لا يحتوي على مكتبات native المطلوبة: %1$s.</string>
|
||||||
|
<string name="error_failed_to_bind_plugin_service">تعذّر ربط خدمة المكوّن الإضافي %1$s.</string>
|
||||||
|
<string name="error_timeout_while_querying_plugin_info">انتهت مهلة الاستعلام عن معلومات المكوّن الإضافي %1$s.</string>
|
||||||
|
<string name="error_plugin_returned_empty_info">أعاد المكوّن الإضافي %1$s معلومات فارغة.</string>
|
||||||
|
<string name="error_plugin_returned_invalid_variant">أعاد المكوّن الإضافي %1$s variant غير صالح: %2$s.</string>
|
||||||
|
<string name="error_no_embedded_paddle_ocr_assets_found">لم يتم العثور على موارد Paddle OCR المضمّنة. يُرجى إعادة الحزم مع تفعيل Paddle OCR.</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1176,5 +1176,15 @@
|
|||||||
<string name="text_sort_by_name">Sort by name</string>
|
<string name="text_sort_by_name">Sort by name</string>
|
||||||
<string name="text_sort_by_last_update_time">Sort by last update time</string>
|
<string name="text_sort_by_last_update_time">Sort by last update time</string>
|
||||||
<string name="text_sort_by_package_size">Sort by package size</string>
|
<string name="text_sort_by_package_size">Sort by package size</string>
|
||||||
|
<string name="error_missing_required_plugin_for_module_label">Missing required plugin for \"%1$s\". Please install the plugin and try again.</string>
|
||||||
|
<string name="error_no_enabled_plugin_for_module_label">No enabled plugin for \"%1$s\". Please enable a plugin and try again.</string>
|
||||||
|
<string name="error_no_available_enabled_plugin_variants_found">No available enabled %1$s plugin variants found (%2$s).</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_assets_for_variant">Plugin APK does not contain required assets for variant=\"%1$s\": %2$s.</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_native_libraries">Plugin APK does not contain required native libraries: %1$s.</string>
|
||||||
|
<string name="error_failed_to_bind_plugin_service">Failed to bind %1$s plugin service.</string>
|
||||||
|
<string name="error_timeout_while_querying_plugin_info">Timeout while querying %1$s plugin info.</string>
|
||||||
|
<string name="error_plugin_returned_empty_info">%1$s plugin returned empty info.</string>
|
||||||
|
<string name="error_plugin_returned_invalid_variant">%1$s plugin returned invalid variant: %2$s.</string>
|
||||||
|
<string name="error_no_embedded_paddle_ocr_assets_found">No embedded Paddle OCR assets found. Please re-package with Paddle OCR enabled.</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1179,5 +1179,15 @@
|
|||||||
<string name="text_sort_by_name">Ordenar por nombre</string>
|
<string name="text_sort_by_name">Ordenar por nombre</string>
|
||||||
<string name="text_sort_by_last_update_time">Ordenar por última actualización</string>
|
<string name="text_sort_by_last_update_time">Ordenar por última actualización</string>
|
||||||
<string name="text_sort_by_package_size">Ordenar por tamaño del paquete</string>
|
<string name="text_sort_by_package_size">Ordenar por tamaño del paquete</string>
|
||||||
|
<string name="error_missing_required_plugin_for_module_label">Falta el plugin requerido para \"%1$s\". Instala el plugin e inténtalo de nuevo.</string>
|
||||||
|
<string name="error_no_enabled_plugin_for_module_label">No hay ningún plugin habilitado para \"%1$s\". Habilita un plugin e inténtalo de nuevo.</string>
|
||||||
|
<string name="error_no_available_enabled_plugin_variants_found">No se encontraron variantes de plugin %1$s habilitadas y disponibles (%2$s).</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_assets_for_variant">El APK del plugin no contiene los recursos necesarios para variant=\"%1$s\": %2$s.</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_native_libraries">El APK del plugin no contiene las bibliotecas nativas requeridas: %1$s.</string>
|
||||||
|
<string name="error_failed_to_bind_plugin_service">No se pudo vincular el servicio del plugin %1$s.</string>
|
||||||
|
<string name="error_timeout_while_querying_plugin_info">Tiempo de espera agotado al consultar la información del plugin %1$s.</string>
|
||||||
|
<string name="error_plugin_returned_empty_info">El plugin %1$s devolvió información vacía.</string>
|
||||||
|
<string name="error_plugin_returned_invalid_variant">El plugin %1$s devolvió una variante no válida: %2$s.</string>
|
||||||
|
<string name="error_no_embedded_paddle_ocr_assets_found">No se encontraron recursos integrados de Paddle OCR. Vuelve a empaquetar con Paddle OCR habilitado.</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1179,5 +1179,15 @@
|
|||||||
<string name="text_sort_by_name">Trier par nom</string>
|
<string name="text_sort_by_name">Trier par nom</string>
|
||||||
<string name="text_sort_by_last_update_time">Trier par dernière mise à jour</string>
|
<string name="text_sort_by_last_update_time">Trier par dernière mise à jour</string>
|
||||||
<string name="text_sort_by_package_size">Trier par taille du paquet</string>
|
<string name="text_sort_by_package_size">Trier par taille du paquet</string>
|
||||||
|
<string name="error_missing_required_plugin_for_module_label">Plugin requis manquant pour \"%1$s\". Veuillez installer le plugin et réessayer.</string>
|
||||||
|
<string name="error_no_enabled_plugin_for_module_label">Aucun plugin activé pour \"%1$s\". Veuillez activer un plugin et réessayer.</string>
|
||||||
|
<string name="error_no_available_enabled_plugin_variants_found">Aucune variante de plugin %1$s activée et disponible n\'a été trouvée (%2$s).</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_assets_for_variant">L\'APK du plugin ne contient pas les ressources requises pour variant=\"%1$s\": %2$s.</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_native_libraries">L\'APK du plugin ne contient pas les bibliothèques natives requises: %1$s.</string>
|
||||||
|
<string name="error_failed_to_bind_plugin_service">Échec de la liaison du service du plugin %1$s.</string>
|
||||||
|
<string name="error_timeout_while_querying_plugin_info">Délai d\'attente dépassé lors de la requête des informations du plugin %1$s.</string>
|
||||||
|
<string name="error_plugin_returned_empty_info">Le plugin %1$s a renvoyé des informations vides.</string>
|
||||||
|
<string name="error_plugin_returned_invalid_variant">Le plugin %1$s a renvoyé une variante invalide: %2$s.</string>
|
||||||
|
<string name="error_no_embedded_paddle_ocr_assets_found">Aucune ressource Paddle OCR intégrée n\'a été trouvée. Veuillez reconditionner avec Paddle OCR activé.</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1180,5 +1180,15 @@
|
|||||||
<string name="text_sort_by_name">名前で並べ替え</string>
|
<string name="text_sort_by_name">名前で並べ替え</string>
|
||||||
<string name="text_sort_by_last_update_time">最終更新日で並べ替え</string>
|
<string name="text_sort_by_last_update_time">最終更新日で並べ替え</string>
|
||||||
<string name="text_sort_by_package_size">パッケージサイズで並べ替え</string>
|
<string name="text_sort_by_package_size">パッケージサイズで並べ替え</string>
|
||||||
|
<string name="error_missing_required_plugin_for_module_label">\"%1$s\" に必要なプラグインが見つかりません. プラグインをインストールしてから再試行してください.</string>
|
||||||
|
<string name="error_no_enabled_plugin_for_module_label">\"%1$s\" に有効化されたプラグインがありません. プラグインを有効化してから再試行してください.</string>
|
||||||
|
<string name="error_no_available_enabled_plugin_variants_found">利用可能で有効化された %1$s プラグインの variant が見つかりません (%2$s).</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_assets_for_variant">プラグイン APK に variant=\"%1$s\" に必要な assets が含まれていません: %2$s.</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_native_libraries">プラグイン APK に必要な native ライブラリが含まれていません: %1$s.</string>
|
||||||
|
<string name="error_failed_to_bind_plugin_service">%1$s プラグインサービスのバインドに失敗しました.</string>
|
||||||
|
<string name="error_timeout_while_querying_plugin_info">%1$s プラグイン情報の取得がタイムアウトしました.</string>
|
||||||
|
<string name="error_plugin_returned_empty_info">%1$s プラグインが空の info を返しました.</string>
|
||||||
|
<string name="error_plugin_returned_invalid_variant">%1$s プラグインが無効な variant を返しました: %2$s.</string>
|
||||||
|
<string name="error_no_embedded_paddle_ocr_assets_found">埋め込みの Paddle OCR assets が見つかりません. Paddle OCR を有効にして再パッケージしてください.</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1181,5 +1181,15 @@
|
|||||||
<string name="text_sort_by_name">이름순 정렬</string>
|
<string name="text_sort_by_name">이름순 정렬</string>
|
||||||
<string name="text_sort_by_last_update_time">최근 업데이트순 정렬</string>
|
<string name="text_sort_by_last_update_time">최근 업데이트순 정렬</string>
|
||||||
<string name="text_sort_by_package_size">패키지 크기순 정렬</string>
|
<string name="text_sort_by_package_size">패키지 크기순 정렬</string>
|
||||||
|
<string name="error_missing_required_plugin_for_module_label">\"%1$s\"에 필요한 플러그인이 없습니다. 플러그인을 설치한 후 다시 시도해 주세요.</string>
|
||||||
|
<string name="error_no_enabled_plugin_for_module_label">\"%1$s\"에 활성화된 플러그인이 없습니다. 플러그인을 활성화한 후 다시 시도해 주세요.</string>
|
||||||
|
<string name="error_no_available_enabled_plugin_variants_found">사용 가능하며 활성화된 %1$s 플러그인 variant를 찾을 수 없습니다 (%2$s).</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_assets_for_variant">플러그인 APK에 variant=\"%1$s\"에 필요한 assets가 포함되어 있지 않습니다: %2$s.</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_native_libraries">플러그인 APK에 필요한 native 라이브러리가 포함되어 있지 않습니다: %1$s.</string>
|
||||||
|
<string name="error_failed_to_bind_plugin_service">%1$s 플러그인 서비스 바인딩에 실패했습니다.</string>
|
||||||
|
<string name="error_timeout_while_querying_plugin_info">%1$s 플러그인 정보 조회가 시간 초과되었습니다.</string>
|
||||||
|
<string name="error_plugin_returned_empty_info">%1$s 플러그인이 빈 info를 반환했습니다.</string>
|
||||||
|
<string name="error_plugin_returned_invalid_variant">%1$s 플러그인이 잘못된 variant를 반환했습니다: %2$s.</string>
|
||||||
|
<string name="error_no_embedded_paddle_ocr_assets_found">내장된 Paddle OCR assets를 찾을 수 없습니다. Paddle OCR을 활성화하여 다시 패키징해 주세요.</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1179,5 +1179,15 @@
|
|||||||
<string name="text_sort_by_name">Сортировать по имени</string>
|
<string name="text_sort_by_name">Сортировать по имени</string>
|
||||||
<string name="text_sort_by_last_update_time">Сортировать по времени последнего обновления</string>
|
<string name="text_sort_by_last_update_time">Сортировать по времени последнего обновления</string>
|
||||||
<string name="text_sort_by_package_size">Сортировать по размеру пакета</string>
|
<string name="text_sort_by_package_size">Сортировать по размеру пакета</string>
|
||||||
|
<string name="error_missing_required_plugin_for_module_label">Отсутствует требуемый плагин для \"%1$s\". Установите плагин и повторите попытку.</string>
|
||||||
|
<string name="error_no_enabled_plugin_for_module_label">Для \"%1$s\" нет включённого плагина. Включите плагин и повторите попытку.</string>
|
||||||
|
<string name="error_no_available_enabled_plugin_variants_found">Не найдено доступных и включённых вариантов плагина %1$s (%2$s).</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_assets_for_variant">APK плагина не содержит требуемые ресурсы для variant=\"%1$s\": %2$s.</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_native_libraries">APK плагина не содержит требуемые native-библиотеки: %1$s.</string>
|
||||||
|
<string name="error_failed_to_bind_plugin_service">Не удалось привязаться к службе плагина %1$s.</string>
|
||||||
|
<string name="error_timeout_while_querying_plugin_info">Тайм-аут при запросе информации о плагине %1$s.</string>
|
||||||
|
<string name="error_plugin_returned_empty_info">Плагин %1$s вернул пустую информацию.</string>
|
||||||
|
<string name="error_plugin_returned_invalid_variant">Плагин %1$s вернул недопустимый variant: %2$s.</string>
|
||||||
|
<string name="error_no_embedded_paddle_ocr_assets_found">Не найдены встроенные ресурсы Paddle OCR. Перепакуйте приложение с включённым Paddle OCR.</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
@@ -71,7 +71,7 @@
|
|||||||
<string name="description_all_files_access" tools:ignore="TypographyEllipsis">\"管理所有文件\" (或 \"所有文件訪問\") 權限允許 AutoJs6 在共享存儲空間中通過常規文件路徑直接 [ 創建 / 讀取 / 修改 / 刪除 ] 文件, 使腳本可以訪問 \"內部存儲 (Internal Storage)\", 使文件管理器可以正常顯示及管理文件.\n\n在 Android 11+ 設備上, 這是實現全盤文件讀寫能力的主要方式.</string>
|
<string name="description_all_files_access" tools:ignore="TypographyEllipsis">\"管理所有文件\" (或 \"所有文件訪問\") 權限允許 AutoJs6 在共享存儲空間中通過常規文件路徑直接 [ 創建 / 讀取 / 修改 / 刪除 ] 文件, 使腳本可以訪問 \"內部存儲 (Internal Storage)\", 使文件管理器可以正常顯示及管理文件.\n\n在 Android 11+ 設備上, 這是實現全盤文件讀寫能力的主要方式.</string>
|
||||||
<string name="description_app_language_preference">設置選項用於修改 AutoJs6 應用的文本內容顯示語言, 同時包括腳本運行產生的錯誤消息等.\n\n注: 部分內容可能需要重啓應用才能完成語言切換.</string>
|
<string name="description_app_language_preference">設置選項用於修改 AutoJs6 應用的文本內容顯示語言, 同時包括腳本運行產生的錯誤消息等.\n\n注: 部分內容可能需要重啓應用才能完成語言切換.</string>
|
||||||
<string name="description_auto_night_mode">自動夜間模式開啓後, AutoJs6 將根據系統設置自動切換夜間模式.\n\注: 自動夜間模式開關與夜間模式開關互相關聯且互相影響.</string>
|
<string name="description_auto_night_mode">自動夜間模式開啓後, AutoJs6 將根據系統設置自動切換夜間模式.\n\注: 自動夜間模式開關與夜間模式開關互相關聯且互相影響.</string>
|
||||||
<string name="description_background_popup_permission" tools:ignore="TypographyEllipsis">\"後台彈出界面\" (也稱 \"後台啓動界面\" 或 \"後台彈出頁面\") 權限允許 AutoJs6 在應用位於後台或未顯示界面時, 仍可主動啓動界面(Activity) 或打開特定設置頁, 適合 [ 定時任務觸發時打開 UI / 在鎖屏或待機後恢復交互 / 由通知或快捷方式喚起腳本配置頁 ] 等場景.\n\n注: 在 Xiaomi (MIUI/HyperOS), Vivo (OriginOS/Funtouch OS) 等系統上, 該權限可能默認關閉. 未授予時, 腳本嘗試從後台打開頁面可能會被系統攔截, 表現為 [ 無響應 / 僅後台執行但不顯示界面 / 跳轉失敗 ].\n\n授予後仍可能受到系統其他策略影響, 如 [ 電池優化 / 自啓動限制 / 後台凍結 / 應用待機 ] 等, 可結合相關權限或白名單設置一起調整.</string>
|
<string name="description_background_popup_permission" tools:ignore="TypographyEllipsis">\"後台彈出界面\" (也稱 \"後台啓動界面\" 或 \"後台彈出頁面\") 權限允許 AutoJs6 在應用位於後台或未顯示界面時, 仍可主動啓動界面 (Activity) 或打開特定設置頁, 適合 [ 定時任務觸發時打開 UI / 在鎖屏或待機後恢復交互 / 由通知或快捷方式喚起腳本配置頁 ] 等場景.\n\n注: 在 Xiaomi (MIUI/HyperOS), Vivo (OriginOS/Funtouch OS) 等系統上, 該權限可能默認關閉. 未授予時, 腳本嘗試從後台打開頁面可能會被系統攔截, 表現為 [ 無響應 / 僅後台執行但不顯示界面 / 跳轉失敗 ].\n\n授予後仍可能受到系統其他策略影響, 如 [ 電池優化 / 自啓動限制 / 後台凍結 / 應用待機 ] 等, 可結合相關權限或白名單設置一起調整.</string>
|
||||||
<string name="description_change_working_dir_preference">更改包含腳本的文件夾路徑</string>
|
<string name="description_change_working_dir_preference">更改包含腳本的文件夾路徑</string>
|
||||||
<string name="description_check_for_updates_preference">AutoJs6 從 GitHub 獲取並下載更新.</string>
|
<string name="description_check_for_updates_preference">AutoJs6 從 GitHub 獲取並下載更新.</string>
|
||||||
<string name="description_client_mode">客户端模式用於讓 AutoJs6 主動連接到遠端服務端, 以便進行 [ 腳本傳輸 / 打印日誌 / 遠程控制 ] 等.\n\n通常需要設備與服務端處於同一局域網或可互相訪問的網絡環境.</string>
|
<string name="description_client_mode">客户端模式用於讓 AutoJs6 主動連接到遠端服務端, 以便進行 [ 腳本傳輸 / 打印日誌 / 遠程控制 ] 等.\n\n通常需要設備與服務端處於同一局域網或可互相訪問的網絡環境.</string>
|
||||||
@@ -1177,5 +1177,15 @@
|
|||||||
<string name="text_sort_by_name">按名稱排序</string>
|
<string name="text_sort_by_name">按名稱排序</string>
|
||||||
<string name="text_sort_by_last_update_time">按最近更新排序</string>
|
<string name="text_sort_by_last_update_time">按最近更新排序</string>
|
||||||
<string name="text_sort_by_package_size">按安裝包大小排序</string>
|
<string name="text_sort_by_package_size">按安裝包大小排序</string>
|
||||||
|
<string name="error_missing_required_plugin_for_module_label">缺少 \"%1$s\" 所需的插件. 請先安裝插件, 然後重試.</string>
|
||||||
|
<string name="error_no_enabled_plugin_for_module_label">\"%1$s\" 沒有已啓用的插件. 請先啓用插件, 然後重試.</string>
|
||||||
|
<string name="error_no_available_enabled_plugin_variants_found">未找到可用且已啓用的 %1$s 插件變體 (%2$s).</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_assets_for_variant">插件 APK 不包含變體 \"%1$s\" 所需的資源文件: %2$s.</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_native_libraries">插件 APK 不包含所需的 native 庫文件: %1$s.</string>
|
||||||
|
<string name="error_failed_to_bind_plugin_service">綁定 %1$s 插件服務失敗.</string>
|
||||||
|
<string name="error_timeout_while_querying_plugin_info">查詢 %1$s 插件信息超時.</string>
|
||||||
|
<string name="error_plugin_returned_empty_info">%1$s 插件返回的 info 為空.</string>
|
||||||
|
<string name="error_plugin_returned_invalid_variant">%1$s 插件返回的 variant 無效: %2$s.</string>
|
||||||
|
<string name="error_no_embedded_paddle_ocr_assets_found">未找到內置 Paddle OCR 資源, 請在打包時勾選並注入 Paddle OCR 後重試.</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
@@ -71,7 +71,7 @@
|
|||||||
<string name="description_all_files_access" tools:ignore="TypographyEllipsis">\"管理所有檔案\" (或 \"所有檔案訪問\") 許可權允許 AutoJs6 在共享儲存空間中透過常規檔案路徑直接 [ 建立 / 讀取 / 修改 / 刪除 ] 檔案, 使指令碼可以訪問 \"內部儲存 (Internal Storage)\", 使檔案管理器可以正常顯示及管理檔案.\n\n在 Android 11+ 裝置上, 這是實現全盤檔案讀寫能力的主要方式.</string>
|
<string name="description_all_files_access" tools:ignore="TypographyEllipsis">\"管理所有檔案\" (或 \"所有檔案訪問\") 許可權允許 AutoJs6 在共享儲存空間中透過常規檔案路徑直接 [ 建立 / 讀取 / 修改 / 刪除 ] 檔案, 使指令碼可以訪問 \"內部儲存 (Internal Storage)\", 使檔案管理器可以正常顯示及管理檔案.\n\n在 Android 11+ 裝置上, 這是實現全盤檔案讀寫能力的主要方式.</string>
|
||||||
<string name="description_app_language_preference">設定選項用於修改 AutoJs6 應用的文字內容顯示語言, 同時包括指令碼執行產生的錯誤訊息等.\n\n注: 部分內容可能需要重啟應用才能完成語言切換.</string>
|
<string name="description_app_language_preference">設定選項用於修改 AutoJs6 應用的文字內容顯示語言, 同時包括指令碼執行產生的錯誤訊息等.\n\n注: 部分內容可能需要重啟應用才能完成語言切換.</string>
|
||||||
<string name="description_auto_night_mode">自動夜間模式開啟後, AutoJs6 將根據系統設定自動切換夜間模式.\n\注: 自動夜間模式開關與夜間模式開關互相關聯且互相影響.</string>
|
<string name="description_auto_night_mode">自動夜間模式開啟後, AutoJs6 將根據系統設定自動切換夜間模式.\n\注: 自動夜間模式開關與夜間模式開關互相關聯且互相影響.</string>
|
||||||
<string name="description_background_popup_permission" tools:ignore="TypographyEllipsis">\"後臺彈出介面\" (也稱 \"後臺啟動介面\" 或 \"後臺彈出頁面\") 許可權允許 AutoJs6 在應用位於後臺或未顯示介面時, 仍可主動啟動介面(Activity) 或開啟特定設定頁, 適合 [ 定時任務觸發時開啟 UI / 在鎖屏或待機後恢復互動 / 由通知或快捷方式喚起指令碼配置頁 ] 等場景.\n\n注: 在 Xiaomi (MIUI/HyperOS), Vivo (OriginOS/Funtouch OS) 等系統上, 該許可權可能預設關閉. 未授予時, 指令碼嘗試從後臺開啟頁面可能會被系統攔截, 表現為 [ 無響應 / 僅後臺執行但不顯示介面 / 跳轉失敗 ].\n\n授予後仍可能受到系統其他策略影響, 如 [ 電池最佳化 / 自啟動限制 / 後臺凍結 / 應用待機 ] 等, 可結合相關許可權或白名單設定一起調整.</string>
|
<string name="description_background_popup_permission" tools:ignore="TypographyEllipsis">\"後臺彈出介面\" (也稱 \"後臺啟動介面\" 或 \"後臺彈出頁面\") 許可權允許 AutoJs6 在應用位於後臺或未顯示介面時, 仍可主動啟動介面 (Activity) 或開啟特定設定頁, 適合 [ 定時任務觸發時開啟 UI / 在鎖屏或待機後恢復互動 / 由通知或快捷方式喚起指令碼配置頁 ] 等場景.\n\n注: 在 Xiaomi (MIUI/HyperOS), Vivo (OriginOS/Funtouch OS) 等系統上, 該許可權可能預設關閉. 未授予時, 指令碼嘗試從後臺開啟頁面可能會被系統攔截, 表現為 [ 無響應 / 僅後臺執行但不顯示介面 / 跳轉失敗 ].\n\n授予後仍可能受到系統其他策略影響, 如 [ 電池最佳化 / 自啟動限制 / 後臺凍結 / 應用待機 ] 等, 可結合相關許可權或白名單設定一起調整.</string>
|
||||||
<string name="description_change_working_dir_preference">更改包含指令碼的資料夾路徑</string>
|
<string name="description_change_working_dir_preference">更改包含指令碼的資料夾路徑</string>
|
||||||
<string name="description_check_for_updates_preference">AutoJs6 從 GitHub 獲取並下載更新.</string>
|
<string name="description_check_for_updates_preference">AutoJs6 從 GitHub 獲取並下載更新.</string>
|
||||||
<string name="description_client_mode">客戶端模式用於讓 AutoJs6 主動連線到遠端服務端, 以便進行 [ 指令碼傳輸 / 列印日誌 / 遠端控制 ] 等.\n\n通常需要裝置與服務端處於同一區域網或可互相訪問的網路環境.</string>
|
<string name="description_client_mode">客戶端模式用於讓 AutoJs6 主動連線到遠端服務端, 以便進行 [ 指令碼傳輸 / 列印日誌 / 遠端控制 ] 等.\n\n通常需要裝置與服務端處於同一區域網或可互相訪問的網路環境.</string>
|
||||||
@@ -1177,5 +1177,15 @@
|
|||||||
<string name="text_sort_by_name">按名稱排序</string>
|
<string name="text_sort_by_name">按名稱排序</string>
|
||||||
<string name="text_sort_by_last_update_time">按最近更新排序</string>
|
<string name="text_sort_by_last_update_time">按最近更新排序</string>
|
||||||
<string name="text_sort_by_package_size">按安裝包大小排序</string>
|
<string name="text_sort_by_package_size">按安裝包大小排序</string>
|
||||||
|
<string name="error_missing_required_plugin_for_module_label">缺少 \"%1$s\" 所需的外掛. 請先安裝外掛, 然後重試.</string>
|
||||||
|
<string name="error_no_enabled_plugin_for_module_label">\"%1$s\" 沒有已啟用的外掛. 請先啟用外掛, 然後重試.</string>
|
||||||
|
<string name="error_no_available_enabled_plugin_variants_found">未找到可用且已啟用的 %1$s 外掛變體 (%2$s).</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_assets_for_variant">外掛 APK 不包含變體 \"%1$s\" 所需的資原始檔: %2$s.</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_native_libraries">外掛 APK 不包含所需的 native 庫檔案: %1$s.</string>
|
||||||
|
<string name="error_failed_to_bind_plugin_service">繫結 %1$s 外掛服務失敗.</string>
|
||||||
|
<string name="error_timeout_while_querying_plugin_info">查詢 %1$s 外掛資訊超時.</string>
|
||||||
|
<string name="error_plugin_returned_empty_info">%1$s 外掛返回的 info 為空.</string>
|
||||||
|
<string name="error_plugin_returned_invalid_variant">%1$s 外掛返回的 variant 無效: %2$s.</string>
|
||||||
|
<string name="error_no_embedded_paddle_ocr_assets_found">未找到內建 Paddle OCR 資源, 請在打包時勾選並注入 Paddle OCR 後重試.</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
@@ -70,7 +70,7 @@
|
|||||||
<string name="description_all_files_access" tools:ignore="TypographyEllipsis">\"管理所有文件\" (或 \"所有文件访问\") 权限允许 AutoJs6 在共享存储空间中通过常规文件路径直接 [ 创建 / 读取 / 修改 / 删除 ] 文件, 使脚本可以访问 \"内部存储 (Internal Storage)\", 使文件管理器可以正常显示及管理文件.\n\n在 Android 11+ 设备上, 这是实现全盘文件读写能力的主要方式.</string>
|
<string name="description_all_files_access" tools:ignore="TypographyEllipsis">\"管理所有文件\" (或 \"所有文件访问\") 权限允许 AutoJs6 在共享存储空间中通过常规文件路径直接 [ 创建 / 读取 / 修改 / 删除 ] 文件, 使脚本可以访问 \"内部存储 (Internal Storage)\", 使文件管理器可以正常显示及管理文件.\n\n在 Android 11+ 设备上, 这是实现全盘文件读写能力的主要方式.</string>
|
||||||
<string name="description_app_language_preference">设置选项用于修改 AutoJs6 应用的文本内容显示语言, 同时包括脚本运行产生的错误消息等.\n\n注: 部分内容可能需要重启应用才能完成语言切换.</string>
|
<string name="description_app_language_preference">设置选项用于修改 AutoJs6 应用的文本内容显示语言, 同时包括脚本运行产生的错误消息等.\n\n注: 部分内容可能需要重启应用才能完成语言切换.</string>
|
||||||
<string name="description_auto_night_mode">自动夜间模式开启后, AutoJs6 将根据系统设置自动切换夜间模式.\n\注: 自动夜间模式开关与夜间模式开关互相关联且互相影响.</string>
|
<string name="description_auto_night_mode">自动夜间模式开启后, AutoJs6 将根据系统设置自动切换夜间模式.\n\注: 自动夜间模式开关与夜间模式开关互相关联且互相影响.</string>
|
||||||
<string name="description_background_popup_permission" tools:ignore="TypographyEllipsis">\"后台弹出界面\" (也称 \"后台启动界面\" 或 \"后台弹出页面\") 权限允许 AutoJs6 在应用位于后台或未显示界面时, 仍可主动启动界面(Activity) 或打开特定设置页, 适合 [ 定时任务触发时打开 UI / 在锁屏或待机后恢复交互 / 由通知或快捷方式唤起脚本配置页 ] 等场景.\n\n注: 在 Xiaomi (MIUI/HyperOS), Vivo (OriginOS/Funtouch OS) 等系统上, 该权限可能默认关闭. 未授予时, 脚本尝试从后台打开页面可能会被系统拦截, 表现为 [ 无响应 / 仅后台执行但不显示界面 / 跳转失败 ].\n\n授予后仍可能受到系统其他策略影响, 如 [ 电池优化 / 自启动限制 / 后台冻结 / 应用待机 ] 等, 可结合相关权限或白名单设置一起调整.</string>
|
<string name="description_background_popup_permission" tools:ignore="TypographyEllipsis">\"后台弹出界面\" (也称 \"后台启动界面\" 或 \"后台弹出页面\") 权限允许 AutoJs6 在应用位于后台或未显示界面时, 仍可主动启动界面 (Activity) 或打开特定设置页, 适合 [ 定时任务触发时打开 UI / 在锁屏或待机后恢复交互 / 由通知或快捷方式唤起脚本配置页 ] 等场景.\n\n注: 在 Xiaomi (MIUI/HyperOS), Vivo (OriginOS/Funtouch OS) 等系统上, 该权限可能默认关闭. 未授予时, 脚本尝试从后台打开页面可能会被系统拦截, 表现为 [ 无响应 / 仅后台执行但不显示界面 / 跳转失败 ].\n\n授予后仍可能受到系统其他策略影响, 如 [ 电池优化 / 自启动限制 / 后台冻结 / 应用待机 ] 等, 可结合相关权限或白名单设置一起调整.</string>
|
||||||
<string name="description_change_working_dir_preference">更改包含脚本的文件夹路径</string>
|
<string name="description_change_working_dir_preference">更改包含脚本的文件夹路径</string>
|
||||||
<string name="description_check_for_updates_preference">AutoJs6 从 GitHub 获取并下载更新.</string>
|
<string name="description_check_for_updates_preference">AutoJs6 从 GitHub 获取并下载更新.</string>
|
||||||
<string name="description_client_mode">客户端模式用于让 AutoJs6 主动连接到远端服务端, 以便进行 [ 脚本传输 / 打印日志 / 远程控制 ] 等.\n\n通常需要设备与服务端处于同一局域网或可互相访问的网络环境.</string>
|
<string name="description_client_mode">客户端模式用于让 AutoJs6 主动连接到远端服务端, 以便进行 [ 脚本传输 / 打印日志 / 远程控制 ] 等.\n\n通常需要设备与服务端处于同一局域网或可互相访问的网络环境.</string>
|
||||||
@@ -1177,5 +1177,15 @@
|
|||||||
<string name="text_sort_by_name">按名称排序</string>
|
<string name="text_sort_by_name">按名称排序</string>
|
||||||
<string name="text_sort_by_last_update_time">按最近更新排序</string>
|
<string name="text_sort_by_last_update_time">按最近更新排序</string>
|
||||||
<string name="text_sort_by_package_size">按安装包大小排序</string>
|
<string name="text_sort_by_package_size">按安装包大小排序</string>
|
||||||
|
<string name="error_missing_required_plugin_for_module_label">缺少 \"%1$s\" 所需的插件. 请先安装插件, 然后重试.</string>
|
||||||
|
<string name="error_no_enabled_plugin_for_module_label">\"%1$s\" 没有已启用的插件. 请先启用插件, 然后重试.</string>
|
||||||
|
<string name="error_no_available_enabled_plugin_variants_found">未找到可用且已启用的 %1$s 插件变体 (%2$s).</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_assets_for_variant">插件 APK 不包含变体 \"%1$s\" 所需的资源文件: %2$s.</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_native_libraries">插件 APK 不包含所需的 native 库文件: %1$s.</string>
|
||||||
|
<string name="error_failed_to_bind_plugin_service">绑定 %1$s 插件服务失败.</string>
|
||||||
|
<string name="error_timeout_while_querying_plugin_info">查询 %1$s 插件信息超时.</string>
|
||||||
|
<string name="error_plugin_returned_empty_info">%1$s 插件返回的 info 为空.</string>
|
||||||
|
<string name="error_plugin_returned_invalid_variant">%1$s 插件返回的 variant 无效: %2$s.</string>
|
||||||
|
<string name="error_no_embedded_paddle_ocr_assets_found">未找到内置 Paddle OCR 资源, 请在打包时勾选并注入 Paddle OCR 后重试.</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
@@ -1434,5 +1434,15 @@
|
|||||||
<string name="text_sort_by_name">Sort by name</string>
|
<string name="text_sort_by_name">Sort by name</string>
|
||||||
<string name="text_sort_by_last_update_time">Sort by last update time</string>
|
<string name="text_sort_by_last_update_time">Sort by last update time</string>
|
||||||
<string name="text_sort_by_package_size">Sort by package size</string>
|
<string name="text_sort_by_package_size">Sort by package size</string>
|
||||||
|
<string name="error_missing_required_plugin_for_module_label">Missing required plugin for \"%1$s\". Please install the plugin and try again.</string>
|
||||||
|
<string name="error_no_enabled_plugin_for_module_label">No enabled plugin for \"%1$s\". Please enable a plugin and try again.</string>
|
||||||
|
<string name="error_no_available_enabled_plugin_variants_found">No available enabled %1$s plugin variants found (%2$s).</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_assets_for_variant">Plugin APK does not contain required assets for variant=\"%1$s\": %2$s.</string>
|
||||||
|
<string name="error_plugin_apk_does_not_contain_required_native_libraries">Plugin APK does not contain required native libraries: %1$s.</string>
|
||||||
|
<string name="error_failed_to_bind_plugin_service">Failed to bind %1$s plugin service.</string>
|
||||||
|
<string name="error_timeout_while_querying_plugin_info">Timeout while querying %1$s plugin info.</string>
|
||||||
|
<string name="error_plugin_returned_empty_info">%1$s plugin returned empty info.</string>
|
||||||
|
<string name="error_plugin_returned_invalid_variant">%1$s plugin returned invalid variant: %2$s.</string>
|
||||||
|
<string name="error_no_embedded_paddle_ocr_assets_found">No embedded Paddle OCR assets found. Please re-package with Paddle OCR enabled.</string>
|
||||||
|
|
||||||
</resources>
|
</resources>
|
||||||
@@ -7,7 +7,7 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = "org.autojs.plugin.paddle.ocr"
|
namespace = "org.autojs.plugin.paddle.ocr.api"
|
||||||
|
|
||||||
compileSdk = versions.sdkVersionCompile
|
compileSdk = versions.sdkVersionCompile
|
||||||
|
|
||||||
File renamed without changes.
+4
-4
@@ -1,8 +1,8 @@
|
|||||||
package org.autojs.plugin.paddle.ocr;
|
package org.autojs.plugin.paddle.ocr.api;
|
||||||
|
|
||||||
import org.autojs.plugin.paddle.ocr.PluginInfo;
|
import org.autojs.plugin.paddle.ocr.api.PluginInfo;
|
||||||
import org.autojs.plugin.paddle.ocr.OcrOptions;
|
import org.autojs.plugin.paddle.ocr.api.OcrOptions;
|
||||||
import org.autojs.plugin.paddle.ocr.OcrResult;
|
import org.autojs.plugin.paddle.ocr.api.OcrResult;
|
||||||
import android.os.ParcelFileDescriptor;
|
import android.os.ParcelFileDescriptor;
|
||||||
|
|
||||||
interface IOcrPlugin {
|
interface IOcrPlugin {
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package org.autojs.plugin.paddle.ocr;
|
package org.autojs.plugin.paddle.ocr.api;
|
||||||
|
|
||||||
parcelable OcrOptions {
|
parcelable OcrOptions {
|
||||||
int cpuThreadNum;
|
int cpuThreadNum;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package org.autojs.plugin.paddle.ocr;
|
package org.autojs.plugin.paddle.ocr.api;
|
||||||
|
|
||||||
parcelable OcrResult {
|
parcelable OcrResult {
|
||||||
String text;
|
String text;
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package org.autojs.plugin.paddle.ocr;
|
package org.autojs.plugin.paddle.ocr.api;
|
||||||
|
|
||||||
parcelable PluginInfo {
|
parcelable PluginInfo {
|
||||||
|
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
plugins {
|
||||||
|
id("org.autojs.build.versions")
|
||||||
|
id("org.autojs.build.jvm-convention")
|
||||||
|
id("com.android.library")
|
||||||
|
id("org.jetbrains.kotlin.android")
|
||||||
|
kotlin("plugin.parcelize")
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "com.baidu.paddle.lite.ocr"
|
||||||
|
|
||||||
|
compileSdk = versions.sdkVersionCompile
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
minSdk = versions.sdkVersionMin
|
||||||
|
consumerProguardFiles("consumer-rules.pro")
|
||||||
|
}
|
||||||
|
|
||||||
|
lint {
|
||||||
|
targetSdk = versions.sdkVersionTarget
|
||||||
|
abortOnError = false
|
||||||
|
}
|
||||||
|
|
||||||
|
buildFeatures {
|
||||||
|
buildConfig = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
// Depend on AIDL api types (OcrOptions/OcrResult) to keep unified DTO in host/plugin.
|
||||||
|
// zh-CN: 依赖 AIDL api 类型 (OcrOptions/OcrResult), 以保持宿主/插件 DTO 统一.
|
||||||
|
implementation(projects.pluginApi.paddleOcrApi)
|
||||||
|
|
||||||
|
// OpenCV is required at compile time because OCRPredictorNative references OpenCVLoader.
|
||||||
|
// zh-CN: OCRPredictorNative 引用了 OpenCVLoader, 因此需要 OpenCV 编译期依赖.
|
||||||
|
compileOnly(projects.libs.orgOpencv480)
|
||||||
|
|
||||||
|
implementation(libs.core.ktx)
|
||||||
|
implementation(libs.preference.ktx)
|
||||||
|
}
|
||||||
Whitespace-only changes.
+123
@@ -0,0 +1,123 @@
|
|||||||
|
package com.baidu.paddle.lite.ocr;
|
||||||
|
|
||||||
|
import android.graphics.Bitmap;
|
||||||
|
import android.util.Log;
|
||||||
|
|
||||||
|
import org.opencv.android.OpenCVLoader;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean;
|
||||||
|
import java.util.concurrent.locks.ReentrantLock;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author PaddleOCR
|
||||||
|
* Modified by TonyJiangWJ
|
||||||
|
* @since 2023-08-06
|
||||||
|
*/
|
||||||
|
public class OCRPredictorNative {
|
||||||
|
|
||||||
|
private static final AtomicBoolean isSOLoaded = new AtomicBoolean();
|
||||||
|
private static final ReentrantLock lock = new ReentrantLock();
|
||||||
|
|
||||||
|
public static void loadLibrary() throws RuntimeException {
|
||||||
|
if (!isSOLoaded.get() && isSOLoaded.compareAndSet(false, true)) {
|
||||||
|
try {
|
||||||
|
// 可能和 AJ 中的 OpenCV 冲突, 直接初始化一遍
|
||||||
|
OpenCVLoader.initDebug();
|
||||||
|
System.loadLibrary("Native");
|
||||||
|
} catch (Throwable e) {
|
||||||
|
throw new RuntimeException(
|
||||||
|
"Load libNative.so failed, please check it exists in apk file.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private long nativePointer;
|
||||||
|
|
||||||
|
public OCRPredictorNative(Config config) {
|
||||||
|
lock.lock();
|
||||||
|
try {
|
||||||
|
loadLibrary();
|
||||||
|
nativePointer = init(config.detModelFilename, config.recModelFilename, config.clsModelFilename, config.useOpenCL,
|
||||||
|
config.cpuThreadNum, config.cpuPower);
|
||||||
|
Log.i("OCRPredictorNative", "load success " + nativePointer);
|
||||||
|
} finally {
|
||||||
|
lock.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public ArrayList<OcrResultModel> runImage(Bitmap originalImage, int max_size_len, int run_det, int run_cls, int run_rec) {
|
||||||
|
lock.lock();
|
||||||
|
try {
|
||||||
|
Log.i("OCRPredictorNative", "begin to run image");
|
||||||
|
float[] rawResults = forward(nativePointer, originalImage, max_size_len, run_det, run_cls, run_rec);
|
||||||
|
return postprocess(rawResults);
|
||||||
|
} finally {
|
||||||
|
lock.unlock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class Config {
|
||||||
|
public int useOpenCL;
|
||||||
|
public int cpuThreadNum;
|
||||||
|
public String cpuPower;
|
||||||
|
public String detModelFilename;
|
||||||
|
public String recModelFilename;
|
||||||
|
public String clsModelFilename;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public void destroy() {
|
||||||
|
if (nativePointer != 0) {
|
||||||
|
release(nativePointer);
|
||||||
|
nativePointer = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected native long init(String detModelPath, String recModelPath, String clsModelPath, int useOpenCL, int threadNum, String cpuMode);
|
||||||
|
|
||||||
|
protected native float[] forward(long pointer, Bitmap originalImage, int max_size_len, int run_det, int run_cls, int run_rec);
|
||||||
|
|
||||||
|
protected native void release(long pointer);
|
||||||
|
|
||||||
|
private ArrayList<OcrResultModel> postprocess(float[] raw) {
|
||||||
|
ArrayList<OcrResultModel> results = new ArrayList<>();
|
||||||
|
int begin = 0;
|
||||||
|
|
||||||
|
while (begin < raw.length) {
|
||||||
|
int point_num = Math.round(raw[begin]);
|
||||||
|
int word_num = Math.round(raw[begin + 1]);
|
||||||
|
OcrResultModel model = parse(raw, begin + 2, point_num, word_num);
|
||||||
|
begin += 2 + 1 + point_num * 2 + word_num + 2;
|
||||||
|
results.add(model);
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
private OcrResultModel parse(float[] raw, int begin, int pointNum, int wordNum) {
|
||||||
|
int current = begin;
|
||||||
|
OcrResultModel model = new OcrResultModel();
|
||||||
|
model.setConfidence(raw[current]);
|
||||||
|
current++;
|
||||||
|
for (int i = 0; i < pointNum; i++) {
|
||||||
|
model.addPoints(Math.round(raw[current + i * 2]), Math.round(raw[current + i * 2 + 1]));
|
||||||
|
}
|
||||||
|
current += (pointNum * 2);
|
||||||
|
for (int i = 0; i < wordNum; i++) {
|
||||||
|
int index = Math.round(raw[current + i]);
|
||||||
|
model.addWordIndex(index);
|
||||||
|
}
|
||||||
|
current += wordNum;
|
||||||
|
model.setClsIdx(raw[current]);
|
||||||
|
model.setClsConfidence(raw[current + 1]);
|
||||||
|
// Log.i("OCRPredictorNative", "word finished " + wordNum);
|
||||||
|
return model;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void finalize() throws Throwable {
|
||||||
|
super.finalize();
|
||||||
|
destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package com.baidu.paddle.lite.ocr;
|
||||||
|
|
||||||
|
import android.graphics.Point;
|
||||||
|
import android.graphics.Rect;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author PaddleOCR
|
||||||
|
* Modified by TonyJiangWJ
|
||||||
|
* @since 2023-08-06
|
||||||
|
*/
|
||||||
|
public class OcrResult implements Comparable<OcrResult> {
|
||||||
|
private String label;
|
||||||
|
private float confidence;
|
||||||
|
private Rect bounds;
|
||||||
|
private final List<OcrResult> elements = new ArrayList<>();
|
||||||
|
|
||||||
|
public OcrResult() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public OcrResult(OcrResultModel resultModel) {
|
||||||
|
this.label = resultModel.getLabel();
|
||||||
|
this.confidence = resultModel.getConfidence();
|
||||||
|
int left = -1, right = -1, top = -1, bottom = -1;
|
||||||
|
for (Point point : resultModel.getPoints()) {
|
||||||
|
if (point.x < left || left == -1) {
|
||||||
|
left = point.x;
|
||||||
|
}
|
||||||
|
if (point.x > right || right == -1) {
|
||||||
|
right = point.x;
|
||||||
|
}
|
||||||
|
if (point.y < top || top == -1) {
|
||||||
|
top = point.y;
|
||||||
|
}
|
||||||
|
if (point.y > bottom || bottom == -1) {
|
||||||
|
bottom = point.y;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.bounds = new Rect(left, top, right, bottom);
|
||||||
|
}
|
||||||
|
|
||||||
|
public OcrResult(String label, float confidence, Rect bounds) {
|
||||||
|
this.label = label;
|
||||||
|
this.confidence = confidence;
|
||||||
|
this.bounds = bounds;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLabel() {
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLabel(String label) {
|
||||||
|
this.label = label;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getConfidence() {
|
||||||
|
return confidence;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setConfidence(float confidence) {
|
||||||
|
this.confidence = confidence;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Rect getBounds() {
|
||||||
|
return bounds;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBounds(Rect bounds) {
|
||||||
|
this.bounds = bounds;
|
||||||
|
}
|
||||||
|
|
||||||
|
public RectLocation getLocation() {
|
||||||
|
return new RectLocation(bounds);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getWords() {
|
||||||
|
return label.trim().replace("\r", "");
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<OcrResult> getElements() {
|
||||||
|
return this.elements;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addElements(OcrResult element) {
|
||||||
|
this.elements.add(element);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int compareTo(OcrResult o) {
|
||||||
|
// 上下差距小于二分之一的高度 判定为同一行
|
||||||
|
int deviation = Math.max(this.bounds.height(), o.bounds.height()) / 2;
|
||||||
|
// 通过垂直中心点的距离判定
|
||||||
|
if (Math.abs((this.bounds.top + this.bounds.bottom) / 2 - (o.bounds.top + o.bounds.bottom) / 2) < deviation) {
|
||||||
|
return this.bounds.left - o.bounds.left;
|
||||||
|
} else {
|
||||||
|
return this.bounds.bottom - o.bounds.bottom;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "OcrResult{" + "label='" + label + '\'' +
|
||||||
|
", confidence=" + confidence +
|
||||||
|
", bounds=" + bounds +
|
||||||
|
", elements=" + elements +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class RectLocation {
|
||||||
|
public int left;
|
||||||
|
public int top;
|
||||||
|
public int width;
|
||||||
|
public int height;
|
||||||
|
|
||||||
|
public RectLocation() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public RectLocation(int left, int top, int width, int height) {
|
||||||
|
this.left = left;
|
||||||
|
this.top = top;
|
||||||
|
this.width = width;
|
||||||
|
this.height = height;
|
||||||
|
}
|
||||||
|
|
||||||
|
public RectLocation(Rect rect) {
|
||||||
|
left = rect.left;
|
||||||
|
top = rect.top;
|
||||||
|
width = rect.right - rect.left;
|
||||||
|
height = rect.bottom - rect.top;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+97
@@ -0,0 +1,97 @@
|
|||||||
|
package com.baidu.paddle.lite.ocr;
|
||||||
|
|
||||||
|
import android.graphics.Point;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author PaddleOCR
|
||||||
|
* Modified by TonyJiangWJ
|
||||||
|
* @since 2023-08-06
|
||||||
|
*/
|
||||||
|
public class OcrResultModel {
|
||||||
|
private final List<Point> points;
|
||||||
|
private final List<Integer> wordIndex;
|
||||||
|
private String label;
|
||||||
|
private float confidence;
|
||||||
|
private float clsIdx;
|
||||||
|
private String clsLabel;
|
||||||
|
private float clsConfidence;
|
||||||
|
|
||||||
|
public OcrResultModel() {
|
||||||
|
super();
|
||||||
|
points = new ArrayList<>();
|
||||||
|
wordIndex = new ArrayList<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addPoints(int x, int y) {
|
||||||
|
Point point = new Point(x, y);
|
||||||
|
points.add(point);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void addWordIndex(int index) {
|
||||||
|
wordIndex.add(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Point> getPoints() {
|
||||||
|
return points;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Integer> getWordIndex() {
|
||||||
|
return wordIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLabel() {
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLabel(String label) {
|
||||||
|
this.label = label;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getConfidence() {
|
||||||
|
return confidence;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setConfidence(float confidence) {
|
||||||
|
this.confidence = confidence;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getClsIdx() {
|
||||||
|
return clsIdx;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setClsIdx(float idx) {
|
||||||
|
this.clsIdx = idx;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getClsLabel() {
|
||||||
|
return clsLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setClsLabel(String label) {
|
||||||
|
this.clsLabel = label;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getClsConfidence() {
|
||||||
|
return clsConfidence;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setClsConfidence(float confidence) {
|
||||||
|
this.clsConfidence = confidence;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "OcrResultModel{" +
|
||||||
|
"points=" + points +
|
||||||
|
", wordIndex=" + wordIndex +
|
||||||
|
", label='" + label + '\'' +
|
||||||
|
", confidence=" + confidence +
|
||||||
|
", clsIdx=" + clsIdx +
|
||||||
|
", clsLabel='" + clsLabel + '\'' +
|
||||||
|
", clsConfidence=" + clsConfidence +
|
||||||
|
'}';
|
||||||
|
}
|
||||||
|
}
|
||||||
+155
@@ -0,0 +1,155 @@
|
|||||||
|
package com.baidu.paddle.lite.ocr;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.os.Build;
|
||||||
|
import android.util.Log;
|
||||||
|
|
||||||
|
public final class OpenCLGuard {
|
||||||
|
|
||||||
|
private static final String TAG = "OpenCLGuard";
|
||||||
|
private static final String SP = "paddle_opencl_probe";
|
||||||
|
private static final String KEY_CACHED_RES = "res_";
|
||||||
|
private static final String KEY_CACHED_AT = "at_";
|
||||||
|
// Timestamp of crash fuse.
|
||||||
|
// zh-CN: 崩溃保险丝时间戳.
|
||||||
|
private static final String KEY_LAST_FUSE = "fuse_";
|
||||||
|
private static final long CACHE_TTL_MS = 24L * 60 * 60 * 1000; // 24h
|
||||||
|
private static final long FUSE_MUTE_MS = 7L * 24 * 60 * 60 * 1000; // 7d
|
||||||
|
|
||||||
|
private static final String FINGERPRINT = android.os.Build.FINGERPRINT;
|
||||||
|
private static final String CACHE_KEY_RES = KEY_CACHED_RES + FINGERPRINT;
|
||||||
|
private static final String CACHE_KEY_AT = KEY_CACHED_AT + FINGERPRINT;
|
||||||
|
private static final String FUSE_KEY = KEY_LAST_FUSE + FINGERPRINT;
|
||||||
|
|
||||||
|
private static final String[] CANDIDATES = new String[]{
|
||||||
|
// Common Treble partitions.
|
||||||
|
// zh-CN: 常见 Treble 分区.
|
||||||
|
"/vendor/lib64/libOpenCL.so",
|
||||||
|
"/system/lib64/libOpenCL.so",
|
||||||
|
"/system/vendor/lib64/libOpenCL.so",
|
||||||
|
"/odm/lib64/libOpenCL.so",
|
||||||
|
// Some vendors put OpenCL in GPU APEX/extension area (not standard, just try).
|
||||||
|
// zh-CN: 部分厂商会把 OpenCL 放到 GPU APEX/扩展区 (并不标准, 仅做尝试).
|
||||||
|
"/apex/com.android.hwext/lib64/libOpenCL.so",
|
||||||
|
// Some devices put ICD in a proprietary directory (rare).
|
||||||
|
// zh-CN: 部分设备把 ICD 放在专有目录 (罕见).
|
||||||
|
"/vendor/lib64/egl/libOpenCL.so"
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark: About to initialize OpenCL (if APP crashes, it can be detected next time).
|
||||||
|
* zh-CN: 标记: 准备开始初始化 OpenCL (若 APP 崩溃, 下次就能检测到).
|
||||||
|
*/
|
||||||
|
public static void markInitStart(Context ctx) {
|
||||||
|
ctx.getSharedPreferences(SP, 0).edit().putLong(FUSE_KEY, System.currentTimeMillis()).apply();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark: OpenCL initialization has safely ended (regardless of success or failure).
|
||||||
|
* zh-CN: 标记: OpenCL 初始化已安全结束 (无论成功或失败).
|
||||||
|
*/
|
||||||
|
public static void markInitEnd(Context ctx) {
|
||||||
|
ctx.getSharedPreferences(SP, 0).edit().remove(FUSE_KEY).apply();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether to recommend enabling OpenCL (with cache + fuse + absolute path loading attempt).
|
||||||
|
* zh-CN: 是否建议启用 OpenCL (带缓存 + 保险丝 + 绝对路径加载尝试).
|
||||||
|
*/
|
||||||
|
public static boolean isOpenCLRuntimeAvailable(Context ctx) {
|
||||||
|
// Crash fuse: last initialization did not end normally -> pause for 7 days.
|
||||||
|
// zh-CN: 崩溃保险丝: 上次初始化未正常结束 -> 暂停 7 天.
|
||||||
|
long fuseTs = ctx.getSharedPreferences(SP, 0).getLong(FUSE_KEY, 0L);
|
||||||
|
if (fuseTs > 0 && (System.currentTimeMillis() - fuseTs) < FUSE_MUTE_MS) {
|
||||||
|
Log.w(TAG, "[OpenCL] Fuse active, skip probing.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only try in 64-bit process + arm64 device.
|
||||||
|
// zh-CN: 只在 64-bit 进程 + arm64 设备尝试.
|
||||||
|
boolean isArm64Device = false;
|
||||||
|
try {
|
||||||
|
String[] abis64 = Build.SUPPORTED_64_BIT_ABIS;
|
||||||
|
if (abis64 != null) for (String abi : abis64) {
|
||||||
|
if ("arm64-v8a".equalsIgnoreCase(abi)) {
|
||||||
|
isArm64Device = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Throwable ignore) {
|
||||||
|
/* Ignored. */
|
||||||
|
}
|
||||||
|
boolean is64Process = System.getProperty("os.arch", "").contains("64");
|
||||||
|
if (!(isArm64Device && is64Process)) {
|
||||||
|
Log.i(TAG, "[OpenCL] Not arm64/64-bit process, skip. dev=" + isArm64Device + " proc=" + is64Process);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read cache.
|
||||||
|
// zh-CN: 读取缓存.
|
||||||
|
final var sp = ctx.getSharedPreferences(SP, 0);
|
||||||
|
long cachedAt = sp.getLong(CACHE_KEY_AT, 0L);
|
||||||
|
if (cachedAt > 0 && (System.currentTimeMillis() - cachedAt) < CACHE_TTL_MS) {
|
||||||
|
boolean cached = sp.getBoolean(CACHE_KEY_RES, false);
|
||||||
|
Log.i(TAG, "[OpenCL] use cached=" + cached);
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1) Absolute path existence.
|
||||||
|
// zh-CN: 1) 绝对路径存在性.
|
||||||
|
String hitPath = null;
|
||||||
|
for (String p : CANDIDATES) {
|
||||||
|
try {
|
||||||
|
if (new java.io.File(p).exists()) {
|
||||||
|
hitPath = p;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch (Throwable ignore) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) Try loading (absolute path first, then loadLibrary("OpenCL")).
|
||||||
|
// zh-CN: 2) 尝试加载 (绝对路径优先, 其次 loadLibrary("OpenCL")).
|
||||||
|
boolean loadOk = false;
|
||||||
|
// 2.1 Absolute path dlopen.
|
||||||
|
// zh-CN: 2.1 绝对路径 dlopen.
|
||||||
|
if (hitPath != null) {
|
||||||
|
try {
|
||||||
|
System.load(hitPath);
|
||||||
|
loadOk = true;
|
||||||
|
Log.i(TAG, "[OpenCL] System.load hit: " + hitPath);
|
||||||
|
} catch (Throwable t) {
|
||||||
|
Log.i(TAG, "[OpenCL] System.load failed: " + hitPath + " -> " + t.getClass().getSimpleName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 2.2 Regular link name.
|
||||||
|
// zh-CN: 2.2 常规链接名.
|
||||||
|
if (!loadOk) {
|
||||||
|
try {
|
||||||
|
System.loadLibrary("OpenCL");
|
||||||
|
loadOk = true;
|
||||||
|
Log.i(TAG, "[OpenCL] loadLibrary(\"OpenCL\") ok.");
|
||||||
|
} catch (Throwable t) {
|
||||||
|
Log.i(TAG, "[OpenCL] loadLibrary(\"OpenCL\") failed: " + t.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int probe = -999;
|
||||||
|
if (loadOk) {
|
||||||
|
try {
|
||||||
|
probe = OpenCLProbe.nativeProbeOpenCL();
|
||||||
|
} catch (Throwable t) {
|
||||||
|
Log.i(TAG, "[OpenCL] nativeProbeOpenCL error: " + t.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// At least 1 platform.
|
||||||
|
// zh-CN: 至少 1 个平台.
|
||||||
|
boolean available = loadOk && probe >= 1;
|
||||||
|
Log.i(TAG, "[OpenCL] available=" + available + " (loadOk=" + loadOk + ", platforms=" + probe + ")");
|
||||||
|
|
||||||
|
// Write cache.
|
||||||
|
// zh-CN: 写缓存.
|
||||||
|
sp.edit().putBoolean(CACHE_KEY_RES, available).putLong(CACHE_KEY_AT, System.currentTimeMillis()).apply();
|
||||||
|
return available;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package com.baidu.paddle.lite.ocr;
|
||||||
|
|
||||||
|
public final class OpenCLProbe {
|
||||||
|
static {
|
||||||
|
try { System.loadLibrary("opencl_probe"); } catch (Throwable ignore) {}
|
||||||
|
}
|
||||||
|
public static native int nativeProbeOpenCL();
|
||||||
|
}
|
||||||
+286
@@ -0,0 +1,286 @@
|
|||||||
|
package com.baidu.paddle.lite.ocr
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.graphics.BitmapFactory
|
||||||
|
import org.autojs.plugin.paddle.ocr.api.OcrOptions
|
||||||
|
import org.autojs.plugin.paddle.ocr.api.OcrResult
|
||||||
|
import java.io.FileNotFoundException
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A unified embedded Paddle OCR engine API for both host (INRT) and plugin APK.
|
||||||
|
* zh-CN: 面向宿主 (INRT) 与插件 APK 的统一 Paddle OCR 内置引擎 API.
|
||||||
|
*
|
||||||
|
* Created by JetBrains AI Assistant (GPT-5.2) on Jan 17, 2026.
|
||||||
|
* Modified by SuperMonster003 as of Jan 18, 2026.
|
||||||
|
*/
|
||||||
|
class PaddleOcrEngine(
|
||||||
|
private val appContext: Context,
|
||||||
|
private val variant: VariantSpec,
|
||||||
|
private val bridge: NativeBridge = PredictorNativeBridge(),
|
||||||
|
) {
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var initialized: Boolean = false
|
||||||
|
|
||||||
|
private val lock = Any()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize native libs and load models.
|
||||||
|
* zh-CN: 初始化 native 库并加载模型.
|
||||||
|
*/
|
||||||
|
fun ensureInitialized(options: OcrOptions) {
|
||||||
|
if (initialized) return
|
||||||
|
synchronized(lock) {
|
||||||
|
if (initialized) return
|
||||||
|
|
||||||
|
// Resolve model profile by options + variant.
|
||||||
|
// zh-CN: 根据 options + variant 决定模型组合.
|
||||||
|
val profile = variant.resolveProfile(options)
|
||||||
|
|
||||||
|
// Ensure required assets exist.
|
||||||
|
// zh-CN: 确保所需 assets 存在.
|
||||||
|
variant.assertAssetsExist(appContext, profile)
|
||||||
|
|
||||||
|
// Prepare checking bitmap from drawable resource.
|
||||||
|
// zh-CN: 从 drawable 资源准备检查用 bitmap.
|
||||||
|
val checkingBitmap = decodeDrawable(appContext, variant.checkingDrawableRes)
|
||||||
|
|
||||||
|
// Delegate to bridge for real initialization.
|
||||||
|
// zh-CN: 委托给 bridge 执行真实初始化.
|
||||||
|
bridge.init(
|
||||||
|
context = appContext,
|
||||||
|
profile = profile,
|
||||||
|
checkingBitmap = checkingBitmap,
|
||||||
|
)
|
||||||
|
|
||||||
|
initialized = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recognize text only.
|
||||||
|
* zh-CN: 仅识别文本.
|
||||||
|
*/
|
||||||
|
fun recognizeText(bitmap: Bitmap, options: OcrOptions): List<String> {
|
||||||
|
ensureInitialized(options)
|
||||||
|
return bridge.recognizeText(bitmap, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detect with boxes.
|
||||||
|
* zh-CN: 检测并返回文本框信息.
|
||||||
|
*/
|
||||||
|
fun detect(bitmap: Bitmap, options: OcrOptions): List<OcrResult> {
|
||||||
|
ensureInitialized(options)
|
||||||
|
return bridge.detect(bitmap, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeDrawable(context: Context, resId: Int): Bitmap {
|
||||||
|
return BitmapFactory.decodeResource(context.resources, resId)
|
||||||
|
?: throw IllegalStateException(
|
||||||
|
context.getString(R.string.error_failed_to_decode_checking_drawable_resource)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A single point for real predictor/native invocation.
|
||||||
|
* zh-CN: 真实 predictor/native 调用的单点封装.
|
||||||
|
*/
|
||||||
|
interface NativeBridge {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize predictor with model paths.
|
||||||
|
* zh-CN: 用模型路径初始化 predictor.
|
||||||
|
*/
|
||||||
|
fun init(
|
||||||
|
context: Context,
|
||||||
|
profile: ModelProfile,
|
||||||
|
checkingBitmap: Bitmap,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recognize text.
|
||||||
|
* zh-CN: 识别文本.
|
||||||
|
*/
|
||||||
|
fun recognizeText(bitmap: Bitmap, options: OcrOptions): List<String>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detect results with boxes.
|
||||||
|
* zh-CN: 检测并返回带框结果.
|
||||||
|
*/
|
||||||
|
fun detect(bitmap: Bitmap, options: OcrOptions): List<OcrResult>
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolved model paths for one run configuration.
|
||||||
|
* zh-CN: 单次运行配置解析出的模型路径集合.
|
||||||
|
*/
|
||||||
|
data class ModelProfile(
|
||||||
|
val variantName: String,
|
||||||
|
val labelAssetPath: String,
|
||||||
|
|
||||||
|
// v5 uses Predictor's internal default dirs; v3 uses explicit dir.
|
||||||
|
// zh-CN: v5 由 Predictor 内部默认目录决定, v3 使用显式目录.
|
||||||
|
val modelDir: String?,
|
||||||
|
|
||||||
|
val useSlim: Boolean,
|
||||||
|
val useOpenCL: Boolean,
|
||||||
|
val cpuThreadNum: Int,
|
||||||
|
val detModelFile: String,
|
||||||
|
val recModelFile: String,
|
||||||
|
val clsModelFile: String,
|
||||||
|
val assetsToCheck: List<String>,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Engine variant specification (v3/v5).
|
||||||
|
* zh-CN: 引擎变体规范 (v3/v5).
|
||||||
|
*/
|
||||||
|
data class VariantSpec(
|
||||||
|
val name: String,
|
||||||
|
val supportsOpenCL: Boolean,
|
||||||
|
val labelAssetPath: String,
|
||||||
|
|
||||||
|
// Explicit model directories.
|
||||||
|
// zh-CN: 显式模型目录配置.
|
||||||
|
|
||||||
|
val modelDirCpu: String,
|
||||||
|
val modelDirCpuSlim: String? = null,
|
||||||
|
val modelDirOpenCL: String? = null,
|
||||||
|
val modelDirOpenCLSlim: String? = null,
|
||||||
|
|
||||||
|
val detModelFile: String,
|
||||||
|
val recModelFile: String,
|
||||||
|
val clsModelFile: String,
|
||||||
|
|
||||||
|
val checkingDrawableRes: Int,
|
||||||
|
) {
|
||||||
|
|
||||||
|
fun resolveProfile(options: OcrOptions): ModelProfile {
|
||||||
|
val useSlim = options.useSlim
|
||||||
|
val useOpenCLRequested = options.useOpenCL && supportsOpenCL
|
||||||
|
|
||||||
|
val resolvedDir: String? = if (name == NAME_V5) {
|
||||||
|
// v5: let Predictor decide between CPU/OpenCL + fallback internally.
|
||||||
|
// zh-CN: v5: 让 Predictor 内部决定 CPU/OpenCL 并自动回退.
|
||||||
|
null
|
||||||
|
} else {
|
||||||
|
// v3: choose deterministic dir here (OpenCL ignored).
|
||||||
|
// zh-CN: v3: 在此确定性选择目录 (OpenCL 被忽略).
|
||||||
|
if (useSlim) (modelDirCpuSlim ?: modelDirCpu) else modelDirCpu
|
||||||
|
}
|
||||||
|
|
||||||
|
// Assets to check:
|
||||||
|
// - Always check label file.
|
||||||
|
// - For v3: check the resolved model dir files.
|
||||||
|
// - For v5: check CPU + slim dirs always, and additionally OpenCL dirs if requested.
|
||||||
|
// zh-CN:
|
||||||
|
// - 总是检查 label 文件.
|
||||||
|
// - v3: 检查解析出的模型目录及其文件.
|
||||||
|
// - v5: 总是检查 CPU/INT8 目录, 若用户请求 OpenCL 再额外检查 OpenCL 目录.
|
||||||
|
val assets = buildList {
|
||||||
|
add(labelAssetPath)
|
||||||
|
|
||||||
|
val cpuDir = modelDirCpu
|
||||||
|
add("$cpuDir/$detModelFile")
|
||||||
|
add("$cpuDir/$recModelFile")
|
||||||
|
add("$cpuDir/$clsModelFile")
|
||||||
|
|
||||||
|
modelDirCpuSlim?.let { slimDir ->
|
||||||
|
add("$slimDir/$detModelFile")
|
||||||
|
add("$slimDir/$recModelFile")
|
||||||
|
add("$slimDir/$clsModelFile")
|
||||||
|
}
|
||||||
|
|
||||||
|
if (useOpenCLRequested) {
|
||||||
|
modelDirOpenCL?.let { clDir ->
|
||||||
|
add("$clDir/$detModelFile")
|
||||||
|
add("$clDir/$recModelFile")
|
||||||
|
add("$clDir/$clsModelFile")
|
||||||
|
}
|
||||||
|
modelDirOpenCLSlim?.let { clSlimDir ->
|
||||||
|
add("$clSlimDir/$detModelFile")
|
||||||
|
add("$clSlimDir/$recModelFile")
|
||||||
|
add("$clSlimDir/$clsModelFile")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// v3 deterministic dir check (override list to minimal set).
|
||||||
|
// zh-CN: v3 确定性目录检查 (覆盖为最小集合).
|
||||||
|
if (name != NAME_V5) {
|
||||||
|
clear()
|
||||||
|
add(labelAssetPath)
|
||||||
|
val dir = requireNotNull(resolvedDir)
|
||||||
|
add("$dir/$detModelFile")
|
||||||
|
add("$dir/$recModelFile")
|
||||||
|
add("$dir/$clsModelFile")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ModelProfile(
|
||||||
|
variantName = name,
|
||||||
|
labelAssetPath = labelAssetPath,
|
||||||
|
modelDir = resolvedDir,
|
||||||
|
useSlim = useSlim,
|
||||||
|
useOpenCL = useOpenCLRequested,
|
||||||
|
cpuThreadNum = options.cpuThreadNum,
|
||||||
|
detModelFile = detModelFile,
|
||||||
|
recModelFile = recModelFile,
|
||||||
|
clsModelFile = clsModelFile,
|
||||||
|
assetsToCheck = assets.distinct(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun assertAssetsExist(context: Context, profile: ModelProfile) {
|
||||||
|
fun assertOne(path: String) {
|
||||||
|
try {
|
||||||
|
context.assets.open(path).use { }
|
||||||
|
} catch (e: FileNotFoundException) {
|
||||||
|
throw IllegalStateException(context.getString(R.string.error_missing_required_paddle_ocr_asset, path), e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
profile.assetsToCheck.forEach(::assertOne)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val NAME_V5 = "v5"
|
||||||
|
const val NAME_V3 = "v3"
|
||||||
|
|
||||||
|
fun v5(): VariantSpec = VariantSpec(
|
||||||
|
name = NAME_V5,
|
||||||
|
supportsOpenCL = true,
|
||||||
|
labelAssetPath = "labels/ppocr_keys_ocrv5.txt",
|
||||||
|
|
||||||
|
modelDirCpu = "models/pp-ocrv5-arm",
|
||||||
|
modelDirCpuSlim = "models/pp-ocrv5-arm-int8",
|
||||||
|
modelDirOpenCL = "models/pp-ocrv5-arm-opencl",
|
||||||
|
modelDirOpenCLSlim = "models/pp-ocrv5-arm-opencl-int8",
|
||||||
|
|
||||||
|
detModelFile = "PP-OCRv5_mobile_det.nb",
|
||||||
|
recModelFile = "PP-OCRv5_mobile_rec.nb",
|
||||||
|
clsModelFile = "PP-LCNet_x1_0_textline_ori.nb",
|
||||||
|
|
||||||
|
checkingDrawableRes = R.drawable.paddle_ocr_test,
|
||||||
|
)
|
||||||
|
|
||||||
|
fun v3(): VariantSpec = VariantSpec(
|
||||||
|
name = NAME_V3,
|
||||||
|
supportsOpenCL = false,
|
||||||
|
labelAssetPath = "labels/ppocr_keys_v1.txt",
|
||||||
|
|
||||||
|
modelDirCpu = "models/ocr_v3_for_cpu",
|
||||||
|
modelDirCpuSlim = "models/ocr_v3_for_cpu(slim)",
|
||||||
|
|
||||||
|
modelDirOpenCL = null,
|
||||||
|
modelDirOpenCLSlim = null,
|
||||||
|
|
||||||
|
detModelFile = "det_opt.nb",
|
||||||
|
recModelFile = "rec_opt.nb",
|
||||||
|
clsModelFile = "cls_opt.nb",
|
||||||
|
|
||||||
|
checkingDrawableRes = R.drawable.paddle_ocr_test,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,582 @@
|
|||||||
|
package com.baidu.paddle.lite.ocr;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.graphics.Bitmap;
|
||||||
|
import android.graphics.BitmapFactory;
|
||||||
|
import android.os.Build;
|
||||||
|
import android.util.Base64;
|
||||||
|
import android.util.Log;
|
||||||
|
import androidx.preference.PreferenceManager;
|
||||||
|
import org.opencv.BuildConfig;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Predictor for Paddle-Lite OCR engine, managing model loading, runtime configuration,
|
||||||
|
* and end-to-end inference flow.
|
||||||
|
* zh-CN: 面向 Paddle-Lite OCR 引擎的预测器, 负责模型加载/运行时配置以及端到端推理流程.
|
||||||
|
*
|
||||||
|
* @author <a href="https://github.com/TonyJiangWJ">TonyJiangWJ</a>
|
||||||
|
* @see <a href="https://github.com/PaddlePaddle/PaddleOCR/blob/main/deploy/android_demo/app/src/main/java/com/baidu/paddle/lite/demo/ocr/Predictor.java">
|
||||||
|
* PaddlePaddle/PaddleOCR (Predictor.java)</a>
|
||||||
|
* @since Aug 6, 2023
|
||||||
|
*
|
||||||
|
* <p> Modified by TonyJiangWJ as of Aug 7, 2023. </p>
|
||||||
|
* <p> Modified by JetBrains AI Assistant (GPT-5.2) as of Jan 17, 2026. </p>
|
||||||
|
* <p> Modified by SuperMonster003 as of Jan 18, 2026. </p>
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public class Predictor {
|
||||||
|
|
||||||
|
public static final int DEFAULT_CPU_THREAD_NUM = 4;
|
||||||
|
public static final boolean DEFAULT_USE_SLIM = true;
|
||||||
|
public static final boolean DEFAULT_USE_OPENCL = false;
|
||||||
|
|
||||||
|
private static final String TAG = Predictor.class.getSimpleName();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Probe bitmap cache for init-check.
|
||||||
|
* zh-CN: 初始化校验使用的探测位图缓存.
|
||||||
|
*/
|
||||||
|
private static Bitmap checkingBitmap;
|
||||||
|
/**
|
||||||
|
* Default label file path.
|
||||||
|
* zh-CN: 默认字典文件路径.
|
||||||
|
*/
|
||||||
|
private final String defaultLabelPath = "labels/ppocr_keys_ocrv5.txt";
|
||||||
|
/**
|
||||||
|
* Default CPU model directory (standard).
|
||||||
|
* zh-CN: 默认 CPU 标准模型目录.
|
||||||
|
*/
|
||||||
|
private final String defaultModelPath = "models/pp-ocrv5-arm";
|
||||||
|
/**
|
||||||
|
* Default OpenCL model directory (standard).
|
||||||
|
* zh-CN: 默认 OpenCL 标准模型目录.
|
||||||
|
*/
|
||||||
|
private final String defaultModelPathOpenCL = "models/pp-ocrv5-arm-opencl";
|
||||||
|
/**
|
||||||
|
* Default CPU model directory (INT8 slim).
|
||||||
|
* zh-CN: 默认 CPU INT8 slim 模型目录.
|
||||||
|
*/
|
||||||
|
private final String defaultModelPathSlim = "models/pp-ocrv5-arm-int8";
|
||||||
|
/**
|
||||||
|
* Default OpenCL model directory (INT8 slim).
|
||||||
|
* zh-CN: 默认 OpenCL INT8 slim 模型目录.
|
||||||
|
*/
|
||||||
|
private final String defaultModelPathOpenCLSlim = "models/pp-ocrv5-arm-opencl-int8";
|
||||||
|
|
||||||
|
/** Detection model. [zh-CN: 检测模型]. */
|
||||||
|
public String detModelFilename = "PP-OCRv5_mobile_det.nb";
|
||||||
|
/** Recognition model. [zh-CN: 识别模型]. */
|
||||||
|
public String recModelFilename = "PP-OCRv5_mobile_rec.nb";
|
||||||
|
/** Text direction (cls) model. [zh-CN: 方向分类 (cls) 模型]. */
|
||||||
|
public String clsModelFilename = "PP-LCNet_x1_0_textline_ori.nb";
|
||||||
|
|
||||||
|
/** Whether the model is loaded. [zh-CN: 模型是否已加载]. */
|
||||||
|
public boolean isLoaded = false;
|
||||||
|
/** Warm-up iteration count. [zh-CN: 预热迭代次数]. */
|
||||||
|
public int warmupIterNum = 1;
|
||||||
|
/** Inference iteration count for timing. [zh-CN: 用于计时的推理迭代次数]. */
|
||||||
|
public int inferIterNum = 1;
|
||||||
|
/** CPU thread count. [zh-CN: CPU 线程数]. */
|
||||||
|
public int cpuThreadNum = DEFAULT_CPU_THREAD_NUM;
|
||||||
|
/** CPU power mode string (Lite power hint). [zh-CN: CPU 能耗模式字符串 (Lite 电源提示)]. */
|
||||||
|
public String cpuPowerMode = "LITE_POWER_HIGH";
|
||||||
|
|
||||||
|
/** Selected model resolved absolute path. [zh-CN: 选定模型解析后的绝对路径]. */
|
||||||
|
public String modelPath = "";
|
||||||
|
/** Selected model directory name. [zh-CN: 选定模型目录名]. */
|
||||||
|
public String modelName = "";
|
||||||
|
|
||||||
|
/** Use slim (INT8) model. [zh-CN: 是否使用 slim (INT8) 模型]. */
|
||||||
|
public boolean useSlim = DEFAULT_USE_SLIM;
|
||||||
|
/** Use OpenCL backend (if available). [zh-CN: 是否启用 OpenCL 后端 (若可用)]. */
|
||||||
|
public boolean useOpenCL = DEFAULT_USE_OPENCL;
|
||||||
|
/** Validate initialization with a preset image. [zh-CN: 是否通过预设图片校验初始化]. */
|
||||||
|
public boolean checkModelLoaded = BuildConfig.DEBUG;
|
||||||
|
|
||||||
|
/** Enable classification (cls). [zh-CN: 启用方向分类 (cls)]. */
|
||||||
|
public boolean isClassificationEnabled = false;
|
||||||
|
/** Enable detection (det). [zh-CN: 启用文本检测 (det)]. */
|
||||||
|
public boolean isDetectionEnabled = false;
|
||||||
|
/** Enable recognition (rec). [zh-CN: 启用文本识别 (rec)]. */
|
||||||
|
public boolean isRecognitionEnabled = true;
|
||||||
|
|
||||||
|
/** Score threshold for filtering results. [zh-CN: 结果过滤的置信度阈值]. */
|
||||||
|
public float scoreThreshold = 0.1f;
|
||||||
|
/** Max long side for det input resize. [zh-CN: 检测输入缩放的最长边]. */
|
||||||
|
protected int detLongSize = 960;
|
||||||
|
|
||||||
|
/** Native predictor bridge. [zh-CN: Native 预测器桥接对象]. */
|
||||||
|
protected OCRPredictorNative paddlePredictor = null;
|
||||||
|
/** Inference time in milliseconds. [zh-CN: 推理耗时 (毫秒)]. */
|
||||||
|
protected float inferenceTime = 0;
|
||||||
|
/** Labels for recognition post-processing. [zh-CN: 识别后处理所需的字典标签]. */
|
||||||
|
protected List<String> wordLabels = new ArrayList<>();
|
||||||
|
/** Input image buffer (ARGB_8888). [zh-CN: 输入图像缓冲 (ARGB_8888)]. */
|
||||||
|
protected Bitmap inputImage = null;
|
||||||
|
/** Preprocess time in milliseconds. [zh-CN: 预处理耗时 (毫秒)]. */
|
||||||
|
protected float preprocessTime = 0;
|
||||||
|
|
||||||
|
/** Validation attempt counter. [zh-CN: 初始化校验重试计数器]. */
|
||||||
|
private int validationAttempt = 1;
|
||||||
|
/** Initialization attempt counter. [zh-CN: 初始化尝试计数器]. */
|
||||||
|
private int initializationAttempt = 1;
|
||||||
|
|
||||||
|
// @Archived by SuperMonster003 on Nov 7, 2025.
|
||||||
|
// ! Legacy default paths and filenames for PP-OCRv3 are archived here.
|
||||||
|
// ! zh-CN: 旧版 PP-OCRv3 的默认路径与文件名在此归档保留.
|
||||||
|
// # private final String defaultLabelPath = "labels/ppocr_keys_v1.txt";
|
||||||
|
// # private final String defaultModelPath = "models/ocr_v3_for_cpu";
|
||||||
|
// # public String detModelFilename = "det_opt.nb";
|
||||||
|
// # public String recModelFilename = "rec_opt.nb";
|
||||||
|
// # public String clsModelFilename = "cls_opt.nb";
|
||||||
|
// # // Slim model converted by opt 2.10; 2.11 had issues.
|
||||||
|
// # // zh-CN: Slim 模型由 2.10 版 opt 转换; 2.11 存在兼容问题.
|
||||||
|
// # private final String defaultModelPathSlim = "models/ocr_v3_for_cpu(slim)";
|
||||||
|
|
||||||
|
public Predictor() {
|
||||||
|
/* Empty body. */
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String md5(String text) {
|
||||||
|
MessageDigest md;
|
||||||
|
byte[] bytesOfMessage = text.getBytes();
|
||||||
|
try {
|
||||||
|
md = MessageDigest.getInstance("MD5");
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
return Base64.encodeToString(md.digest(bytesOfMessage), Base64.DEFAULT);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean init(Context appCtx) {
|
||||||
|
return this.init(appCtx, defaultModelPath, defaultLabelPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean init(Context appCtx, boolean useSlim) {
|
||||||
|
return this.init(appCtx, useSlim, DEFAULT_USE_OPENCL);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean init(Context appCtx, boolean useSlim, boolean useOpenCL) {
|
||||||
|
Log.d(TAG, "use slim: " + useSlim);
|
||||||
|
Log.d(TAG, "use opencl: " + useOpenCL);
|
||||||
|
|
||||||
|
// If already loaded and switches are consistent, reuse directly.
|
||||||
|
// zh-CN: 若已加载且开关一致, 直接复用.
|
||||||
|
if (this.isLoaded && this.useSlim == useSlim && this.useOpenCL == useOpenCL) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean openclAvailable = false;
|
||||||
|
if (useOpenCL) {
|
||||||
|
try {
|
||||||
|
openclAvailable = OpenCLGuard.isOpenCLRuntimeAvailable(appCtx);
|
||||||
|
if (!openclAvailable) {
|
||||||
|
Log.w(TAG, "[OpenCL] Unavailable or fused, fallback to CPU.");
|
||||||
|
}
|
||||||
|
} catch (Throwable t) {
|
||||||
|
Log.w(TAG, "[OpenCL] Probe exception, fallback to CPU: " + t.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.useSlim = useSlim;
|
||||||
|
this.useOpenCL = openclAvailable;
|
||||||
|
|
||||||
|
String modelDir;
|
||||||
|
if (this.useSlim) {
|
||||||
|
modelDir = this.useOpenCL ? defaultModelPathOpenCLSlim : defaultModelPathSlim;
|
||||||
|
} else {
|
||||||
|
modelDir = this.useOpenCL ? defaultModelPathOpenCL : defaultModelPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean ok;
|
||||||
|
if (this.useOpenCL) {
|
||||||
|
OpenCLGuard.markInitStart(appCtx);
|
||||||
|
try {
|
||||||
|
ok = this.init(appCtx, modelDir, defaultLabelPath);
|
||||||
|
} finally {
|
||||||
|
OpenCLGuard.markInitEnd(appCtx);
|
||||||
|
}
|
||||||
|
if (!ok) {
|
||||||
|
Log.w(TAG, "[OpenCL] Init failed without crash, fallback to CPU.");
|
||||||
|
this.useOpenCL = false;
|
||||||
|
String cpuModelDir = this.useSlim ? defaultModelPathSlim : defaultModelPath;
|
||||||
|
ok = this.init(appCtx, cpuModelDir, defaultLabelPath);
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
} else {
|
||||||
|
return this.init(appCtx, modelDir, defaultLabelPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean init(Context appCtx, String modelPath, String labelPath) {
|
||||||
|
Log.d(TAG, "init whit model: " + modelPath + " label: " + labelPath);
|
||||||
|
isLoaded = loadModel(appCtx, modelPath, cpuThreadNum, cpuPowerMode);
|
||||||
|
if (!isLoaded) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
isLoaded = loadLabel(appCtx, labelPath);
|
||||||
|
if (!checkModelLoadedSuccess(appCtx)) {
|
||||||
|
if (initializationAttempt++ < 3) {
|
||||||
|
return init(appCtx, modelPath, labelPath);
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return isLoaded;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize and validate models by running inference on a preset test image.
|
||||||
|
* Retry up to several times as a workaround (deeper cause needs investigation).
|
||||||
|
* zh-CN:
|
||||||
|
* 初始化模型后通过识别预设图片校验是否初始化成功.
|
||||||
|
* 曲线救国, 深层的失败原因需要后续排查.
|
||||||
|
*/
|
||||||
|
private boolean checkModelLoadedSuccess(Context context) {
|
||||||
|
if (!checkModelLoaded) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!isLoaded) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
List<OcrResult> results = runOcr(getCheckingBitmap(context));
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (OcrResult result : results) {
|
||||||
|
sb.append(result.getLabel());
|
||||||
|
}
|
||||||
|
// The image contains a single recognizable text string "测试" (Chinese word "test").
|
||||||
|
// zh-CN: 图片中包含唯一可识别文本 "测试".
|
||||||
|
boolean check = sb.toString().contains("测试");
|
||||||
|
Log.d(TAG, "Validation attempt " + validationAttempt + ": { initialized: " + check + ", result: " + sb + " }");
|
||||||
|
boolean result = check || validationAttempt++ >= 5;
|
||||||
|
if (!check && validationAttempt >= 5) {
|
||||||
|
Log.e(TAG, "Model initialization failed");
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Bitmap getCheckingBitmap(Context context) {
|
||||||
|
if (checkingBitmap == null) {
|
||||||
|
checkingBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.paddle_ocr_test);
|
||||||
|
}
|
||||||
|
return checkingBitmap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean init(Context appCtx, String modelPath, String labelPath, int cpuThreadNum, String cpuPowerMode) {
|
||||||
|
isLoaded = loadModel(appCtx, modelPath, cpuThreadNum, cpuPowerMode);
|
||||||
|
if (!isLoaded) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
isLoaded = loadLabel(appCtx, labelPath);
|
||||||
|
return isLoaded;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean init(Context appCtx, String modelPath, String labelPath, int cpuThreadNum, String cpuPowerMode, int detLongSize, float scoreThreshold) {
|
||||||
|
boolean isLoaded = init(appCtx, modelPath, labelPath, cpuThreadNum, cpuPowerMode);
|
||||||
|
if (!isLoaded) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
this.detLongSize = detLongSize;
|
||||||
|
this.scoreThreshold = scoreThreshold;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected boolean loadModel(Context appCtx, String modelPath, int cpuThreadNum, String cpuPowerMode) {
|
||||||
|
// Release model if exists.
|
||||||
|
// zh-CN: 释放模型如果存在.
|
||||||
|
releaseModel();
|
||||||
|
|
||||||
|
// Load model.
|
||||||
|
// zh-CN: 加载模型.
|
||||||
|
if (modelPath.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String realPath = modelPath;
|
||||||
|
if (modelPath.charAt(0) != '/') {
|
||||||
|
// Read model files from custom path if the first character of mode path is '/'
|
||||||
|
// otherwise copy model to cache from assets.
|
||||||
|
// zh-CN: 如果模型路径首字符为 '/' 则从自定义路径读取模型文件, 否则从 assets 复制模型到缓存.
|
||||||
|
realPath = appCtx.getCacheDir() + File.separator + modelPath;
|
||||||
|
|
||||||
|
// @SectionBegin("copyModelAssets") by TonyJiangWJ on Aug 7, 2023.
|
||||||
|
String key = "PADDLE_MODEL_LOADED" + md5(modelPath);
|
||||||
|
// Model has been updated, force override the old model.
|
||||||
|
// zh-CN: 进行了模型更新, 需要强制覆盖旧模型.
|
||||||
|
boolean loaded = PreferenceManager.getDefaultSharedPreferences(appCtx).getBoolean(key, false);
|
||||||
|
if (loaded) {
|
||||||
|
// No need to copy every time.
|
||||||
|
// zh-CN: 没有必要每次都复制.
|
||||||
|
Utils.copyDirectoryFromAssetsIfNeeded(appCtx, modelPath, realPath);
|
||||||
|
} else {
|
||||||
|
Utils.copyDirectoryFromAssets(appCtx, modelPath, realPath);
|
||||||
|
PreferenceManager.getDefaultSharedPreferences(appCtx).edit().putBoolean(key, true).apply();
|
||||||
|
}
|
||||||
|
// @SectionEnd("copyModelAssets")
|
||||||
|
}
|
||||||
|
|
||||||
|
OCRPredictorNative.Config config = new OCRPredictorNative.Config();
|
||||||
|
|
||||||
|
// Whether to use GPU (OpenCL), only set to 1 when useOpenCL is confirmed available at Java level.
|
||||||
|
// zh-CN: 是否使用 GPU (OpenCL), 只有在 Java 层确认 useOpenCL 可用时才真正置 1.
|
||||||
|
config.useOpenCL = useOpenCL ? 1 : 0;
|
||||||
|
config.cpuThreadNum = cpuThreadNum;
|
||||||
|
config.detModelFilename = realPath + File.separator + detModelFilename;
|
||||||
|
config.recModelFilename = realPath + File.separator + recModelFilename;
|
||||||
|
config.clsModelFilename = realPath + File.separator + clsModelFilename;
|
||||||
|
Log.i("Predictor", "model path" + config.detModelFilename + " ; " + config.recModelFilename + ";" + config.clsModelFilename);
|
||||||
|
config.cpuPower = cpuPowerMode;
|
||||||
|
|
||||||
|
paddlePredictor = new OCRPredictorNative(config);
|
||||||
|
|
||||||
|
this.cpuThreadNum = cpuThreadNum;
|
||||||
|
this.cpuPowerMode = cpuPowerMode;
|
||||||
|
this.modelPath = realPath;
|
||||||
|
this.modelName = realPath.substring(realPath.lastIndexOf(File.separator) + 1);
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void releaseModel() {
|
||||||
|
if (paddlePredictor != null) {
|
||||||
|
paddlePredictor.destroy();
|
||||||
|
paddlePredictor = null;
|
||||||
|
}
|
||||||
|
isLoaded = false;
|
||||||
|
modelPath = "";
|
||||||
|
modelName = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
protected boolean loadLabel(Context appCtx, String labelPath) {
|
||||||
|
wordLabels.clear();
|
||||||
|
wordLabels.add("black");
|
||||||
|
// Load word labels from file.
|
||||||
|
// zh-CN: 从文件中加载字典标签.
|
||||||
|
try {
|
||||||
|
InputStream labelInputStream;
|
||||||
|
if (labelPath.startsWith(File.separator)) {
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
labelInputStream = Files.newInputStream(Paths.get(labelPath));
|
||||||
|
} else {
|
||||||
|
labelInputStream = new FileInputStream(labelPath);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
labelInputStream = appCtx.getAssets().open(labelPath);
|
||||||
|
}
|
||||||
|
int available = labelInputStream.available();
|
||||||
|
byte[] lines = new byte[available];
|
||||||
|
if (labelInputStream.read(lines) <= 0) {
|
||||||
|
Log.e(TAG, "Failed to read label");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
labelInputStream.close();
|
||||||
|
String words = new String(lines);
|
||||||
|
// Compatible with \r\n line endings on Windows.
|
||||||
|
// zh-CN: 兼容 Windows 系统下的 \r\n 换行符.
|
||||||
|
String[] contents = words.split("(\r)?\n");
|
||||||
|
wordLabels.addAll(Arrays.asList(contents));
|
||||||
|
wordLabels.add(" ");
|
||||||
|
Log.i(TAG, "Word label size: " + wordLabels.size());
|
||||||
|
} catch (Exception e) {
|
||||||
|
Log.e(TAG, e.getMessage(), e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<OcrResult> runOcr(Bitmap inputImage) {
|
||||||
|
if (inputImage == null || !isLoaded()) {
|
||||||
|
return Collections.emptyList();
|
||||||
|
}
|
||||||
|
int run_det = isDetectionEnabled ? 1 : 0;
|
||||||
|
int run_cls = isClassificationEnabled ? 1 : 0;
|
||||||
|
int run_rec = isRecognitionEnabled ? 1 : 0;
|
||||||
|
// Warm up.
|
||||||
|
// zh-CN: 预热.
|
||||||
|
for (int i = 0; i < warmupIterNum; i++) {
|
||||||
|
paddlePredictor.runImage(inputImage, detLongSize, run_det, run_cls, run_rec);
|
||||||
|
}
|
||||||
|
// Do not need warm.
|
||||||
|
// zh-CN: 不需要预热.
|
||||||
|
warmupIterNum = 0;
|
||||||
|
// Run inference.
|
||||||
|
// zh-CN: 执行推理.
|
||||||
|
Date start = new Date();
|
||||||
|
ArrayList<OcrResultModel> results = paddlePredictor.runImage(inputImage, detLongSize, run_det, run_cls, run_rec);
|
||||||
|
Date end = new Date();
|
||||||
|
inferenceTime = (end.getTime() - start.getTime()) / (float) inferIterNum;
|
||||||
|
|
||||||
|
postProcess(results);
|
||||||
|
Log.i(TAG, "[stat] Preprocess Time: " + preprocessTime + "; Inference Time: " + inferenceTime + "; Box Size: " + results.size());
|
||||||
|
List<OcrResult> ocrResults = new ArrayList<>();
|
||||||
|
for (OcrResultModel resultModel : results) {
|
||||||
|
// Log.d(TAG, "Recognize: " + resultModel);
|
||||||
|
if (resultModel.getConfidence() >= scoreThreshold) {
|
||||||
|
ocrResults.add(new OcrResult(resultModel));
|
||||||
|
} else {
|
||||||
|
// Log.d(TAG, "Discard: " + resultModel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Collections.sort(ocrResults);
|
||||||
|
return ocrResults;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether model is loaded and predictor is valid.
|
||||||
|
* zh-CN: 模型是否已加载且预测器有效.
|
||||||
|
*/
|
||||||
|
public boolean isLoaded() {
|
||||||
|
return paddlePredictor != null && isLoaded;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String modelPath() {
|
||||||
|
return modelPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String modelName() {
|
||||||
|
return modelName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int cpuThreadNum() {
|
||||||
|
return cpuThreadNum;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String cpuPowerMode() {
|
||||||
|
return cpuPowerMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float inferenceTime() {
|
||||||
|
return inferenceTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Bitmap inputImage() {
|
||||||
|
return inputImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float preprocessTime() {
|
||||||
|
return preprocessTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDefaultLabelPath() {
|
||||||
|
return defaultLabelPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDefaultModelPath() {
|
||||||
|
return defaultModelPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get default OpenCL model directory (standard).
|
||||||
|
* zh-CN: 获取默认的 OpenCL 标准模型目录.
|
||||||
|
*/
|
||||||
|
public String getDefaultModelPathOpenCL() {
|
||||||
|
return defaultModelPathOpenCL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get default CPU model directory (INT8 slim).
|
||||||
|
* zh-CN: 获取默认的 CPU INT8 slim 模型目录.
|
||||||
|
*/
|
||||||
|
public String getDefaultModelPathSlim() {
|
||||||
|
return defaultModelPathSlim;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get default OpenCL model directory (INT8 slim).
|
||||||
|
* zh-CN: 获取默认的 OpenCL INT8 slim 模型目录.
|
||||||
|
*/
|
||||||
|
public String getDefaultModelPathOpenCLSlim() {
|
||||||
|
return defaultModelPathOpenCLSlim;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isUseSlim() {
|
||||||
|
return useSlim;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isUseOpenCL() {
|
||||||
|
return useOpenCL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set input image buffer (copy to ARGB_8888).
|
||||||
|
* zh-CN: 设置输入图像缓冲 (复制为 ARGB_8888).
|
||||||
|
*/
|
||||||
|
public void setInputImage(Bitmap image) {
|
||||||
|
if (image != null) {
|
||||||
|
this.inputImage = image.copy(Bitmap.Config.ARGB_8888, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert raw recognition outputs to text labels and metadata.
|
||||||
|
* zh-CN: 将识别原始输出转换为文本标签及元数据.
|
||||||
|
*/
|
||||||
|
private void postProcess(ArrayList<OcrResultModel> results) {
|
||||||
|
for (OcrResultModel r : results) {
|
||||||
|
StringBuilder word = new StringBuilder();
|
||||||
|
for (int index : r.getWordIndex()) {
|
||||||
|
if (index >= 0 && index < wordLabels.size()) {
|
||||||
|
word.append(wordLabels.get(index));
|
||||||
|
} else {
|
||||||
|
Log.e(TAG, "Word index is not in label list:" + index);
|
||||||
|
word.append(" ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
r.setLabel(word.toString());
|
||||||
|
r.setClsLabel(r.getClsIdx() == 1 ? "180" : "0");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enable/disable classification (cls).
|
||||||
|
* zh-CN: 启用/禁用方向分类 (cls).
|
||||||
|
*/
|
||||||
|
public void setClassificationEnabled(boolean enable) {
|
||||||
|
this.isClassificationEnabled = enable;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enable/disable detection (det).
|
||||||
|
* zh-CN: 启用/禁用文本检测 (det).
|
||||||
|
*/
|
||||||
|
public void setDetectionEnabled(boolean enable) {
|
||||||
|
this.isDetectionEnabled = enable;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enable/disable recognition (rec).
|
||||||
|
* zh-CN: 启用/禁用文本识别 (rec).
|
||||||
|
*/
|
||||||
|
public void setRecognitionEnabled(boolean enable) {
|
||||||
|
this.isRecognitionEnabled = enable;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set max long side for detection input (smaller is usually faster, e.g., 736-960).
|
||||||
|
* zh-CN: 设置检测输入的最长边 (越小通常越快, 例如 736-960).
|
||||||
|
*/
|
||||||
|
public void setDetLongSize(int detLongSize) {
|
||||||
|
this.detLongSize = detLongSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set score threshold (slightly improves speed by pruning noisy boxes).
|
||||||
|
* zh-CN: 设置置信度阈值 (通过剔除噪声框可略微提速).
|
||||||
|
*/
|
||||||
|
public void setScoreThreshold(float scoreThreshold) {
|
||||||
|
this.scoreThreshold = scoreThreshold;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+138
@@ -0,0 +1,138 @@
|
|||||||
|
package com.baidu.paddle.lite.ocr
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Bitmap
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.os.Looper
|
||||||
|
import android.util.Log
|
||||||
|
import org.autojs.plugin.paddle.ocr.api.OcrOptions
|
||||||
|
import org.autojs.plugin.paddle.ocr.api.OcrResult
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Native bridge based on com.baidu.paddle.lite.ocr.Predictor.
|
||||||
|
* zh-CN: 基于 com.baidu.paddle.lite.ocr.Predictor 的 native bridge.
|
||||||
|
*
|
||||||
|
* Created by JetBrains AI Assistant (GPT-5.2) on Jan 17, 2026.
|
||||||
|
* Modified by SuperMonster003 as of Jan 18, 2026.
|
||||||
|
*/
|
||||||
|
class PredictorNativeBridge : NativeBridge {
|
||||||
|
|
||||||
|
private val predictor = Predictor()
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var lastProfileKey: String? = null
|
||||||
|
|
||||||
|
override fun init(context: Context, profile: ModelProfile, checkingBitmap: Bitmap) {
|
||||||
|
|
||||||
|
val desiredThreadNum = profile.cpuThreadNum
|
||||||
|
val desiredUseSlim = profile.useSlim
|
||||||
|
val desiredUseOpenCL = profile.useOpenCL
|
||||||
|
|
||||||
|
// Compute a simple cache key to avoid redundant re-init.
|
||||||
|
// zh-CN: 计算简单缓存 key, 避免重复初始化.
|
||||||
|
val key = "${profile.variantName}|t=$desiredThreadNum|slim=$desiredUseSlim|opencl=$desiredUseOpenCL|dir=${profile.modelDir ?: "-"}"
|
||||||
|
if (predictor.isLoaded && lastProfileKey == key) return
|
||||||
|
|
||||||
|
// Predictor.init() may do heavy work and should not block main thread.
|
||||||
|
// zh-CN: Predictor.init() 可能较耗时, 不应阻塞主线程.
|
||||||
|
val ok = if (Looper.getMainLooper() == Looper.myLooper()) {
|
||||||
|
val lock = Object()
|
||||||
|
val completed = booleanArrayOf(false)
|
||||||
|
val initResult = booleanArrayOf(false)
|
||||||
|
|
||||||
|
Thread {
|
||||||
|
initResult[0] = initInternal(context, profile)
|
||||||
|
synchronized(lock) {
|
||||||
|
completed[0] = true
|
||||||
|
lock.notifyAll()
|
||||||
|
}
|
||||||
|
}.start()
|
||||||
|
|
||||||
|
val deadline = System.currentTimeMillis() + 60_000
|
||||||
|
var interrupted = false
|
||||||
|
synchronized(lock) {
|
||||||
|
try {
|
||||||
|
while (!completed[0]) {
|
||||||
|
val remaining = deadline - System.currentTimeMillis()
|
||||||
|
if (remaining <= 0) break
|
||||||
|
lock.wait(remaining)
|
||||||
|
}
|
||||||
|
} catch (_: InterruptedException) {
|
||||||
|
Thread.currentThread().interrupt()
|
||||||
|
interrupted = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
!interrupted && completed[0] && initResult[0]
|
||||||
|
} else {
|
||||||
|
initInternal(context, profile)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ok) {
|
||||||
|
throw IllegalStateException(context.getString(R.string.error_failed_to_initialize_paddle_ocr_predictor))
|
||||||
|
}
|
||||||
|
|
||||||
|
lastProfileKey = key
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initInternal(context: Context, profile: ModelProfile): Boolean {
|
||||||
|
// Ensure cpuThreadNum updates take effect.
|
||||||
|
// zh-CN: 确保 cpuThreadNum 更新生效.
|
||||||
|
if (predictor.cpuThreadNum != profile.cpuThreadNum) {
|
||||||
|
predictor.releaseModel()
|
||||||
|
predictor.cpuThreadNum = profile.cpuThreadNum
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply per-variant model file names (both v3/v5).
|
||||||
|
// zh-CN: 应用按变体区分的模型文件名 (同时覆盖 v3/v5).
|
||||||
|
predictor.detModelFilename = profile.detModelFile
|
||||||
|
predictor.recModelFilename = profile.recModelFile
|
||||||
|
predictor.clsModelFilename = profile.clsModelFile
|
||||||
|
|
||||||
|
return if (profile.variantName == VariantSpec.NAME_V5) {
|
||||||
|
// Use v5 built-in OpenCLGuard + fallback logic.
|
||||||
|
// zh-CN: 使用 v5 内置的 OpenCLGuard + fallback 逻辑.
|
||||||
|
predictor.init(
|
||||||
|
context.applicationContext,
|
||||||
|
profile.useSlim,
|
||||||
|
profile.useOpenCL,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// v3: OpenCL is ignored at variant level; init by resolved modelDir/labelPath.
|
||||||
|
// zh-CN: v3: OpenCL 在变体层被忽略; 按解析后的 modelDir/labelPath 初始化.
|
||||||
|
predictor.init(
|
||||||
|
context.applicationContext,
|
||||||
|
requireNotNull(profile.modelDir) {
|
||||||
|
context.getString(R.string.error_missing_modeldir_for_variant, profile.variantName)
|
||||||
|
},
|
||||||
|
profile.labelAssetPath,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun recognizeText(bitmap: Bitmap, options: OcrOptions): List<String> {
|
||||||
|
val results = predictor.runOcr(bitmap)
|
||||||
|
val out = ArrayList<String>(results.size)
|
||||||
|
for (r in results) out.add(r.label)
|
||||||
|
|
||||||
|
// Only print summary or first several items to avoid heavy I/O.
|
||||||
|
// zh-CN: 仅打印摘要或前若干条, 避免大量 I/O.
|
||||||
|
Log.i("PaddleOcrEngine", "recognized ${out.size} items")
|
||||||
|
for (i in 0 until minOf(5, out.size)) {
|
||||||
|
Log.d("PaddleOcrEngine", "item[$i]: ${out[i]}")
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun detect(bitmap: Bitmap, options: OcrOptions): List<OcrResult> {
|
||||||
|
val results = predictor.runOcr(bitmap)
|
||||||
|
return results.map { r ->
|
||||||
|
OcrResult().apply {
|
||||||
|
text = r.label
|
||||||
|
confidence = r.confidence
|
||||||
|
bounds = r.bounds
|
||||||
|
extras = Bundle()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
package com.baidu.paddle.lite.ocr;
|
||||||
|
|
||||||
|
import android.content.Context;
|
||||||
|
import android.graphics.Bitmap;
|
||||||
|
import android.graphics.Matrix;
|
||||||
|
import android.media.ExifInterface;
|
||||||
|
import android.os.Environment;
|
||||||
|
import android.util.Log;
|
||||||
|
|
||||||
|
import java.io.BufferedInputStream;
|
||||||
|
import java.io.BufferedOutputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @author PaddleOCR
|
||||||
|
* @since Aug 6, 2023
|
||||||
|
*
|
||||||
|
* <p> Modified by TonyJiangWJ as of Aug 7, 2023. </p>
|
||||||
|
* <p> Modified by SuperMonster003 as of Jan 18, 2026. </p>
|
||||||
|
*/
|
||||||
|
@SuppressWarnings({"ResultOfMethodCallIgnored", "CallToPrintStackTrace", "unused"})
|
||||||
|
public class Utils {
|
||||||
|
private static final String TAG = Utils.class.getSimpleName();
|
||||||
|
|
||||||
|
public static void copyFileFromAssets(Context appCtx, String srcPath, String dstPath) {
|
||||||
|
if (srcPath.isEmpty() || dstPath.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try (InputStream is = new BufferedInputStream(appCtx.getAssets().open(srcPath)); OutputStream os = new BufferedOutputStream(new FileOutputStream(dstPath))) {
|
||||||
|
try {
|
||||||
|
byte[] buffer = new byte[1024];
|
||||||
|
int length;
|
||||||
|
while ((length = is.read(buffer)) != -1) {
|
||||||
|
os.write(buffer, 0, length);
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void copyDirectoryFromAssets(Context appCtx, String srcDir, String dstDir) {
|
||||||
|
if (srcDir.isEmpty() || dstDir.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (!new File(dstDir).exists()) {
|
||||||
|
new File(dstDir).mkdirs();
|
||||||
|
}
|
||||||
|
String[] list = appCtx.getAssets().list(srcDir);
|
||||||
|
if (list == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (String fileName : list) {
|
||||||
|
String srcSubPath = srcDir + File.separator + fileName;
|
||||||
|
String dstSubPath = dstDir + File.separator + fileName;
|
||||||
|
if (new File(srcSubPath).isDirectory()) {
|
||||||
|
copyDirectoryFromAssets(appCtx, srcSubPath, dstSubPath);
|
||||||
|
} else {
|
||||||
|
Log.d(TAG, "Copy asset file: " + srcSubPath + " -> " + dstSubPath);
|
||||||
|
copyFileFromAssets(appCtx, srcSubPath, dstSubPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void copyDirectoryFromAssetsIfNeeded(Context appCtx, String srcDir, String dstDir) {
|
||||||
|
if (srcDir.isEmpty() || dstDir.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (!new File(dstDir).exists()) {
|
||||||
|
new File(dstDir).mkdirs();
|
||||||
|
}
|
||||||
|
String[] list = appCtx.getAssets().list(srcDir);
|
||||||
|
if (list == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (String fileName : list) {
|
||||||
|
String srcSubPath = srcDir + File.separator + fileName;
|
||||||
|
String dstSubPath = dstDir + File.separator + fileName;
|
||||||
|
if (new File(srcSubPath).isDirectory()) {
|
||||||
|
copyDirectoryFromAssetsIfNeeded(appCtx, srcSubPath, dstSubPath);
|
||||||
|
} else {
|
||||||
|
if (new File(dstSubPath).exists()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Log.d(TAG, "Copy asset file: " + srcSubPath + " -> " + dstSubPath);
|
||||||
|
copyFileFromAssets(appCtx, srcSubPath, dstSubPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static float[] parseFloatsFromString(String string, String delimiter) {
|
||||||
|
String[] pieces = string.trim().toLowerCase().split(delimiter);
|
||||||
|
float[] floats = new float[pieces.length];
|
||||||
|
for (int i = 0; i < pieces.length; i++) {
|
||||||
|
floats[i] = Float.parseFloat(pieces[i].trim());
|
||||||
|
}
|
||||||
|
return floats;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static long[] parseLongsFromString(String string, String delimiter) {
|
||||||
|
String[] pieces = string.trim().toLowerCase().split(delimiter);
|
||||||
|
long[] longs = new long[pieces.length];
|
||||||
|
for (int i = 0; i < pieces.length; i++) {
|
||||||
|
longs[i] = Long.parseLong(pieces[i].trim());
|
||||||
|
}
|
||||||
|
return longs;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getSDCardDirectory() {
|
||||||
|
return Environment.getExternalStorageDirectory().getAbsolutePath();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isSupportedNPU() {
|
||||||
|
return false;
|
||||||
|
// String hardware = android.os.Build.HARDWARE;
|
||||||
|
// return hardware.equalsIgnoreCase("kirin810") || hardware.equalsIgnoreCase("kirin990");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Bitmap resizeWithStep(Bitmap bitmap, int maxLength, int step) {
|
||||||
|
int width = bitmap.getWidth();
|
||||||
|
int height = bitmap.getHeight();
|
||||||
|
int maxWH = Math.max(width, height);
|
||||||
|
float ratio;
|
||||||
|
int newWidth = width;
|
||||||
|
int newHeight = height;
|
||||||
|
if (maxWH > maxLength) {
|
||||||
|
ratio = maxLength * 1.0f / maxWH;
|
||||||
|
newWidth = (int) Math.floor(ratio * width);
|
||||||
|
newHeight = (int) Math.floor(ratio * height);
|
||||||
|
}
|
||||||
|
|
||||||
|
newWidth = newWidth - newWidth % step;
|
||||||
|
if (newWidth == 0) {
|
||||||
|
newWidth = step;
|
||||||
|
}
|
||||||
|
newHeight = newHeight - newHeight % step;
|
||||||
|
if (newHeight == 0) {
|
||||||
|
newHeight = step;
|
||||||
|
}
|
||||||
|
return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Bitmap rotateBitmap(Bitmap bitmap, int orientation) {
|
||||||
|
|
||||||
|
Matrix matrix = new Matrix();
|
||||||
|
switch (orientation) {
|
||||||
|
case ExifInterface.ORIENTATION_NORMAL:
|
||||||
|
return bitmap;
|
||||||
|
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
|
||||||
|
matrix.setScale(-1, 1);
|
||||||
|
break;
|
||||||
|
case ExifInterface.ORIENTATION_ROTATE_180:
|
||||||
|
matrix.setRotate(180);
|
||||||
|
break;
|
||||||
|
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
|
||||||
|
matrix.setRotate(180);
|
||||||
|
matrix.postScale(-1, 1);
|
||||||
|
break;
|
||||||
|
case ExifInterface.ORIENTATION_TRANSPOSE:
|
||||||
|
matrix.setRotate(90);
|
||||||
|
matrix.postScale(-1, 1);
|
||||||
|
break;
|
||||||
|
case ExifInterface.ORIENTATION_ROTATE_90:
|
||||||
|
matrix.setRotate(90);
|
||||||
|
break;
|
||||||
|
case ExifInterface.ORIENTATION_TRANSVERSE:
|
||||||
|
matrix.setRotate(-90);
|
||||||
|
matrix.postScale(-1, 1);
|
||||||
|
break;
|
||||||
|
case ExifInterface.ORIENTATION_ROTATE_270:
|
||||||
|
matrix.setRotate(-90);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return bitmap;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
|
||||||
|
bitmap.recycle();
|
||||||
|
return bmRotated;
|
||||||
|
} catch (OutOfMemoryError e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 2.7 KiB |
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="error_failed_to_initialize_paddle_ocr_predictor">تعذّرت تهيئة Paddle OCR predictor.</string>
|
||||||
|
<string name="error_missing_modeldir_for_variant">modelDir مفقود لـ variant=%1$s.</string>
|
||||||
|
<string name="error_failed_to_decode_checking_drawable_resource">تعذّر فك ترميز مورد drawable الخاص بالتحقق.</string>
|
||||||
|
<string name="error_missing_required_paddle_ocr_asset">مورد Paddle OCR المطلوب مفقود: %1$s.</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="error_failed_to_initialize_paddle_ocr_predictor">Failed to initialize Paddle OCR predictor.</string>
|
||||||
|
<string name="error_missing_modeldir_for_variant">Missing modelDir for variant=%1$s.</string>
|
||||||
|
<string name="error_failed_to_decode_checking_drawable_resource">Failed to decode checking drawable resource.</string>
|
||||||
|
<string name="error_missing_required_paddle_ocr_asset">Missing required Paddle OCR asset: %1$s.</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="error_failed_to_initialize_paddle_ocr_predictor">No se pudo inicializar el predictor de Paddle OCR.</string>
|
||||||
|
<string name="error_missing_modeldir_for_variant">Falta modelDir para variant=%1$s.</string>
|
||||||
|
<string name="error_failed_to_decode_checking_drawable_resource">No se pudo decodificar el recurso drawable de verificación.</string>
|
||||||
|
<string name="error_missing_required_paddle_ocr_asset">Falta el recurso requerido de Paddle OCR: %1$s.</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="error_failed_to_initialize_paddle_ocr_predictor">Échec de l\'initialisation du prédicteur Paddle OCR.</string>
|
||||||
|
<string name="error_missing_modeldir_for_variant">modelDir manquant pour variant=%1$s.</string>
|
||||||
|
<string name="error_failed_to_decode_checking_drawable_resource">Échec du décodage de la ressource drawable de vérification.</string>
|
||||||
|
<string name="error_missing_required_paddle_ocr_asset">Ressource Paddle OCR requise manquante: %1$s.</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="error_failed_to_initialize_paddle_ocr_predictor">Paddle OCR predictor の初期化に失敗しました.</string>
|
||||||
|
<string name="error_missing_modeldir_for_variant">variant=%1$s の modelDir が見つかりません.</string>
|
||||||
|
<string name="error_failed_to_decode_checking_drawable_resource">確認用 drawable リソースのデコードに失敗しました.</string>
|
||||||
|
<string name="error_missing_required_paddle_ocr_asset">必要な Paddle OCR asset が見つかりません: %1$s.</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="error_failed_to_initialize_paddle_ocr_predictor">Paddle OCR predictor 초기화에 실패했습니다.</string>
|
||||||
|
<string name="error_missing_modeldir_for_variant">variant=%1$s에 대한 modelDir가 없습니다.</string>
|
||||||
|
<string name="error_failed_to_decode_checking_drawable_resource">검사용 drawable 리소스 디코딩에 실패했습니다.</string>
|
||||||
|
<string name="error_missing_required_paddle_ocr_asset">필수 Paddle OCR asset이 없습니다: %1$s.</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="error_failed_to_initialize_paddle_ocr_predictor">Не удалось инициализировать predictor Paddle OCR.</string>
|
||||||
|
<string name="error_missing_modeldir_for_variant">Отсутствует modelDir для variant=%1$s.</string>
|
||||||
|
<string name="error_failed_to_decode_checking_drawable_resource">Не удалось декодировать проверочный ресурс drawable.</string>
|
||||||
|
<string name="error_missing_required_paddle_ocr_asset">Отсутствует требуемый ресурс Paddle OCR: %1$s.</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="error_failed_to_initialize_paddle_ocr_predictor">初始化 Paddle OCR predictor 失敗.</string>
|
||||||
|
<string name="error_missing_modeldir_for_variant">變體缺少 modelDir: variant=%1$s.</string>
|
||||||
|
<string name="error_failed_to_decode_checking_drawable_resource">解碼檢查用 drawable 資源失敗.</string>
|
||||||
|
<string name="error_missing_required_paddle_ocr_asset">缺少 Paddle OCR 必要資源文件: %1$s.</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="error_failed_to_initialize_paddle_ocr_predictor">初始化 Paddle OCR predictor 失敗.</string>
|
||||||
|
<string name="error_missing_modeldir_for_variant">變體缺少 modelDir: variant=%1$s.</string>
|
||||||
|
<string name="error_failed_to_decode_checking_drawable_resource">解碼檢查用 drawable 資源失敗.</string>
|
||||||
|
<string name="error_missing_required_paddle_ocr_asset">缺少 Paddle OCR 必要資原始檔: %1$s.</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="error_failed_to_initialize_paddle_ocr_predictor">初始化 Paddle OCR predictor 失败.</string>
|
||||||
|
<string name="error_missing_modeldir_for_variant">变体缺少 modelDir: variant=%1$s.</string>
|
||||||
|
<string name="error_failed_to_decode_checking_drawable_resource">解码检查用 drawable 资源失败.</string>
|
||||||
|
<string name="error_missing_required_paddle_ocr_asset">缺少 Paddle OCR 必要资源文件: %1$s.</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<string name="error_failed_to_initialize_paddle_ocr_predictor">Failed to initialize Paddle OCR predictor.</string>
|
||||||
|
<string name="error_missing_modeldir_for_variant">Missing modelDir for variant=%1$s.</string>
|
||||||
|
<string name="error_failed_to_decode_checking_drawable_resource">Failed to decode checking drawable resource.</string>
|
||||||
|
<string name="error_missing_required_paddle_ocr_asset">Missing required Paddle OCR asset: %1$s.</string>
|
||||||
|
</resources>
|
||||||
+2
-1
@@ -40,7 +40,8 @@ private val libs = listOf(
|
|||||||
)
|
)
|
||||||
|
|
||||||
private val pluginApi = listOf(
|
private val pluginApi = listOf(
|
||||||
"paddle-ocr",
|
"paddle-ocr-api",
|
||||||
|
"paddle-ocr-engine",
|
||||||
)
|
)
|
||||||
|
|
||||||
include(
|
include(
|
||||||
|
|||||||
Reference in new issue
Block a user