37 lines
1.2 KiB
Dart
37 lines
1.2 KiB
Dart
|
|
import 'package:flutter/foundation.dart';
|
||
|
|
import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';
|
||
|
|
|
||
|
|
class OcrService {
|
||
|
|
late final TextRecognizer _textRecognizer;
|
||
|
|
|
||
|
|
OcrService() {
|
||
|
|
_textRecognizer = TextRecognizer(script: TextRecognitionScript.japanese);
|
||
|
|
}
|
||
|
|
|
||
|
|
Future<String> extractText(String imagePath) async {
|
||
|
|
try {
|
||
|
|
final inputImage = InputImage.fromFilePath(imagePath);
|
||
|
|
final RecognizedText recognizedText = await _textRecognizer.processImage(inputImage);
|
||
|
|
return recognizedText.text;
|
||
|
|
} catch (e) {
|
||
|
|
debugPrint('Japanese OCR Error: $e');
|
||
|
|
// Fallback to Latin script if Japanese model fails
|
||
|
|
try {
|
||
|
|
final latinRecognizer = TextRecognizer(script: TextRecognitionScript.latin);
|
||
|
|
final inputImage = InputImage.fromFilePath(imagePath);
|
||
|
|
final RecognizedText recognizedText = await latinRecognizer.processImage(inputImage);
|
||
|
|
await latinRecognizer.close();
|
||
|
|
debugPrint('Fallback to Latin OCR successful');
|
||
|
|
return recognizedText.text;
|
||
|
|
} catch (e2) {
|
||
|
|
debugPrint('Latin OCR also failed: $e2');
|
||
|
|
return ''; // Return empty string on error to allow fallback to image analysis
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
void dispose() {
|
||
|
|
_textRecognizer.close();
|
||
|
|
}
|
||
|
|
}
|