analysis_screen.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import 'dart:io';
  2. import 'dart:ui';
  3. import 'package:flutter/material.dart';
  4. import 'package:path_provider/path_provider.dart';
  5. import 'package:path/path.dart' as p;
  6. import '../services/tflite_service.dart';
  7. import '../services/database_helper.dart';
  8. import '../models/palm_record.dart';
  9. class AnalysisScreen extends StatefulWidget {
  10. const AnalysisScreen({super.key});
  11. @override
  12. State<AnalysisScreen> createState() => _AnalysisScreenState();
  13. }
  14. class _AnalysisScreenState extends State<AnalysisScreen> with SingleTickerProviderStateMixin {
  15. final TfliteService _tfliteService = TfliteService();
  16. final DatabaseHelper _dbHelper = DatabaseHelper();
  17. late AnimationController _scanningController;
  18. bool _isAnalyzing = false;
  19. File? _selectedImage;
  20. List<DetectionResult>? _detections;
  21. String? _errorMessage;
  22. @override
  23. void initState() {
  24. super.initState();
  25. _scanningController = AnimationController(
  26. vsync: this,
  27. duration: const Duration(seconds: 2),
  28. );
  29. _initModel();
  30. }
  31. Future<void> _initModel() async {
  32. try {
  33. await _tfliteService.initModel();
  34. } catch (e) {
  35. if (mounted) {
  36. setState(() {
  37. _errorMessage = "Failed to initialize AI model: $e";
  38. });
  39. }
  40. }
  41. }
  42. Future<void> _processGalleryImage() async {
  43. final image = await _tfliteService.pickImage();
  44. if (image == null) return;
  45. if (mounted) {
  46. setState(() {
  47. _isAnalyzing = true;
  48. _selectedImage = File(image.path);
  49. _detections = null;
  50. _errorMessage = null;
  51. });
  52. _scanningController.repeat(reverse: true);
  53. // Give the UI a frame to paint the loading state
  54. await Future.delayed(const Duration(milliseconds: 50));
  55. }
  56. try {
  57. // 1. Run Inference
  58. final detections = await _tfliteService.runInference(image.path);
  59. if (detections.isNotEmpty) {
  60. // 2. Persist Image to Documents Directory
  61. final appDocDir = await getApplicationDocumentsDirectory();
  62. final fileName = p.basename(image.path);
  63. final persistentPath = p.join(appDocDir.path, 'palm_${DateTime.now().millisecondsSinceEpoch}_$fileName');
  64. await File(image.path).copy(persistentPath);
  65. // 3. Update UI
  66. if (mounted) {
  67. setState(() {
  68. _detections = detections;
  69. _selectedImage = File(persistentPath);
  70. });
  71. }
  72. // 4. Save to Database
  73. final best = detections.first;
  74. final record = PalmRecord(
  75. imagePath: persistentPath,
  76. ripenessClass: best.className,
  77. confidence: best.confidence,
  78. timestamp: DateTime.now(),
  79. x1: best.normalizedBox.left,
  80. y1: best.normalizedBox.top,
  81. x2: best.normalizedBox.right,
  82. y2: best.normalizedBox.bottom,
  83. detections: detections.map((d) => {
  84. 'className': d.className,
  85. 'classIndex': d.classIndex,
  86. 'confidence': d.confidence,
  87. 'x1': d.normalizedBox.left,
  88. 'y1': d.normalizedBox.top,
  89. 'x2': d.normalizedBox.right,
  90. 'y2': d.normalizedBox.bottom,
  91. }).toList(),
  92. );
  93. await _dbHelper.insertRecord(record);
  94. } else {
  95. if (mounted) {
  96. setState(() {
  97. _errorMessage = "No palm bunches detected.";
  98. });
  99. }
  100. }
  101. } catch (e) {
  102. if (mounted) {
  103. setState(() {
  104. _errorMessage = "Analysis error: $e";
  105. });
  106. }
  107. } finally {
  108. if (mounted) {
  109. setState(() {
  110. _isAnalyzing = false;
  111. });
  112. _scanningController.stop();
  113. _scanningController.reset();
  114. }
  115. }
  116. }
  117. bool _isHealthAlert(String label) {
  118. return label == 'Empty_Bunch' || label == 'Abnormal';
  119. }
  120. @override
  121. Widget build(BuildContext context) {
  122. return Scaffold(
  123. appBar: AppBar(title: const Text('AI Analysis')),
  124. body: Stack(
  125. children: [
  126. Column(
  127. children: [
  128. Expanded(
  129. child: Center(
  130. child: _selectedImage == null
  131. ? const Text("Select a photo to start AI analysis")
  132. : AspectRatio(
  133. aspectRatio: 1.0,
  134. child: Padding(
  135. padding: const EdgeInsets.all(8.0),
  136. child: Stack(
  137. children: [
  138. // Main Image
  139. ClipRRect(
  140. borderRadius: BorderRadius.circular(12),
  141. child: Image.file(
  142. _selectedImage!,
  143. fit: BoxFit.contain,
  144. width: double.infinity,
  145. height: double.infinity,
  146. ),
  147. ),
  148. // Bounding Box Overlays
  149. if (_detections != null)
  150. Positioned.fill(
  151. child: LayoutBuilder(
  152. builder: (context, constraints) {
  153. return Stack(
  154. children: _detections!
  155. .map((d) => _buildBoundingBox(d, constraints))
  156. .toList(),
  157. );
  158. },
  159. ),
  160. ),
  161. // Scanning Animation
  162. if (_isAnalyzing)
  163. _ScanningOverlay(animation: _scanningController),
  164. ],
  165. ),
  166. ),
  167. ),
  168. ),
  169. ),
  170. if (_detections != null) _buildResultSummary(),
  171. Padding(
  172. padding: const EdgeInsets.all(32.0),
  173. child: ElevatedButton.icon(
  174. onPressed: _isAnalyzing ? null : _processGalleryImage,
  175. icon: const Icon(Icons.add_a_photo),
  176. label: const Text("Pick Image from Gallery"),
  177. style: ElevatedButton.styleFrom(
  178. minimumSize: const Size(double.infinity, 54),
  179. shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
  180. ),
  181. ),
  182. ),
  183. ],
  184. ),
  185. if (_isAnalyzing) _buildLoadingOverlay(),
  186. if (_errorMessage != null) _buildErrorToast(),
  187. ],
  188. ),
  189. );
  190. }
  191. Widget _buildBoundingBox(DetectionResult detection, BoxConstraints constraints) {
  192. final rect = detection.normalizedBox;
  193. final color = detection.getStatusColor();
  194. return Positioned(
  195. left: rect.left * constraints.maxWidth,
  196. top: rect.top * constraints.maxHeight,
  197. width: rect.width * constraints.maxWidth,
  198. height: rect.height * constraints.maxHeight,
  199. child: Container(
  200. decoration: BoxDecoration(
  201. border: Border.all(color: color, width: 3),
  202. borderRadius: BorderRadius.circular(4),
  203. ),
  204. child: Align(
  205. alignment: Alignment.topLeft,
  206. child: Container(
  207. padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
  208. color: color,
  209. child: Text(
  210. "${detection.className} ${(detection.confidence * 100).toStringAsFixed(0)}%",
  211. style: const TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.bold),
  212. ),
  213. ),
  214. ),
  215. ),
  216. );
  217. }
  218. // Removed _getStatusColor local method in favor of DetectionResult.getStatusColor()
  219. Widget _buildResultSummary() {
  220. final best = _detections!.first;
  221. return Container(
  222. padding: const EdgeInsets.all(16),
  223. margin: const EdgeInsets.symmetric(horizontal: 16),
  224. decoration: BoxDecoration(
  225. color: Colors.white,
  226. borderRadius: BorderRadius.circular(12),
  227. boxShadow: [const BoxShadow(color: Colors.black12, blurRadius: 10)],
  228. ),
  229. child: Column(
  230. children: [
  231. Row(
  232. mainAxisAlignment: MainAxisAlignment.center,
  233. children: [
  234. Icon(Icons.check_circle, color: best.getStatusColor(), size: 32),
  235. const SizedBox(width: 12),
  236. Text(
  237. best.className,
  238. style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
  239. ),
  240. ],
  241. ),
  242. Text(
  243. "Confidence: ${(best.confidence * 100).toStringAsFixed(1)}%",
  244. style: const TextStyle(fontSize: 14, color: Colors.grey),
  245. ),
  246. if (_isHealthAlert(best.className))
  247. const Padding(
  248. padding: EdgeInsets.only(top: 8.0),
  249. child: Text(
  250. "HEALTH ALERT: Abnormal detected!",
  251. style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold),
  252. ),
  253. ),
  254. if (_detections!.length > 1)
  255. Padding(
  256. padding: const EdgeInsets.only(top: 8.0),
  257. child: Text(
  258. "${_detections!.length} bunches detected",
  259. style: const TextStyle(fontSize: 13, color: Colors.grey),
  260. ),
  261. ),
  262. ],
  263. ),
  264. );
  265. }
  266. Widget _buildLoadingOverlay() {
  267. return Positioned.fill(
  268. child: BackdropFilter(
  269. filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
  270. child: Container(
  271. color: Colors.black.withOpacity(0.3),
  272. child: const Center(
  273. child: Column(
  274. mainAxisSize: MainAxisSize.min,
  275. children: [
  276. CircularProgressIndicator(
  277. color: Colors.white,
  278. strokeWidth: 6,
  279. ),
  280. SizedBox(height: 24),
  281. Text(
  282. "AI is Analyzing...",
  283. style: TextStyle(
  284. color: Colors.white,
  285. fontSize: 22,
  286. fontWeight: FontWeight.bold,
  287. letterSpacing: 1.2,
  288. ),
  289. ),
  290. Text(
  291. "Optimizing detection parameters",
  292. style: TextStyle(color: Colors.white70, fontSize: 14),
  293. ),
  294. ],
  295. ),
  296. ),
  297. ),
  298. ),
  299. );
  300. }
  301. Widget _buildErrorToast() {
  302. return Positioned(
  303. bottom: 20,
  304. left: 20,
  305. right: 20,
  306. child: Container(
  307. padding: const EdgeInsets.all(16),
  308. decoration: BoxDecoration(
  309. color: Colors.red.shade800,
  310. borderRadius: BorderRadius.circular(12),
  311. boxShadow: [const BoxShadow(color: Colors.black26, blurRadius: 8)],
  312. ),
  313. child: Column(
  314. mainAxisSize: MainAxisSize.min,
  315. crossAxisAlignment: CrossAxisAlignment.start,
  316. children: [
  317. const Row(
  318. children: [
  319. Icon(Icons.error_outline, color: Colors.white),
  320. SizedBox(width: 8),
  321. Text("Error Details", style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
  322. ],
  323. ),
  324. const SizedBox(height: 8),
  325. Text(
  326. _errorMessage!,
  327. style: const TextStyle(color: Colors.white, fontSize: 12),
  328. ),
  329. const SizedBox(height: 8),
  330. TextButton(
  331. onPressed: () => setState(() => _errorMessage = null),
  332. child: const Text("Dismiss", style: TextStyle(color: Colors.white)),
  333. ),
  334. ],
  335. ),
  336. ),
  337. );
  338. }
  339. @override
  340. void dispose() {
  341. _scanningController.dispose();
  342. _tfliteService.dispose();
  343. super.dispose();
  344. }
  345. }
  346. class _ScanningOverlay extends StatelessWidget {
  347. final Animation<double> animation;
  348. const _ScanningOverlay({required this.animation});
  349. @override
  350. Widget build(BuildContext context) {
  351. return AnimatedBuilder(
  352. animation: animation,
  353. builder: (context, child) {
  354. return Stack(
  355. children: [
  356. Positioned(
  357. top: animation.value * MediaQuery.of(context).size.width, // Rough estimation since AspectRatio is 1.0
  358. left: 0,
  359. right: 0,
  360. child: Container(
  361. height: 4,
  362. decoration: BoxDecoration(
  363. gradient: LinearGradient(
  364. colors: [
  365. Colors.transparent,
  366. Colors.greenAccent.withOpacity(0.8),
  367. Colors.transparent,
  368. ],
  369. ),
  370. boxShadow: [
  371. BoxShadow(
  372. color: Colors.greenAccent.withOpacity(0.6),
  373. blurRadius: 15,
  374. spreadRadius: 2,
  375. ),
  376. ],
  377. ),
  378. ),
  379. ),
  380. ],
  381. );
  382. },
  383. );
  384. }
  385. }