record_detail_screen.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. import 'dart:io';
  2. import 'dart:ui';
  3. import 'package:flutter/material.dart';
  4. import 'package:path/path.dart' as p;
  5. import '../models/palm_record.dart';
  6. import '../models/palm_correction.dart';
  7. import '../services/database_helper.dart';
  8. import '../constants/mpob_colors.dart';
  9. import '../theme/app_theme.dart';
  10. import '../widgets/palm_bounding_box.dart';
  11. import '../widgets/class_picker_sheet.dart';
  12. import 'detection_editor_screen.dart';
  13. /// Detection data parsed from the JSON-serialized `detections` list stored
  14. /// on a [PalmRecord] (or a [PalmCorrection]'s corrected detections).
  15. class DetectionData {
  16. final String className;
  17. final double confidence;
  18. final Rect normalizedBox;
  19. final bool isManual;
  20. const DetectionData({
  21. required this.className,
  22. required this.confidence,
  23. required this.normalizedBox,
  24. this.isManual = false,
  25. });
  26. factory DetectionData.fromMap(Map<String, dynamic> m) {
  27. return DetectionData(
  28. className: (m['className'] ?? m['class'] ?? 'Unknown').toString(),
  29. confidence: (m['confidence'] as num?)?.toDouble() ?? 0.0,
  30. normalizedBox: Rect.fromLTRB(
  31. (m['x1'] as num?)?.toDouble() ?? 0.0,
  32. (m['y1'] as num?)?.toDouble() ?? 0.0,
  33. (m['x2'] as num?)?.toDouble() ?? 1.0,
  34. (m['y2'] as num?)?.toDouble() ?? 1.0,
  35. ),
  36. isManual: m['isManual'] == true,
  37. );
  38. }
  39. Map<String, dynamic> toMap() {
  40. return {
  41. 'className': className,
  42. 'classIndex': mpobClasses.indexOf(className),
  43. 'confidence': confidence,
  44. 'x1': normalizedBox.left,
  45. 'y1': normalizedBox.top,
  46. 'x2': normalizedBox.right,
  47. 'y2': normalizedBox.bottom,
  48. 'isManual': isManual,
  49. };
  50. }
  51. DetectionData copyWith({String? className, bool? isManual}) {
  52. return DetectionData(
  53. className: className ?? this.className,
  54. confidence: confidence,
  55. normalizedBox: normalizedBox,
  56. isManual: isManual ?? this.isManual,
  57. );
  58. }
  59. }
  60. /// Full-screen record detail view with prev/next navigation between the
  61. /// frames of the same batch (or a single-frame list for standalone records).
  62. class RecordDetailScreen extends StatefulWidget {
  63. final List<PalmRecord> frames;
  64. final int initialIndex;
  65. const RecordDetailScreen({super.key, required this.frames, required this.initialIndex});
  66. @override
  67. State<RecordDetailScreen> createState() => _RecordDetailScreenState();
  68. }
  69. class _RecordDetailScreenState extends State<RecordDetailScreen> {
  70. late final PageController _pageController;
  71. late int _index;
  72. @override
  73. void initState() {
  74. super.initState();
  75. _index = widget.initialIndex;
  76. _pageController = PageController(initialPage: widget.initialIndex);
  77. }
  78. @override
  79. void dispose() {
  80. _pageController.dispose();
  81. super.dispose();
  82. }
  83. void _goTo(int index) {
  84. _pageController.animateToPage(
  85. index,
  86. duration: const Duration(milliseconds: 250),
  87. curve: Curves.easeOut,
  88. );
  89. }
  90. @override
  91. Widget build(BuildContext context) {
  92. final isFirst = _index == 0;
  93. final isLast = _index == widget.frames.length - 1;
  94. return Scaffold(
  95. appBar: AppBar(
  96. title: Text(widget.frames.length > 1 ? "Frame ${_index + 1} of ${widget.frames.length}" : "Record Details"),
  97. actions: widget.frames.length > 1
  98. ? [
  99. IconButton(
  100. icon: const Icon(Icons.chevron_left),
  101. onPressed: isFirst ? null : () => _goTo(_index - 1),
  102. ),
  103. IconButton(
  104. icon: const Icon(Icons.chevron_right),
  105. onPressed: isLast ? null : () => _goTo(_index + 1),
  106. ),
  107. ]
  108. : null,
  109. ),
  110. body: PageView.builder(
  111. controller: _pageController,
  112. itemCount: widget.frames.length,
  113. onPageChanged: (i) => setState(() => _index = i),
  114. itemBuilder: (context, i) => _RecordDetailBody(record: widget.frames[i]),
  115. ),
  116. );
  117. }
  118. }
  119. enum _ViewMode { ai, corrected }
  120. class _RecordDetailBody extends StatefulWidget {
  121. final PalmRecord record;
  122. const _RecordDetailBody({required this.record});
  123. @override
  124. State<_RecordDetailBody> createState() => _RecordDetailBodyState();
  125. }
  126. class _RecordDetailBodyState extends State<_RecordDetailBody> {
  127. final DatabaseHelper _dbHelper = DatabaseHelper();
  128. _ViewMode _viewMode = _ViewMode.ai;
  129. late List<DetectionData> _aiDetections;
  130. late List<DetectionData> _correctionDraft;
  131. DateTime? _lastCorrectedAt;
  132. bool _isLoading = true;
  133. bool _isSaving = false;
  134. bool get _hasCorrection => _lastCorrectedAt != null;
  135. @override
  136. void initState() {
  137. super.initState();
  138. _aiDetections = widget.record.detections.map((d) => DetectionData.fromMap(d)).toList();
  139. _loadExistingCorrection();
  140. }
  141. Future<void> _loadExistingCorrection() async {
  142. final recordId = widget.record.id;
  143. if (recordId == null) {
  144. setState(() {
  145. _correctionDraft = List.of(_aiDetections);
  146. _isLoading = false;
  147. });
  148. return;
  149. }
  150. final existing = await _dbHelper.getLatestCorrection(recordId);
  151. if (!mounted) return;
  152. setState(() {
  153. if (existing != null) {
  154. _correctionDraft = existing.correctedDetections.map((d) => DetectionData.fromMap(d)).toList();
  155. _lastCorrectedAt = existing.timestamp;
  156. _viewMode = _ViewMode.corrected;
  157. } else {
  158. _correctionDraft = List.of(_aiDetections);
  159. }
  160. _isLoading = false;
  161. });
  162. }
  163. Future<void> _editDetection(int index) async {
  164. final result = await showClassPickerSheet(
  165. context,
  166. currentClass: _correctionDraft[index].className,
  167. showRemoveOption: true,
  168. );
  169. if (result == null) return;
  170. if (result.remove) {
  171. setState(() => _correctionDraft.removeAt(index));
  172. await _persistCorrection();
  173. } else if (result.className != null) {
  174. setState(() {
  175. _correctionDraft[index] = _correctionDraft[index].copyWith(className: result.className);
  176. });
  177. await _persistCorrection();
  178. }
  179. }
  180. Future<void> _handleBoxTap(int index) async {
  181. if (_viewMode != _ViewMode.corrected) {
  182. setState(() => _viewMode = _ViewMode.corrected);
  183. }
  184. await _editDetection(index);
  185. }
  186. /// Opens the full-screen editor for placing boxes the AI missed entirely.
  187. /// Always available — even a photo with zero AI detections needs a way
  188. /// into correction mode.
  189. Future<void> _openDetectionEditor() async {
  190. if (_viewMode != _ViewMode.corrected) {
  191. setState(() => _viewMode = _ViewMode.corrected);
  192. }
  193. final added = await Navigator.push<List<DetectionData>>(
  194. context,
  195. MaterialPageRoute(
  196. builder: (context) => DetectionEditorScreen(
  197. imagePath: widget.record.imagePath,
  198. existingDetections: _correctionDraft,
  199. ),
  200. ),
  201. );
  202. if (added != null && added.isNotEmpty) {
  203. setState(() => _correctionDraft.addAll(added));
  204. await _persistCorrection();
  205. }
  206. }
  207. /// Writes the current [_correctionDraft] as a new correction row. Called
  208. /// automatically after every box edit and after a reset — there is no
  209. /// separate manual "save" step to forget.
  210. Future<void> _persistCorrection() async {
  211. final recordId = widget.record.id;
  212. if (recordId == null || _correctionDraft.isEmpty) return;
  213. setState(() => _isSaving = true);
  214. final correction = PalmCorrection(
  215. originalRecordId: recordId,
  216. correctedClass: _correctionDraft.first.className,
  217. correctedDetections: _correctionDraft.map((d) => d.toMap()).toList(),
  218. timestamp: DateTime.now(),
  219. );
  220. await _dbHelper.insertCorrection(correction);
  221. if (!mounted) return;
  222. setState(() {
  223. _lastCorrectedAt = correction.timestamp;
  224. _isSaving = false;
  225. });
  226. }
  227. /// Wipes any saved correction for this photo entirely — back to a clean
  228. /// "no correction yet" state, so the correction tab hides again.
  229. Future<void> _resetCorrection() async {
  230. final recordId = widget.record.id;
  231. if (recordId != null) {
  232. await _dbHelper.deleteCorrectionsForRecord(recordId);
  233. }
  234. if (!mounted) return;
  235. setState(() {
  236. _correctionDraft = List.of(_aiDetections);
  237. _lastCorrectedAt = null;
  238. _viewMode = _ViewMode.ai;
  239. });
  240. ScaffoldMessenger.of(context).showSnackBar(
  241. const SnackBar(content: Text("Correction reset.")),
  242. );
  243. }
  244. @override
  245. Widget build(BuildContext context) {
  246. final colorScheme = Theme.of(context).colorScheme;
  247. final accents = AppTheme.chartAccents;
  248. if (_isLoading) {
  249. return const Center(child: CircularProgressIndicator());
  250. }
  251. final record = widget.record;
  252. final fileName = p.basename(record.imagePath);
  253. final activeDetections = _viewMode == _ViewMode.ai ? _aiDetections : _correctionDraft;
  254. final primaryGrade = activeDetections.isEmpty ? record.ripenessClass : activeDetections.first.className;
  255. final tally = <String, int>{};
  256. for (final d in activeDetections) {
  257. tally[d.className] = (tally[d.className] ?? 0) + 1;
  258. }
  259. return SingleChildScrollView(
  260. padding: const EdgeInsets.all(24),
  261. child: Column(
  262. crossAxisAlignment: CrossAxisAlignment.start,
  263. children: [
  264. if (_hasCorrection) ...[
  265. SegmentedButton<_ViewMode>(
  266. segments: const [
  267. ButtonSegment(value: _ViewMode.ai, label: Text("AI Result"), icon: Icon(Icons.smart_toy_outlined)),
  268. ButtonSegment(value: _ViewMode.corrected, label: Text("Your Correction"), icon: Icon(Icons.edit_outlined)),
  269. ],
  270. selected: {_viewMode},
  271. showSelectedIcon: false,
  272. style: SegmentedButton.styleFrom(
  273. selectedBackgroundColor: colorScheme.primary,
  274. selectedForegroundColor: colorScheme.onPrimary,
  275. ),
  276. onSelectionChanged: (selection) => setState(() => _viewMode = selection.first),
  277. ),
  278. const SizedBox(height: 8),
  279. ],
  280. Row(
  281. children: [
  282. Expanded(
  283. child: Text(
  284. _viewMode == _ViewMode.ai
  285. ? "Tap a bunch on the photo to correct its grade."
  286. : (_isSaving ? "Saving..." : "Last corrected: ${_lastCorrectedAt.toString().split('.')[0]}"),
  287. style: TextStyle(fontSize: 12, color: colorScheme.onSurface.withOpacity(0.6)),
  288. ),
  289. ),
  290. if (_viewMode == _ViewMode.corrected && _hasCorrection)
  291. TextButton.icon(
  292. onPressed: _isSaving ? null : _resetCorrection,
  293. icon: const Icon(Icons.restart_alt, size: 18),
  294. label: const Text("Reset"),
  295. ),
  296. ],
  297. ),
  298. const SizedBox(height: 8),
  299. Align(
  300. alignment: Alignment.centerLeft,
  301. child: OutlinedButton.icon(
  302. onPressed: _isSaving ? null : _openDetectionEditor,
  303. icon: const Icon(Icons.add_box_outlined, size: 18),
  304. label: const Text("Add Missed Bunch"),
  305. ),
  306. ),
  307. const SizedBox(height: 16),
  308. // Image with Bounding Boxes
  309. AspectRatio(
  310. aspectRatio: 1, // Assuming squared input 640x640
  311. child: Container(
  312. decoration: BoxDecoration(
  313. color: colorScheme.surfaceContainerHighest,
  314. borderRadius: BorderRadius.circular(12),
  315. ),
  316. child: record.imagePath.isNotEmpty && File(record.imagePath).existsSync()
  317. ? ClipRRect(
  318. borderRadius: BorderRadius.circular(12),
  319. child: Stack(
  320. children: [
  321. Positioned.fill(
  322. child: Image.file(File(record.imagePath), fit: BoxFit.contain),
  323. ),
  324. Positioned.fill(
  325. child: LayoutBuilder(
  326. builder: (context, constraints) {
  327. final boxes = activeDetections.map<Widget>((d) {
  328. return PalmBoundingBox(
  329. normalizedRect: d.normalizedBox,
  330. label: d.className,
  331. confidence: d.confidence,
  332. constraints: constraints,
  333. isManual: d.isManual,
  334. );
  335. }).toList();
  336. // Every box is tappable, in both views — tapping
  337. // one always jumps into (or stays in) correction mode.
  338. final tapTargets = activeDetections.asMap().entries.map<Widget>((entry) {
  339. final i = entry.key;
  340. final rect = entry.value.normalizedBox;
  341. return Positioned(
  342. left: rect.left * constraints.maxWidth,
  343. top: rect.top * constraints.maxHeight,
  344. width: rect.width * constraints.maxWidth,
  345. height: rect.height * constraints.maxHeight,
  346. child: GestureDetector(
  347. behavior: HitTestBehavior.opaque,
  348. onTap: () => _handleBoxTap(i),
  349. ),
  350. );
  351. }).toList();
  352. return Stack(children: [...boxes, ...tapTargets]);
  353. },
  354. ),
  355. ),
  356. ],
  357. ),
  358. )
  359. : Center(
  360. child: Icon(Icons.image, size: 64, color: colorScheme.onSurface.withOpacity(0.4)),
  361. ),
  362. ),
  363. ),
  364. const SizedBox(height: 24),
  365. _buildDetailItem("File Name", fileName, accents[4], colorScheme),
  366. _buildDetailItem("Primary Grade", primaryGrade, getStatusColor(primaryGrade), colorScheme),
  367. _buildDetailItem("Total Detections", activeDetections.length.toString(), colorScheme.onSurface, colorScheme),
  368. _buildDetailItem("Inference Time", record.inferenceMs == null ? "N/A" : "${record.inferenceMs} ms", accents[3], colorScheme),
  369. _buildDetailItem("Timestamp", record.timestamp.toString().split('.')[0], colorScheme.onSurface, colorScheme),
  370. if (tally.isNotEmpty) ...[
  371. const Divider(height: 32),
  372. Text("Frame Summary", style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: colorScheme.onSurface)),
  373. const SizedBox(height: 12),
  374. Wrap(
  375. spacing: 16,
  376. runSpacing: 8,
  377. children: tally.entries.map((e) {
  378. return Row(
  379. mainAxisSize: MainAxisSize.min,
  380. children: [
  381. Container(width: 12, height: 12, decoration: BoxDecoration(color: getMPOBColor(e.key), shape: BoxShape.circle)),
  382. const SizedBox(width: 6),
  383. Text("${e.key}: ${e.value}", style: TextStyle(fontSize: 13, color: colorScheme.onSurface)),
  384. ],
  385. );
  386. }).toList(),
  387. ),
  388. ],
  389. const Divider(height: 32),
  390. Text(
  391. _viewMode == _ViewMode.ai ? "Analytical Breakdown" : "Corrected Breakdown (tap a bunch above to edit or remove)",
  392. style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: colorScheme.onSurface),
  393. ),
  394. const SizedBox(height: 12),
  395. ...activeDetections.map((d) => Padding(
  396. padding: const EdgeInsets.only(bottom: 8),
  397. child: Row(
  398. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  399. children: [
  400. Row(
  401. children: [
  402. Container(
  403. width: 12,
  404. height: 12,
  405. decoration: BoxDecoration(
  406. color: getStatusColor(d.className),
  407. shape: BoxShape.circle,
  408. ),
  409. ),
  410. const SizedBox(width: 8),
  411. Text(d.className, style: TextStyle(fontWeight: FontWeight.w500, color: colorScheme.onSurface)),
  412. ],
  413. ),
  414. Text("${(d.confidence * 100).toStringAsFixed(1)}%", style: TextStyle(color: colorScheme.onSurface.withOpacity(0.6))),
  415. ],
  416. ),
  417. )),
  418. const SizedBox(height: 24),
  419. Text(
  420. "Industrial Summary: This image has been verified for harvest quality. All detected bunches are categorized according to ripeness standards.",
  421. style: TextStyle(fontStyle: FontStyle.italic, color: colorScheme.onSurface.withOpacity(0.6)),
  422. ),
  423. const SizedBox(height: 24),
  424. ],
  425. ),
  426. );
  427. }
  428. Widget _buildDetailItem(String label, String value, Color valueColor, ColorScheme colorScheme) {
  429. return Padding(
  430. padding: const EdgeInsets.only(bottom: 12),
  431. child: Row(
  432. crossAxisAlignment: CrossAxisAlignment.start,
  433. children: [
  434. Text("$label: ", style: TextStyle(fontWeight: FontWeight.w600, fontSize: 16, color: colorScheme.onSurface)),
  435. Expanded(
  436. child: Text(value, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16, color: valueColor)),
  437. ),
  438. ],
  439. ),
  440. );
  441. }
  442. }