61 lines
1.8 KiB
Dart
61 lines
1.8 KiB
Dart
import 'dart:io';
|
|
import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';
|
|
import 'package:image_picker/image_picker.dart';
|
|
|
|
class OcrResult {
|
|
final double? amount;
|
|
final String? rawText;
|
|
|
|
OcrResult({this.amount, this.rawText});
|
|
}
|
|
|
|
class OcrService {
|
|
final ImagePicker _picker = ImagePicker();
|
|
|
|
Future<OcrResult?> scanReceiptFromCamera() async {
|
|
final XFile? image = await _picker.pickImage(source: ImageSource.camera);
|
|
if (image == null) return null;
|
|
return await _processImage(File(image.path));
|
|
}
|
|
|
|
Future<OcrResult?> scanReceiptFromGallery() async {
|
|
final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
|
|
if (image == null) return null;
|
|
return await _processImage(File(image.path));
|
|
}
|
|
|
|
Future<OcrResult> _processImage(File file) async {
|
|
final inputImage = InputImage.fromFile(file);
|
|
final textRecognizer = TextRecognizer(script: TextRecognitionScript.latin);
|
|
|
|
try {
|
|
final RecognizedText recognizedText = await textRecognizer.processImage(inputImage);
|
|
String text = recognizedText.text;
|
|
|
|
// Simple regex to find a monetary amount (e.g., $145.50 or 145.50)
|
|
final RegExp amountRegex = RegExp(r'\$?\d+\.\d{2}');
|
|
final Iterable<Match> matches = amountRegex.allMatches(text);
|
|
|
|
double? maxAmount;
|
|
for (final Match m in matches) {
|
|
final matchText = m.group(0)?.replaceAll('\$', '');
|
|
if (matchText != null) {
|
|
final amount = double.tryParse(matchText);
|
|
if (amount != null) {
|
|
if (maxAmount == null || amount > maxAmount) {
|
|
maxAmount = amount; // Usually the total is the largest amount
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return OcrResult(
|
|
amount: maxAmount,
|
|
rawText: text,
|
|
);
|
|
} finally {
|
|
textRecognizer.close();
|
|
}
|
|
}
|
|
}
|