双档位训练体系(s高识别/n高性能 串行排队、按档发布)与 TFLite 硬件加速补丁

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-09-03 09:20:46 +08:00
co-authored by Claude Opus 4.7
parent bb75c69d91
commit 6f8c54c31d
23 changed files with 651 additions and 269 deletions
@@ -1,3 +1,4 @@
import 'dart:io' show Platform;
import 'dart:typed_data';
import 'package:flutter/foundation.dart' show debugPrint;
@@ -44,12 +45,28 @@ class TfliteDetector {
/// 模型缺失或加载失败返回 null(App 降级为仅预览)。
/// 在后台 isolate 内调用(模型字节由主 isolate 读取后传入)。
/// 加速:Android 挂 TFLite GPU delegate、iOS 挂 CoreML delegateANE/GPU),
/// 均为浮点计算不降精度(对比 int8 量化);delegate 初始化失败自动回退纯 CPU 4 线程。
static Future<TfliteDetector?> fromBuffer(
Uint8List bytes,
List<String> labels, {
int modelId = -1,
String modelName = '',
}) async {
final delegate = _createAccelDelegate();
if (delegate != null) {
try {
final options = InterpreterOptions()..threads = 4;
options.addDelegate(delegate);
final interpreter = Interpreter.fromBuffer(bytes, options: options);
debugPrint('[TfliteDetector] 加速生效 model=$modelName '
'(${Platform.isIOS ? 'CoreML' : 'GPU'})');
return TfliteDetector._fromModel(
interpreter, labels, modelId, modelName);
} catch (e) {
debugPrint('[TfliteDetector] 加速 delegate 初始化失败,回退 CPU: $e');
}
}
try {
final interpreter = Interpreter.fromBuffer(
bytes,
@@ -62,6 +79,26 @@ class TfliteDetector {
}
}
/// 平台加速 delegateAndroid=TFLite GPUlibtensorflowlite_gpu_jni.so 已 vendor 到
/// android/app/src/main/jniLibsAAR 因 AGP namespace 冲突保持排除)、iOS=CoreML。
/// 老设备/驱动/符号缺失时创建失败返回 null,走 CPU。
static Delegate? _createAccelDelegate() {
if (Platform.isIOS) {
try {
return CoreMlDelegate();
} catch (e) {
debugPrint('[TfliteDetector] CoreML delegate 创建失败: $e');
}
} else if (Platform.isAndroid) {
try {
return GpuDelegateV2();
} catch (e) {
debugPrint('[TfliteDetector] GPU delegate 创建失败: $e');
}
}
return null;
}
/// 输出布局 [1, 4+nc, anchors] 取自模型本身,类别数不与 labels 文件长度耦合。
factory TfliteDetector._fromModel(Interpreter interpreter,
List<String> labels, int modelId, String modelName) {