batch_report_screen.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import 'dart:io';
  2. import 'package:flutter/material.dart';
  3. import '../services/database_helper.dart';
  4. import '../models/palm_record.dart';
  5. import '../models/palm_correction.dart';
  6. import '../constants/mpob_colors.dart';
  7. import '../theme/app_theme.dart';
  8. import '../services/app_strings.dart';
  9. import '../theme/locale_controller.dart';
  10. import 'record_detail_screen.dart';
  11. class BatchReportScreen extends StatefulWidget {
  12. final String batchId;
  13. const BatchReportScreen({super.key, required this.batchId});
  14. @override
  15. State<BatchReportScreen> createState() => _BatchReportScreenState();
  16. }
  17. class _BatchReportScreenState extends State<BatchReportScreen> {
  18. final DatabaseHelper _dbHelper = DatabaseHelper();
  19. List<PalmRecord> _records = [];
  20. Map<int, PalmCorrection> _latestCorrections = {};
  21. bool _isLoading = true;
  22. @override
  23. void initState() {
  24. super.initState();
  25. _load();
  26. }
  27. Future<void> _load() async {
  28. final records = await _dbHelper.getRecordsByBatch(widget.batchId);
  29. final corrections = <int, PalmCorrection>{};
  30. for (final record in records) {
  31. if (record.id == null) continue;
  32. final correction = await _dbHelper.getLatestCorrection(record.id!);
  33. if (correction != null) corrections[record.id!] = correction;
  34. }
  35. setState(() {
  36. _records = records;
  37. _latestCorrections = corrections;
  38. _isLoading = false;
  39. });
  40. }
  41. /// Per photo: use the harvester's correction if one exists, else fall
  42. /// back to the AI's own detections. Never mutates either source list.
  43. List<Map<String, dynamic>> _detectionsFor(PalmRecord record) {
  44. final correction = record.id == null ? null : _latestCorrections[record.id];
  45. return correction?.correctedDetections ?? record.detections;
  46. }
  47. int get _correctedFrameCount => _records.where((r) => r.id != null && _latestCorrections.containsKey(r.id)).length;
  48. Map<String, int> get _correctedClassTally {
  49. final tally = <String, int>{};
  50. for (final record in _records) {
  51. for (final d in _detectionsFor(record)) {
  52. final className = (d['className'] ?? d['class'] ?? 'Unknown').toString();
  53. tally[className] = (tally[className] ?? 0) + 1;
  54. }
  55. }
  56. return tally;
  57. }
  58. int get _totalDetections => _records.fold(0, (sum, r) => sum + r.detections.length);
  59. double get _avgConfidence =>
  60. _records.isEmpty ? 0 : _records.map((r) => r.confidence).reduce((a, b) => a + b) / _records.length;
  61. double? get _avgInferenceMs {
  62. final withTiming = _records.where((r) => r.inferenceMs != null).toList();
  63. if (withTiming.isEmpty) return null;
  64. return withTiming.map((r) => r.inferenceMs!).reduce((a, b) => a + b) / withTiming.length;
  65. }
  66. Map<String, int> get _classTally {
  67. final tally = <String, int>{};
  68. for (final record in _records) {
  69. for (final d in record.detections) {
  70. final className = (d['className'] ?? d['class'] ?? 'Unknown').toString();
  71. tally[className] = (tally[className] ?? 0) + 1;
  72. }
  73. }
  74. return tally;
  75. }
  76. @override
  77. Widget build(BuildContext context) {
  78. return ValueListenableBuilder<String>(
  79. valueListenable: LocaleController.localeCode,
  80. builder: (context, _, _) => _buildScaffold(context),
  81. );
  82. }
  83. Widget _buildScaffold(BuildContext context) {
  84. final colorScheme = Theme.of(context).colorScheme;
  85. if (_isLoading) {
  86. return const Scaffold(body: Center(child: CircularProgressIndicator()));
  87. }
  88. if (_records.isEmpty) {
  89. return Scaffold(
  90. appBar: AppBar(title: Text(AppStrings.t('batch_report_title'))),
  91. body: Center(child: Text(AppStrings.t('batch_no_records'))),
  92. );
  93. }
  94. final start = _records.first.timestamp;
  95. final end = _records.last.timestamp;
  96. final tally = _classTally;
  97. final totalTally = tally.values.fold(0, (a, b) => a + b);
  98. return Scaffold(
  99. appBar: AppBar(title: Text(AppStrings.t('batch_report_title'))),
  100. body: ListView(
  101. padding: const EdgeInsets.all(16),
  102. children: [
  103. _buildKpiGrid(start, end, colorScheme),
  104. const SizedBox(height: 24),
  105. Text(AppStrings.t('mpob_class_distribution_title'), style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: colorScheme.onSurface)),
  106. const SizedBox(height: 4),
  107. Text(AppStrings.t('ai_result_label'), style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: colorScheme.onSurface.withValues(alpha: 0.6))),
  108. const SizedBox(height: 8),
  109. if (totalTally == 0)
  110. Text(AppStrings.t('no_detections_in_batch'), style: TextStyle(color: colorScheme.onSurface.withValues(alpha: 0.6)))
  111. else ...[
  112. _buildTallyBar(tally, totalTally),
  113. const SizedBox(height: 12),
  114. _buildTallyLegend(tally, totalTally),
  115. ],
  116. if (_correctedFrameCount > 0) ...[
  117. const SizedBox(height: 24),
  118. Row(
  119. children: [
  120. Text(AppStrings.t('batch_corrected_label'), style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: colorScheme.onSurface.withValues(alpha: 0.6))),
  121. const SizedBox(width: 8),
  122. Container(
  123. padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
  124. decoration: BoxDecoration(
  125. color: colorScheme.primary.withValues(alpha: 0.12),
  126. borderRadius: BorderRadius.circular(20),
  127. ),
  128. child: Text(
  129. AppStrings.tp('frames_corrected_pill', {'count': '$_correctedFrameCount', 'total': '${_records.length}'}),
  130. style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: colorScheme.primary),
  131. ),
  132. ),
  133. ],
  134. ),
  135. const SizedBox(height: 8),
  136. Builder(builder: (context) {
  137. final correctedTally = _correctedClassTally;
  138. final correctedTotal = correctedTally.values.fold(0, (a, b) => a + b);
  139. if (correctedTotal == 0) {
  140. return Text(AppStrings.t('no_detections_in_batch'), style: TextStyle(color: colorScheme.onSurface.withValues(alpha: 0.6)));
  141. }
  142. return Column(
  143. crossAxisAlignment: CrossAxisAlignment.start,
  144. children: [
  145. _buildTallyBar(correctedTally, correctedTotal),
  146. const SizedBox(height: 12),
  147. _buildTallyLegend(correctedTally, correctedTotal),
  148. ],
  149. );
  150. }),
  151. ],
  152. const SizedBox(height: 24),
  153. Text(AppStrings.tp('frames_section_title', {'count': '${_records.length}'}), style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: colorScheme.onSurface)),
  154. const SizedBox(height: 12),
  155. _buildFrameGrid(),
  156. ],
  157. ),
  158. );
  159. }
  160. Widget _buildKpiGrid(DateTime start, DateTime end, ColorScheme colorScheme) {
  161. final avgInference = _avgInferenceMs;
  162. final accents = AppTheme.chartAccents;
  163. return GridView.count(
  164. crossAxisCount: 2,
  165. shrinkWrap: true,
  166. physics: const NeverScrollableScrollPhysics(),
  167. mainAxisSpacing: 12,
  168. crossAxisSpacing: 12,
  169. childAspectRatio: 2.2,
  170. children: [
  171. _kpiCard(AppStrings.t('kpi_frames'), "${_records.length}", Icons.photo_library, accents[0], colorScheme),
  172. _kpiCard(AppStrings.t('kpi_total_detections'), "$_totalDetections", Icons.center_focus_strong, accents[1], colorScheme),
  173. _kpiCard(AppStrings.t('kpi_avg_confidence'), "${(_avgConfidence * 100).toStringAsFixed(1)}%", Icons.verified, accents[2], colorScheme),
  174. _kpiCard(
  175. AppStrings.t('kpi_avg_inference'),
  176. avgInference == null ? AppStrings.t('na_label') : "${avgInference.toStringAsFixed(0)} ms",
  177. Icons.speed,
  178. accents[3],
  179. colorScheme,
  180. ),
  181. _kpiCard(AppStrings.t('kpi_start'), _formatTime(start), Icons.play_circle_outline, accents[4], colorScheme),
  182. _kpiCard(AppStrings.t('kpi_end'), _formatTime(end), Icons.stop_circle_outlined, accents[4], colorScheme),
  183. ],
  184. );
  185. }
  186. Widget _kpiCard(String label, String value, IconData icon, Color color, ColorScheme colorScheme) {
  187. return Container(
  188. padding: const EdgeInsets.all(12),
  189. decoration: BoxDecoration(
  190. color: colorScheme.surfaceContainerHighest,
  191. borderRadius: BorderRadius.circular(12),
  192. border: Border.all(color: color.withValues(alpha: 0.2)),
  193. boxShadow: [BoxShadow(color: color.withValues(alpha: 0.08), blurRadius: 8, offset: const Offset(0, 4))],
  194. ),
  195. child: Row(
  196. children: [
  197. Icon(icon, color: color, size: 28),
  198. const SizedBox(width: 10),
  199. Expanded(
  200. child: Column(
  201. crossAxisAlignment: CrossAxisAlignment.start,
  202. mainAxisSize: MainAxisSize.min,
  203. children: [
  204. Text(value, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: colorScheme.onSurface), overflow: TextOverflow.ellipsis),
  205. Text(label, style: TextStyle(fontSize: 11, color: colorScheme.onSurface.withValues(alpha: 0.6))),
  206. ],
  207. ),
  208. ),
  209. ],
  210. ),
  211. );
  212. }
  213. Widget _buildTallyBar(Map<String, int> tally, int total) {
  214. return ClipRRect(
  215. borderRadius: BorderRadius.circular(8),
  216. child: SizedBox(
  217. height: 24,
  218. child: Row(
  219. children: mpobClasses.where((c) => (tally[c] ?? 0) > 0).map((className) {
  220. final count = tally[className]!;
  221. return Expanded(
  222. flex: count,
  223. child: Container(color: getMPOBColor(className)),
  224. );
  225. }).toList(),
  226. ),
  227. ),
  228. );
  229. }
  230. Widget _buildTallyLegend(Map<String, int> tally, int total) {
  231. final colorScheme = Theme.of(context).colorScheme;
  232. return Wrap(
  233. spacing: 16,
  234. runSpacing: 8,
  235. children: mpobClasses.where((c) => (tally[c] ?? 0) > 0).map((className) {
  236. final count = tally[className]!;
  237. final pct = (count / total * 100).toStringAsFixed(1);
  238. return Row(
  239. mainAxisSize: MainAxisSize.min,
  240. children: [
  241. Container(width: 12, height: 12, decoration: BoxDecoration(color: getMPOBColor(className), shape: BoxShape.circle)),
  242. const SizedBox(width: 6),
  243. Text("${AppStrings.className(className)}: $count ($pct%)", style: TextStyle(fontSize: 13, color: colorScheme.onSurface)),
  244. ],
  245. );
  246. }).toList(),
  247. );
  248. }
  249. Widget _buildFrameGrid() {
  250. return GridView.builder(
  251. shrinkWrap: true,
  252. physics: const NeverScrollableScrollPhysics(),
  253. gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
  254. crossAxisCount: 3,
  255. mainAxisSpacing: 8,
  256. crossAxisSpacing: 8,
  257. ),
  258. itemCount: _records.length,
  259. itemBuilder: (context, index) {
  260. final record = _records[index];
  261. final color = getStatusColor(record.ripenessClass);
  262. final hasImage = record.imagePath.isNotEmpty && File(record.imagePath).existsSync();
  263. return GestureDetector(
  264. onTap: () => Navigator.push(
  265. context,
  266. MaterialPageRoute(builder: (context) => RecordDetailScreen(frames: _records, initialIndex: index)),
  267. ),
  268. child: ClipRRect(
  269. borderRadius: BorderRadius.circular(10),
  270. child: Stack(
  271. fit: StackFit.expand,
  272. children: [
  273. hasImage
  274. ? Image.file(File(record.imagePath), fit: BoxFit.cover)
  275. : Container(color: Colors.grey.shade200, child: const Icon(Icons.image, color: Colors.grey)),
  276. Positioned(
  277. left: 0,
  278. right: 0,
  279. bottom: 0,
  280. child: Container(
  281. padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
  282. color: color.withValues(alpha: 0.85),
  283. child: Text(
  284. AppStrings.className(record.ripenessClass),
  285. style: const TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold),
  286. overflow: TextOverflow.ellipsis,
  287. ),
  288. ),
  289. ),
  290. ],
  291. ),
  292. ),
  293. );
  294. },
  295. );
  296. }
  297. String _formatTime(DateTime t) {
  298. final h = t.hour.toString().padLeft(2, '0');
  299. final m = t.minute.toString().padLeft(2, '0');
  300. final s = t.second.toString().padLeft(2, '0');
  301. return "$h:$m:$s";
  302. }
  303. }