first commit

This commit is contained in:
vl.arkhangelskii
2026-09-27 19:12:14 +03:00
commit ba3ba38fc9
318 changed files with 9377 additions and 0 deletions
+317
View File
@@ -0,0 +1,317 @@
import 'package:camera/camera.dart';
import 'package:flutter/cupertino.dart';
import '../../core/branding/app_brand.dart';
import '../../theme/tokens.dart';
import '../../ui/ui.dart';
import '../catalog/catalog_page.dart';
import '../theme/sign_style.dart';
import 'recognition_controller.dart';
import 'sign_panel.dart';
class CameraScreen extends StatefulWidget {
const CameraScreen({super.key, required this.controller});
final RecognitionController controller;
@override
State<CameraScreen> createState() => _CameraScreenState();
}
class _CameraScreenState extends State<CameraScreen>
with WidgetsBindingObserver {
RecognitionController get controller => widget.controller;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
controller.addListener(_onChange);
controller.initialize();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
final camera = controller.cameraController;
if (camera == null || !camera.value.isInitialized) {
if (state == AppLifecycleState.resumed) {
controller.openCamera();
}
return;
}
if (state == AppLifecycleState.inactive) {
controller.pause();
} else if (state == AppLifecycleState.resumed) {
controller.openCamera();
}
}
void _onChange() {
if (mounted) {
setState(() {});
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
controller.removeListener(_onChange);
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final camera = controller.cameraController;
return ColoredBox(
color: const Color(0xFF101114),
child: Stack(
fit: StackFit.expand,
children: [
if (camera != null && camera.value.isInitialized)
_Preview(controller: controller)
else
_CameraPlaceholder(message: controller.cameraMessage),
const _TopBar(),
Align(
alignment: Alignment.bottomCenter,
child: _BottomSheet(controller: controller),
),
],
),
);
}
}
class _Preview extends StatelessWidget {
const _Preview({required this.controller});
final RecognitionController controller;
@override
Widget build(BuildContext context) {
final camera = controller.cameraController!;
final preview = camera.value.previewSize;
if (preview == null) {
return const SizedBox.shrink();
}
final isPortrait =
MediaQuery.orientationOf(context) == Orientation.portrait;
return ClipRect(
child: FittedBox(
fit: BoxFit.cover,
child: SizedBox(
width: isPortrait ? preview.height : preview.width,
height: isPortrait ? preview.width : preview.height,
child: CameraPreview(
camera,
child: DetectionOverlay(
detections: controller.detections,
onSelect: (detection) => controller.pin(detection.rawLabel),
),
),
),
),
);
}
}
class _CameraPlaceholder extends StatelessWidget {
const _CameraPlaceholder({required this.message});
final String? message;
@override
Widget build(BuildContext context) {
return ColoredBox(
color: const Color(0xFF101114),
child: Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(
message ?? 'Открываю камеру…',
textAlign: TextAlign.center,
style: const TextStyle(color: Color(0xFFFFFFFF), fontSize: 16),
),
),
),
);
}
}
class _TopBar extends StatelessWidget {
const _TopBar();
@override
Widget build(BuildContext context) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(8),
child: Image.asset(AppBrand.iconAsset, width: 36, height: 36),
),
const SizedBox(width: 10),
const Text(
AppBrand.name,
style: TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 20,
fontWeight: FontWeight.w700,
),
),
const Spacer(),
CupertinoButton(
padding: const EdgeInsets.all(8),
onPressed: () {
Navigator.of(context).push(
CupertinoPageRoute<void>(
builder: (_) => const CatalogPage(),
),
);
},
child: const Icon(
CupertinoIcons.book,
color: Color(0xFFFFFFFF),
),
),
CupertinoButton(
padding: const EdgeInsets.all(8),
onPressed: () => _showHelp(context),
child: const Icon(
CupertinoIcons.slider_horizontal_3,
color: Color(0xFFFFFFFF),
),
),
],
),
),
);
}
void _showHelp(BuildContext context) {
final controller = context
.findAncestorStateOfType<_CameraScreenState>()!
.controller;
showCupertinoModalPopup<void>(
context: context,
builder: (context) {
return ListenableBuilder(
listenable: controller,
builder: (context, _) {
final background = AppColors.of(
context,
AppColors.groupedSurface,
);
return Align(
alignment: Alignment.bottomCenter,
child: Container(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.75,
),
decoration: BoxDecoration(
color: background,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(AppRadii.xl),
),
),
child: SafeArea(
top: false,
child: ListView(
shrinkWrap: true,
padding: const EdgeInsets.fromLTRB(20, 16, 20, 24),
children: [
const AppText.headline('Порог уверенности'),
const SizedBox(height: AppSpacing.s2),
AppText.callout(
'${(controller.confidenceThreshold * 100).round()}%. Ниже — больше срабатываний и больше ложных.',
),
CupertinoSlider(
value: controller.confidenceThreshold,
min: 0.25,
max: 0.9,
onChanged: controller.setConfidenceThreshold,
),
const SizedBox(height: AppSpacing.s3),
const AppText.headline('Модель'),
const SizedBox(height: AppSpacing.s2),
const AppText.body(
'Распознавание идёт на телефоне, модель уже лежит в приложении.',
),
const SizedBox(height: AppSpacing.s2),
const AppText.callout(
'Модель собирается скриптом tools/train_signs_model.py на датасете российских знаков. Классы в assets/models/labels.txt идут в том же порядке, что classes.txt этого датасета. Варианты 3.24.1, 3.24.2 и дальше открывают один знак 3.24: цифра скорости на нём, а не номер класса.',
),
const SizedBox(height: AppSpacing.s3),
const AppText.callout(
'Жёлтый фон и знаки на переносных опорах временные. Если временный знак противоречит стационарному, водитель руководствуется временным.',
),
const SizedBox(height: AppSpacing.s3),
const AppText.footnote(datasetAttribution),
],
),
),
),
);
},
);
},
);
}
}
class _BottomSheet extends StatelessWidget {
const _BottomSheet({required this.controller});
final RecognitionController controller;
@override
Widget build(BuildContext context) {
return SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
child: DecoratedBox(
decoration: BoxDecoration(
color: AppColors.of(context, AppColors.groupedSurface),
borderRadius: BorderRadius.circular(AppRadii.xl),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 12),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const AppText.footnote(safetyLine),
const SizedBox(height: AppSpacing.s3),
_body(),
if (controller.inferenceMs != null) ...[
const SizedBox(height: AppSpacing.s1),
AppText.caption('Кадр ${controller.inferenceMs} мс'),
],
],
),
),
),
),
);
}
Widget _body() {
return switch (controller.modelStatus) {
ModelStatus.checking => const AppText.body('Проверяю модель…'),
ModelStatus.missing => const AppText.body(
'Модель не установлена, поэтому знаки в кадре не называются. Справочник работает без неё. Как положить свою модель — кнопка настройки сверху.',
),
ModelStatus.failed => AppText.body(
controller.modelMessage ?? 'Модель не запустилась.',
),
ModelStatus.ready => SignPanel(
detections: controller.detections,
primary: controller.primary,
onSelect: (detection) => controller.pin(detection.rawLabel),
),
};
}
}
@@ -0,0 +1,317 @@
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 ?? 'Не удалось открыть камеру.',
};
}
+185
View File
@@ -0,0 +1,185 @@
import 'package:flutter/cupertino.dart';
import '../../domain/detection_stabilizer.dart';
import '../../theme/tokens.dart';
import '../../ui/ui.dart';
import '../catalog/sign_detail_page.dart';
import '../catalog/sign_glyph.dart';
import '../theme/sign_style.dart';
class SignPanel extends StatelessWidget {
const SignPanel({
super.key,
required this.detections,
required this.primary,
required this.onSelect,
});
final List<SignDetection> detections;
final SignDetection? primary;
final ValueChanged<SignDetection> onSelect;
@override
Widget build(BuildContext context) {
final current = primary;
if (current == null) {
return const AppText.callout(
'Наведите камеру на знак. Рамка появится, когда знак удержится в кадре.',
);
}
final sign = current.sign;
final color = categoryColor(sign?.category);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (detections.length > 1)
SizedBox(
height: 36,
child: ListView.separated(
scrollDirection: Axis.horizontal,
itemCount: detections.length,
separatorBuilder: (_, _) => const SizedBox(width: 8),
itemBuilder: (context, index) {
final detection = detections[index];
final selected = detection.rawLabel == current.rawLabel;
return CupertinoButton(
padding: const EdgeInsets.symmetric(horizontal: 12),
minimumSize: const Size(44, 32),
color: selected
? AppColors.of(context, AppColors.accent)
: AppColors.of(context, AppColors.systemGray5),
borderRadius: BorderRadius.circular(AppRadii.capsule),
onPressed: () => onSelect(detection),
child: Text(
detection.titleCode,
style: TextStyle(
fontSize: 13,
color: selected
? const Color(0xFFFFFFFF)
: AppColors.of(context, AppColors.label),
),
),
);
},
),
),
if (detections.length > 1) const SizedBox(height: AppSpacing.s2),
Row(
children: [
AppText.title(current.titleCode, color: color),
const SizedBox(width: AppSpacing.s3),
AppText.callout('${(current.confidence * 100).round()}%'),
],
),
const SizedBox(height: AppSpacing.s2),
if (sign == null)
AppText.body(
'Модель назвала «${current.rawLabel}». Такого номера нет в справочнике, поэтому правило не показываю.',
)
else ...[
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SignGlyph(sign: sign, size: 64),
const SizedBox(width: AppSpacing.s3),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AppText.headline(sign.name),
const SizedBox(height: AppSpacing.s2),
AppText.callout(sign.action),
],
),
),
],
),
if (sign.requiresReadingTheSign) ...[
const SizedBox(height: AppSpacing.s2),
const AppText.footnote(
faceReadingWarning,
color: AppColors.systemOrange,
),
],
Align(
alignment: Alignment.centerLeft,
child: CupertinoButton(
padding: const EdgeInsets.only(top: AppSpacing.s2),
onPressed: () {
Navigator.of(context).push(
CupertinoPageRoute<void>(
builder: (_) => SignDetailPage(sign: sign),
),
);
},
child: const Text('Подробнее'),
),
),
],
],
);
}
}
class DetectionOverlay extends StatelessWidget {
const DetectionOverlay({
super.key,
required this.detections,
required this.onSelect,
});
final List<SignDetection> detections;
final ValueChanged<SignDetection> onSelect;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final width = constraints.maxWidth;
final height = constraints.maxHeight;
return Stack(
children: [
for (final detection in detections)
Positioned(
left: detection.box.left * width,
top: detection.box.top * height,
width: detection.box.width * width,
height: detection.box.height * height,
child: GestureDetector(
onTap: () => onSelect(detection),
child: DecoratedBox(
decoration: BoxDecoration(
border: Border.all(
color: categoryColor(detection.sign?.category),
width: 3,
),
borderRadius: BorderRadius.circular(8),
),
child: Align(
alignment: Alignment.topLeft,
child: ColoredBox(
color: categoryColor(detection.sign?.category),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 2,
),
child: Text(
detection.titleCode,
style: const TextStyle(
color: Color(0xFF000000),
fontWeight: FontWeight.w700,
),
),
),
),
),
),
),
),
],
);
},
);
}
}