tflite_service.dart 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. import 'dart:io';
  2. import 'dart:typed_data';
  3. import 'dart:isolate';
  4. import 'dart:async';
  5. import 'package:flutter/services.dart';
  6. import 'package:flutter/foundation.dart';
  7. import 'package:image/image.dart' as img;
  8. import 'package:image_picker/image_picker.dart';
  9. import 'package:tflite_flutter/tflite_flutter.dart';
  10. import 'package:camera/camera.dart';
  11. import '../constants/mpob_colors.dart' as mpob_colors;
  12. class DetectionResult {
  13. final String className;
  14. final int classIndex;
  15. final double confidence;
  16. final Rect normalizedBox;
  17. const DetectionResult({
  18. required this.className,
  19. required this.classIndex,
  20. required this.confidence,
  21. required this.normalizedBox,
  22. });
  23. Color getStatusColor() => mpob_colors.getStatusColor(className);
  24. }
  25. class TfliteService {
  26. static const _modelAsset = 'best.tflite';
  27. static const _labelsAsset = 'labels.txt';
  28. static const int _inputSize = 640;
  29. static const double _confidenceThreshold = 0.25;
  30. Isolate? _isolate;
  31. SendPort? _sendPort;
  32. ReceivePort? _receivePort;
  33. final ImagePicker _picker = ImagePicker();
  34. bool _isInitialized = false;
  35. bool _isIsolateBusy = false;
  36. bool get isInitialized => _isInitialized;
  37. bool get isIsolateBusy => _isIsolateBusy;
  38. Future<void> initModel() async {
  39. try {
  40. final labelData = await rootBundle.loadString('assets/$_labelsAsset');
  41. final modelData = await rootBundle.load('assets/$_modelAsset');
  42. final modelBytes = modelData.buffer.asUint8List();
  43. _receivePort = ReceivePort();
  44. _isolate = await Isolate.spawn(_isolateEntry, _receivePort!.sendPort);
  45. final completer = Completer<SendPort>();
  46. StreamSubscription? sub;
  47. sub = _receivePort!.listen((message) {
  48. if (message is SendPort) {
  49. completer.complete(message);
  50. sub?.cancel();
  51. }
  52. });
  53. _sendPort = await completer.future;
  54. final initCompleter = Completer<void>();
  55. final initReplyPort = ReceivePort();
  56. _sendPort!.send({
  57. 'command': 'init',
  58. 'modelBytes': modelBytes,
  59. 'labelData': labelData,
  60. 'replyPort': initReplyPort.sendPort,
  61. });
  62. StreamSubscription? initSub;
  63. initSub = initReplyPort.listen((message) {
  64. if (message == 'init_done') {
  65. initCompleter.complete();
  66. initSub?.cancel();
  67. initReplyPort.close();
  68. }
  69. });
  70. await initCompleter.future;
  71. _isInitialized = true;
  72. debugPrint('TfliteService: Model loaded via persistent isolate.');
  73. } catch (e) {
  74. debugPrint('TfliteService init error: $e');
  75. rethrow;
  76. }
  77. }
  78. Future<XFile?> pickImage() async {
  79. return await _picker.pickImage(
  80. source: ImageSource.gallery,
  81. maxWidth: _inputSize.toDouble(),
  82. maxHeight: _inputSize.toDouble(),
  83. );
  84. }
  85. Future<List<XFile>> pickMultiImage() async {
  86. return await _picker.pickMultiImage(
  87. maxWidth: _inputSize.toDouble(),
  88. maxHeight: _inputSize.toDouble(),
  89. );
  90. }
  91. Future<List<DetectionResult>> runInference(String imagePath) async {
  92. if (!_isInitialized) await initModel();
  93. final imageBytes = await File(imagePath).readAsBytes();
  94. final replyPort = ReceivePort();
  95. _sendPort!.send({
  96. 'command': 'inference_static',
  97. 'imageBytes': imageBytes,
  98. 'replyPort': replyPort.sendPort,
  99. });
  100. final detections = await replyPort.first;
  101. replyPort.close();
  102. return detections as List<DetectionResult>;
  103. }
  104. Future<List<DetectionResult>> runInferenceOnStream(CameraImage image) async {
  105. if (!_isInitialized) await initModel();
  106. // The gatekeeper logic has moved up to LiveAnalysisScreen (Atomic Lock)
  107. // but we keep the safety bypass here just in case.
  108. if (_isIsolateBusy) return <DetectionResult>[];
  109. _isIsolateBusy = true;
  110. final replyPort = ReceivePort();
  111. _sendPort!.send({
  112. 'command': 'inference_stream',
  113. 'planes': image.planes.map((p) => {
  114. 'bytes': p.bytes,
  115. 'bytesPerRow': p.bytesPerRow,
  116. 'bytesPerPixel': p.bytesPerPixel,
  117. }).toList(),
  118. 'width': image.width,
  119. 'height': image.height,
  120. 'format': image.format.group,
  121. 'replyPort': replyPort.sendPort,
  122. });
  123. final detections = await replyPort.first;
  124. replyPort.close();
  125. _isIsolateBusy = false;
  126. return detections as List<DetectionResult>;
  127. }
  128. static void _isolateEntry(SendPort sendPort) {
  129. final receivePort = ReceivePort();
  130. sendPort.send(receivePort.sendPort);
  131. Interpreter? interpreter;
  132. List<String> labels = [];
  133. receivePort.listen((message) {
  134. if (message is Map) {
  135. final command = message['command'];
  136. final replyPort = message['replyPort'] as SendPort;
  137. if (command == 'init') {
  138. final modelBytes = message['modelBytes'] as Uint8List;
  139. final labelData = message['labelData'] as String;
  140. final interpreterOptions = InterpreterOptions()..threads = 4;
  141. interpreter = Interpreter.fromBuffer(modelBytes, options: interpreterOptions);
  142. labels = labelData.split('\n').where((l) => l.trim().isNotEmpty).map((l) => l.trim()).toList();
  143. replyPort.send('init_done');
  144. } else if (command == 'inference_static') {
  145. if (interpreter == null) {
  146. replyPort.send(<DetectionResult>[]);
  147. return;
  148. }
  149. final imageBytes = message['imageBytes'] as Uint8List;
  150. final results = _inferenceStaticTask(imageBytes, interpreter!, labels);
  151. replyPort.send(results);
  152. } else if (command == 'inference_stream') {
  153. if (interpreter == null) {
  154. replyPort.send(<DetectionResult>[]);
  155. return;
  156. }
  157. final planes = message['planes'] as List<dynamic>;
  158. final width = message['width'] as int;
  159. final height = message['height'] as int;
  160. final format = message['format'];
  161. final results = _inferenceStreamTask(planes, width, height, format, interpreter!, labels);
  162. replyPort.send(results);
  163. }
  164. }
  165. });
  166. }
  167. static List<DetectionResult> _inferenceStaticTask(Uint8List imageBytes, Interpreter interpreter, List<String> labels) {
  168. try {
  169. final decoded = img.decodeImage(imageBytes);
  170. if (decoded == null) throw Exception('Could not decode image');
  171. final int width = decoded.width;
  172. final int height = decoded.height;
  173. final int size = width < height ? width : height;
  174. final int offsetX = (width - size) ~/ 2;
  175. final int offsetY = (height - size) ~/ 2;
  176. final cropped = img.copyCrop(decoded, x: offsetX, y: offsetY, width: size, height: size);
  177. final resized = img.copyResize(cropped, width: _inputSize, height: _inputSize, interpolation: img.Interpolation.linear);
  178. final inputTensor = List.generate(1, (_) =>
  179. List.generate(_inputSize, (y) =>
  180. List.generate(_inputSize, (x) {
  181. final pixel = resized.getPixel(x, y);
  182. return [pixel.r / 255.0, pixel.g / 255.0, pixel.b / 255.0];
  183. })
  184. )
  185. );
  186. final outputShape = interpreter.getOutputTensors()[0].shape;
  187. final outputTensor = List.generate(1, (_) =>
  188. List.generate(outputShape[1], (_) =>
  189. List<double>.filled(outputShape[2], 0.0)
  190. )
  191. );
  192. interpreter.run(inputTensor, outputTensor);
  193. return _decodeDetections(
  194. outputTensor[0],
  195. labels,
  196. cropSize: size,
  197. offsetX: offsetX,
  198. offsetY: offsetY,
  199. fullWidth: width,
  200. fullHeight: height
  201. );
  202. } catch (e) {
  203. debugPrint('Isolate static inference error: $e');
  204. return <DetectionResult>[];
  205. }
  206. }
  207. static List<DetectionResult> _inferenceStreamTask(
  208. List<dynamic> planes, int width, int height, dynamic format,
  209. Interpreter interpreter, List<String> labels
  210. ) {
  211. try {
  212. final size = width < height ? width : height;
  213. final offsetX = (width - size) ~/ 2;
  214. final offsetY = (height - size) ~/ 2;
  215. img.Image? image;
  216. if (format == ImageFormatGroup.bgra8888) {
  217. final fullImage = img.Image.fromBytes(
  218. width: width,
  219. height: height,
  220. bytes: planes[0]['bytes'].buffer,
  221. format: img.Format.uint8,
  222. numChannels: 4,
  223. order: img.ChannelOrder.bgra,
  224. );
  225. image = img.copyCrop(fullImage, x: offsetX, y: offsetY, width: size, height: size);
  226. } else if (format == ImageFormatGroup.yuv420) {
  227. image = _convertYUV420ToImage(
  228. planes: planes,
  229. width: width,
  230. height: height,
  231. cropSize: size,
  232. offsetX: offsetX,
  233. offsetY: offsetY,
  234. );
  235. } else {
  236. debugPrint("TfliteService: Unsupported format: $format. Ensure platform correctly requests YUV420 or BGRA.");
  237. return <DetectionResult>[];
  238. }
  239. final resized = img.copyResize(image, width: _inputSize, height: _inputSize);
  240. final inputTensor = List.generate(1, (_) =>
  241. List.generate(_inputSize, (y) =>
  242. List.generate(_inputSize, (x) {
  243. final pixel = resized.getPixel(x, y);
  244. return [pixel.r / 255.0, pixel.g / 255.0, pixel.b / 255.0];
  245. })
  246. )
  247. );
  248. final outputShape = interpreter.getOutputTensors()[0].shape;
  249. final outputTensor = List.generate(1, (_) =>
  250. List.generate(outputShape[1], (_) =>
  251. List<double>.filled(outputShape[2], 0.0)
  252. )
  253. );
  254. interpreter.run(inputTensor, outputTensor);
  255. return _decodeDetections(
  256. outputTensor[0],
  257. labels,
  258. cropSize: size,
  259. offsetX: offsetX,
  260. offsetY: offsetY,
  261. fullWidth: width,
  262. fullHeight: height
  263. );
  264. } catch (e) {
  265. debugPrint('Isolate stream inference error: $e');
  266. return <DetectionResult>[];
  267. }
  268. }
  269. static img.Image _convertYUV420ToImage({
  270. required List<dynamic> planes,
  271. required int width,
  272. required int height,
  273. required int cropSize,
  274. required int offsetX,
  275. required int offsetY,
  276. }) {
  277. final yPlane = planes[0];
  278. final uPlane = planes[1];
  279. final vPlane = planes[2];
  280. final yBytes = yPlane['bytes'] as Uint8List;
  281. final uBytes = uPlane['bytes'] as Uint8List;
  282. final vBytes = vPlane['bytes'] as Uint8List;
  283. final yRowStride = yPlane['bytesPerRow'] as int;
  284. final uvRowStride = uPlane['bytesPerRow'] as int;
  285. final uvPixelStride = uPlane['bytesPerPixel'] as int;
  286. // Fast 32-bit Native memory buffer
  287. final Uint32List bgraData = Uint32List(cropSize * cropSize);
  288. int bufferIndex = 0;
  289. for (int y = 0; y < cropSize; y++) {
  290. for (int x = 0; x < cropSize; x++) {
  291. final int actualX = x + offsetX;
  292. final int actualY = y + offsetY;
  293. final int uvIndex = (uvRowStride * (actualY >> 1)) + (uvPixelStride * (actualX >> 1));
  294. final int yIndex = (actualY * yRowStride) + actualX;
  295. if (yIndex >= yBytes.length || uvIndex >= uBytes.length || uvIndex >= vBytes.length) {
  296. bufferIndex++;
  297. continue;
  298. }
  299. final int yp = yBytes[yIndex];
  300. final int up = uBytes[uvIndex];
  301. final int vp = vBytes[uvIndex];
  302. // Standard YUV to RGB conversion
  303. int r = (yp + (1.370705 * (vp - 128))).toInt();
  304. int g = (yp - (0.337633 * (up - 128)) - (0.698001 * (vp - 128))).toInt();
  305. int b = (yp + (1.732446 * (up - 128))).toInt();
  306. // Clamp inline for max speed
  307. r = r < 0 ? 0 : (r > 255 ? 255 : r);
  308. g = g < 0 ? 0 : (g > 255 ? 255 : g);
  309. b = b < 0 ? 0 : (b > 255 ? 255 : b);
  310. // Pack into 32-bit integer: 0xAARRGGBB -> Memory writes it Little Endian: B, G, R, A.
  311. bgraData[bufferIndex++] = (255 << 24) | (r << 16) | (g << 8) | b;
  312. }
  313. }
  314. return img.Image.fromBytes(
  315. width: cropSize,
  316. height: cropSize,
  317. bytes: bgraData.buffer,
  318. format: img.Format.uint8,
  319. numChannels: 4, // Packed 4 channels (BGRA)
  320. order: img.ChannelOrder.bgra, // Explicitly tell image package it's BGRA
  321. );
  322. }
  323. /// Decodes YOLO26 NMS-Free detections.
  324. /// Unlike legacy YOLOv8, this model produces unique, final predictions
  325. /// directly in the output tensor, eliminating the need for a secondary
  326. /// Non-Max Suppression (NMS) loop in Dart.
  327. static List<DetectionResult> _decodeDetections(
  328. List<List<double>> rawDetections,
  329. List<String> labels, {
  330. int? cropSize,
  331. int? offsetX,
  332. int? offsetY,
  333. int? fullWidth,
  334. int? fullHeight,
  335. }) {
  336. // YOLO26 E2E models typically return a fixed number of detections (e.g., top 100)
  337. // We only need to filter by confidence and map back to the original frame.
  338. final detections = <DetectionResult>[];
  339. for (final det in rawDetections) {
  340. if (det.length < 6) continue;
  341. final conf = det[4];
  342. if (conf < _confidenceThreshold) continue;
  343. double x1 = det[0].clamp(0.0, 1.0);
  344. double y1 = det[1].clamp(0.0, 1.0);
  345. double x2 = det[2].clamp(0.0, 1.0);
  346. double y2 = det[3].clamp(0.0, 1.0);
  347. // If crop info is provided, map back to full frame
  348. if (cropSize != null && offsetX != null && offsetY != null && fullWidth != null && fullHeight != null) {
  349. x1 = (x1 * cropSize + offsetX) / fullWidth;
  350. x2 = (x2 * cropSize + offsetX) / fullWidth;
  351. y1 = (y1 * cropSize + offsetY) / fullHeight;
  352. y2 = (y2 * cropSize + offsetY) / fullHeight;
  353. }
  354. final classId = det[5].round();
  355. if (x2 <= x1 || y2 <= y1) continue;
  356. final label = (classId >= 0 && classId < labels.length) ? labels[classId] : 'Unknown';
  357. detections.add(DetectionResult(
  358. className: label,
  359. classIndex: classId,
  360. confidence: conf,
  361. normalizedBox: Rect.fromLTRB(x1, y1, x2, y2),
  362. ));
  363. }
  364. detections.sort((a, b) => b.confidence.compareTo(a.confidence));
  365. return detections;
  366. }
  367. void dispose() {
  368. _receivePort?.close();
  369. if (_isolate != null) {
  370. _isolate!.kill(priority: Isolate.immediate);
  371. _isolate = null;
  372. }
  373. _isInitialized = false;
  374. }
  375. }