first commit
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../core/branding/app_brand.dart';
|
||||
import '../presentation/camera/camera_screen.dart';
|
||||
import '../presentation/camera/recognition_controller.dart';
|
||||
import '../theme/theme.dart';
|
||||
|
||||
class SignCheckerApp extends StatelessWidget {
|
||||
const SignCheckerApp({super.key, this.controller});
|
||||
|
||||
final RecognitionController? controller;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CupertinoApp(
|
||||
title: AppBrand.name,
|
||||
theme: buildDarkTheme(),
|
||||
builder: (context, child) {
|
||||
final brightness = MediaQuery.platformBrightnessOf(context);
|
||||
final overlay = systemUiOverlayFor(brightness);
|
||||
return CupertinoTheme(
|
||||
data: brightness == Brightness.dark
|
||||
? buildDarkTheme()
|
||||
: buildLightTheme(),
|
||||
child: AnnotatedRegion<SystemUiOverlayStyle>(
|
||||
value: overlay,
|
||||
child: child ?? const SizedBox.shrink(),
|
||||
),
|
||||
);
|
||||
},
|
||||
home: CameraScreen(controller: controller ?? RecognitionController()),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
abstract final class AppBrand {
|
||||
static const name = 'Sign Detector';
|
||||
static const iconAsset = 'assets/branding/app_icon.png';
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import '../../domain/sign_catalog.dart';
|
||||
import 'sign_definitions.dart';
|
||||
|
||||
final SignCatalog bundledSignCatalog = SignCatalog(signDefinitions);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,219 @@
|
||||
// Generated by tools/fetch_drom_sign_svgs.py.
|
||||
const Set<String> signImageAssets = {
|
||||
'1.1',
|
||||
'1.2',
|
||||
'1.3.1',
|
||||
'1.3.2',
|
||||
'1.4.1',
|
||||
'1.4.2',
|
||||
'1.4.3',
|
||||
'1.4.4',
|
||||
'1.4.5',
|
||||
'1.4.6',
|
||||
'1.5',
|
||||
'1.6',
|
||||
'1.7',
|
||||
'1.8',
|
||||
'1.9',
|
||||
'1.10',
|
||||
'1.11.1',
|
||||
'1.11.2',
|
||||
'1.12.1',
|
||||
'1.12.2',
|
||||
'1.13',
|
||||
'1.14',
|
||||
'1.15',
|
||||
'1.16',
|
||||
'1.17',
|
||||
'1.18',
|
||||
'1.19',
|
||||
'1.20.1',
|
||||
'1.20.2',
|
||||
'1.20.3',
|
||||
'1.21',
|
||||
'1.22',
|
||||
'1.23',
|
||||
'1.24',
|
||||
'1.25',
|
||||
'1.26',
|
||||
'1.27',
|
||||
'1.28',
|
||||
'1.29',
|
||||
'1.30',
|
||||
'1.31',
|
||||
'1.32',
|
||||
'1.33',
|
||||
'1.34.1',
|
||||
'1.34.2',
|
||||
'1.34.3',
|
||||
'1.35',
|
||||
'2.1',
|
||||
'2.2',
|
||||
'2.3.1',
|
||||
'2.3.2',
|
||||
'2.3.3',
|
||||
'2.3.4',
|
||||
'2.3.5',
|
||||
'2.3.6',
|
||||
'2.3.7',
|
||||
'2.4',
|
||||
'2.5',
|
||||
'2.6',
|
||||
'2.7',
|
||||
'3.1',
|
||||
'3.2',
|
||||
'3.3',
|
||||
'3.4',
|
||||
'3.5',
|
||||
'3.6',
|
||||
'3.7',
|
||||
'3.8',
|
||||
'3.9',
|
||||
'3.10',
|
||||
'3.11',
|
||||
'3.12',
|
||||
'3.13',
|
||||
'3.14',
|
||||
'3.15',
|
||||
'3.16',
|
||||
'3.17.1',
|
||||
'3.17.2',
|
||||
'3.17.3',
|
||||
'3.18.1',
|
||||
'3.18.2',
|
||||
'3.19',
|
||||
'3.20',
|
||||
'3.21',
|
||||
'3.22',
|
||||
'3.23',
|
||||
'3.24',
|
||||
'3.25',
|
||||
'3.26',
|
||||
'3.27',
|
||||
'3.28',
|
||||
'3.29',
|
||||
'3.30',
|
||||
'3.31',
|
||||
'3.32',
|
||||
'3.33',
|
||||
'3.34',
|
||||
'3.35',
|
||||
'4.1.1',
|
||||
'4.1.2',
|
||||
'4.1.3',
|
||||
'4.1.4',
|
||||
'4.1.5',
|
||||
'4.1.6',
|
||||
'4.2.1',
|
||||
'4.2.2',
|
||||
'4.2.3',
|
||||
'4.3',
|
||||
'4.4.1',
|
||||
'4.4.2',
|
||||
'4.5.1',
|
||||
'4.5.2',
|
||||
'4.5.3',
|
||||
'4.5.4',
|
||||
'4.5.5',
|
||||
'4.5.6',
|
||||
'4.5.7',
|
||||
'4.6',
|
||||
'4.7',
|
||||
'4.8.1',
|
||||
'4.8.2',
|
||||
'4.8.3',
|
||||
'5.1',
|
||||
'5.2',
|
||||
'5.3',
|
||||
'5.4',
|
||||
'5.5',
|
||||
'5.6',
|
||||
'5.7.1',
|
||||
'5.7.2',
|
||||
'5.8',
|
||||
'5.9',
|
||||
'5.10',
|
||||
'5.11.1',
|
||||
'5.11.2',
|
||||
'5.12.1',
|
||||
'5.12.2',
|
||||
'5.13.1',
|
||||
'5.13.2',
|
||||
'5.14.1',
|
||||
'5.14.2',
|
||||
'5.14.3',
|
||||
'5.14.4',
|
||||
'5.15.1',
|
||||
'5.15.2',
|
||||
'5.15.3',
|
||||
'5.15.4',
|
||||
'5.15.5',
|
||||
'5.15.6',
|
||||
'5.15.7',
|
||||
'5.15.8',
|
||||
'5.16',
|
||||
'5.17',
|
||||
'5.18',
|
||||
'5.19.1',
|
||||
'5.19.2',
|
||||
'5.20',
|
||||
'5.21',
|
||||
'5.22',
|
||||
'5.23.1',
|
||||
'5.23.2',
|
||||
'5.24.1',
|
||||
'5.24.2',
|
||||
'5.25',
|
||||
'5.26',
|
||||
'5.27',
|
||||
'5.28',
|
||||
'5.29',
|
||||
'5.30',
|
||||
'5.31',
|
||||
'5.32',
|
||||
'5.33',
|
||||
'5.34',
|
||||
'5.35',
|
||||
'5.36',
|
||||
'5.37',
|
||||
'5.38',
|
||||
'5.39',
|
||||
'5.40',
|
||||
'6.1',
|
||||
'6.2',
|
||||
'6.3.1',
|
||||
'6.3.2',
|
||||
'6.4',
|
||||
'6.5',
|
||||
'6.6',
|
||||
'6.7',
|
||||
'6.8.1',
|
||||
'6.8.2',
|
||||
'6.8.3',
|
||||
'6.16',
|
||||
'6.22',
|
||||
'7.1',
|
||||
'7.2',
|
||||
'7.3',
|
||||
'7.4',
|
||||
'7.5',
|
||||
'7.7',
|
||||
'7.12',
|
||||
'7.19',
|
||||
'7.21',
|
||||
'8.1.1',
|
||||
'8.2.1',
|
||||
'8.2.2',
|
||||
'8.2.3',
|
||||
'8.2.4',
|
||||
'8.13',
|
||||
'8.14',
|
||||
'8.15',
|
||||
'8.16',
|
||||
'8.17',
|
||||
'8.18',
|
||||
'8.22.1',
|
||||
'8.22.2',
|
||||
'8.22.3',
|
||||
'8.24',
|
||||
};
|
||||
@@ -0,0 +1,290 @@
|
||||
import 'dart:async';
|
||||
import 'dart:isolate';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:tflite_flutter/tflite_flutter.dart';
|
||||
|
||||
import '../../domain/letterbox.dart';
|
||||
import '../../domain/norm_rect.dart';
|
||||
import '../../domain/rotation.dart';
|
||||
import '../../domain/yolo_decoder.dart';
|
||||
import '../frame/yuv_sampler.dart';
|
||||
|
||||
class FrameHit {
|
||||
const FrameHit({
|
||||
required this.label,
|
||||
required this.confidence,
|
||||
required this.box,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final double confidence;
|
||||
final NormRect box;
|
||||
}
|
||||
|
||||
class FrameOutcome {
|
||||
const FrameOutcome({required this.hits, required this.elapsedMs});
|
||||
|
||||
final List<FrameHit> hits;
|
||||
final int elapsedMs;
|
||||
}
|
||||
|
||||
class DetectorWorker {
|
||||
Isolate? _isolate;
|
||||
SendPort? _send;
|
||||
final ReceivePort _incoming = ReceivePort();
|
||||
StreamSubscription<dynamic>? _subscription;
|
||||
final Map<int, Completer<Object>> _pending = {};
|
||||
var _nextId = 0;
|
||||
var _ready = false;
|
||||
|
||||
bool get isReady => _ready;
|
||||
|
||||
Future<int> start({
|
||||
required Uint8List modelBytes,
|
||||
required List<String> labels,
|
||||
}) async {
|
||||
_isolate = await Isolate.spawn(detectorIsolateMain, _incoming.sendPort);
|
||||
final sendCompleter = Completer<SendPort>();
|
||||
_subscription = _incoming.listen((message) {
|
||||
if (message is SendPort) {
|
||||
if (!sendCompleter.isCompleted) {
|
||||
sendCompleter.complete(message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
_onMessage(message);
|
||||
});
|
||||
_send = await sendCompleter.future;
|
||||
final id = _nextId++;
|
||||
final pending = Completer<Object>();
|
||||
_pending[id] = pending;
|
||||
_send!.send(_LoadModel(id, modelBytes, labels));
|
||||
final inputSize = await pending.future;
|
||||
_ready = true;
|
||||
return inputSize as int;
|
||||
}
|
||||
|
||||
Future<FrameOutcome> detect({
|
||||
required YuvFrame frame,
|
||||
required int clockwiseDegrees,
|
||||
required double confidenceThreshold,
|
||||
double iouThreshold = 0.45,
|
||||
}) {
|
||||
final send = _send;
|
||||
if (send == null || !_ready) {
|
||||
return Future.error(StateError('Детектор не загружен'));
|
||||
}
|
||||
final id = _nextId++;
|
||||
final pending = Completer<Object>();
|
||||
_pending[id] = pending;
|
||||
send.send(
|
||||
_FrameJob(
|
||||
id: id,
|
||||
frame: frame,
|
||||
clockwiseDegrees: clockwiseDegrees,
|
||||
confidenceThreshold: confidenceThreshold,
|
||||
iouThreshold: iouThreshold,
|
||||
),
|
||||
);
|
||||
return pending.future.then((value) => value as FrameOutcome);
|
||||
}
|
||||
|
||||
void _onMessage(Object? message) {
|
||||
if (message is _Ready) {
|
||||
_pending.remove(message.id)?.complete(message.inputSize);
|
||||
return;
|
||||
}
|
||||
if (message is _FrameDone) {
|
||||
_pending
|
||||
.remove(message.id)
|
||||
?.complete(
|
||||
FrameOutcome(hits: message.hits, elapsedMs: message.elapsedMs),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (message is _Failed) {
|
||||
_pending.remove(message.id)?.completeError(StateError(message.reason));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> dispose() async {
|
||||
_isolate?.kill(priority: Isolate.immediate);
|
||||
await _subscription?.cancel();
|
||||
_incoming.close();
|
||||
_isolate = null;
|
||||
_send = null;
|
||||
_ready = false;
|
||||
}
|
||||
}
|
||||
|
||||
class _LoadModel {
|
||||
const _LoadModel(this.id, this.bytes, this.labels);
|
||||
|
||||
final int id;
|
||||
final Uint8List bytes;
|
||||
final List<String> labels;
|
||||
}
|
||||
|
||||
class _FrameJob {
|
||||
const _FrameJob({
|
||||
required this.id,
|
||||
required this.frame,
|
||||
required this.clockwiseDegrees,
|
||||
required this.confidenceThreshold,
|
||||
required this.iouThreshold,
|
||||
});
|
||||
|
||||
final int id;
|
||||
final YuvFrame frame;
|
||||
final int clockwiseDegrees;
|
||||
final double confidenceThreshold;
|
||||
final double iouThreshold;
|
||||
}
|
||||
|
||||
class _Ready {
|
||||
const _Ready(this.id, this.inputSize);
|
||||
|
||||
final int id;
|
||||
final int inputSize;
|
||||
}
|
||||
|
||||
class _FrameDone {
|
||||
const _FrameDone(this.id, this.hits, this.elapsedMs);
|
||||
|
||||
final int id;
|
||||
final List<FrameHit> hits;
|
||||
final int elapsedMs;
|
||||
}
|
||||
|
||||
class _Failed {
|
||||
const _Failed(this.id, this.reason);
|
||||
|
||||
final int id;
|
||||
final String reason;
|
||||
}
|
||||
|
||||
void detectorIsolateMain(SendPort mainPort) {
|
||||
final inbox = ReceivePort();
|
||||
mainPort.send(inbox.sendPort);
|
||||
const decoder = YoloDecoder();
|
||||
final sampler = YuvSampler();
|
||||
Interpreter? interpreter;
|
||||
List<String> labels = const [];
|
||||
var inputSize = 0;
|
||||
List<int> outputShape = const [];
|
||||
Uint8List? inputBytes;
|
||||
Uint8List? outputBytes;
|
||||
|
||||
inbox.listen((message) {
|
||||
if (message is _LoadModel) {
|
||||
try {
|
||||
final options = InterpreterOptions()..threads = 4;
|
||||
final created = Interpreter.fromBuffer(message.bytes, options: options);
|
||||
final inputTensor = created.getInputTensors().first;
|
||||
final outputTensor = created.getOutputTensors().first;
|
||||
if (inputTensor.type != TensorType.float32 ||
|
||||
outputTensor.type != TensorType.float32) {
|
||||
created.close();
|
||||
mainPort.send(
|
||||
_Failed(
|
||||
message.id,
|
||||
'Нужна модель float32. Экспортируйте без half и без int8.',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
final shape = inputTensor.shape;
|
||||
if (shape.length != 4 || shape[3] != 3 || shape[1] != shape[2]) {
|
||||
created.close();
|
||||
mainPort.send(
|
||||
_Failed(
|
||||
message.id,
|
||||
'Ожидался вход NHWC [1, N, N, 3], получено $shape.',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
interpreter = created;
|
||||
labels = message.labels;
|
||||
inputSize = shape[1];
|
||||
outputShape = outputTensor.shape;
|
||||
inputBytes = Uint8List(inputSize * inputSize * 3 * 4);
|
||||
final elements = outputShape.fold<int>(1, (a, b) => a * b);
|
||||
outputBytes = Uint8List(elements * 4);
|
||||
mainPort.send(_Ready(message.id, inputSize));
|
||||
} catch (error) {
|
||||
mainPort.send(_Failed(message.id, '$error'));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (message is! _FrameJob) {
|
||||
return;
|
||||
}
|
||||
final current = interpreter;
|
||||
final input = inputBytes;
|
||||
final output = outputBytes;
|
||||
if (current == null || input == null || output == null) {
|
||||
mainPort.send(_Failed(message.id, 'Модель не загружена'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final started = DateTime.now().microsecondsSinceEpoch;
|
||||
final floats = sampler.sample(
|
||||
frame: message.frame,
|
||||
clockwiseDegrees: message.clockwiseDegrees,
|
||||
inputSize: inputSize,
|
||||
);
|
||||
input.setAll(
|
||||
0,
|
||||
floats.buffer.asUint8List(floats.offsetInBytes, floats.lengthInBytes),
|
||||
);
|
||||
current.run(input, output);
|
||||
final scores = Float32List.view(output.buffer);
|
||||
final boxes = decoder.decode(
|
||||
data: scores,
|
||||
shape: outputShape,
|
||||
inputSize: inputSize,
|
||||
confidenceThreshold: message.confidenceThreshold,
|
||||
iouThreshold: message.iouThreshold,
|
||||
);
|
||||
final upright = uprightSize(
|
||||
rawWidth: message.frame.width,
|
||||
rawHeight: message.frame.height,
|
||||
clockwiseDegrees: message.clockwiseDegrees,
|
||||
);
|
||||
final letterbox = Letterbox.fit(
|
||||
srcWidth: upright.$1,
|
||||
srcHeight: upright.$2,
|
||||
inputSize: inputSize,
|
||||
);
|
||||
final hits = <FrameHit>[
|
||||
for (final box in boxes)
|
||||
FrameHit(
|
||||
label: box.classIndex >= 0 && box.classIndex < labels.length
|
||||
? labels[box.classIndex]
|
||||
: 'class_${box.classIndex}',
|
||||
confidence: box.score,
|
||||
box: _toUpright(box, letterbox, upright.$1, upright.$2),
|
||||
),
|
||||
];
|
||||
final elapsedMs =
|
||||
((DateTime.now().microsecondsSinceEpoch - started) / 1000).round();
|
||||
mainPort.send(_FrameDone(message.id, hits, elapsedMs));
|
||||
} catch (error) {
|
||||
mainPort.send(_Failed(message.id, '$error'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
NormRect _toUpright(YoloBox box, Letterbox letterbox, int width, int height) {
|
||||
double nx(double value) => (value - letterbox.padX) / letterbox.scale / width;
|
||||
double ny(double value) =>
|
||||
(value - letterbox.padY) / letterbox.scale / height;
|
||||
final left = nx(box.left);
|
||||
final top = ny(box.top);
|
||||
final right = nx(box.right);
|
||||
final bottom = ny(box.bottom);
|
||||
return NormRect(left, top, right - left, bottom - top).clamped();
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../../domain/letterbox.dart';
|
||||
import '../../domain/rotation.dart';
|
||||
|
||||
class YuvFrame {
|
||||
const YuvFrame({
|
||||
required this.width,
|
||||
required this.height,
|
||||
required this.y,
|
||||
required this.u,
|
||||
required this.v,
|
||||
required this.yRowStride,
|
||||
required this.yPixelStride,
|
||||
required this.uvRowStride,
|
||||
required this.uvPixelStride,
|
||||
});
|
||||
|
||||
final int width;
|
||||
final int height;
|
||||
final Uint8List y;
|
||||
final Uint8List u;
|
||||
final Uint8List v;
|
||||
final int yRowStride;
|
||||
final int yPixelStride;
|
||||
final int uvRowStride;
|
||||
final int uvPixelStride;
|
||||
}
|
||||
|
||||
/// Samples a camera frame directly into a square NHWC float tensor.
|
||||
///
|
||||
/// Padding uses 114/255, the letterbox color Ultralytics trains with.
|
||||
class YuvSampler {
|
||||
Float32List sample({
|
||||
required YuvFrame frame,
|
||||
required int clockwiseDegrees,
|
||||
required int inputSize,
|
||||
}) {
|
||||
final upright = uprightSize(
|
||||
rawWidth: frame.width,
|
||||
rawHeight: frame.height,
|
||||
clockwiseDegrees: clockwiseDegrees,
|
||||
);
|
||||
final letterbox = Letterbox.fit(
|
||||
srcWidth: upright.$1,
|
||||
srcHeight: upright.$2,
|
||||
inputSize: inputSize,
|
||||
);
|
||||
final output = Float32List(inputSize * inputSize * 3);
|
||||
var offset = 0;
|
||||
for (var dy = 0; dy < inputSize; dy++) {
|
||||
for (var dx = 0; dx < inputSize; dx++) {
|
||||
final source = letterbox.uprightFromModelPixel(dx, dy);
|
||||
final ux = source.$1.floor();
|
||||
final uy = source.$2.floor();
|
||||
if (ux < 0 || uy < 0 || ux >= upright.$1 || uy >= upright.$2) {
|
||||
output[offset++] = _pad;
|
||||
output[offset++] = _pad;
|
||||
output[offset++] = _pad;
|
||||
continue;
|
||||
}
|
||||
final raw = rawPixelFromUpright(
|
||||
ux: ux,
|
||||
uy: uy,
|
||||
rawWidth: frame.width,
|
||||
rawHeight: frame.height,
|
||||
clockwiseDegrees: clockwiseDegrees,
|
||||
);
|
||||
final rgb = _rgbAt(frame, raw.$1, raw.$2);
|
||||
output[offset++] = rgb.$1;
|
||||
output[offset++] = rgb.$2;
|
||||
output[offset++] = rgb.$3;
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
static const double _pad = 114 / 255;
|
||||
|
||||
(double, double, double) _rgbAt(YuvFrame frame, int x, int y) {
|
||||
final yIndex = y * frame.yRowStride + x * frame.yPixelStride;
|
||||
final uvX = x >> 1;
|
||||
final uvY = y >> 1;
|
||||
final uvIndex = uvY * frame.uvRowStride + uvX * frame.uvPixelStride;
|
||||
final yp = _byte(frame.y, yIndex, 0);
|
||||
final up = _byte(frame.u, uvIndex, 128) - 128;
|
||||
final vp = _byte(frame.v, uvIndex, 128) - 128;
|
||||
final r = _clamp8(yp + ((1436 * vp) >> 10));
|
||||
final g = _clamp8(yp - ((352 * up + 731 * vp) >> 10));
|
||||
final b = _clamp8(yp + ((1815 * up) >> 10));
|
||||
return (r / 255, g / 255, b / 255);
|
||||
}
|
||||
|
||||
int _byte(Uint8List plane, int index, int fallback) {
|
||||
if (index < 0 || index >= plane.length) {
|
||||
return fallback;
|
||||
}
|
||||
return plane[index];
|
||||
}
|
||||
|
||||
int _clamp8(int value) {
|
||||
if (value < 0) {
|
||||
return 0;
|
||||
}
|
||||
if (value > 255) {
|
||||
return 255;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import 'norm_rect.dart';
|
||||
import 'traffic_sign.dart';
|
||||
|
||||
class SignDetection {
|
||||
const SignDetection({
|
||||
required this.rawLabel,
|
||||
required this.confidence,
|
||||
required this.box,
|
||||
this.sign,
|
||||
});
|
||||
|
||||
final String rawLabel;
|
||||
final double confidence;
|
||||
final NormRect box;
|
||||
final TrafficSign? sign;
|
||||
|
||||
String get titleCode => sign?.code ?? rawLabel;
|
||||
}
|
||||
|
||||
/// Keeps a sign on screen only after it has been seen on several frames.
|
||||
class DetectionStabilizer {
|
||||
DetectionStabilizer({
|
||||
this.minHits = 2,
|
||||
this.holdMisses = 1,
|
||||
this.maxMisses = 3,
|
||||
this.iouThreshold = 0.3,
|
||||
});
|
||||
|
||||
final int minHits;
|
||||
final int holdMisses;
|
||||
final int maxMisses;
|
||||
final double iouThreshold;
|
||||
|
||||
final List<_Track> _tracks = [];
|
||||
|
||||
void reset() => _tracks.clear();
|
||||
|
||||
List<SignDetection> update(List<SignDetection> frame) {
|
||||
final matched = <int>{};
|
||||
for (final track in _tracks) {
|
||||
var bestIndex = -1;
|
||||
var bestIou = iouThreshold;
|
||||
for (var i = 0; i < frame.length; i++) {
|
||||
if (matched.contains(i)) {
|
||||
continue;
|
||||
}
|
||||
if (frame[i].rawLabel != track.rawLabel) {
|
||||
continue;
|
||||
}
|
||||
final overlap = rectIou(track.box, frame[i].box);
|
||||
if (overlap >= bestIou) {
|
||||
bestIou = overlap;
|
||||
bestIndex = i;
|
||||
}
|
||||
}
|
||||
if (bestIndex >= 0) {
|
||||
matched.add(bestIndex);
|
||||
final detection = frame[bestIndex];
|
||||
track
|
||||
..hits += 1
|
||||
..misses = 0
|
||||
..confidence = detection.confidence
|
||||
..box = track.box.lerp(detection.box, 0.65)
|
||||
..sign = detection.sign;
|
||||
} else {
|
||||
track.misses += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < frame.length; i++) {
|
||||
if (!matched.contains(i)) {
|
||||
_tracks.add(_Track(frame[i]));
|
||||
}
|
||||
}
|
||||
_tracks.removeWhere((track) => track.misses > maxMisses);
|
||||
|
||||
final visible = <SignDetection>[];
|
||||
for (final track in _tracks) {
|
||||
if (track.hits >= minHits && track.misses <= holdMisses) {
|
||||
visible.add(track.toDetection());
|
||||
}
|
||||
}
|
||||
visible.sort((a, b) => b.confidence.compareTo(a.confidence));
|
||||
return visible;
|
||||
}
|
||||
}
|
||||
|
||||
class _Track {
|
||||
_Track(SignDetection detection)
|
||||
: rawLabel = detection.rawLabel,
|
||||
box = detection.box,
|
||||
confidence = detection.confidence,
|
||||
sign = detection.sign;
|
||||
|
||||
final String rawLabel;
|
||||
NormRect box;
|
||||
double confidence;
|
||||
TrafficSign? sign;
|
||||
int hits = 1;
|
||||
int misses = 0;
|
||||
|
||||
SignDetection toDetection() {
|
||||
return SignDetection(
|
||||
rawLabel: rawLabel,
|
||||
confidence: confidence,
|
||||
box: box,
|
||||
sign: sign,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
/// Ultralytics-style letterbox: fit the source into a square without stretching.
|
||||
class Letterbox {
|
||||
const Letterbox({
|
||||
required this.inputSize,
|
||||
required this.scale,
|
||||
required this.padX,
|
||||
required this.padY,
|
||||
});
|
||||
|
||||
final int inputSize;
|
||||
final double scale;
|
||||
final double padX;
|
||||
final double padY;
|
||||
|
||||
factory Letterbox.fit({
|
||||
required int srcWidth,
|
||||
required int srcHeight,
|
||||
required int inputSize,
|
||||
}) {
|
||||
final scale = math.min(inputSize / srcWidth, inputSize / srcHeight);
|
||||
return Letterbox(
|
||||
inputSize: inputSize,
|
||||
scale: scale,
|
||||
padX: (inputSize - srcWidth * scale) / 2,
|
||||
padY: (inputSize - srcHeight * scale) / 2,
|
||||
);
|
||||
}
|
||||
|
||||
/// Center of a model pixel, in upright source pixels. May fall outside the image.
|
||||
(double x, double y) uprightFromModelPixel(int dx, int dy) {
|
||||
return ((dx + 0.5 - padX) / scale, (dy + 0.5 - padY) / scale);
|
||||
}
|
||||
|
||||
(double x, double y) uprightFromModel(double mx, double my) {
|
||||
return ((mx - padX) / scale, (my - padY) / scale);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/// Axis-aligned box in normalized image space, origin at the top-left.
|
||||
class NormRect {
|
||||
const NormRect(this.left, this.top, this.width, this.height);
|
||||
|
||||
final double left;
|
||||
final double top;
|
||||
final double width;
|
||||
final double height;
|
||||
|
||||
double get right => left + width;
|
||||
double get bottom => top + height;
|
||||
|
||||
NormRect clamped() {
|
||||
final l = left.clamp(0.0, 1.0);
|
||||
final t = top.clamp(0.0, 1.0);
|
||||
final r = right.clamp(0.0, 1.0);
|
||||
final b = bottom.clamp(0.0, 1.0);
|
||||
return NormRect(l, t, (r - l).clamp(0.0, 1.0), (b - t).clamp(0.0, 1.0));
|
||||
}
|
||||
|
||||
NormRect lerp(NormRect other, double t) {
|
||||
double mix(double a, double b) => a + (b - a) * t;
|
||||
return NormRect(
|
||||
mix(left, other.left),
|
||||
mix(top, other.top),
|
||||
mix(width, other.width),
|
||||
mix(height, other.height),
|
||||
);
|
||||
}
|
||||
|
||||
/// Horizontal mirror used for the mirrored front-camera preview.
|
||||
NormRect mirroredHorizontally() {
|
||||
return NormRect(1 - right, top, width, height);
|
||||
}
|
||||
}
|
||||
|
||||
double rectIou(NormRect a, NormRect b) {
|
||||
final interLeft = a.left > b.left ? a.left : b.left;
|
||||
final interTop = a.top > b.top ? a.top : b.top;
|
||||
final interRight = a.right < b.right ? a.right : b.right;
|
||||
final interBottom = a.bottom < b.bottom ? a.bottom : b.bottom;
|
||||
final w = interRight - interLeft;
|
||||
final h = interBottom - interTop;
|
||||
if (w <= 0 || h <= 0) {
|
||||
return 0;
|
||||
}
|
||||
final inter = w * h;
|
||||
final union = a.width * a.height + b.width * b.height - inter;
|
||||
if (union <= 0) {
|
||||
return 0;
|
||||
}
|
||||
return inter / union;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/// Clockwise degrees that turn a camera buffer upright on screen.
|
||||
///
|
||||
/// Same compensation ML Kit uses for the Android camera plugin:
|
||||
/// back camera `(sensor - device) mod 360`, front camera `(sensor + device) mod 360`.
|
||||
int uprightClockwiseDegrees({
|
||||
required int sensorOrientation,
|
||||
required int deviceDegrees,
|
||||
required bool frontCamera,
|
||||
}) {
|
||||
if (frontCamera) {
|
||||
return (sensorOrientation + deviceDegrees) % 360;
|
||||
}
|
||||
return (sensorOrientation - deviceDegrees + 360) % 360;
|
||||
}
|
||||
|
||||
/// Maps a pixel of the upright image back to the raw camera buffer.
|
||||
(int x, int y) rawPixelFromUpright({
|
||||
required int ux,
|
||||
required int uy,
|
||||
required int rawWidth,
|
||||
required int rawHeight,
|
||||
required int clockwiseDegrees,
|
||||
}) {
|
||||
switch (clockwiseDegrees) {
|
||||
case 0:
|
||||
return (ux, uy);
|
||||
case 90:
|
||||
// destX = rawHeight - 1 - ry, destY = rx
|
||||
return (uy, rawHeight - 1 - ux);
|
||||
case 180:
|
||||
return (rawWidth - 1 - ux, rawHeight - 1 - uy);
|
||||
case 270:
|
||||
// destX = ry, destY = rawWidth - 1 - rx
|
||||
return (rawWidth - 1 - uy, ux);
|
||||
default:
|
||||
throw ArgumentError(
|
||||
'Поворот должен быть 0, 90, 180 или 270, получено $clockwiseDegrees',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
(int width, int height) uprightSize({
|
||||
required int rawWidth,
|
||||
required int rawHeight,
|
||||
required int clockwiseDegrees,
|
||||
}) {
|
||||
switch (clockwiseDegrees) {
|
||||
case 0:
|
||||
case 180:
|
||||
return (rawWidth, rawHeight);
|
||||
case 90:
|
||||
case 270:
|
||||
return (rawHeight, rawWidth);
|
||||
default:
|
||||
throw ArgumentError(
|
||||
'Поворот должен быть 0, 90, 180 или 270, получено $clockwiseDegrees',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import 'traffic_sign.dart';
|
||||
import 'sign_code.dart';
|
||||
|
||||
class SignCatalog {
|
||||
SignCatalog(List<TrafficSign> signs)
|
||||
: _byCode = {for (final sign in signs) sign.code: sign} {
|
||||
final seen = <String>{};
|
||||
for (final sign in signs) {
|
||||
if (!seen.add(sign.code)) {
|
||||
throw ArgumentError('Повторяющийся номер знака: ${sign.code}');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final Map<String, TrafficSign> _byCode;
|
||||
|
||||
List<TrafficSign> get signs {
|
||||
final values = _byCode.values.toList();
|
||||
values.sort((a, b) => compareSignCodes(a.code, b.code));
|
||||
return values;
|
||||
}
|
||||
|
||||
TrafficSign? findByCode(String code) => _byCode[code];
|
||||
|
||||
/// Returns a catalog entry only for a known sign number or a traffic-light
|
||||
/// class from the training set. Unknown labels stay empty on purpose.
|
||||
TrafficSign? findByLabel(String rawLabel) {
|
||||
final signalCode = _trafficSignalCodes[rawLabel.trim().toLowerCase()];
|
||||
if (signalCode != null) {
|
||||
return _byCode[signalCode];
|
||||
}
|
||||
final code = normalizeSignCode(rawLabel);
|
||||
if (code == null) {
|
||||
return null;
|
||||
}
|
||||
// The dataset splits one speed-limit sign into 3.24.1, 3.24.2, …
|
||||
// Those suffixes are not speeds and not GOST numbers.
|
||||
if (_speedLimitVariant.hasMatch(code)) {
|
||||
return _byCode['3.24'];
|
||||
}
|
||||
return _byCode[code];
|
||||
}
|
||||
|
||||
List<TrafficSign> byCategory(SignCategory category) {
|
||||
return signs.where((sign) => sign.category == category).toList();
|
||||
}
|
||||
}
|
||||
|
||||
final RegExp _speedLimitVariant = RegExp(r'^3\.24(?:\.\d+)+$');
|
||||
|
||||
/// Class names from Dognellaf/russian-road-signs. Keys are lowercase.
|
||||
const Map<String, String> _trafficSignalCodes = {
|
||||
'redtrafficlights': 'signal.red',
|
||||
'yellowtrafficlights': 'signal.yellow',
|
||||
'greentrafficlights': 'signal.green',
|
||||
'redyellowtrafficlights': 'signal.redYellow',
|
||||
'trafficlights': 'signal.unknown',
|
||||
};
|
||||
|
||||
int compareSignCodes(String a, String b) {
|
||||
final aParts = a.split('.');
|
||||
final bParts = b.split('.');
|
||||
final length = aParts.length > bParts.length ? aParts.length : bParts.length;
|
||||
for (var i = 0; i < length; i++) {
|
||||
final aText = i < aParts.length ? aParts[i] : '';
|
||||
final bText = i < bParts.length ? bParts[i] : '';
|
||||
final aNumber = int.tryParse(aText);
|
||||
final bNumber = int.tryParse(bText);
|
||||
if (aNumber != null && bNumber != null && aNumber != bNumber) {
|
||||
return aNumber.compareTo(bNumber);
|
||||
}
|
||||
if (aNumber != null && bNumber == null) {
|
||||
return -1;
|
||||
}
|
||||
if (aNumber == null && bNumber != null) {
|
||||
return 1;
|
||||
}
|
||||
final textOrder = aText.compareTo(bText);
|
||||
if (textOrder != 0) {
|
||||
return textOrder;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
final RegExp _signCodePattern = RegExp(r'\d+(?:\.\d+)+');
|
||||
|
||||
/// Pulls a GOST/ПДД number out of a model label.
|
||||
///
|
||||
/// `3.27`, `3_27` and `sign-3.27` all become `3.27`.
|
||||
/// Labels without a dotted number return null: the app must not guess a rule.
|
||||
String? normalizeSignCode(String rawLabel) {
|
||||
final unified = rawLabel.trim().replaceAll('_', '.').replaceAll('-', '.');
|
||||
return _signCodePattern.firstMatch(unified)?.group(0);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
enum SignCategory {
|
||||
warning,
|
||||
priority,
|
||||
prohibitory,
|
||||
mandatory,
|
||||
special,
|
||||
information,
|
||||
service,
|
||||
plate,
|
||||
signal,
|
||||
}
|
||||
|
||||
class TrafficSign {
|
||||
const TrafficSign({
|
||||
required this.code,
|
||||
required this.name,
|
||||
required this.category,
|
||||
required this.summary,
|
||||
required this.action,
|
||||
this.requiresReadingTheSign = false,
|
||||
});
|
||||
|
||||
/// Номер по приложению 1 к ПДД, например `3.27`.
|
||||
final String code;
|
||||
final String name;
|
||||
final SignCategory category;
|
||||
|
||||
/// Что означает знак.
|
||||
final String summary;
|
||||
|
||||
/// Что делать водителю. Формулировка короче текста ПДД и не заменяет его.
|
||||
final String action;
|
||||
|
||||
/// На знаке есть число или схема, без которых тип знака не задаёт требование полностью.
|
||||
final bool requiresReadingTheSign;
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import 'dart:math' as math;
|
||||
import 'dart:typed_data';
|
||||
|
||||
class YoloBox {
|
||||
const YoloBox({
|
||||
required this.left,
|
||||
required this.top,
|
||||
required this.right,
|
||||
required this.bottom,
|
||||
required this.classIndex,
|
||||
required this.score,
|
||||
});
|
||||
|
||||
final double left;
|
||||
final double top;
|
||||
final double right;
|
||||
final double bottom;
|
||||
final int classIndex;
|
||||
final double score;
|
||||
|
||||
double get width => right - left;
|
||||
double get height => bottom - top;
|
||||
}
|
||||
|
||||
/// Decodes an Ultralytics YOLO detect head from a TFLite output tensor.
|
||||
///
|
||||
/// Supports the raw head `[1, 4+classes, anchors]` (or transposed) and an
|
||||
/// end-to-end NMS head `[1, detections, 6]`. Coordinates are returned in
|
||||
/// model-input pixels.
|
||||
class YoloDecoder {
|
||||
const YoloDecoder({this.maxDetections = 8});
|
||||
|
||||
final int maxDetections;
|
||||
|
||||
static const int nmsFeatureCount = 6;
|
||||
static const int nmsMaxRows = 300;
|
||||
|
||||
List<YoloBox> decode({
|
||||
required Float32List data,
|
||||
required List<int> shape,
|
||||
required int inputSize,
|
||||
required double confidenceThreshold,
|
||||
required double iouThreshold,
|
||||
}) {
|
||||
if (shape.length != 3 || shape[0] != 1) {
|
||||
throw FormatException(
|
||||
'Ожидался выход YOLO формы [1, A, B], получено $shape',
|
||||
);
|
||||
}
|
||||
final dimA = shape[1];
|
||||
final dimB = shape[2];
|
||||
if (data.length < dimA * dimB) {
|
||||
throw FormatException('Буфер выхода короче, чем форма $shape');
|
||||
}
|
||||
|
||||
if (_isNmsLayout(dimA, dimB)) {
|
||||
return _decodeNms(
|
||||
data: data,
|
||||
rows: dimA,
|
||||
confidenceThreshold: confidenceThreshold,
|
||||
inputSize: inputSize,
|
||||
);
|
||||
}
|
||||
|
||||
final channelsFirst = dimA < dimB;
|
||||
final numChannels = channelsFirst ? dimA : dimB;
|
||||
final numAnchors = channelsFirst ? dimB : dimA;
|
||||
if (numChannels < 5) {
|
||||
throw FormatException('В выходе YOLO меньше 5 каналов: $shape');
|
||||
}
|
||||
|
||||
double at(int channel, int anchor) {
|
||||
if (channelsFirst) {
|
||||
return data[channel * numAnchors + anchor];
|
||||
}
|
||||
return data[anchor * numChannels + channel];
|
||||
}
|
||||
|
||||
var maxCoord = 0.0;
|
||||
var scoresLookLikeLogits = false;
|
||||
for (var anchor = 0; anchor < numAnchors; anchor++) {
|
||||
for (var channel = 0; channel < 4; channel++) {
|
||||
final value = at(channel, anchor).abs();
|
||||
if (value > maxCoord) {
|
||||
maxCoord = value;
|
||||
}
|
||||
}
|
||||
for (var channel = 4; channel < numChannels; channel++) {
|
||||
final score = at(channel, anchor);
|
||||
if (score < 0 || score > 1) {
|
||||
scoresLookLikeLogits = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
final coordScale = maxCoord <= 2 ? inputSize.toDouble() : 1.0;
|
||||
|
||||
final candidates = <YoloBox>[];
|
||||
for (var anchor = 0; anchor < numAnchors; anchor++) {
|
||||
var bestClass = 0;
|
||||
var bestScore = 0.0;
|
||||
for (var classIndex = 0; classIndex < numChannels - 4; classIndex++) {
|
||||
final raw = at(4 + classIndex, anchor);
|
||||
final score = scoresLookLikeLogits ? _sigmoid(raw) : raw;
|
||||
if (score > bestScore) {
|
||||
bestScore = score;
|
||||
bestClass = classIndex;
|
||||
}
|
||||
}
|
||||
if (bestScore < confidenceThreshold) {
|
||||
continue;
|
||||
}
|
||||
final cx = at(0, anchor) * coordScale;
|
||||
final cy = at(1, anchor) * coordScale;
|
||||
final w = at(2, anchor) * coordScale;
|
||||
final h = at(3, anchor) * coordScale;
|
||||
if (w < 4 || h < 4) {
|
||||
continue;
|
||||
}
|
||||
candidates.add(
|
||||
YoloBox(
|
||||
left: cx - w / 2,
|
||||
top: cy - h / 2,
|
||||
right: cx + w / 2,
|
||||
bottom: cy + h / 2,
|
||||
classIndex: bestClass,
|
||||
score: bestScore,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return _nms(candidates, iouThreshold);
|
||||
}
|
||||
|
||||
/// End-to-end NMS export is `[1, detections, 6]` with at most 300 rows.
|
||||
/// A raw 2-class head is `[1, 6, anchors]`; at 320 px there are far more
|
||||
/// than 300 anchors, so the two layouts do not collide.
|
||||
bool _isNmsLayout(int dimA, int dimB) {
|
||||
return dimB == nmsFeatureCount && dimA <= nmsMaxRows;
|
||||
}
|
||||
|
||||
List<YoloBox> _decodeNms({
|
||||
required Float32List data,
|
||||
required int rows,
|
||||
required double confidenceThreshold,
|
||||
required int inputSize,
|
||||
}) {
|
||||
double at(int row, int feature) {
|
||||
return data[row * nmsFeatureCount + feature];
|
||||
}
|
||||
|
||||
var maxCoord = 0.0;
|
||||
for (var row = 0; row < rows; row++) {
|
||||
for (var feature = 0; feature < 4; feature++) {
|
||||
final value = at(row, feature).abs();
|
||||
if (value > maxCoord) {
|
||||
maxCoord = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
final coordScale = maxCoord <= 2 ? inputSize.toDouble() : 1.0;
|
||||
final boxes = <YoloBox>[];
|
||||
for (var row = 0; row < rows; row++) {
|
||||
final score = at(row, 4);
|
||||
if (score < confidenceThreshold) {
|
||||
continue;
|
||||
}
|
||||
final classIndex = at(row, 5).round();
|
||||
boxes.add(
|
||||
YoloBox(
|
||||
left: at(row, 0) * coordScale,
|
||||
top: at(row, 1) * coordScale,
|
||||
right: at(row, 2) * coordScale,
|
||||
bottom: at(row, 3) * coordScale,
|
||||
classIndex: classIndex,
|
||||
score: score,
|
||||
),
|
||||
);
|
||||
}
|
||||
boxes.sort((a, b) => b.score.compareTo(a.score));
|
||||
if (boxes.length > maxDetections) {
|
||||
return boxes.sublist(0, maxDetections);
|
||||
}
|
||||
return boxes;
|
||||
}
|
||||
|
||||
List<YoloBox> _nms(List<YoloBox> boxes, double iouThreshold) {
|
||||
boxes.sort((a, b) => b.score.compareTo(a.score));
|
||||
final suppressed = List<bool>.filled(boxes.length, false);
|
||||
final kept = <YoloBox>[];
|
||||
for (var i = 0; i < boxes.length; i++) {
|
||||
if (suppressed[i]) {
|
||||
continue;
|
||||
}
|
||||
kept.add(boxes[i]);
|
||||
if (kept.length >= maxDetections) {
|
||||
break;
|
||||
}
|
||||
for (var j = i + 1; j < boxes.length; j++) {
|
||||
if (suppressed[j]) {
|
||||
continue;
|
||||
}
|
||||
if (boxes[i].classIndex != boxes[j].classIndex) {
|
||||
continue;
|
||||
}
|
||||
if (_iou(boxes[i], boxes[j]) > iouThreshold) {
|
||||
suppressed[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
double _iou(YoloBox a, YoloBox b) {
|
||||
final interLeft = math.max(a.left, b.left);
|
||||
final interTop = math.max(a.top, b.top);
|
||||
final interRight = math.min(a.right, b.right);
|
||||
final interBottom = math.min(a.bottom, b.bottom);
|
||||
final w = interRight - interLeft;
|
||||
final h = interBottom - interTop;
|
||||
if (w <= 0 || h <= 0) {
|
||||
return 0;
|
||||
}
|
||||
final inter = w * h;
|
||||
final union = a.width * a.height + b.width * b.height - inter;
|
||||
if (union <= 0) {
|
||||
return 0;
|
||||
}
|
||||
return inter / union;
|
||||
}
|
||||
|
||||
double _sigmoid(double value) {
|
||||
if (value >= 0) {
|
||||
final z = math.exp(-value);
|
||||
return 1 / (1 + z);
|
||||
}
|
||||
final z = math.exp(value);
|
||||
return z / (1 + z);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'app/sign_checker_app.dart';
|
||||
|
||||
void main() {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
runApp(const SignCheckerApp());
|
||||
}
|
||||
@@ -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 ?? 'Не удалось открыть камеру.',
|
||||
};
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
|
||||
import '../../data/catalog/bundled_sign_catalog.dart';
|
||||
import '../../domain/sign_catalog.dart';
|
||||
import '../../domain/traffic_sign.dart';
|
||||
import '../../theme/tokens.dart';
|
||||
import '../../ui/ui.dart';
|
||||
import '../theme/sign_style.dart';
|
||||
import 'sign_detail_page.dart';
|
||||
import 'sign_glyph.dart';
|
||||
|
||||
class CatalogPage extends StatefulWidget {
|
||||
const CatalogPage({super.key, this.catalog});
|
||||
|
||||
final SignCatalog? catalog;
|
||||
|
||||
@override
|
||||
State<CatalogPage> createState() => _CatalogPageState();
|
||||
}
|
||||
|
||||
class _CatalogPageState extends State<CatalogPage> {
|
||||
final _query = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_query.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final catalog = widget.catalog ?? bundledSignCatalog;
|
||||
final query = _query.text.trim().toLowerCase();
|
||||
final signs = catalog.signs.where((sign) {
|
||||
if (query.isEmpty) {
|
||||
return true;
|
||||
}
|
||||
return sign.code.toLowerCase().contains(query) ||
|
||||
sign.name.toLowerCase().contains(query);
|
||||
}).toList();
|
||||
|
||||
return CupertinoPageScaffold(
|
||||
backgroundColor: AppColors.of(context, AppColors.groupedBackground),
|
||||
navigationBar: const CupertinoNavigationBar(middle: Text('Справочник')),
|
||||
child: SafeArea(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.only(bottom: AppSpacing.s6),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
AppSpacing.gutter,
|
||||
AppSpacing.s3,
|
||||
AppSpacing.gutter,
|
||||
AppSpacing.s2,
|
||||
),
|
||||
child: AppTextField(
|
||||
controller: _query,
|
||||
onChanged: (_) => setState(() {}),
|
||||
placeholder: 'Номер или название, например 3.27',
|
||||
prefixIcon: CupertinoIcons.search,
|
||||
),
|
||||
),
|
||||
if (signs.isEmpty)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(AppSpacing.s5),
|
||||
child: AppText.footnote(
|
||||
'Ничего не найдено',
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
)
|
||||
else
|
||||
for (final category in SignCategory.values)
|
||||
_CategorySection(
|
||||
category: category,
|
||||
signs: signs
|
||||
.where((sign) => sign.category == category)
|
||||
.toList(),
|
||||
),
|
||||
const Padding(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
AppSpacing.gutter,
|
||||
AppSpacing.s4,
|
||||
AppSpacing.gutter,
|
||||
0,
|
||||
),
|
||||
child: AppText.footnote(signImageAttribution),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CategorySection extends StatelessWidget {
|
||||
const _CategorySection({required this.category, required this.signs});
|
||||
|
||||
final SignCategory category;
|
||||
final List<TrafficSign> signs;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (signs.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return AppListSection(
|
||||
header: categoryTitle(category),
|
||||
separatorIndent: 76,
|
||||
children: [
|
||||
for (final sign in signs)
|
||||
AppListTile(
|
||||
leading: SignGlyph(sign: sign, size: 44),
|
||||
title: sign.name,
|
||||
subtitle: sign.action,
|
||||
value: sign.code,
|
||||
onTap: () {
|
||||
Navigator.of(context).push(
|
||||
CupertinoPageRoute<void>(
|
||||
builder: (_) => SignDetailPage(sign: sign),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
|
||||
import '../../domain/traffic_sign.dart';
|
||||
import '../../theme/tokens.dart';
|
||||
import '../../ui/ui.dart';
|
||||
import '../theme/sign_style.dart';
|
||||
import 'sign_glyph.dart';
|
||||
|
||||
class SignDetailPage extends StatelessWidget {
|
||||
const SignDetailPage({super.key, required this.sign});
|
||||
|
||||
final TrafficSign sign;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CupertinoPageScaffold(
|
||||
backgroundColor: AppColors.of(context, AppColors.groupedBackground),
|
||||
navigationBar: CupertinoNavigationBar(middle: Text(sign.code)),
|
||||
child: SafeArea(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.only(bottom: AppSpacing.s7),
|
||||
children: [
|
||||
const SizedBox(height: AppSpacing.s4),
|
||||
Center(child: SignGlyph(sign: sign, size: 140)),
|
||||
const SizedBox(height: AppSpacing.s3),
|
||||
AppText.title(sign.name, textAlign: TextAlign.center),
|
||||
const SizedBox(height: AppSpacing.s1),
|
||||
AppText.footnote(
|
||||
categoryTitle(sign.category),
|
||||
textAlign: TextAlign.center,
|
||||
color: categoryColor(sign.category),
|
||||
),
|
||||
AppListSection(
|
||||
header: 'Что означает',
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.gutter),
|
||||
child: AppText.body(sign.summary),
|
||||
),
|
||||
],
|
||||
),
|
||||
AppListSection(
|
||||
header: 'Что делать',
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.gutter),
|
||||
child: AppText.body(sign.action),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (sign.requiresReadingTheSign)
|
||||
const Padding(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
AppSpacing.gutter,
|
||||
AppSpacing.s4,
|
||||
AppSpacing.gutter,
|
||||
0,
|
||||
),
|
||||
child: AppText.footnote(
|
||||
faceReadingWarning,
|
||||
color: AppColors.systemOrange,
|
||||
),
|
||||
),
|
||||
const Padding(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
AppSpacing.gutter,
|
||||
AppSpacing.s4,
|
||||
AppSpacing.gutter,
|
||||
0,
|
||||
),
|
||||
child: AppText.footnote(safetyLine),
|
||||
),
|
||||
const Padding(
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
AppSpacing.gutter,
|
||||
AppSpacing.s3,
|
||||
AppSpacing.gutter,
|
||||
0,
|
||||
),
|
||||
child: AppText.caption(signImageAttribution),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_svg/flutter_svg.dart';
|
||||
|
||||
import '../../data/catalog/sign_image_assets.dart';
|
||||
import '../../domain/traffic_sign.dart';
|
||||
import '../theme/sign_style.dart';
|
||||
|
||||
class SignGlyph extends StatelessWidget {
|
||||
const SignGlyph({super.key, required this.sign, this.size = 48});
|
||||
|
||||
final TrafficSign sign;
|
||||
final double size;
|
||||
|
||||
static Future<String?>? _assetPackage;
|
||||
|
||||
/// The app stores diagrams at `assets/signs/`. Widgetbook is a separate
|
||||
/// package, so the same files are exposed as `packages/sign_checker/...`.
|
||||
static Future<String?> _resolveAssetPackage() async {
|
||||
final manifest = await AssetManifest.loadFromAssetBundle(rootBundle);
|
||||
final names = manifest.listAssets();
|
||||
if (names.contains('assets/signs/1.1.svg')) {
|
||||
return null;
|
||||
}
|
||||
if (names.contains('packages/sign_checker/assets/signs/1.1.svg')) {
|
||||
return 'sign_checker';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!signImageAssets.contains(sign.code)) {
|
||||
return _frame(image: false, child: _codeLabel());
|
||||
}
|
||||
_assetPackage ??= _resolveAssetPackage();
|
||||
return FutureBuilder<String?>(
|
||||
future: _assetPackage,
|
||||
builder: (context, snapshot) {
|
||||
if (snapshot.connectionState != ConnectionState.done) {
|
||||
return _frame(image: true, child: const SizedBox.shrink());
|
||||
}
|
||||
return _frame(
|
||||
image: true,
|
||||
child: SvgPicture.asset(
|
||||
'assets/signs/${sign.code}.svg',
|
||||
package: snapshot.data,
|
||||
width: size,
|
||||
height: size,
|
||||
fit: BoxFit.contain,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _codeLabel() {
|
||||
return Text(
|
||||
sign.code,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
color: Color(0xFF000000),
|
||||
fontWeight: FontWeight.w700,
|
||||
fontSize: 11,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _frame({required bool image, required Widget child}) {
|
||||
return Container(
|
||||
width: size + 8,
|
||||
height: size + 8,
|
||||
alignment: Alignment.center,
|
||||
decoration: BoxDecoration(
|
||||
color: image ? const Color(0xFFFFFFFF) : categoryColor(sign.category),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import 'package:flutter/painting.dart';
|
||||
|
||||
import '../../domain/traffic_sign.dart';
|
||||
|
||||
const String faceReadingWarning =
|
||||
'Часть требования написана или нарисована на самом знаке. Приложение определяет тип, цифру и схему смотрите на знаке.';
|
||||
|
||||
const String safetyLine =
|
||||
'Подсказка, не замена ПДД. Решение за водителем, сверяйтесь со знаком.';
|
||||
|
||||
String categoryTitle(SignCategory category) {
|
||||
return switch (category) {
|
||||
SignCategory.warning => 'Предупреждающие',
|
||||
SignCategory.priority => 'Приоритет',
|
||||
SignCategory.prohibitory => 'Запрещающие',
|
||||
SignCategory.mandatory => 'Предписывающие',
|
||||
SignCategory.special => 'Особые предписания',
|
||||
SignCategory.information => 'Информационные',
|
||||
SignCategory.service => 'Сервис',
|
||||
SignCategory.plate => 'Таблички',
|
||||
SignCategory.signal => 'Светофоры',
|
||||
};
|
||||
}
|
||||
|
||||
Color categoryColor(SignCategory? category) {
|
||||
return switch (category) {
|
||||
SignCategory.warning => const Color(0xFFE6A23C),
|
||||
SignCategory.priority => const Color(0xFFF2C200),
|
||||
SignCategory.prohibitory => const Color(0xFFE23B3B),
|
||||
SignCategory.mandatory => const Color(0xFF3D7EFF),
|
||||
SignCategory.special => const Color(0xFF2F9E6B),
|
||||
SignCategory.information => const Color(0xFF2AA39A),
|
||||
SignCategory.service => const Color(0xFF6EA8FF),
|
||||
SignCategory.plate => const Color(0xFFB7C0CC),
|
||||
SignCategory.signal => const Color(0xFFF5D90A),
|
||||
null => const Color(0xFFECEFF4),
|
||||
};
|
||||
}
|
||||
|
||||
const String signImageAttribution =
|
||||
'Схемы знаков взяты со страницы drom.ru/pdd/pdd/signs/ и повторяют ГОСТ Р 52290-2004. '
|
||||
'Пояснения с той страницы в приложение не копировались.';
|
||||
|
||||
const String datasetAttribution =
|
||||
'Детектор учится на датасете Dognellaf/russian-road-signs (CC BY 4.0). '
|
||||
'Автор датасета указан по условиям лицензии: '
|
||||
'https://huggingface.co/datasets/Dognellaf/russian-road-signs';
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import 'package:sign_checker/theme/tokens.dart';
|
||||
|
||||
TextStyle _sf(TextStyle style, {Color? color}) {
|
||||
return GoogleFonts.inter(textStyle: style, color: color);
|
||||
}
|
||||
|
||||
CupertinoTextThemeData _textTheme() {
|
||||
return CupertinoTextThemeData(
|
||||
primaryColor: AppColors.accent,
|
||||
textStyle: _sf(AppTypography.body, color: AppColors.label),
|
||||
actionTextStyle: _sf(AppTypography.body, color: AppColors.accent),
|
||||
tabLabelTextStyle: _sf(
|
||||
AppTypography.caption2,
|
||||
color: AppColors.secondaryLabel,
|
||||
),
|
||||
navTitleTextStyle: _sf(AppTypography.headline, color: AppColors.label),
|
||||
navLargeTitleTextStyle: _sf(
|
||||
AppTypography.largeTitle,
|
||||
color: AppColors.label,
|
||||
),
|
||||
navActionTextStyle: _sf(AppTypography.body, color: AppColors.accent),
|
||||
);
|
||||
}
|
||||
|
||||
CupertinoThemeData buildLightTheme() => _buildTheme(Brightness.light);
|
||||
|
||||
CupertinoThemeData buildDarkTheme() => _buildTheme(Brightness.dark);
|
||||
|
||||
CupertinoThemeData _buildTheme(Brightness brightness) {
|
||||
return CupertinoThemeData(
|
||||
brightness: brightness,
|
||||
primaryColor: AppColors.accent,
|
||||
primaryContrastingColor: const Color(0xFFFFFFFF),
|
||||
scaffoldBackgroundColor: AppColors.groupedBackground,
|
||||
barBackgroundColor: AppColors.barBackground,
|
||||
applyThemeToAll: true,
|
||||
textTheme: _textTheme(),
|
||||
);
|
||||
}
|
||||
|
||||
SystemUiOverlayStyle systemUiOverlayFor(Brightness brightness) {
|
||||
final dark = brightness == Brightness.dark;
|
||||
return SystemUiOverlayStyle(
|
||||
statusBarColor: const Color(0x00000000),
|
||||
statusBarBrightness: brightness,
|
||||
statusBarIconBrightness: dark ? Brightness.light : Brightness.dark,
|
||||
systemNavigationBarColor: dark
|
||||
? const Color(0x00000000)
|
||||
: const Color(0x00FFFFFF),
|
||||
systemNavigationBarDividerColor: const Color(0x00000000),
|
||||
systemNavigationBarIconBrightness: dark ? Brightness.light : Brightness.dark,
|
||||
systemNavigationBarContrastEnforced: false,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export 'app_theme.dart';
|
||||
export 'tokens.dart';
|
||||
@@ -0,0 +1,181 @@
|
||||
/// Design tokens copied from the Please Pay Me iOS kit.
|
||||
///
|
||||
/// Spacing, type scale and grouped surfaces stay the same. The accent is blue
|
||||
/// so Sign Detector does not inherit that product's green brand.
|
||||
library;
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
|
||||
abstract final class AppColors {
|
||||
static const accent = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFF0A64D8),
|
||||
darkColor: Color(0xFF4C9DFF),
|
||||
);
|
||||
|
||||
static const accentSoft = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFFE6F0FC),
|
||||
darkColor: Color(0xFF142033),
|
||||
);
|
||||
|
||||
static const systemRed = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFFFF3B30),
|
||||
darkColor: Color(0xFFFF453A),
|
||||
);
|
||||
static const systemOrange = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFFFF9500),
|
||||
darkColor: Color(0xFFFF9F0A),
|
||||
);
|
||||
static const systemGreen = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFF34C759),
|
||||
darkColor: Color(0xFF30D158),
|
||||
);
|
||||
static const systemGray = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFF8E8E93),
|
||||
darkColor: Color(0xFF8E8E93),
|
||||
);
|
||||
static const systemGray3 = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFFC7C7CC),
|
||||
darkColor: Color(0xFF48484A),
|
||||
);
|
||||
static const systemGray5 = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFFE5E5EA),
|
||||
darkColor: Color(0xFF2C2C2E),
|
||||
);
|
||||
static const systemGray6 = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFFF2F2F7),
|
||||
darkColor: Color(0xFF1C1C1E),
|
||||
);
|
||||
|
||||
static const label = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFF000000),
|
||||
darkColor: Color(0xFFFFFFFF),
|
||||
);
|
||||
static const secondaryLabel = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0x993C3C43),
|
||||
darkColor: Color(0x99EBEBF5),
|
||||
);
|
||||
static const tertiaryLabel = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0x4D3C3C43),
|
||||
darkColor: Color(0x4DEBEBF5),
|
||||
);
|
||||
|
||||
static const separator = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0x4A3C3C43),
|
||||
darkColor: Color(0xA6545458),
|
||||
);
|
||||
static const opaqueSeparator = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFFC6C6C8),
|
||||
darkColor: Color(0xFF38383A),
|
||||
);
|
||||
static const groupedBackground = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFFF2F2F7),
|
||||
darkColor: Color(0xFF000000),
|
||||
);
|
||||
static const groupedSurface = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xFFFFFFFF),
|
||||
darkColor: Color(0xFF1C1C1E),
|
||||
);
|
||||
static const barBackground = CupertinoDynamicColor.withBrightness(
|
||||
color: Color(0xF0F9F9F9),
|
||||
darkColor: Color(0xF01D1D1D),
|
||||
);
|
||||
|
||||
static Color of(BuildContext context, Color color) =>
|
||||
CupertinoDynamicColor.resolve(color, context);
|
||||
}
|
||||
|
||||
abstract final class AppSpacing {
|
||||
static const double s1 = 4;
|
||||
static const double s2 = 8;
|
||||
static const double s3 = 12;
|
||||
static const double s4 = 16;
|
||||
static const double s5 = 20;
|
||||
static const double s6 = 28;
|
||||
static const double s7 = 40;
|
||||
static const double s8 = 56;
|
||||
static const double gutter = 16;
|
||||
}
|
||||
|
||||
abstract final class AppRadii {
|
||||
static const double sm = 6;
|
||||
static const double md = 10;
|
||||
static const double lg = 12;
|
||||
static const double xl = 16;
|
||||
static const double capsule = 999;
|
||||
}
|
||||
|
||||
abstract final class AppSizes {
|
||||
static const double buttonLarge = 50;
|
||||
static const double buttonMedium = 44;
|
||||
static const double buttonSmall = 34;
|
||||
static const double rowMinHeight = 44;
|
||||
static const double hairline = 0.5;
|
||||
}
|
||||
|
||||
abstract final class AppTypography {
|
||||
static const largeTitle = TextStyle(
|
||||
fontSize: 34,
|
||||
height: 1.2,
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: 0.37,
|
||||
);
|
||||
static const title1 = TextStyle(
|
||||
fontSize: 28,
|
||||
height: 1.2,
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: 0.36,
|
||||
);
|
||||
static const title2 = TextStyle(
|
||||
fontSize: 22,
|
||||
height: 1.25,
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: 0.35,
|
||||
);
|
||||
static const title3 = TextStyle(
|
||||
fontSize: 20,
|
||||
height: 1.25,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: 0.38,
|
||||
);
|
||||
static const headline = TextStyle(
|
||||
fontSize: 17,
|
||||
height: 1.3,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: -0.41,
|
||||
);
|
||||
static const body = TextStyle(
|
||||
fontSize: 17,
|
||||
height: 1.3,
|
||||
fontWeight: FontWeight.w400,
|
||||
letterSpacing: -0.41,
|
||||
);
|
||||
static const callout = TextStyle(
|
||||
fontSize: 16,
|
||||
height: 1.3,
|
||||
fontWeight: FontWeight.w400,
|
||||
letterSpacing: -0.32,
|
||||
);
|
||||
static const subhead = TextStyle(
|
||||
fontSize: 15,
|
||||
height: 1.3,
|
||||
fontWeight: FontWeight.w400,
|
||||
letterSpacing: -0.24,
|
||||
);
|
||||
static const footnote = TextStyle(
|
||||
fontSize: 13,
|
||||
height: 1.3,
|
||||
fontWeight: FontWeight.w400,
|
||||
letterSpacing: -0.08,
|
||||
);
|
||||
static const caption1 = TextStyle(
|
||||
fontSize: 12,
|
||||
height: 1.3,
|
||||
fontWeight: FontWeight.w400,
|
||||
);
|
||||
static const caption2 = TextStyle(
|
||||
fontSize: 11,
|
||||
height: 1.3,
|
||||
fontWeight: FontWeight.w400,
|
||||
letterSpacing: 0.07,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import 'package:sign_checker/theme/tokens.dart';
|
||||
|
||||
enum AppButtonStyle { filled, tinted, gray, plain, destructive }
|
||||
|
||||
enum AppButtonSize { large, medium, small }
|
||||
|
||||
class AppButton extends StatelessWidget {
|
||||
const AppButton({
|
||||
super.key,
|
||||
required this.label,
|
||||
this.onPressed,
|
||||
this.style = AppButtonStyle.filled,
|
||||
this.size = AppButtonSize.large,
|
||||
this.expanded = true,
|
||||
this.icon,
|
||||
this.loading = false,
|
||||
});
|
||||
|
||||
final String label;
|
||||
final VoidCallback? onPressed;
|
||||
final AppButtonStyle style;
|
||||
final AppButtonSize size;
|
||||
final bool expanded;
|
||||
final IconData? icon;
|
||||
final bool loading;
|
||||
|
||||
double get _height => switch (size) {
|
||||
AppButtonSize.large => AppSizes.buttonLarge,
|
||||
AppButtonSize.medium => AppSizes.buttonMedium,
|
||||
AppButtonSize.small => AppSizes.buttonSmall,
|
||||
};
|
||||
|
||||
TextStyle get _textStyle => switch (size) {
|
||||
AppButtonSize.large => AppTypography.headline,
|
||||
AppButtonSize.medium => AppTypography.body,
|
||||
AppButtonSize.small => AppTypography.subhead.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
};
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final accent = AppColors.of(context, AppColors.accent);
|
||||
final red = AppColors.of(context, AppColors.systemRed);
|
||||
|
||||
final (Color background, Color foreground) = switch (style) {
|
||||
AppButtonStyle.filled => (accent, const Color(0xFFFFFFFF)),
|
||||
AppButtonStyle.tinted => (accent.withValues(alpha: 0.15), accent),
|
||||
AppButtonStyle.gray => (
|
||||
AppColors.of(context, AppColors.systemGray5),
|
||||
AppColors.of(context, AppColors.label),
|
||||
),
|
||||
AppButtonStyle.plain => (const Color(0x00000000), accent),
|
||||
AppButtonStyle.destructive => (red.withValues(alpha: 0.15), red),
|
||||
};
|
||||
|
||||
final disabled = onPressed == null || loading;
|
||||
final content = loading
|
||||
? CupertinoActivityIndicator(
|
||||
radius: size == AppButtonSize.small ? 8 : 10,
|
||||
color: foreground,
|
||||
)
|
||||
: Row(
|
||||
mainAxisSize: expanded ? MainAxisSize.max : MainAxisSize.min,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
if (icon != null) ...[
|
||||
Icon(
|
||||
icon,
|
||||
size: size == AppButtonSize.small ? 16 : 19,
|
||||
color: foreground,
|
||||
),
|
||||
const SizedBox(width: AppSpacing.s2),
|
||||
],
|
||||
Flexible(
|
||||
child: Text(
|
||||
label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: GoogleFonts.inter(
|
||||
textStyle: _textStyle,
|
||||
color: foreground,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
return Opacity(
|
||||
opacity: disabled && !loading ? 0.35 : 1,
|
||||
child: SizedBox(
|
||||
height: _height,
|
||||
width: expanded ? double.infinity : null,
|
||||
child: CupertinoButton(
|
||||
onPressed: disabled ? null : onPressed,
|
||||
color: style == AppButtonStyle.plain ? null : background,
|
||||
disabledColor: background,
|
||||
borderRadius: BorderRadius.circular(
|
||||
size == AppButtonSize.small ? AppRadii.md : AppRadii.lg,
|
||||
),
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal: size == AppButtonSize.small
|
||||
? AppSpacing.s3
|
||||
: AppSpacing.s4,
|
||||
),
|
||||
minimumSize: Size.zero,
|
||||
child: content,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import 'package:sign_checker/theme/tokens.dart';
|
||||
|
||||
class AppText extends StatelessWidget {
|
||||
const AppText(
|
||||
this.data, {
|
||||
super.key,
|
||||
this.style = AppTypography.body,
|
||||
this.color = AppColors.label,
|
||||
this.maxLines,
|
||||
this.overflow,
|
||||
this.textAlign,
|
||||
});
|
||||
|
||||
const AppText.largeTitle(
|
||||
this.data, {
|
||||
super.key,
|
||||
this.color = AppColors.label,
|
||||
this.maxLines,
|
||||
this.overflow,
|
||||
this.textAlign,
|
||||
}) : style = AppTypography.largeTitle;
|
||||
|
||||
const AppText.title(
|
||||
this.data, {
|
||||
super.key,
|
||||
this.color = AppColors.label,
|
||||
this.maxLines,
|
||||
this.overflow,
|
||||
this.textAlign,
|
||||
}) : style = AppTypography.title2;
|
||||
|
||||
const AppText.headline(
|
||||
this.data, {
|
||||
super.key,
|
||||
this.color = AppColors.label,
|
||||
this.maxLines,
|
||||
this.overflow,
|
||||
this.textAlign,
|
||||
}) : style = AppTypography.headline;
|
||||
|
||||
const AppText.body(
|
||||
this.data, {
|
||||
super.key,
|
||||
this.color = AppColors.label,
|
||||
this.maxLines,
|
||||
this.overflow,
|
||||
this.textAlign,
|
||||
}) : style = AppTypography.body;
|
||||
|
||||
const AppText.callout(
|
||||
this.data, {
|
||||
super.key,
|
||||
this.color = AppColors.secondaryLabel,
|
||||
this.maxLines,
|
||||
this.overflow,
|
||||
this.textAlign,
|
||||
}) : style = AppTypography.callout;
|
||||
|
||||
const AppText.subhead(
|
||||
this.data, {
|
||||
super.key,
|
||||
this.color = AppColors.secondaryLabel,
|
||||
this.maxLines,
|
||||
this.overflow,
|
||||
this.textAlign,
|
||||
}) : style = AppTypography.subhead;
|
||||
|
||||
const AppText.footnote(
|
||||
this.data, {
|
||||
super.key,
|
||||
this.color = AppColors.secondaryLabel,
|
||||
this.maxLines,
|
||||
this.overflow,
|
||||
this.textAlign,
|
||||
}) : style = AppTypography.footnote;
|
||||
|
||||
const AppText.caption(
|
||||
this.data, {
|
||||
super.key,
|
||||
this.color = AppColors.tertiaryLabel,
|
||||
this.maxLines,
|
||||
this.overflow,
|
||||
this.textAlign,
|
||||
}) : style = AppTypography.caption1;
|
||||
|
||||
final String data;
|
||||
final TextStyle style;
|
||||
final Color color;
|
||||
final int? maxLines;
|
||||
final TextOverflow? overflow;
|
||||
final TextAlign? textAlign;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Text(
|
||||
data,
|
||||
maxLines: maxLines,
|
||||
overflow: overflow,
|
||||
textAlign: textAlign,
|
||||
style: GoogleFonts.inter(
|
||||
textStyle: style,
|
||||
color: AppColors.of(context, color),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AppSectionHeader extends StatelessWidget {
|
||||
const AppSectionHeader(this.text, {super.key, this.padding});
|
||||
|
||||
final String text;
|
||||
final EdgeInsetsGeometry? padding;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding:
|
||||
padding ??
|
||||
const EdgeInsets.fromLTRB(
|
||||
AppSpacing.gutter,
|
||||
AppSpacing.s4,
|
||||
AppSpacing.gutter,
|
||||
AppSpacing.s2,
|
||||
),
|
||||
child: Text(
|
||||
text.toUpperCase(),
|
||||
style: GoogleFonts.inter(
|
||||
textStyle: AppTypography.footnote,
|
||||
color: AppColors.of(context, AppColors.secondaryLabel),
|
||||
letterSpacing: 0.4,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import 'package:sign_checker/theme/tokens.dart';
|
||||
import 'package:sign_checker/ui/atoms/app_text.dart';
|
||||
|
||||
class AppTextField extends StatelessWidget {
|
||||
const AppTextField({
|
||||
super.key,
|
||||
this.label,
|
||||
this.placeholder,
|
||||
this.controller,
|
||||
this.onChanged,
|
||||
this.keyboardType,
|
||||
this.obscureText = false,
|
||||
this.enabled = true,
|
||||
this.errorText,
|
||||
this.prefixIcon,
|
||||
this.clearable = true,
|
||||
this.maxLines = 1,
|
||||
});
|
||||
|
||||
final String? label;
|
||||
final String? placeholder;
|
||||
final TextEditingController? controller;
|
||||
final ValueChanged<String>? onChanged;
|
||||
final TextInputType? keyboardType;
|
||||
final bool obscureText;
|
||||
final bool enabled;
|
||||
final String? errorText;
|
||||
final IconData? prefixIcon;
|
||||
final bool clearable;
|
||||
final int maxLines;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hasError = errorText != null && errorText!.isNotEmpty;
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (label != null)
|
||||
AppSectionHeader(
|
||||
label!,
|
||||
padding: const EdgeInsets.only(bottom: AppSpacing.s2),
|
||||
),
|
||||
Opacity(
|
||||
opacity: enabled ? 1 : 0.4,
|
||||
child: CupertinoTextField(
|
||||
controller: controller,
|
||||
onChanged: onChanged,
|
||||
keyboardType: keyboardType,
|
||||
obscureText: obscureText,
|
||||
enabled: enabled,
|
||||
maxLines: maxLines,
|
||||
placeholder: placeholder,
|
||||
clearButtonMode: clearable
|
||||
? OverlayVisibilityMode.editing
|
||||
: OverlayVisibilityMode.never,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.s3,
|
||||
vertical: AppSpacing.s3,
|
||||
),
|
||||
prefix: prefixIcon == null
|
||||
? null
|
||||
: Padding(
|
||||
padding: const EdgeInsets.only(left: AppSpacing.s3),
|
||||
child: Icon(
|
||||
prefixIcon,
|
||||
size: 20,
|
||||
color: AppColors.of(context, AppColors.secondaryLabel),
|
||||
),
|
||||
),
|
||||
placeholderStyle: GoogleFonts.inter(
|
||||
textStyle: AppTypography.body,
|
||||
color: AppColors.of(context, AppColors.tertiaryLabel),
|
||||
),
|
||||
style: GoogleFonts.inter(
|
||||
textStyle: AppTypography.body,
|
||||
color: AppColors.of(context, AppColors.label),
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.of(context, AppColors.groupedSurface),
|
||||
borderRadius: BorderRadius.circular(AppRadii.md),
|
||||
border: Border.all(
|
||||
color: hasError
|
||||
? AppColors.of(context, AppColors.systemRed)
|
||||
: AppColors.of(context, AppColors.opaqueSeparator),
|
||||
width: AppSizes.hairline,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (hasError)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(
|
||||
top: AppSpacing.s2,
|
||||
left: AppSpacing.s1,
|
||||
),
|
||||
child: AppText.footnote(errorText!, color: AppColors.systemRed),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:sign_checker/theme/tokens.dart';
|
||||
import 'package:sign_checker/ui/atoms/app_text.dart';
|
||||
|
||||
class AppListSection extends StatelessWidget {
|
||||
const AppListSection({
|
||||
super.key,
|
||||
required this.children,
|
||||
this.header,
|
||||
this.footer,
|
||||
this.separatorIndent = 16,
|
||||
this.margin = const EdgeInsets.symmetric(horizontal: AppSpacing.gutter),
|
||||
});
|
||||
|
||||
final List<Widget> children;
|
||||
final String? header;
|
||||
final String? footer;
|
||||
final double separatorIndent;
|
||||
final EdgeInsetsGeometry margin;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final rows = <Widget>[];
|
||||
for (var i = 0; i < children.length; i++) {
|
||||
rows.add(children[i]);
|
||||
if (i < children.length - 1) {
|
||||
rows.add(
|
||||
Padding(
|
||||
padding: EdgeInsets.only(left: separatorIndent),
|
||||
child: Container(
|
||||
height: AppSizes.hairline,
|
||||
color: AppColors.of(context, AppColors.opaqueSeparator),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (header != null) AppSectionHeader(header!),
|
||||
Container(
|
||||
margin: margin,
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.of(context, AppColors.groupedSurface),
|
||||
borderRadius: BorderRadius.circular(AppRadii.lg),
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: Column(children: rows),
|
||||
),
|
||||
if (footer != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
AppSpacing.gutter + 4,
|
||||
AppSpacing.s2,
|
||||
AppSpacing.gutter + 4,
|
||||
0,
|
||||
),
|
||||
child: AppText.footnote(footer!),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:sign_checker/theme/tokens.dart';
|
||||
import 'package:sign_checker/ui/atoms/app_text.dart';
|
||||
|
||||
class AppListTile extends StatefulWidget {
|
||||
const AppListTile({
|
||||
super.key,
|
||||
required this.title,
|
||||
this.subtitle,
|
||||
this.leading,
|
||||
this.value,
|
||||
this.trailing,
|
||||
this.onTap,
|
||||
this.showChevron = true,
|
||||
this.destructive = false,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String? subtitle;
|
||||
final Widget? leading;
|
||||
final String? value;
|
||||
final Widget? trailing;
|
||||
final VoidCallback? onTap;
|
||||
final bool showChevron;
|
||||
final bool destructive;
|
||||
|
||||
@override
|
||||
State<AppListTile> createState() => _AppListTileState();
|
||||
}
|
||||
|
||||
class _AppListTileState extends State<AppListTile> {
|
||||
bool _pressed = false;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final tappable = widget.onTap != null;
|
||||
|
||||
final row = Container(
|
||||
color: _pressed
|
||||
? AppColors.of(context, AppColors.systemGray5)
|
||||
: AppColors.of(context, AppColors.groupedSurface),
|
||||
constraints: const BoxConstraints(minHeight: AppSizes.rowMinHeight),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.gutter,
|
||||
vertical: AppSpacing.s2 + 2,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
if (widget.leading != null) ...[
|
||||
widget.leading!,
|
||||
const SizedBox(width: AppSpacing.s3),
|
||||
],
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
AppText.body(
|
||||
widget.title,
|
||||
color: widget.destructive
|
||||
? AppColors.systemRed
|
||||
: AppColors.label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
if (widget.subtitle != null) ...[
|
||||
const SizedBox(height: 2),
|
||||
AppText.footnote(
|
||||
widget.subtitle!,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
if (widget.trailing != null)
|
||||
widget.trailing!
|
||||
else ...[
|
||||
if (widget.value != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: AppSpacing.s2),
|
||||
child: AppText.body(
|
||||
widget.value!,
|
||||
color: AppColors.secondaryLabel,
|
||||
),
|
||||
),
|
||||
if (tappable && widget.showChevron)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: AppSpacing.s1),
|
||||
child: Icon(
|
||||
CupertinoIcons.chevron_forward,
|
||||
size: 16,
|
||||
color: AppColors.of(context, AppColors.tertiaryLabel),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (!tappable) return row;
|
||||
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: widget.onTap,
|
||||
onTapDown: (_) => setState(() => _pressed = true),
|
||||
onTapUp: (_) => setState(() => _pressed = false),
|
||||
onTapCancel: () => setState(() => _pressed = false),
|
||||
child: row,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export 'atoms/app_button.dart';
|
||||
export 'atoms/app_text.dart';
|
||||
export 'atoms/app_text_field.dart';
|
||||
export 'molecules/app_list_section.dart';
|
||||
export 'molecules/app_list_tile.dart';
|
||||
Reference in New Issue
Block a user