ADD ALOT OF POLISHING AND UPDATES...
This commit is contained in:
@@ -0,0 +1,290 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:camera/camera.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../app/injection_container.dart';
|
||||
import '../../core/ai/detection_export.dart';
|
||||
import '../../core/constants/app_constants.dart';
|
||||
import '../../core/services/tts_service.dart';
|
||||
import '../../shared/widgets/feature_page.dart';
|
||||
|
||||
class AiBenchmarkScreen extends StatefulWidget {
|
||||
const AiBenchmarkScreen({super.key});
|
||||
|
||||
@override
|
||||
State<AiBenchmarkScreen> createState() => _AiBenchmarkScreenState();
|
||||
}
|
||||
|
||||
class _AiBenchmarkScreenState extends State<AiBenchmarkScreen> {
|
||||
static const _runsKey = 'ai_benchmark_runs';
|
||||
List<String> _models = const [];
|
||||
String _selectedModel = AppConstants.yoloModelPath;
|
||||
List<Map<String, dynamic>> _runs = const [];
|
||||
bool _running = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
}
|
||||
|
||||
Future<void> _load() async {
|
||||
final models = await _discoverTfliteModels();
|
||||
final selected = await AppConstants.getSelectedYoloModelPath();
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final rawRuns = prefs.getStringList(_runsKey) ?? const [];
|
||||
setState(() {
|
||||
_models = models.isEmpty ? [selected] : models;
|
||||
_selectedModel = _models.contains(selected) ? selected : _models.first;
|
||||
_runs = rawRuns
|
||||
.map((e) => Map<String, dynamic>.from(jsonDecode(e) as Map))
|
||||
.toList()
|
||||
.reversed
|
||||
.toList();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _setModel(String? value) async {
|
||||
if (value == null) return;
|
||||
await AppConstants.setSelectedYoloModelPath(value);
|
||||
sl<YoloDetector>().dispose();
|
||||
await sl<YoloDetector>().init();
|
||||
setState(() => _selectedModel = value);
|
||||
_snack('Model aktif: ${value.split('/').last}');
|
||||
}
|
||||
|
||||
Future<void> _runBenchmark() async {
|
||||
setState(() => _running = true);
|
||||
final started = DateTime.now();
|
||||
final captureMs = await _measureCapture();
|
||||
|
||||
final inferenceWatch = Stopwatch()..start();
|
||||
final modelLoaded = sl<YoloDetector>().isReady;
|
||||
final detection = await sl<YoloDetector>().detectSynthetic();
|
||||
inferenceWatch.stop();
|
||||
|
||||
final label = detection?.label ?? 'no detection';
|
||||
final direction = detection?.directionName ?? '-';
|
||||
final distance = detection?.estimatedDistance ?? '-';
|
||||
final text = detection == null
|
||||
? 'Tidak ada obstacle di atas threshold.'
|
||||
: 'Obstacle $label di $direction, jarak $distance';
|
||||
|
||||
final notifWatch = Stopwatch()..start();
|
||||
final notificationText = text;
|
||||
notifWatch.stop();
|
||||
|
||||
final ttsWatch = Stopwatch()..start();
|
||||
try {
|
||||
await sl<TtsService>()
|
||||
.speakImmediate(notificationText)
|
||||
.timeout(const Duration(seconds: 3));
|
||||
} catch (_) {}
|
||||
ttsWatch.stop();
|
||||
|
||||
final run = {
|
||||
'time': started.toIso8601String(),
|
||||
'model': _selectedModel,
|
||||
'modelLoaded': modelLoaded,
|
||||
'captureMs': captureMs,
|
||||
'inferenceMs': inferenceWatch.elapsedMilliseconds,
|
||||
'notificationMs': notifWatch.elapsedMicroseconds / 1000,
|
||||
'ttsMs': ttsWatch.elapsedMilliseconds,
|
||||
'label': label,
|
||||
'direction': direction,
|
||||
};
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final next = [
|
||||
jsonEncode(run),
|
||||
...((prefs.getStringList(_runsKey) ?? const []).take(24)),
|
||||
];
|
||||
await prefs.setStringList(_runsKey, next);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_runs = [run, ..._runs].take(25).toList();
|
||||
_running = false;
|
||||
});
|
||||
}
|
||||
|
||||
Future<int> _measureCapture() async {
|
||||
final watch = Stopwatch()..start();
|
||||
CameraController? controller;
|
||||
try {
|
||||
final cameras =
|
||||
await availableCameras().timeout(const Duration(seconds: 3));
|
||||
if (cameras.isNotEmpty) {
|
||||
controller = CameraController(
|
||||
cameras.first,
|
||||
ResolutionPreset.low,
|
||||
enableAudio: false,
|
||||
);
|
||||
await controller.initialize().timeout(const Duration(seconds: 5));
|
||||
await controller.takePicture().timeout(const Duration(seconds: 5));
|
||||
}
|
||||
} catch (_) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 16));
|
||||
} finally {
|
||||
await controller?.dispose();
|
||||
}
|
||||
watch.stop();
|
||||
return watch.elapsedMilliseconds;
|
||||
}
|
||||
|
||||
Future<void> _clearRuns() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_runsKey);
|
||||
setState(() => _runs = const []);
|
||||
}
|
||||
|
||||
void _snack(String message) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hasRealModel = _models.any((model) => model.endsWith('.tflite'));
|
||||
return FeaturePage(
|
||||
title: 'AI Benchmark',
|
||||
subtitle: 'Capture, inference, notification text, and TTS timing',
|
||||
child: ListView(
|
||||
children: [
|
||||
DropdownButtonFormField<String>(
|
||||
initialValue: _selectedModel,
|
||||
decoration: const InputDecoration(labelText: 'Model file'),
|
||||
items: [
|
||||
for (final model in _models)
|
||||
DropdownMenuItem(
|
||||
value: model,
|
||||
child: Text(model.split('/').last),
|
||||
),
|
||||
],
|
||||
onChanged: _setModel,
|
||||
),
|
||||
if (!hasRealModel) ...[
|
||||
const SizedBox(height: 10),
|
||||
const _StatusBox(
|
||||
success: false,
|
||||
message:
|
||||
'Belum ada file .tflite di assets/models. Tambahkan model lalu restart app.',
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
FilledButton.icon(
|
||||
onPressed: _running ? null : _runBenchmark,
|
||||
icon: _running
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.play_arrow),
|
||||
label: Text(_running ? 'Running benchmark...' : 'Run benchmark'),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _clearRuns,
|
||||
icon: const Icon(Icons.delete_outline),
|
||||
label: const Text('Clear log'),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
for (final run in _runs) _BenchmarkCard(run: run),
|
||||
if (_runs.isEmpty)
|
||||
const FeatureEmptyPanel(
|
||||
icon: Icons.speed,
|
||||
title: 'Belum ada log',
|
||||
message:
|
||||
'Klik Run benchmark untuk mencatat capture, inference, notification, dan TTS.',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _BenchmarkCard extends StatelessWidget {
|
||||
final Map<String, dynamic> run;
|
||||
|
||||
const _BenchmarkCard({required this.run});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final time = DateTime.tryParse(run['time']?.toString() ?? '')?.toLocal();
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 10),
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: const Color(0xFFE2E8F0)),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
time == null
|
||||
? 'Benchmark run'
|
||||
: '${_two(time.hour)}:${_two(time.minute)}:${_two(time.second)}',
|
||||
style: const TextStyle(fontWeight: FontWeight.w800),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Model: ${run['model'].toString().split('/').last} (${run['modelLoaded'] == true ? 'loaded' : 'not ready'})'),
|
||||
Text('Capture: ${run['captureMs']} ms'),
|
||||
Text('Model/inference: ${run['inferenceMs']} ms'),
|
||||
Text('Notification text: ${run['notificationMs']} ms'),
|
||||
Text('TTS start: ${run['ttsMs']} ms'),
|
||||
Text('Result: ${run['label']} ${run['direction']}'),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StatusBox extends StatelessWidget {
|
||||
final bool success;
|
||||
final String message;
|
||||
|
||||
const _StatusBox({required this.success, required this.message});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: success ? const Color(0xFFF0FDF4) : const Color(0xFFFEF2F2),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Text(
|
||||
message,
|
||||
style: TextStyle(
|
||||
color: success ? const Color(0xFF166534) : const Color(0xFF991B1B),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<String>> _discoverTfliteModels() async {
|
||||
try {
|
||||
final manifestRaw = await rootBundle.loadString('AssetManifest.json');
|
||||
final manifest = jsonDecode(manifestRaw) as Map<String, dynamic>;
|
||||
final models = manifest.keys
|
||||
.where((key) =>
|
||||
key.startsWith('assets/models/') && key.endsWith('.tflite'))
|
||||
.toList()
|
||||
..sort();
|
||||
return models;
|
||||
} catch (_) {
|
||||
return const [];
|
||||
}
|
||||
}
|
||||
|
||||
String _two(int value) => value.toString().padLeft(2, '0');
|
||||
Reference in New Issue
Block a user