tflite_service.dart 14 KB

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