batch_report_screen.dart 12 KB

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