1817 lines
60 KiB
Dart
1817 lines
60 KiB
Dart
import 'dart:async';
|
||
import 'dart:convert';
|
||
import 'dart:io';
|
||
import 'dart:math';
|
||
import 'package:sefer_driver/constant/box_name.dart';
|
||
import 'package:sefer_driver/constant/info.dart';
|
||
import 'package:sefer_driver/constant/links.dart';
|
||
import 'package:sefer_driver/constant/style.dart';
|
||
import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
|
||
import 'package:sefer_driver/controller/firebase/firbase_messge.dart';
|
||
import 'package:sefer_driver/controller/firebase/local_notification.dart';
|
||
import 'package:sefer_driver/controller/functions/crud.dart';
|
||
import 'package:sefer_driver/controller/functions/device_info.dart';
|
||
import 'package:sefer_driver/controller/notification/notification_captain_controller.dart';
|
||
import 'package:sefer_driver/main.dart';
|
||
import 'package:sefer_driver/views/home/Captin/home_captain/home_captin.dart';
|
||
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
|
||
import 'package:sefer_driver/views/widgets/mydialoug.dart';
|
||
import 'package:flutter/material.dart';
|
||
import 'package:get/get.dart';
|
||
import 'package:image_cropper/image_cropper.dart';
|
||
import 'package:image_picker/image_picker.dart';
|
||
import 'package:http/http.dart' as http;
|
||
import 'package:image/image.dart' as img;
|
||
import 'package:path_provider/path_provider.dart';
|
||
import 'package:secure_string_operations/secure_string_operations.dart';
|
||
|
||
import '../../constant/api_key.dart';
|
||
import '../../constant/char_map.dart';
|
||
import '../../constant/colors.dart';
|
||
import '../../print.dart';
|
||
import 'tts.dart';
|
||
import 'upload_image.dart';
|
||
|
||
enum LicenseSide {
|
||
front,
|
||
back,
|
||
unknown,
|
||
}
|
||
|
||
enum DocumentType {
|
||
carLicenseFront,
|
||
carLicenseBack,
|
||
idCardFront,
|
||
nonIdCardFront,
|
||
nonIdCardBack,
|
||
idCardBack,
|
||
driverLicense,
|
||
unknown,
|
||
}
|
||
|
||
class AI extends GetxController {
|
||
bool approved = false;
|
||
bool isDriverSaved = false;
|
||
bool isCarSaved = false;
|
||
bool isInviteDriverFound = false;
|
||
final invitationCodeController = TextEditingController();
|
||
final formKey = GlobalKey<FormState>();
|
||
bool isTimerComplete = false;
|
||
double progressValue = 1.0;
|
||
int remainingSeconds = 30;
|
||
|
||
void startTimer() {
|
||
Timer.periodic(const Duration(seconds: 1), (timer) {
|
||
if (remainingSeconds == 0) {
|
||
timer.cancel();
|
||
isTimerComplete = true;
|
||
update(); // Notify the UI
|
||
} else {
|
||
remainingSeconds--;
|
||
progressValue = remainingSeconds / 30.0; // Update progress
|
||
update(); // Notify the UI
|
||
}
|
||
});
|
||
}
|
||
|
||
void resetTimer() {
|
||
isTimerComplete = false;
|
||
progressValue = 1.0;
|
||
remainingSeconds = 40;
|
||
update(); // Notify the UI
|
||
startTimer(); // Restart the timer
|
||
}
|
||
|
||
void setApproved() {
|
||
approved = true;
|
||
update();
|
||
}
|
||
|
||
Future updateInvitationCodeFromRegister() async {
|
||
var res = await CRUD().post(
|
||
link: AppLink.updateDriverInvitationDirectly,
|
||
payload: {
|
||
"inviterDriverPhone": '+2${box.read(BoxName.phoneDriver).toString()}',
|
||
"driverId": box.read(BoxName.driverID).toString(),
|
||
},
|
||
);
|
||
|
||
if (res != 'failure') {
|
||
isInviteDriverFound = true;
|
||
update();
|
||
// mySnackbarSuccess("Code approved".tr); // Localized success message
|
||
box.write(BoxName.isInstall, '1');
|
||
NotificationController().showNotification(
|
||
"Code approved".tr, "Code approved".tr, 'tone2', '');
|
||
// Notification text with dynamic token
|
||
FirebaseMessagesController().sendNotificationToDriverMAP(
|
||
'You have received a gift token!'.tr,
|
||
'for '.tr + box.read(BoxName.phoneDriver).toString(),
|
||
jsonDecode(res)['message'][0]['token'].toString(),
|
||
[],
|
||
'tone2', // Type of notification
|
||
);
|
||
} else {
|
||
// mySnackeBarError(
|
||
// "You dont have invitation code".tr); // Localized error message
|
||
}
|
||
}
|
||
|
||
Future updatePassengersInvitation() async {
|
||
if (formKey.currentState!.validate()) {
|
||
var res = await CRUD().post(
|
||
link: AppLink.updatePassengersInvitation,
|
||
payload: {"inviteCode": invitationCodeController.text});
|
||
if (res != 'failure') {
|
||
isInviteDriverFound = true;
|
||
update();
|
||
mySnackbarSuccess("Code approved".tr);
|
||
} else {
|
||
mySnackeBarError("Code not approved".tr);
|
||
}
|
||
}
|
||
}
|
||
|
||
final today = DateTime.now();
|
||
|
||
Future<void> addDriverAndCarEgypt() async {
|
||
final expiryDate = responseIdEgyptDriverLicense['expiry_date'];
|
||
final expiryDateTime = DateTime.tryParse(expiryDate);
|
||
final isExpired = expiryDateTime != null && expiryDateTime.isBefore(today);
|
||
|
||
final taxExpiryDate = responseIdCardDriverEgyptBack['tax_expiry'];
|
||
|
||
// Get the inspection date from the response
|
||
final inspectionDate = responseIdCardDriverEgyptBack['inspection_date'];
|
||
final year = int.parse(inspectionDate.split('-')[0]);
|
||
// Try parsing the tax expiry date. If it fails, set it to null.
|
||
final taxExpiryDateTime = DateTime.tryParse(taxExpiryDate ?? '');
|
||
final isExpiredCar =
|
||
taxExpiryDateTime != null && taxExpiryDateTime.isBefore(today);
|
||
|
||
// Check if the inspection date is before today
|
||
final inspectionDateTime = DateTime(year, 12, 31);
|
||
final isInspectionExpired = inspectionDateTime.isBefore(today);
|
||
// Add birthdate comparison for non-Egyptian ID
|
||
final frontBirthDate =
|
||
DateTime.tryParse(responseNonIdCardFront['birthdate'] ?? '');
|
||
final backBirthDate =
|
||
DateTime.tryParse(responseNonIdCardBack['birthDate'] ?? '');
|
||
final birthdatesMismatch = frontBirthDate != null &&
|
||
backBirthDate != null &&
|
||
frontBirthDate != backBirthDate;
|
||
|
||
if (isExpiredCar || isInspectionExpired) {
|
||
Get.defaultDialog(
|
||
title: 'Expired Driver’s License'.tr,
|
||
content: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
const Icon(Icons.warning, size: 48, color: Colors.red),
|
||
const SizedBox(height: 16),
|
||
Text(
|
||
"Your driver’s license and/or car tax has expired. Please renew them before proceeding."
|
||
.tr,
|
||
textAlign: TextAlign.center,
|
||
style: AppStyle.title,
|
||
),
|
||
const SizedBox(height: 16),
|
||
IconButton(
|
||
onPressed: () async {
|
||
await Get.find<TextToSpeechController>().speakText(
|
||
"Your driver’s license and/or car tax has expired. Please renew them before proceeding."
|
||
.tr,
|
||
);
|
||
},
|
||
icon: const Icon(Icons.volume_up),
|
||
),
|
||
],
|
||
),
|
||
actions: [
|
||
TextButton(
|
||
onPressed: () {
|
||
Get.back();
|
||
},
|
||
child: const Text('OK'),
|
||
),
|
||
],
|
||
);
|
||
} else if (birthdatesMismatch && !isEgypt) {
|
||
Get.defaultDialog(
|
||
title: 'Birthdate Mismatch'.tr,
|
||
content: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
const Icon(Icons.warning, size: 48, color: Colors.red),
|
||
const SizedBox(height: 16),
|
||
Text(
|
||
"The birthdate on your ID front doesn't match the one on the back. Please verify your documents."
|
||
.tr,
|
||
textAlign: TextAlign.center,
|
||
style: AppStyle.title,
|
||
),
|
||
const SizedBox(height: 16),
|
||
IconButton(
|
||
onPressed: () async {
|
||
await Get.find<TextToSpeechController>().speakText(
|
||
"The birthdate on your ID front doesn't match the one on the back. Please verify your documents."
|
||
.tr,
|
||
);
|
||
},
|
||
icon: const Icon(Icons.volume_up),
|
||
),
|
||
],
|
||
),
|
||
actions: [
|
||
TextButton(
|
||
onPressed: () {
|
||
Get.back();
|
||
},
|
||
child: const Text('OK'),
|
||
),
|
||
],
|
||
);
|
||
} else if (isExpired) {
|
||
Get.defaultDialog(
|
||
title: 'Expired Driver’s License'.tr,
|
||
content: Column(
|
||
mainAxisSize: MainAxisSize.min,
|
||
children: [
|
||
const Icon(Icons.warning, size: 48, color: Colors.red),
|
||
const SizedBox(height: 16),
|
||
Text(
|
||
"Your driver’s license has expired. Please renew it before proceeding."
|
||
.tr,
|
||
textAlign: TextAlign.center,
|
||
style: AppStyle.title,
|
||
),
|
||
const SizedBox(height: 16),
|
||
IconButton(
|
||
onPressed: () async {
|
||
await Get.find<TextToSpeechController>().speakText(
|
||
"Your driver’s license has expired. Please renew it before proceeding."
|
||
.tr);
|
||
},
|
||
icon: const Icon(Icons.volume_up),
|
||
),
|
||
],
|
||
),
|
||
actions: [
|
||
TextButton(
|
||
onPressed: () {
|
||
Get.back();
|
||
},
|
||
child: const Text('OK'),
|
||
),
|
||
],
|
||
);
|
||
}
|
||
// else if (responseIdEgyptDriverLicense['national_number'] !=
|
||
// responseIdEgyptBack['nationalID']) {
|
||
// Get.defaultDialog(
|
||
// barrierDismissible: false,
|
||
// title: 'ID Mismatch'.tr,
|
||
// content: Column(
|
||
// mainAxisSize: MainAxisSize.min,
|
||
// children: [
|
||
// const Icon(Icons.warning, size: 48, color: Colors.red),
|
||
// const SizedBox(height: 16),
|
||
// Text(
|
||
// "The national number on your driver’s license does not match the one on your ID document. Please verify and provide the correct documents."
|
||
// .tr,
|
||
// textAlign: TextAlign.center,
|
||
// style: AppStyle.title,
|
||
// ),
|
||
// const SizedBox(height: 16),
|
||
// IconButton(
|
||
// onPressed: () async {
|
||
// await Get.find<TextToSpeechController>().speakText(
|
||
// "The national number on your driver’s license does not match the one on your ID document. Please verify and provide the correct documents."
|
||
// .tr,
|
||
// );
|
||
// },
|
||
// icon: const Icon(Icons.volume_up),
|
||
// ),
|
||
// ],
|
||
// ),
|
||
// actions: [
|
||
// TextButton(
|
||
// onPressed: () {
|
||
// Get.back();
|
||
// },
|
||
// child: const Text('OK'),
|
||
// ),
|
||
// ],
|
||
// );
|
||
// }
|
||
// else if (responseCriminalRecordEgypt['FullName'] !=
|
||
// responseIdEgyptDriverLicense['name_arabic']) {
|
||
// Get.defaultDialog(
|
||
// barrierDismissible: false,
|
||
// title: 'Criminal Record Mismatch',
|
||
// content: Column(
|
||
// mainAxisSize: MainAxisSize.min,
|
||
// children: [
|
||
// const Icon(Icons.warning, size: 48, color: Colors.red),
|
||
// const SizedBox(height: 16),
|
||
// Text(
|
||
// 'The full name on your criminal record does not match the one on your driver’s license. Please verify and provide the correct documents.'
|
||
// .tr,
|
||
// textAlign: TextAlign.center,
|
||
// style: AppStyle.title,
|
||
// ),
|
||
// const SizedBox(height: 16),
|
||
// IconButton(
|
||
// onPressed: () async {
|
||
// await Get.find<TextToSpeechController>().speakText(
|
||
// 'The full name on your criminal record does not match the one on your driver’s license. Please verify and provide the correct documents.'
|
||
// .tr,
|
||
// );
|
||
// },
|
||
// icon: const Icon(Icons.volume_up),
|
||
// ),
|
||
// ],
|
||
// ),
|
||
// actions: [
|
||
// TextButton(
|
||
// onPressed: () {
|
||
// Get.back();
|
||
// },
|
||
// child: const Text('OK'),
|
||
// ),
|
||
// ],
|
||
// );
|
||
// }
|
||
else {
|
||
isEgypt ? await addDriverEgypt() : await addDriverForeign();
|
||
await addRegistrationCarEgypt();
|
||
|
||
if (isCarSaved && isDriverSaved) {
|
||
// DeviceController().getDeviceSerialNumber();
|
||
box.write(BoxName.phoneVerified, '1');
|
||
Get.offAll(() => HomeCaptain());
|
||
// Get.offAll(() => HomeCaptain());
|
||
}
|
||
}
|
||
}
|
||
|
||
String extractDOB(String nationalNumber) {
|
||
if (nationalNumber.length != 14) {
|
||
throw ArgumentError('National number must be 14 digits long.');
|
||
}
|
||
|
||
// Extract the first digit to determine the century
|
||
String firstDigit = nationalNumber[0];
|
||
|
||
// Extract year, month, and day parts
|
||
String yearPart = nationalNumber.substring(1, 3);
|
||
String monthPart = nationalNumber.substring(3, 5);
|
||
String dayPart = nationalNumber.substring(5, 7);
|
||
|
||
// Determine the year based on the first digit
|
||
int yearPrefix;
|
||
if (firstDigit == '2') {
|
||
yearPrefix = 1900;
|
||
} else if (firstDigit == '3') {
|
||
yearPrefix = 2000;
|
||
} else {
|
||
throw ArgumentError('Invalid first digit in national number.');
|
||
}
|
||
|
||
// Construct the full year
|
||
int year = yearPrefix + int.parse(yearPart);
|
||
|
||
// Format the date as YYYY-MM-DD
|
||
String dob =
|
||
'$year-${monthPart.padLeft(2, '0')}-${dayPart.padLeft(2, '0')}';
|
||
|
||
return dob;
|
||
}
|
||
|
||
Future<void> addDriverForeign() async {
|
||
isLoading = true;
|
||
update();
|
||
|
||
var payload = {
|
||
'first_name':
|
||
responseNonIdCardFront['full_name']?.toString().split(' ')[0] ??
|
||
'Not specified',
|
||
'last_name':
|
||
responseNonIdCardFront['full_name']?.toString().split(' ').last ??
|
||
'Not specified',
|
||
'email': box.read(BoxName.emailDriver)?.toString() ?? 'Not specified',
|
||
'phone': box.read(BoxName.phoneDriver)?.toString() ?? 'Not specified',
|
||
'id': box.read(BoxName.driverID)?.toString() ?? 'Not specified',
|
||
'password':
|
||
Get.put(LoginDriverController()).passwordController.text.isEmpty
|
||
? box.read(BoxName.emailDriver).toString()
|
||
: Get.find<LoginDriverController>()
|
||
.passwordController
|
||
.text
|
||
.toString(),
|
||
'gender': responseNonIdCardFront['gender']?.toString() ?? 'Not specified',
|
||
'license_type': 'Foreign',
|
||
'national_number':
|
||
responseNonIdCardFront['passport_no']?.toString() ?? 'Not specified',
|
||
'name_arabic':
|
||
responseNonIdCardFront['full_name']?.toString() ?? 'Not specified',
|
||
'name_english': 'Not specified',
|
||
'issue_date':
|
||
responseNonIdCardBack['issueDate']?.toString() ?? 'Not specified',
|
||
'expiry_date':
|
||
responseNonIdCardBack['residencyExpirationDate']?.toString() ??
|
||
'Not specified',
|
||
'license_categories': responseIdEgyptDriverLicense['license_categories']
|
||
is List
|
||
? responseIdEgyptDriverLicense['license_categories'].join(', ')
|
||
: responseIdEgyptDriverLicense['license_categories']?.toString() ??
|
||
'Not specified',
|
||
'address':
|
||
responseNonIdCardFront['address']?.toString() ?? 'Not specified',
|
||
'card_id':
|
||
responseNonIdCardFront['card_id']?.toString() ?? 'Not specified',
|
||
'occupation':
|
||
responseNonIdCardBack['workStatus']?.toString() ?? 'Not specified',
|
||
'education': 'Not specified',
|
||
'licenseIssueDate':
|
||
responseNonIdCardBack['issueDate']?.toString() ?? 'Not specified',
|
||
'religion':
|
||
responseNonIdCardFront['country']?.toString() ?? 'Not specified',
|
||
'status': 'yet',
|
||
'birthdate':
|
||
responseNonIdCardFront['birthdate']?.toString() ?? 'Not specified',
|
||
'maritalStatus': 'Not specified',
|
||
'site': responseNonIdCardFront['address']?.toString() ?? 'Not specified',
|
||
'employmentType':
|
||
responseNonIdCardBack['residencyType']?.toString() ?? 'Not specified',
|
||
};
|
||
|
||
try {
|
||
var res = await CRUD().post(link: AppLink.signUpCaptin, payload: payload);
|
||
|
||
var status1;
|
||
try {
|
||
status1 = jsonDecode(res);
|
||
} catch (e) {
|
||
throw FormatException("Invalid JSON response: $res");
|
||
}
|
||
|
||
isLoading = false;
|
||
update();
|
||
|
||
if (status1['status'] == 'success') {
|
||
isDriverSaved = true;
|
||
CRUD().post(
|
||
link: '${AppLink.seferGizaServer}/auth/captin/register.php',
|
||
payload: payload);
|
||
CRUD().post(
|
||
link: '${AppLink.seferAlexandriaServer}/auth/captin/register.php',
|
||
payload: payload);
|
||
mySnackbarSuccess('Foreign driver data saved successfully');
|
||
} else {
|
||
mySnackeBarError(
|
||
'${'Failed to save driver data'.tr}: ${status1['message']}');
|
||
}
|
||
} catch (e) {
|
||
isLoading = false;
|
||
update();
|
||
mySnackeBarError(
|
||
'An error occurred while saving driver data'.tr,
|
||
);
|
||
}
|
||
}
|
||
|
||
Future<void> addDriverEgypt() async {
|
||
isLoading = true;
|
||
update();
|
||
|
||
var payload = {
|
||
'first_name': responseIdEgyptDriverLicense['firstName']?.toString() ??
|
||
'Not specified',
|
||
'last_name': responseIdEgyptDriverLicense['lastName']?.toString() ??
|
||
'Not specified',
|
||
'email': box.read(BoxName.emailDriver)?.toString() ?? 'Not specified',
|
||
'phone': box.read(BoxName.phoneDriver)?.toString() ?? 'Not specified',
|
||
'id': box.read(BoxName.driverID)?.toString() ?? 'Not specified',
|
||
'password':
|
||
Get.put(LoginDriverController()).passwordController.text.isEmpty
|
||
? box.read(BoxName.emailDriver).toString()
|
||
: Get.find<LoginDriverController>()
|
||
.passwordController
|
||
.text
|
||
.toString(),
|
||
'gender': responseIdEgyptBack['gender']?.toString() ?? 'Not specified',
|
||
'license_type':
|
||
responseIdEgyptDriverLicense['license_type']?.toString() ??
|
||
'Not specified',
|
||
'national_number':
|
||
responseIdEgyptBack['nationalID']?.toString() ?? 'Not specified',
|
||
'name_arabic': responseIdEgyptDriverLicense['name_arabic']?.toString() ??
|
||
'Not specified',
|
||
'name_english':
|
||
responseIdEgyptDriverLicense['name_english']?.toString() ??
|
||
'Not specified',
|
||
'issue_date': responseIdEgyptDriverLicense['issue_date']?.toString() ??
|
||
'Not specified',
|
||
'expiry_date': responseIdEgyptDriverLicense['expiry_date']?.toString() ??
|
||
'Not specified',
|
||
'license_categories': responseIdEgyptDriverLicense['license_categories']
|
||
is List
|
||
? responseIdEgyptDriverLicense['license_categories'].join(', ')
|
||
: responseIdEgyptDriverLicense['license_categories']?.toString() ??
|
||
'Not specified',
|
||
'address': responseIdEgyptFront['address']?.toString() ?? 'Not specified',
|
||
'card_id': responseIdEgyptFront['card_id']?.toString() ?? 'Not specified',
|
||
'occupation':
|
||
responseIdEgyptBack['occupation']?.toString() ?? 'Not specified',
|
||
'education':
|
||
responseIdEgyptBack['occupation']?.toString() ?? 'Not specified',
|
||
'licenseIssueDate':
|
||
responseIdEgyptDriverLicense['issue_date']?.toString() ??
|
||
'Not specified',
|
||
'religion':
|
||
responseIdEgyptBack['religion']?.toString() ?? 'Not specified',
|
||
'status': 'yet',
|
||
'birthdate': extractDOB(
|
||
responseIdEgyptDriverLicense['national_number'].toString()),
|
||
'maritalStatus':
|
||
responseIdEgyptBack['maritalStatus']?.toString() ?? 'Not specified',
|
||
'site': responseIdEgyptDriverLicense['address']?.toString() ??
|
||
'Not specified',
|
||
'employmentType':
|
||
responseIdEgyptDriverLicense['employmentType']?.toString() ??
|
||
'Not specified',
|
||
};
|
||
|
||
try {
|
||
var res = await CRUD().post(link: AppLink.signUpCaptin, payload: payload);
|
||
|
||
// Check if response is valid JSON
|
||
var status1;
|
||
try {
|
||
status1 = jsonDecode(res);
|
||
} catch (e) {
|
||
throw FormatException("Invalid JSON response: $res");
|
||
}
|
||
|
||
isLoading = false;
|
||
update();
|
||
|
||
if (status1['status'] == 'success') {
|
||
isDriverSaved = true;
|
||
CRUD().post(
|
||
link: '${AppLink.seferGizaServer}/auth/captin/register.php',
|
||
payload: payload);
|
||
CRUD().post(
|
||
link: '${AppLink.seferAlexandriaServer}/auth/captin/register.php',
|
||
payload: payload);
|
||
mySnackbarSuccess('Driver data saved successfully');
|
||
} else {
|
||
mySnackeBarError(
|
||
'${'Failed to save driver data'.tr}: ${status1['message']}');
|
||
}
|
||
} catch (e) {
|
||
isLoading = false;
|
||
update();
|
||
mySnackeBarError(
|
||
'An error occurred while saving driver data'.tr,
|
||
);
|
||
}
|
||
}
|
||
|
||
addCriminalDocuments() async {
|
||
var res = await CRUD().post(link: AppLink.addCriminalDocuments, payload: {
|
||
"driverId": box.read(BoxName.driverID),
|
||
"IssueDate": responseCriminalRecordEgypt['IssueDate'],
|
||
"InspectionResult": responseCriminalRecordEgypt['InspectionResult'],
|
||
});
|
||
if (res != 'failure') {
|
||
mySnackbarSuccess('uploaded sucssefuly'.tr);
|
||
}
|
||
}
|
||
|
||
Future addRegistrationCarEgypt() async {
|
||
try {
|
||
isLoading = true;
|
||
update();
|
||
var res = await CRUD().post(link: AppLink.addRegisrationCar, payload: {
|
||
'driverID': box.read(BoxName.driverID),
|
||
'vin': responseIdCardDriverEgyptBack['chassis'].toString(),
|
||
'car_plate': responseIdCardDriverEgyptFront['car_plate'].toString(),
|
||
'make': responseIdCardDriverEgyptBack['make'].toString(),
|
||
'model': responseIdCardDriverEgyptBack['model'],
|
||
'year': responseIdCardDriverEgyptBack['year'].toString(),
|
||
'expiration_date':
|
||
responseIdCardDriverEgyptFront['LicenseExpirationDate'].toString(),
|
||
'color': responseIdCardDriverEgyptBack['color'],
|
||
'owner': responseIdCardDriverEgyptFront['owner'],
|
||
'color_hex': responseIdCardDriverEgyptBack['color_hex'].toString(),
|
||
'address': responseIdCardDriverEgyptFront['address'].toString(),
|
||
'displacement': responseIdCardDriverEgyptBack['engine'].toString(),
|
||
'fuel': responseIdCardDriverEgyptBack['fuel'].toString(),
|
||
'registration_date':
|
||
'${responseIdCardDriverEgyptBack['inspection_date']}',
|
||
});
|
||
isLoading = false;
|
||
update();
|
||
var status = jsonDecode(res);
|
||
if (status['status'] == 'success') {
|
||
isCarSaved = true;
|
||
mySnackbarSuccess('');
|
||
CRUD().post(
|
||
link:
|
||
'${AppLink.seferAlexandriaServer}/ride/RegisrationCar/add.php',
|
||
payload: {
|
||
'driverID': box.read(BoxName.driverID),
|
||
'vin': responseIdCardDriverEgyptBack['chassis'].toString(),
|
||
'car_plate':
|
||
responseIdCardDriverEgyptFront['car_plate'].toString(),
|
||
'make': responseIdCardDriverEgyptBack['make'].toString(),
|
||
'model': responseIdCardDriverEgyptBack['model'],
|
||
'year': responseIdCardDriverEgyptBack['year'].toString(),
|
||
'expiration_date':
|
||
responseIdCardDriverEgyptFront['LicenseExpirationDate']
|
||
.toString(),
|
||
'color': responseIdCardDriverEgyptBack['color'],
|
||
'owner': responseIdCardDriverEgyptFront['owner'],
|
||
'color_hex':
|
||
responseIdCardDriverEgyptBack['color_hex'].toString(),
|
||
'address': responseIdCardDriverEgyptFront['address'].toString(),
|
||
'displacement':
|
||
responseIdCardDriverEgyptBack['engine'].toString(),
|
||
'fuel': responseIdCardDriverEgyptBack['fuel'].toString(),
|
||
'registration_date':
|
||
'${responseIdCardDriverEgyptBack['inspection_date']}',
|
||
});
|
||
CRUD().post(
|
||
link: '${AppLink.seferGizaServer}/ride/RegisrationCar/add.php',
|
||
payload: {
|
||
'driverID': box.read(BoxName.driverID),
|
||
'vin': responseIdCardDriverEgyptBack['chassis'].toString(),
|
||
'car_plate':
|
||
responseIdCardDriverEgyptFront['car_plate'].toString(),
|
||
'make': responseIdCardDriverEgyptBack['make'].toString(),
|
||
'model': responseIdCardDriverEgyptBack['model'],
|
||
'year': responseIdCardDriverEgyptBack['year'].toString(),
|
||
'expiration_date':
|
||
responseIdCardDriverEgyptFront['LicenseExpirationDate']
|
||
.toString(),
|
||
'color': responseIdCardDriverEgyptBack['color'],
|
||
'owner': responseIdCardDriverEgyptFront['owner'],
|
||
'color_hex':
|
||
responseIdCardDriverEgyptBack['color_hex'].toString(),
|
||
'address': responseIdCardDriverEgyptFront['address'].toString(),
|
||
'displacement':
|
||
responseIdCardDriverEgyptBack['engine'].toString(),
|
||
'fuel': responseIdCardDriverEgyptBack['fuel'].toString(),
|
||
'registration_date':
|
||
'${responseIdCardDriverEgyptBack['inspection_date']}',
|
||
});
|
||
}
|
||
} catch (e) {}
|
||
}
|
||
|
||
final picker = ImagePicker();
|
||
Map<String, dynamic> responseMap = {};
|
||
Map<String, dynamic> responseCarLicenseMapJordan = {};
|
||
Map<String, dynamic> responseBackCarLicenseMap = {};
|
||
Map<String, dynamic> responseIdCardMap = {};
|
||
Map<String, dynamic> responseIdCardDriverEgyptBack = {};
|
||
Map<String, dynamic> responseForComplaint = {};
|
||
Map<String, dynamic> responseIdCardDriverEgyptFront = {};
|
||
Map<String, dynamic> responseIdEgyptFront = {};
|
||
Map<String, dynamic> responseNonIdCardFront = {};
|
||
Map<String, dynamic> responseNonIdCardBack = {};
|
||
Map<String, dynamic> responseCriminalRecordEgypt = {};
|
||
Map<String, dynamic> responseIdEgyptBack = {};
|
||
Map<String, dynamic> responseIdEgyptDriverLicense = {};
|
||
String? responseIdCardDriverEgypt1;
|
||
bool isloading = false;
|
||
bool isLoading = false;
|
||
bool isEgypt = true;
|
||
var image;
|
||
CroppedFile? croppedFile;
|
||
DateTime now = DateTime.now();
|
||
|
||
changeNationality() {
|
||
isEgypt = !isEgypt;
|
||
update();
|
||
}
|
||
|
||
Future<void> pickImage() async {
|
||
final pickedImage = await picker.pickImage(source: ImageSource.gallery);
|
||
|
||
if (pickedImage != null) {
|
||
image = File(pickedImage.path);
|
||
// Crop the image
|
||
croppedFile = await ImageCropper().cropImage(
|
||
sourcePath: image!.path,
|
||
uiSettings: [
|
||
AndroidUiSettings(
|
||
toolbarTitle: 'Cropper'.tr,
|
||
toolbarColor: AppColor.blueColor,
|
||
toolbarWidgetColor: AppColor.yellowColor,
|
||
initAspectRatio: CropAspectRatioPreset.original,
|
||
lockAspectRatio: false),
|
||
IOSUiSettings(
|
||
title: 'Cropper'.tr,
|
||
),
|
||
],
|
||
);
|
||
// image = croppedFile;
|
||
|
||
// Resize the image
|
||
final rawImage =
|
||
img.decodeImage(File(croppedFile!.path).readAsBytesSync());
|
||
final resizedImage =
|
||
img.copyResize(rawImage!, width: 800); // Adjust the width as needed
|
||
|
||
final appDir = await getTemporaryDirectory();
|
||
final resizedImagePath = '${appDir.path}/resized_image.jpg';
|
||
|
||
final resizedImageFile = File(resizedImagePath);
|
||
resizedImageFile.writeAsBytesSync(
|
||
img.encodeJpg(resizedImage)); // Save the resized image as JPEG
|
||
|
||
image = resizedImageFile;
|
||
update();
|
||
}
|
||
}
|
||
|
||
DocumentType checkDocumentType(String text) {
|
||
// Convert text to lowercase and remove all spaces and new lines
|
||
text = text.toLowerCase().replaceAll(RegExp(r'\s+'), '');
|
||
|
||
// Keywords for each document type
|
||
final Map<DocumentType, List<String>> keywords = {
|
||
DocumentType.carLicenseBack: ['شاسيه', 'موتور', 'سم٣'],
|
||
DocumentType.carLicenseFront: ['وزارةالداخلية', 'رخصةتسيير'],
|
||
DocumentType.idCardFront: [
|
||
'بطاقةتحقيقالشخصية',
|
||
'بطاقة تحقيق الشخصية',
|
||
'تحقيق'
|
||
],
|
||
DocumentType.idCardBack: ['البطاقةساريةحتى'],
|
||
DocumentType.driverLicense: ['قيادةخاصة', 'خاصه', 'قيادة'],
|
||
DocumentType.nonIdCardFront: ['Foreign Residence Card', 'أجنبي', 'جواز'],
|
||
DocumentType.nonIdCardBack: [
|
||
'نوع الإقامة',
|
||
'الإقامة',
|
||
'Cardexpiresbyendofresidencepermit'
|
||
],
|
||
};
|
||
|
||
// Check each document type
|
||
for (var entry in keywords.entries) {
|
||
if (entry.value.any((keyword) => text.contains(keyword))) {
|
||
return entry.key;
|
||
}
|
||
}
|
||
|
||
// If no match is found
|
||
return DocumentType.unknown;
|
||
}
|
||
|
||
Future<void> allMethodForAI(
|
||
String prompt, String linkPHP, String imagePath) async {
|
||
isLoading = true;
|
||
update();
|
||
|
||
try {
|
||
await ImageController().choosImage(linkPHP, imagePath);
|
||
|
||
// if (imagePath == 'driver_license') {
|
||
// await ImageController().choosFaceFromDriverLicense(linkPHP, 'face');
|
||
// }
|
||
|
||
await Future.delayed(const Duration(seconds: 2));
|
||
|
||
var extractedString =
|
||
await CRUD().arabicTextExtractByVisionAndAI(imagePath: imagePath);
|
||
var json = jsonDecode(extractedString);
|
||
// Log.print('extractedString: ${extractedString}');
|
||
var textValues = CRUD().extractTextFromLines(json);
|
||
Log.print('textValues: ${textValues}');
|
||
// Log.print('json: ${json}');
|
||
|
||
DocumentType detectedType = checkDocumentType(textValues);
|
||
String expectedDocument = getExpectedDocument(imagePath);
|
||
String detectedDocument = getDetectedDocument(detectedType);
|
||
|
||
bool isCorrectDocument = (detectedType == getExpectedType(imagePath));
|
||
|
||
if (!isCorrectDocument) {
|
||
MyDialog().getDialog('incorrect_document_title'.tr,
|
||
'${'expected'.tr}: $expectedDocument\n${'detected'.tr}: $detectedDocument',
|
||
() {
|
||
Get.back();
|
||
});
|
||
} else {
|
||
// Process the correct document
|
||
await Get.put(AI()).anthropicAI(textValues, prompt, imagePath);
|
||
}
|
||
} catch (e) {
|
||
MyDialog().getDialog('error'.tr, 'error_processing_document'.tr, () {
|
||
Get.back();
|
||
});
|
||
} finally {
|
||
isLoading = false;
|
||
update();
|
||
}
|
||
}
|
||
|
||
Future<void> allMethodForAINewCar(
|
||
String prompt, String linkPHP, String imagePath, String carID) async {
|
||
isLoading = true;
|
||
update();
|
||
|
||
try {
|
||
await ImageController().choosImageNewCAr(linkPHP, imagePath);
|
||
|
||
// if (imagePath == 'driver_license') {
|
||
// await ImageController().choosFaceFromDriverLicense(linkPHP, 'face');
|
||
// }
|
||
|
||
await Future.delayed(const Duration(seconds: 2));
|
||
|
||
var extractedString =
|
||
await CRUD().arabicTextExtractByVisionAndAI(imagePath: imagePath);
|
||
var json = jsonDecode(extractedString);
|
||
var textValues = CRUD().extractTextFromLines(json);
|
||
|
||
DocumentType detectedType = checkDocumentType(textValues);
|
||
String expectedDocument = getExpectedDocument(imagePath);
|
||
String detectedDocument = getDetectedDocument(detectedType);
|
||
|
||
bool isCorrectDocument = (detectedType == getExpectedType(imagePath));
|
||
|
||
if (!isCorrectDocument) {
|
||
MyDialog().getDialog('incorrect_document_title'.tr,
|
||
'${'expected'.tr}: $expectedDocument\n${'detected'.tr}: $detectedDocument',
|
||
() {
|
||
Get.back();
|
||
});
|
||
} else {
|
||
// Process the correct document
|
||
await Get.put(AI()).anthropicAI(textValues, prompt, imagePath);
|
||
}
|
||
} catch (e) {
|
||
MyDialog().getDialog('error'.tr, 'error_processing_document'.tr, () {
|
||
Get.back();
|
||
});
|
||
} finally {
|
||
isLoading = false;
|
||
update();
|
||
}
|
||
}
|
||
|
||
String getExpectedDocument(String imagePath) {
|
||
switch (imagePath) {
|
||
case 'car_front':
|
||
return 'car_license_front'.tr;
|
||
case 'car_back':
|
||
return 'car_license_back'.tr;
|
||
case 'id_back':
|
||
return 'id_card_back'.tr;
|
||
case 'id_front':
|
||
return 'id_card_front'.tr;
|
||
case 'non_id_front':
|
||
return 'non_id_card_front'.tr;
|
||
case 'non_id_back':
|
||
return 'non_id_card_back'.tr;
|
||
case 'driver_license':
|
||
return 'driver_license'.tr;
|
||
default:
|
||
return 'unknown_document'.tr;
|
||
}
|
||
}
|
||
|
||
DocumentType getExpectedType(String imagePath) {
|
||
switch (imagePath) {
|
||
case 'car_front':
|
||
return DocumentType.carLicenseFront;
|
||
case 'car_back':
|
||
return DocumentType.carLicenseBack;
|
||
case 'id_back':
|
||
return DocumentType.idCardBack;
|
||
case 'id_front':
|
||
return DocumentType.idCardFront;
|
||
case 'non_id_front':
|
||
return DocumentType.nonIdCardFront;
|
||
case 'non_id_back':
|
||
return DocumentType.nonIdCardBack;
|
||
case 'driver_license':
|
||
return DocumentType.driverLicense;
|
||
default:
|
||
return DocumentType.unknown;
|
||
}
|
||
}
|
||
|
||
String getDetectedDocument(DocumentType type) {
|
||
switch (type) {
|
||
case DocumentType.carLicenseFront:
|
||
return 'car_license_front'.tr;
|
||
case DocumentType.carLicenseBack:
|
||
return 'car_license_back'.tr;
|
||
case DocumentType.idCardFront:
|
||
return 'id_card_front'.tr;
|
||
case DocumentType.idCardBack:
|
||
return 'id_card_back'.tr;
|
||
case DocumentType.nonIdCardFront:
|
||
return 'non_id_card_front'.tr;
|
||
case DocumentType.nonIdCardBack:
|
||
return 'non_id_card_back'.tr;
|
||
case DocumentType.driverLicense:
|
||
return 'driver_license'.tr;
|
||
default:
|
||
return 'unknown_document'.tr;
|
||
}
|
||
}
|
||
|
||
Future<void> generateContent() async {
|
||
await pickImage();
|
||
if (image != null) {
|
||
final imageBytes = await image.readAsBytes();
|
||
final imageData = base64Encode(imageBytes);
|
||
|
||
var requestBody = jsonEncode({
|
||
'contents': [
|
||
{
|
||
'parts': [
|
||
{
|
||
'inlineData': {
|
||
'mimeType': 'image/jpeg',
|
||
'data': imageData,
|
||
},
|
||
},
|
||
{
|
||
'text':
|
||
'write json for all data as first name ,last name,dob,licenseID,expiration date,issued date asdress class type ,output json type',
|
||
},
|
||
],
|
||
},
|
||
],
|
||
'generationConfig': {
|
||
'temperature': 0.4,
|
||
'topK': 32,
|
||
'topP': 1,
|
||
'maxOutputTokens': 4096,
|
||
'stopSequences': [],
|
||
},
|
||
'safetySettings': [
|
||
{
|
||
'category': 'HARM_CATEGORY_HARASSMENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_HATE_SPEECH',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
],
|
||
});
|
||
|
||
final response = await http.post(
|
||
Uri.parse(
|
||
'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: requestBody,
|
||
);
|
||
|
||
if (response.statusCode == 200) {
|
||
var responseData = jsonDecode(response.body);
|
||
// Process the responseData as needed
|
||
|
||
var result =
|
||
responseData['candidates'][0]['content']['parts'][0]['text'];
|
||
RegExp regex = RegExp(r"```json([^`]*)```");
|
||
String? jsonString =
|
||
regex.firstMatch(responseData.toString())?.group(1)?.trim();
|
||
|
||
if (jsonString != null) {
|
||
// Convert the JSON object to a String
|
||
jsonString = jsonEncode(json.decode(jsonString));
|
||
} else {}
|
||
|
||
// Rest of your code...
|
||
} else {}
|
||
} else {}
|
||
}
|
||
|
||
Future getComplaintDataToAI() async {
|
||
var res = await CRUD().get(
|
||
link: AppLink.getComplaintAllDataForDriver,
|
||
payload: {'driver_id': box.read(BoxName.driverID).toString()},
|
||
);
|
||
if (res != 'failure') {
|
||
var d = jsonDecode(res)['message'];
|
||
return d;
|
||
} else {
|
||
return [
|
||
{'data': 'no data'}
|
||
];
|
||
}
|
||
}
|
||
|
||
Future<dynamic> anthropicAIForComplaint() async {
|
||
var dataComplaint = await getComplaintDataToAI();
|
||
var messagesData = [
|
||
{
|
||
"role": "user",
|
||
"content": [
|
||
{
|
||
"type": "text",
|
||
"text": "$dataComplaint ${AppInformation.complaintPrompt} "
|
||
}
|
||
]
|
||
}
|
||
];
|
||
var requestBody = jsonEncode({
|
||
"model": "claude-3-haiku-20240307",
|
||
"max_tokens": 1024,
|
||
"temperature": 0,
|
||
"system": "Json output only without any additional ",
|
||
"messages": messagesData,
|
||
});
|
||
final response = await http.post(
|
||
Uri.parse('https://api.anthropic.com/v1/messages'),
|
||
headers: {
|
||
'x-api-key': AK.anthropicAIkeySeferNew,
|
||
'anthropic-version': '2023-06-01',
|
||
'content-type': 'application/json'
|
||
},
|
||
body: requestBody,
|
||
);
|
||
if (response.statusCode == 200) {
|
||
var responseData = jsonDecode(utf8.decode(response.bodyBytes));
|
||
// Process the responseData as needed
|
||
|
||
responseForComplaint = jsonDecode(responseData['content'][0]['text']);
|
||
}
|
||
}
|
||
|
||
Future<dynamic> anthropicAI(
|
||
String payload, String prompt, String idType) async {
|
||
var messagesData = [
|
||
{
|
||
"role": "user",
|
||
"content": [
|
||
{"type": "text", "text": "$payload $prompt"}
|
||
]
|
||
}
|
||
];
|
||
var k = X.r(X.r(X.r(await getAIKey('CLAUDAISEFER'), cn), cC), cs);
|
||
var requestBody = jsonEncode({
|
||
"model": "claude-3-haiku-20240307",
|
||
"max_tokens": 1024,
|
||
"temperature": 0,
|
||
"system": "Json output only without any additional ",
|
||
"messages": messagesData,
|
||
});
|
||
|
||
final response = await http.post(
|
||
Uri.parse('https://api.anthropic.com/v1/messages'),
|
||
headers: {
|
||
'x-api-key': k,
|
||
'anthropic-version': '2023-06-01',
|
||
'content-type': 'application/json'
|
||
},
|
||
body: requestBody,
|
||
);
|
||
|
||
if (response.statusCode == 200) {
|
||
var responseData = jsonDecode(utf8.decode(response.bodyBytes));
|
||
// Process the responseData as needed
|
||
if (idType == 'car_back') {
|
||
responseIdCardDriverEgyptBack =
|
||
jsonDecode(responseData['content'][0]['text']);
|
||
} else if (idType == 'car_front') {
|
||
responseIdCardDriverEgyptFront =
|
||
jsonDecode(responseData['content'][0]['text']);
|
||
} else if (idType == 'id_front') {
|
||
responseIdEgyptFront = jsonDecode(responseData['content'][0]['text']);
|
||
} else if (idType == 'id_back') {
|
||
responseIdEgyptBack = jsonDecode(responseData['content'][0]['text']);
|
||
} else if (idType == 'driver_license') {
|
||
responseIdEgyptDriverLicense =
|
||
jsonDecode(responseData['content'][0]['text']);
|
||
} else if (idType == 'criminalRecord') {
|
||
responseCriminalRecordEgypt =
|
||
jsonDecode(responseData['content'][0]['text']);
|
||
} else if (idType == 'non_id_front') {
|
||
responseNonIdCardFront = jsonDecode(responseData['content'][0]['text']);
|
||
Log.print('responseNonIdCardFront: ${responseNonIdCardFront}');
|
||
} else if (idType == 'non_id_back') {
|
||
responseNonIdCardBack = jsonDecode(responseData['content'][0]['text']);
|
||
}
|
||
|
||
update();
|
||
return responseData.toString();
|
||
}
|
||
return responseIdCardDriverEgyptBack.toString();
|
||
}
|
||
|
||
Future<void> geminiAiExtraction(String prompt, payload, String idType) async {
|
||
var requestBody = jsonEncode({
|
||
"contents": [
|
||
{
|
||
"parts": [
|
||
{"text": "$payload $prompt"}
|
||
]
|
||
}
|
||
],
|
||
"generationConfig": {
|
||
"temperature": 1,
|
||
"topK": 64,
|
||
"topP": 0.95,
|
||
"maxOutputTokens": 8192,
|
||
"stopSequences": []
|
||
},
|
||
"safetySettings": [
|
||
{
|
||
"category": "HARM_CATEGORY_HARASSMENT",
|
||
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
||
},
|
||
{
|
||
"category": "HARM_CATEGORY_HATE_SPEECH",
|
||
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
||
},
|
||
{
|
||
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
|
||
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
||
},
|
||
{
|
||
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
|
||
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
|
||
}
|
||
]
|
||
});
|
||
|
||
final response = await http.post(
|
||
Uri.parse(
|
||
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
|
||
// 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent?key=${AK.geminiApi}'),
|
||
'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro:generateContent?key=${AK.geminiApi}'),
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: requestBody,
|
||
);
|
||
|
||
if (response.statusCode == 200) {
|
||
var responseData = jsonDecode(response.body);
|
||
// Process the responseData as needed
|
||
|
||
var result = responseData['candidates'][0]['content']['parts'][0]['text'];
|
||
RegExp regex = RegExp(r"```json([^`]*)```");
|
||
String? jsonString =
|
||
regex.firstMatch(responseData.toString())?.group(1)?.trim();
|
||
|
||
if (jsonString != null) {
|
||
// Convert the JSON object to a String
|
||
jsonString = jsonEncode(json.decode(jsonString));
|
||
|
||
if (idType == 'car_back') {
|
||
responseIdCardDriverEgyptBack = jsonDecode(jsonString);
|
||
} else if (idType == 'car_front') {
|
||
responseIdCardDriverEgyptFront = jsonDecode(jsonString);
|
||
} else if (idType == 'id_front') {
|
||
responseIdEgyptFront = jsonDecode(jsonString);
|
||
} else if (idType == 'id_back') {
|
||
responseIdEgyptBack = jsonDecode(jsonString);
|
||
} else if (idType == 'driver_license') {
|
||
responseIdEgyptDriverLicense = jsonDecode(jsonString);
|
||
} else if (idType == 'non_id_front') {
|
||
responseNonIdCardFront =
|
||
jsonDecode(responseData['content'][0]['text']);
|
||
} else if (idType == 'non_id_back') {
|
||
responseNonIdCardBack =
|
||
jsonDecode(responseData['content'][0]['text']);
|
||
}
|
||
|
||
update();
|
||
} else {
|
||
mySnackeBarError("JSON string not found");
|
||
}
|
||
|
||
// Rest of your code...
|
||
} else {}
|
||
}
|
||
|
||
Future<void> getDriverLicenseJordanContent() async {
|
||
await pickImage();
|
||
isloading = true;
|
||
update();
|
||
if (image != null) {
|
||
final imageBytes = await image.readAsBytes();
|
||
final imageData = base64Encode(imageBytes);
|
||
|
||
var requestBody = jsonEncode({
|
||
'contents': [
|
||
{
|
||
'parts': [
|
||
{
|
||
'inlineData': {
|
||
'mimeType': 'image/jpeg',
|
||
'data': imageData,
|
||
},
|
||
},
|
||
{
|
||
'text':
|
||
'write json for all data as first name ,last name,dob,id ,expiration date,issued date asdress class type,age in years ,output json type in arabic value and stay engish key and make date format like YYYY-MM-DD , for name please extract name in arabic in Name in json plus first_name ',
|
||
},
|
||
],
|
||
},
|
||
],
|
||
'generationConfig': {
|
||
'temperature': 0.4,
|
||
'topK': 32,
|
||
'topP': 1,
|
||
'maxOutputTokens': 4096,
|
||
'stopSequences': [],
|
||
},
|
||
'safetySettings': [
|
||
{
|
||
'category': 'HARM_CATEGORY_HARASSMENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_HATE_SPEECH',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
],
|
||
});
|
||
|
||
final response = await http.post(
|
||
Uri.parse(
|
||
'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: requestBody,
|
||
);
|
||
isloading = false;
|
||
update();
|
||
if (response.statusCode == 200) {
|
||
var responseData = jsonDecode(response.body);
|
||
// Process the responseData as needed
|
||
|
||
var result =
|
||
responseData['candidates'][0]['content']['parts'][0]['text'];
|
||
RegExp regex = RegExp(r"```json([^`]*)```");
|
||
String? jsonString =
|
||
regex.firstMatch(responseData.toString())?.group(1)?.trim();
|
||
|
||
if (jsonString != null) {
|
||
// Convert the JSON object to a String
|
||
jsonString = jsonEncode(json.decode(jsonString));
|
||
responseMap = jsonDecode(jsonString);
|
||
} else {}
|
||
|
||
// Rest of your code...
|
||
} else {}
|
||
} else {}
|
||
}
|
||
|
||
Future<void> getCarLicenseJordanContent() async {
|
||
await pickImage();
|
||
isloading = true;
|
||
update();
|
||
if (image != null) {
|
||
final imageBytes = await image.readAsBytes();
|
||
final imageData = base64Encode(imageBytes);
|
||
|
||
var requestBody = jsonEncode({
|
||
'contents': [
|
||
{
|
||
'parts': [
|
||
{
|
||
'inlineData': {
|
||
'mimeType': 'image/jpeg',
|
||
'data': imageData,
|
||
},
|
||
},
|
||
{
|
||
'text':
|
||
'''Extract the following information from the front face of the Jordanian ID card:
|
||
Name
|
||
National ID number
|
||
Gender
|
||
Date of birth
|
||
Output the extracted information in the following JSON format''',
|
||
},
|
||
],
|
||
},
|
||
],
|
||
'generationConfig': {
|
||
'temperature': 0.4,
|
||
'topK': 32,
|
||
'topP': 1,
|
||
'maxOutputTokens': 4096,
|
||
'stopSequences': [],
|
||
},
|
||
'safetySettings': [
|
||
{
|
||
'category': 'HARM_CATEGORY_HARASSMENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_HATE_SPEECH',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
],
|
||
});
|
||
|
||
final response = await http.post(
|
||
Uri.parse(
|
||
// 'https://${API_ENDPOINT}/v1/projects/${PROJECT_ID}/locations/${LOCATION_ID}/publishers/google/models/${MODEL_ID}:streamGenerateContent'),
|
||
'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: requestBody,
|
||
);
|
||
isloading = false;
|
||
update();
|
||
if (response.statusCode == 200) {
|
||
var responseData = jsonDecode(response.body);
|
||
// Process the responseData as needed
|
||
|
||
var result =
|
||
responseData['candidates'][0]['content']['parts'][0]['text'];
|
||
RegExp regex = RegExp(r"```json([^`]*)```");
|
||
String? jsonString =
|
||
regex.firstMatch(responseData.toString())?.group(1)?.trim();
|
||
|
||
if (jsonString != null) {
|
||
// Convert the JSON object to a String
|
||
jsonString = jsonEncode(json.decode(jsonString));
|
||
responseCarLicenseMapJordan = jsonDecode(jsonString);
|
||
} else {}
|
||
|
||
// Rest of your code...
|
||
} else {}
|
||
} else {}
|
||
}
|
||
|
||
Future<void> jordanID() async {
|
||
await pickImage();
|
||
isloading = true;
|
||
update();
|
||
if (image != null) {
|
||
final imageBytes = await image.readAsBytes();
|
||
final imageData = base64Encode(imageBytes);
|
||
|
||
var requestBody = jsonEncode({
|
||
'contents': [
|
||
{
|
||
'parts': [
|
||
{
|
||
'inlineData': {
|
||
'mimeType': 'image/jpeg',
|
||
'data': imageData,
|
||
},
|
||
},
|
||
{
|
||
'text':
|
||
'''Extract the following information from the front face of the Jordanian ID card:
|
||
Name
|
||
National ID number
|
||
Gender
|
||
Date of birth
|
||
Output the extracted information in the following JSON format''',
|
||
},
|
||
],
|
||
},
|
||
],
|
||
'generationConfig': {
|
||
'temperature': 0.4,
|
||
'topK': 32,
|
||
'topP': 1,
|
||
'maxOutputTokens': 4096,
|
||
'stopSequences': [],
|
||
},
|
||
'safetySettings': [
|
||
{
|
||
'category': 'HARM_CATEGORY_HARASSMENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_HATE_SPEECH',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
],
|
||
});
|
||
|
||
final response = await http.post(
|
||
Uri.parse(
|
||
'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: requestBody,
|
||
);
|
||
isloading = false;
|
||
update();
|
||
if (response.statusCode == 200) {
|
||
var responseData = jsonDecode(response.body);
|
||
// Process the responseData as needed
|
||
|
||
var result =
|
||
responseData['candidates'][0]['content']['parts'][0]['text'];
|
||
RegExp regex = RegExp(r"```json([^`]*)```");
|
||
String? jsonString =
|
||
regex.firstMatch(responseData.toString())?.group(1)?.trim();
|
||
|
||
if (jsonString != null) {
|
||
// Convert the JSON object to a String
|
||
jsonString = jsonEncode(json.decode(jsonString));
|
||
responseCarLicenseMapJordan = jsonDecode(jsonString);
|
||
} else {}
|
||
|
||
// Rest of your code...
|
||
} else {}
|
||
} else {}
|
||
}
|
||
|
||
Future<void> carLicenseJordan() async {
|
||
await pickImage();
|
||
isloading = true;
|
||
update();
|
||
if (image != null) {
|
||
final imageBytes = await image.readAsBytes();
|
||
final imageData = base64Encode(imageBytes);
|
||
|
||
var requestBody = jsonEncode({
|
||
'contents': [
|
||
{
|
||
'parts': [
|
||
{
|
||
'inlineData': {
|
||
'mimeType': 'image/jpeg',
|
||
'data': imageData,
|
||
},
|
||
},
|
||
{
|
||
'text':
|
||
'''Extract the following information from the front face of the car license card in Jordan:
|
||
|
||
* name
|
||
* Address
|
||
* Vehicle type
|
||
* car_kind
|
||
* car_color
|
||
* Vehicle category
|
||
* car_year
|
||
* car_plate
|
||
* Registration type
|
||
* Usage type
|
||
* expire_date_of_license
|
||
|
||
Output the extracted information in the following JSON formate and make date format like YYYY-MM-DD''',
|
||
},
|
||
],
|
||
},
|
||
],
|
||
'generationConfig': {
|
||
'temperature': 0.4,
|
||
'topK': 32,
|
||
'topP': 1,
|
||
'maxOutputTokens': 4096,
|
||
'stopSequences': [],
|
||
},
|
||
'safetySettings': [
|
||
{
|
||
'category': 'HARM_CATEGORY_HARASSMENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_HATE_SPEECH',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
],
|
||
});
|
||
|
||
final response = await http.post(
|
||
Uri.parse(
|
||
'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro-vision-latest:generateContent?key=${AK.geminiApi}'),
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: requestBody,
|
||
);
|
||
isloading = false;
|
||
update();
|
||
if (response.statusCode == 200) {
|
||
var responseData = jsonDecode(response.body);
|
||
// Process the responseData as needed
|
||
|
||
var result =
|
||
responseData['candidates'][0]['content']['parts'][0]['text'];
|
||
RegExp regex = RegExp(r"```json([^`]*)```");
|
||
String? jsonString =
|
||
regex.firstMatch(responseData.toString())?.group(1)?.trim();
|
||
|
||
if (jsonString != null) {
|
||
// Convert the JSON object to a String
|
||
jsonString = jsonEncode(json.decode(jsonString));
|
||
responseCarLicenseMapJordan = jsonDecode(jsonString);
|
||
} else {}
|
||
|
||
// Rest of your code...
|
||
} else {}
|
||
} else {}
|
||
}
|
||
|
||
Future getTextFromCard(String prompt) async {
|
||
await pickImage();
|
||
isloading = true;
|
||
update();
|
||
if (image != null) {
|
||
final imageBytes = await image.readAsBytes();
|
||
final imageData = base64Encode(imageBytes);
|
||
|
||
var requestBody = jsonEncode({
|
||
'contents': [
|
||
{
|
||
'parts': [
|
||
{
|
||
'inlineData': {
|
||
'mimeType': 'image/jpeg',
|
||
'data': imageData,
|
||
},
|
||
},
|
||
{
|
||
'text': prompt,
|
||
},
|
||
],
|
||
},
|
||
],
|
||
'generationConfig': {
|
||
"temperature": 1,
|
||
"topK": 32,
|
||
"topP": 0.1,
|
||
"maxOutputTokens": 4096,
|
||
"stopSequences": []
|
||
},
|
||
'safetySettings': [
|
||
{
|
||
'category': 'HARM_CATEGORY_HARASSMENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_HATE_SPEECH',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
],
|
||
});
|
||
|
||
final response = await http.post(
|
||
Uri.parse(
|
||
'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.0-pro-vision-latest:generateContent?key=${AK.geminiApi}'),
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: requestBody,
|
||
);
|
||
isloading = false;
|
||
update();
|
||
if (response.statusCode == 200) {
|
||
var responseData = jsonDecode(response.body);
|
||
// Process the responseData as needed
|
||
|
||
var result =
|
||
responseData['candidates'][0]['content']['parts'][0]['text'];
|
||
RegExp regex = RegExp(r"```json([^`]*)```");
|
||
String? jsonString =
|
||
regex.firstMatch(responseData.toString())?.group(1)?.trim();
|
||
|
||
if (jsonString != null) {
|
||
// Convert the JSON object to a String
|
||
jsonString = jsonEncode(json.decode(jsonString));
|
||
responseBackCarLicenseMap = jsonDecode(jsonString);
|
||
} else {}
|
||
|
||
// Rest of your code...
|
||
} else {}
|
||
} else {}
|
||
}
|
||
|
||
Future<void> generateBackCarLicenseJordanContent() async {
|
||
await pickImage();
|
||
isloading = true;
|
||
update();
|
||
if (image != null) {
|
||
final imageBytes = await image.readAsBytes();
|
||
final imageData = base64Encode(imageBytes);
|
||
|
||
var requestBody = jsonEncode({
|
||
'contents': [
|
||
{
|
||
'parts': [
|
||
{
|
||
'inlineData': {
|
||
'mimeType': 'image/jpeg',
|
||
'data': imageData,
|
||
},
|
||
},
|
||
{
|
||
'text':
|
||
'write json output from extracting car license back face for these key ,vin,fuelType,passengerType,curbWeight,insuranceCompany,policyNumber,notes,insuranceType and output it json .dont add data else this image',
|
||
},
|
||
],
|
||
},
|
||
],
|
||
'generationConfig': {
|
||
'temperature': 0.4,
|
||
'topK': 343,
|
||
'topP': 1,
|
||
'maxOutputTokens': 4096,
|
||
'stopSequences': [],
|
||
},
|
||
'safetySettings': [
|
||
{
|
||
'category': 'HARM_CATEGORY_HARASSMENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_HATE_SPEECH',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
],
|
||
});
|
||
|
||
final response = await http.post(
|
||
Uri.parse(
|
||
'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: requestBody,
|
||
);
|
||
isloading = false;
|
||
update();
|
||
if (response.statusCode == 200) {
|
||
var responseData = jsonDecode(response.body);
|
||
// Process the responseData as needed
|
||
|
||
var result =
|
||
responseData['candidates'][0]['content']['parts'][0]['text'];
|
||
RegExp regex = RegExp(r"```json([^`]*)```");
|
||
String? jsonString =
|
||
regex.firstMatch(responseData.toString())?.group(1)?.trim();
|
||
|
||
if (jsonString != null) {
|
||
// Convert the JSON object to a String
|
||
jsonString = jsonEncode(json.decode(jsonString));
|
||
responseBackCarLicenseMap = jsonDecode(jsonString);
|
||
} else {}
|
||
|
||
// Rest of your code...
|
||
} else {}
|
||
} else {}
|
||
}
|
||
|
||
Future<void> getFromCarRegistration() async {
|
||
await pickImage();
|
||
if (image != null) {
|
||
final imageBytes = await image.readAsBytes();
|
||
final imageData = base64Encode(imageBytes);
|
||
|
||
var requestBody = jsonEncode({
|
||
'contents': [
|
||
{
|
||
'parts': [
|
||
{
|
||
'inlineData': {
|
||
'mimeType': 'image/jpeg',
|
||
'data': imageData,
|
||
},
|
||
},
|
||
{
|
||
'text':
|
||
'write output json from image for[ vin, make, model, year, expiration_date, color, owner, registration_date ],output json type ',
|
||
},
|
||
],
|
||
},
|
||
],
|
||
'generationConfig': {
|
||
'temperature': 0.4,
|
||
'topK': 32,
|
||
'topP': 1,
|
||
'maxOutputTokens': 4096,
|
||
'stopSequences': [],
|
||
},
|
||
'safetySettings': [
|
||
{
|
||
'category': 'HARM_CATEGORY_HARASSMENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_HATE_SPEECH',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
{
|
||
'category': 'HARM_CATEGORY_DANGEROUS_CONTENT',
|
||
'threshold': 'BLOCK_MEDIUM_AND_ABOVE',
|
||
},
|
||
],
|
||
});
|
||
|
||
final response = await http.post(
|
||
Uri.parse(
|
||
'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${AK.geminiApi}'),
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: requestBody,
|
||
);
|
||
|
||
if (response.statusCode == 200) {
|
||
var responseData = jsonDecode(response.body);
|
||
// Process the responseData as needed
|
||
var result =
|
||
responseData['candidates'][0]['content']['parts'][0]['text'];
|
||
RegExp regex = RegExp(r"```json([^`]*)```");
|
||
String? jsonString =
|
||
regex.firstMatch(responseData.toString())?.group(1)?.trim();
|
||
|
||
if (jsonString != null) {
|
||
// Convert the JSON object to a String
|
||
jsonString = jsonEncode(json.decode(jsonString));
|
||
} else {}
|
||
|
||
// Rest of your code...
|
||
} else {}
|
||
} else {}
|
||
}
|
||
|
||
List prompts = [];
|
||
getPrompt() async {
|
||
var res = await CRUD()
|
||
.get(link: AppLink.getPromptDriverDocumentsEgypt, payload: {});
|
||
if (res != 'failure') {
|
||
var d = jsonDecode(res)['message'];
|
||
prompts = d;
|
||
} else {}
|
||
}
|
||
|
||
getAIKey(String key) async {
|
||
var res =
|
||
await CRUD().get(link: AppLink.getapiKey, payload: {"keyName": key});
|
||
if (res != 'failure') {
|
||
var d = jsonDecode(res)['message'];
|
||
return d[key].toString();
|
||
} else {}
|
||
}
|
||
|
||
@override
|
||
void onInit() {
|
||
getPrompt();
|
||
super.onInit();
|
||
}
|
||
}
|