Files
BadNote/lib/services/ocr/ocr_backends.dart

46 lines
1.2 KiB
Dart
Raw Permalink Normal View History

import 'dart:typed_data';
import 'native_ocr_backend.dart';
import 'ocr_backend.dart';
import 'onnx_recognition_backend.dart';
/// Selects and caches the active local OCR backend.
///
/// Preference order: the embedded ONNX recognition backend if its model is
/// bundled and loads, otherwise the native platform backend, otherwise none.
class OcrBackends {
OcrBackends._();
static OcrBackend? _active;
static bool _resolved = false;
/// Resolve (once) and return the preferred available backend, or null when
/// no backend is available on this device/build.
static Future<OcrBackend?> active() async {
if (_resolved) return _active;
final candidates = <OcrBackend>[
OnnxRecognitionBackend(),
NativeOcrBackend(),
];
for (final backend in candidates) {
if (await backend.isAvailable()) {
_active = backend;
break;
}
}
_resolved = true;
return _active;
}
/// Recognize text using the active backend. Returns null when no backend is
/// available or nothing was recognized.
static Future<String?> recognize(Uint8List png) async {
final backend = await active();
if (backend == null) return null;
return backend.recognize(png);
}
}