318 lines
8.9 KiB
Dart
318 lines
8.9 KiB
Dart
import 'dart:async';
|
||
|
||
import 'package:camera/camera.dart';
|
||
import 'package:flutter/services.dart';
|
||
import 'package:flutter/widgets.dart';
|
||
|
||
import '../../data/catalog/bundled_sign_catalog.dart';
|
||
import '../../data/detection/detector_worker.dart';
|
||
import '../../data/frame/yuv_sampler.dart';
|
||
import '../../domain/detection_stabilizer.dart';
|
||
import '../../domain/rotation.dart';
|
||
import '../../domain/sign_catalog.dart';
|
||
|
||
enum ModelStatus { checking, missing, ready, failed }
|
||
|
||
class RecognitionController extends ChangeNotifier {
|
||
RecognitionController({SignCatalog? catalog, this._worker})
|
||
: catalog = catalog ?? bundledSignCatalog;
|
||
|
||
final SignCatalog catalog;
|
||
final DetectionStabilizer stabilizer = DetectionStabilizer();
|
||
DetectorWorker? _worker;
|
||
|
||
CameraController? cameraController;
|
||
List<SignDetection> detections = const [];
|
||
String? pinnedLabel;
|
||
ModelStatus modelStatus = ModelStatus.checking;
|
||
String? modelMessage;
|
||
String? cameraMessage;
|
||
int? inferenceMs;
|
||
double confidenceThreshold = 0.45;
|
||
bool get modelReady => modelStatus == ModelStatus.ready;
|
||
|
||
var _busy = false;
|
||
var _disposed = false;
|
||
var _cameraEpoch = 0;
|
||
var _reportedFormat = false;
|
||
|
||
SignDetection? get primary {
|
||
if (detections.isEmpty) {
|
||
return null;
|
||
}
|
||
for (final detection in detections) {
|
||
if (detection.rawLabel == pinnedLabel) {
|
||
return detection;
|
||
}
|
||
}
|
||
return detections.first;
|
||
}
|
||
|
||
Future<void> initialize() async {
|
||
await Future.wait([openCamera(), _loadModel()]);
|
||
}
|
||
|
||
Future<void> openCamera() async {
|
||
if (_disposed) {
|
||
return;
|
||
}
|
||
final epoch = ++_cameraEpoch;
|
||
try {
|
||
final cameras = await availableCameras();
|
||
if (_disposed || epoch != _cameraEpoch) {
|
||
return;
|
||
}
|
||
if (cameras.isEmpty) {
|
||
cameraMessage = 'На устройстве нет камеры.';
|
||
notifyListeners();
|
||
return;
|
||
}
|
||
final description = cameras.firstWhere(
|
||
(camera) => camera.lensDirection == CameraLensDirection.back,
|
||
orElse: () => cameras.first,
|
||
);
|
||
final controller = CameraController(
|
||
description,
|
||
ResolutionPreset.medium,
|
||
enableAudio: false,
|
||
imageFormatGroup: ImageFormatGroup.yuv420,
|
||
);
|
||
await controller.initialize();
|
||
if (_disposed || epoch != _cameraEpoch) {
|
||
await controller.dispose();
|
||
return;
|
||
}
|
||
cameraController = controller;
|
||
cameraMessage = null;
|
||
notifyListeners();
|
||
await _startStream();
|
||
} on CameraException catch (error) {
|
||
if (_disposed || epoch != _cameraEpoch) {
|
||
return;
|
||
}
|
||
cameraMessage = _cameraMessage(error);
|
||
notifyListeners();
|
||
}
|
||
}
|
||
|
||
Future<void> pause() async {
|
||
_cameraEpoch++;
|
||
final controller = cameraController;
|
||
cameraController = null;
|
||
detections = const [];
|
||
stabilizer.reset();
|
||
if (controller != null) {
|
||
if (controller.value.isInitialized &&
|
||
controller.value.isStreamingImages) {
|
||
await controller.stopImageStream();
|
||
}
|
||
await controller.dispose();
|
||
}
|
||
if (!_disposed) {
|
||
notifyListeners();
|
||
}
|
||
}
|
||
|
||
void pin(String rawLabel) {
|
||
pinnedLabel = rawLabel;
|
||
notifyListeners();
|
||
}
|
||
|
||
void setConfidenceThreshold(double value) {
|
||
confidenceThreshold = value.clamp(0.25, 0.9);
|
||
stabilizer.reset();
|
||
detections = const [];
|
||
notifyListeners();
|
||
}
|
||
|
||
Future<void> _loadModel() async {
|
||
try {
|
||
final model = await rootBundle.load('assets/models/signs.tflite');
|
||
final labelsFile = await rootBundle.loadString(
|
||
'assets/models/labels.txt',
|
||
);
|
||
final labels = [
|
||
for (final line in labelsFile.split('\n'))
|
||
if (_labelLine(line) != null) _labelLine(line)!,
|
||
];
|
||
if (labels.isEmpty) {
|
||
modelStatus = ModelStatus.missing;
|
||
modelMessage = 'В labels.txt нет классов. Запишите номера знаков в том порядке, в каком училась модель.';
|
||
notifyListeners();
|
||
return;
|
||
}
|
||
final worker = _worker ?? DetectorWorker();
|
||
_worker = worker;
|
||
await worker.start(
|
||
modelBytes: model.buffer.asUint8List(),
|
||
labels: labels,
|
||
);
|
||
if (_disposed) {
|
||
await worker.dispose();
|
||
return;
|
||
}
|
||
modelStatus = ModelStatus.ready;
|
||
modelMessage = null;
|
||
notifyListeners();
|
||
await _startStream();
|
||
} catch (error) {
|
||
if (_isMissingAsset(error)) {
|
||
modelStatus = ModelStatus.missing;
|
||
modelMessage = null;
|
||
} else {
|
||
modelStatus = ModelStatus.failed;
|
||
modelMessage = '$error';
|
||
}
|
||
if (!_disposed) {
|
||
notifyListeners();
|
||
}
|
||
}
|
||
}
|
||
|
||
Future<void> _startStream() async {
|
||
final controller = cameraController;
|
||
final worker = _worker;
|
||
if (controller == null ||
|
||
worker == null ||
|
||
!worker.isReady ||
|
||
!controller.value.isInitialized ||
|
||
controller.value.isStreamingImages) {
|
||
return;
|
||
}
|
||
await controller.startImageStream(_onFrame);
|
||
}
|
||
|
||
void _onFrame(CameraImage image) {
|
||
if (_busy || _disposed) {
|
||
return;
|
||
}
|
||
final frame = _copyFrame(image);
|
||
if (frame == null) {
|
||
if (!_reportedFormat) {
|
||
_reportedFormat = true;
|
||
cameraMessage = 'Этот формат кадра камера не отдаёт как YUV420.';
|
||
notifyListeners();
|
||
}
|
||
return;
|
||
}
|
||
final controller = cameraController;
|
||
final worker = _worker;
|
||
if (controller == null || worker == null) {
|
||
return;
|
||
}
|
||
_busy = true;
|
||
final degrees = uprightClockwiseDegrees(
|
||
sensorOrientation: controller.description.sensorOrientation,
|
||
deviceDegrees: _deviceDegrees(controller.value.deviceOrientation),
|
||
frontCamera:
|
||
controller.description.lensDirection == CameraLensDirection.front,
|
||
);
|
||
final mirror =
|
||
controller.description.lensDirection == CameraLensDirection.front;
|
||
worker
|
||
.detect(
|
||
frame: frame,
|
||
clockwiseDegrees: degrees,
|
||
confidenceThreshold: confidenceThreshold,
|
||
)
|
||
.then((outcome) {
|
||
_busy = false;
|
||
if (_disposed) {
|
||
return;
|
||
}
|
||
inferenceMs = outcome.elapsedMs;
|
||
final hits = [
|
||
for (final hit in outcome.hits)
|
||
SignDetection(
|
||
rawLabel: hit.label,
|
||
confidence: hit.confidence,
|
||
box: mirror ? hit.box.mirroredHorizontally() : hit.box,
|
||
sign: catalog.findByLabel(hit.label),
|
||
),
|
||
];
|
||
detections = stabilizer.update(hits);
|
||
if (pinnedLabel != null &&
|
||
detections.every((item) => item.rawLabel != pinnedLabel)) {
|
||
pinnedLabel = null;
|
||
}
|
||
notifyListeners();
|
||
})
|
||
.catchError((Object error) {
|
||
_busy = false;
|
||
if (_disposed) {
|
||
return;
|
||
}
|
||
modelStatus = ModelStatus.failed;
|
||
modelMessage = '$error';
|
||
notifyListeners();
|
||
final active = cameraController;
|
||
if (active != null && active.value.isStreamingImages) {
|
||
active.stopImageStream();
|
||
}
|
||
});
|
||
}
|
||
|
||
YuvFrame? _copyFrame(CameraImage image) {
|
||
if (image.format.group != ImageFormatGroup.yuv420 ||
|
||
image.planes.length < 3) {
|
||
return null;
|
||
}
|
||
final y = image.planes[0];
|
||
final u = image.planes[1];
|
||
final v = image.planes[2];
|
||
return YuvFrame(
|
||
width: image.width,
|
||
height: image.height,
|
||
y: Uint8List.fromList(y.bytes),
|
||
u: Uint8List.fromList(u.bytes),
|
||
v: Uint8List.fromList(v.bytes),
|
||
yRowStride: y.bytesPerRow,
|
||
yPixelStride: y.bytesPerPixel ?? 1,
|
||
uvRowStride: u.bytesPerRow,
|
||
uvPixelStride: u.bytesPerPixel ?? 1,
|
||
);
|
||
}
|
||
|
||
@override
|
||
void dispose() {
|
||
_disposed = true;
|
||
final controller = cameraController;
|
||
cameraController = null;
|
||
if (controller != null) {
|
||
controller.dispose();
|
||
}
|
||
unawaited(_worker?.dispose() ?? Future<void>.value());
|
||
super.dispose();
|
||
}
|
||
}
|
||
|
||
String? _labelLine(String line) {
|
||
final trimmed = line.trim();
|
||
if (trimmed.isEmpty || trimmed.startsWith('#')) {
|
||
return null;
|
||
}
|
||
return trimmed;
|
||
}
|
||
|
||
bool _isMissingAsset(Object error) {
|
||
final text = error.toString();
|
||
return text.contains('Unable to load asset') || text.contains('signs.tflite');
|
||
}
|
||
|
||
int _deviceDegrees(DeviceOrientation orientation) {
|
||
return switch (orientation) {
|
||
DeviceOrientation.portraitUp => 0,
|
||
DeviceOrientation.landscapeLeft => 90,
|
||
DeviceOrientation.portraitDown => 180,
|
||
DeviceOrientation.landscapeRight => 270,
|
||
};
|
||
}
|
||
|
||
String _cameraMessage(CameraException error) {
|
||
return switch (error.code) {
|
||
'CameraAccessDenied' || 'CameraAccessDeniedWithoutPrompt' =>
|
||
'Нет доступа к камере. Разрешите его в настройках Android.',
|
||
_ => error.description ?? 'Не удалось открыть камеру.',
|
||
};
|
||
}
|