Files
driver_tripz/lib/controller/functions/camer_controller.dart
Hamza-Ayed 8ce5d972f4 10/27/1
2023-10-27 18:46:51 +03:00

174 lines
4.9 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'package:camera/camera.dart';
import 'package:flutter_tesseract_ocr/flutter_tesseract_ocr.dart';
import 'package:get/get.dart';
import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';
import 'package:ride/constant/box_name.dart';
import 'package:ride/views/widgets/elevated_btn.dart';
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:path/path.dart' as path;
import '../../main.dart';
class CameraClassController extends GetxController {
late CameraController cameraController;
late List<CameraDescription> cameras;
bool isCameraInitialized = false;
final TextRecognizer _textRecognizer = TextRecognizer();
String? scannedText;
bool isloading = false;
@override
void onInit() {
super.onInit();
initializeCamera();
}
Future<void> initializeCamera() async {
try {
cameras = await availableCameras();
update();
cameraController = CameraController(
cameras[0],
ResolutionPreset.max,
enableAudio: false,
);
await cameraController.initialize();
isCameraInitialized = true;
update();
} catch (e) {
if (e is CameraException) {
switch (e.code) {
case 'CameraAccessDenied':
Get.defaultDialog(
title: 'Camera Access Denied.'.tr,
middleText: '',
confirm:
MyElevatedButton(title: 'Open Settings', onPressed: () {}),
);
break;
default:
// Handle other errors here.
break;
}
}
}
}
Future<void> takePictureAndMLGoogleScan() async {
try {
// Construct the path for the image file
final directory = await path_provider.getTemporaryDirectory();
final imagePath =
path.join(directory.path, '${box.read(BoxName.driverID)}.png');
// Capture the image and save it to the specified path
final XFile capturedImage = await cameraController.takePicture();
// Move the captured image to the desired path
await capturedImage.saveTo(imagePath);
// Recognize the text in the image
final InputImage inputImage =
InputImage.fromFile(File(capturedImage.path));
final RecognizedText recognizedText =
await _textRecognizer.processImage(inputImage);
scannedText = recognizedText.text;
// Extract the scanned text line by line
final List<Map<String, dynamic>> lines = [];
for (var i = 0; i < recognizedText.blocks.length; i++) {
lines.add({
'line_number': i,
'text': recognizedText.blocks[i].text,
});
}
// Convert the list of lines to a JSON string
final String jsonOutput = jsonEncode(lines);
update();
// Print the JSON output
print(jsonOutput);
// Get.back();
} catch (e) {
print('Error capturing image: $e');
}
}
String getTextAsJSON(String text) {
final lines = text.split('\n');
final jsonList = lines.map((line) {
return {
'line_text': line,
'num_words': line.trim().split(' ').length,
};
}).toList();
final json = {
'lines': jsonList,
'num_lines': lines.length,
};
return jsonEncode(json);
}
List<String> getTextBlocks(String text) {
return text.split('\n');
}
Future<void> takePictureAndTesseractScan() async {
try {
// Construct the path for the image file
final directory = await path_provider.getTemporaryDirectory();
final imagePath =
path.join(directory.path, '${box.read(BoxName.driverID)}.png');
// Capture the image and save it to the specified path
final XFile capturedImage = await cameraController.takePicture();
// Move the captured image to the desired path
await capturedImage.saveTo(imagePath);
// Recognize the text in the image
final languages = [
'eng',
'ara'
]; // Specify the languages you want to use for text extraction
final text = await FlutterTesseractOcr.extractText(imagePath,
language: languages.join('+'), // Combine multiple languages with '+'
args: {
"psm": "4",
"preserve_interword_spaces": "1",
// "rectangle": const Rect.fromLTWH(100, 100, 200, 200),
} // Additional options if needed
);
isloading = false;
final jsonText = getTextAsJSON(text);
final textBlocks = getTextBlocks(text);
update();
scannedText =
textBlocks.toString(); // Convert the extracted text to JSON.
// Print the JSON to the console.
print(jsonText);
update();
// print(text);
} catch (e) {
print('Error during text extraction: $e');
scannedText = '';
}
}
@override
void onClose() {
cameraController.dispose();
super.onClose();
}
}