import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:convert'; import 'package:crypto/crypto.dart'; 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/env/env.dart'; import 'package:sefer_driver/main.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 '../firebase/notification_service.dart'; import 'encrypt_decrypt.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(); 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": 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 // Get.put(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 // ); NotificationService.sendNotification( target: jsonDecode(res)['message'][0]['token'].toString(), title: 'You have received a gift token!'.tr, body: 'for '.tr + box.read(BoxName.phoneDriver).toString(), isTopic: false, // Important: this is a token tone: 'tone2', driverList: [], category: 'You have received a gift token!', ); } 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 addDriverAndCarEgypt() async { final today = DateTime.now(); // رخصة القيادة final drvExpiry = DateTime.tryParse(licenceBackSy['expiry_date'] ?? ''); final drvExpired = drvExpiry != null && drvExpiry.isBefore(today); // فحص السيارة + الضرائب final inspDate = DateTime.tryParse(vehicleFrontSy['inspection_date'] ?? ''); final taxExpiry = DateTime.tryParse(vehicleBackSy['tax_expiry'] ?? ''); final inspExpired = inspDate != null && inspDate.isBefore(today); final taxExpired = taxExpiry != null && taxExpiry.isBefore(today); // تطابق تاريخَي ميلاد الهوية غير المصرية final birthFront = DateTime.tryParse(responseNonIdCardFront['birthdate'] ?? ''); final birthBack = DateTime.tryParse(responseNonIdCardBack['birthDate'] ?? ''); final birthMismatch = (birthFront != null && birthBack != null && birthFront != birthBack); /* ـــــــ ❷ تحذيرات المستخدم ـــــــ */ if (!isEgypt && birthMismatch) { await _showWarnDialog( title: 'Birthdate Mismatch'.tr, text: 'Birthdate on ID front and back does not match.'.tr, ); return; } if (drvExpired) { await _showWarnDialog( title: 'Expired Driver’s License'.tr, text: 'Your driver’s license has expired. Please renew it.'.tr, ); return; } else { await addDriverEgypt(); await addRegistrationCarEgypt(); if (isCarSaved && isDriverSaved) { // DeviceController().getDeviceSerialNumber(); box.write(BoxName.phoneVerified, true); Get.find().loginWithGoogleCredential( box.read(BoxName.driverID).toString(), box.read(BoxName.emailDriver).toString(), ); } } } 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 _showWarnDialog( {required String title, required String text}) async { await Get.defaultDialog( title: title, content: Column( mainAxisSize: MainAxisSize.min, children: [ const Icon(Icons.warning, size: 48, color: Colors.red), const SizedBox(height: 16), Text(text, textAlign: TextAlign.center, style: AppStyle.title), const SizedBox(height: 16), IconButton( icon: const Icon(Icons.volume_up), onPressed: () async => await Get.find().speakText(text), ) ], ), actions: [ TextButton(onPressed: Get.back, child: const Text('OK')), ], ); } String shortHash(String password) { var bytes = utf8.encode(password); var digest = sha256.convert(bytes); return base64UrlEncode(digest.bytes); } Future addDriverEgypt() async { isLoading = true; update(); final loginDriverController = Get.put(LoginDriverController()); var pass = loginDriverController.passwordController.text.isEmpty ? '${box.read(BoxName.emailDriver)}${box.read(BoxName.driverID)}' : '${loginDriverController.emailController.text.toString()}${box.read(BoxName.driverID)}'; String hashedPassword = shortHash(pass); var payload = { 'first_name': (idFrontSy['full_name'].toString().split(' ')[0]) ?? 'Not specified', 'last_name': (idFrontSy['full_name'].toString().split(' ')[1]) ?? 'Not specified', 'email': 'Not specified', 'phone': box.read(BoxName.phoneDriver)?.toString(), 'id': box.read(BoxName.driverID)?.toString(), 'password': hashedPassword.toString(), 'gender': (idBackSy['gender'].toString()) ?? 'Not specified', 'license_type': (licenceBackSy['license_number'].toString()) ?? 'Not specified', 'national_number': (licenceFrontSy['national_number'].toString()) ?? 'Not specified', 'name_arabic': (licenceFrontSy['name_arabic'].toString()), 'issue_date': licenceBackSy['issue_date']?.toString() ?? 'Not specified', 'expiry_date': licenceBackSy['expiry_date']?.toString() ?? 'Not specified', 'license_categories': licenceBackSy['license_categories'] ?? 'Not specified', 'address': (idBackSy['address'].toString()) ?? 'Not specified', 'licenseIssueDate': licenceBackSy['issue_date'].toString() ?? 'Not specified', 'status': 'yet', 'birthdate': idFrontSy['dob'].toString(), 'maritalStatus': 'Not specified', 'site': (idBackSy['address'].toString()) ?? 'Not specified', 'employmentType': 'Not specified', }; try { var res = await CRUD().post(link: AppLink.signUpCaptin, payload: payload); // Check if response is valid JSON isLoading = false; update(); if (res['status'] == 'success') { isDriverSaved = true; box.write(BoxName.emailDriver, '${box.read(BoxName.phoneDriver)}${Env.email}'); mySnackbarSuccess('Driver data saved successfully'); } else { mySnackeBarError('${'Failed to save driver data'.tr}: }'); } } 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 payload = { 'driverID': box.read(BoxName.driverID), 'vin': vehicleBackSy['chassis'].toString(), 'car_plate': (vehicleFrontSy['car_plate'].toString()), 'make': (vehicleBackSy['make'].toString()), 'model': (vehicleBackSy['model']), 'year': vehicleBackSy['year'].toString(), 'expiration_date': vehicleFrontSy['inspection_date'].toString(), 'color': vehicleFrontSy['color'], 'owner': (vehicleFrontSy['owner']), 'color_hex': vehicleFrontSy['colorHex'].toString(), 'fuel': vehicleBackSy['fuel'].toString(), }; var res = await CRUD().post(link: AppLink.addRegisrationCar, payload: payload); isLoading = false; update(); var status = (res); if (status['status'] == 'success') { isCarSaved = true; mySnackbarSuccess(''); } } catch (e) {} } final picker = ImagePicker(); Map responseMap = {}; Map responseCarLicenseMapJordan = {}; Map responseBackCarLicenseMap = {}; Map responseIdCardMap = {}; Map responseIdCardDriverEgyptBack = {}; Map responseForComplaint = {}; Map responseIdCardDriverEgyptFront = {}; Map responseIdEgyptFront = {}; Map responseNonIdCardFront = {}; Map responseNonIdCardBack = {}; Map responseCriminalRecordEgypt = {}; Map responseIdEgyptBack = {}; Map 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 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> 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; } // تحفّظ كل استجابة على حدة Map idFrontSy = {}; Map idBackSy = {}; Map licenceFrontSy = {}; Map licenceBackSy = {}; Map vehicleFrontSy = {}; Map vehicleBackSy = {}; bool isLoadingidFrontSy = false; bool isLoadingidBackSy = false; bool isLoadingLicenceFrontSy = false; bool isLoadingLicenceBackSy = false; bool isLoadingVehicleFrontSy = false; bool isLoadingVehicleBackSy = false; Future sendToAI(String type, {required File imageFile}) async { final headers = { 'Authorization': 'Bearer ${r(box.read(BoxName.jwt)).split(AppInformation.addd)[0]}', 'X-HMAC-Auth': '${box.read(BoxName.hmac)}', }; final driverID = box.read(BoxName.driverID) ?? 'eddfdfdgfd'; if (driverID == null) { MyDialog() .getDialog("Error".tr, "User not logged in".tr, () => Get.back()); return; } try { isloading = true; update(); final uri = Uri.parse(AppLink.uploadImageToAi); // سكربتك الجديد final request = http.MultipartRequest("POST", uri); request.headers.addAll(headers); request.files .add(await http.MultipartFile.fromPath("image", imageFile.path)); request.fields['driver_id'] = driverID; request.fields['type'] = type; final response = await request.send(); final result = await http.Response.fromStream(response); if (result.statusCode == 200) { final responseData = jsonDecode(result.body); if (responseData['message'] != null && responseData['message']['data'] != null) { // final imageUrl = responseData['message']['image_url']; final data = responseData['message']['data']; switch (type) { case 'id_front_sy': idFrontSy = data; isLoadingidFrontSy = false; update(); break; case 'id_back_sy': idBackSy = data; isLoadingidBackSy = false; update(); break; case 'driving_license_sy_front': licenceFrontSy = data; isLoadingLicenceFrontSy = false; update(); break; case 'driving_license_sy_back': licenceBackSy = data; isLoadingLicenceBackSy = false; update(); break; case 'vehicle_license_sy_front': vehicleFrontSy = data; isLoadingVehicleFrontSy = false; update(); break; case 'vehicle_license_sy_back': vehicleBackSy = data; isLoadingVehicleBackSy = false; update(); break; } isloading = false; update(); } else { MyDialog().getDialog( "Error".tr, "AI failed to extract info".tr, () => Get.back()); } } else { MyDialog() .getDialog("Error".tr, "Upload or AI failed".tr, () => Get.back()); } } catch (e) { isloading = false; update(); MyDialog().getDialog("Error".tr, e.toString(), () => Get.back()); } } Future pickAndSendImage(String type) async { final picker = ImagePicker(); final pickedImage = await picker.pickImage(source: ImageSource.camera); if (pickedImage != null) { image = File(pickedImage.path); // Crop the image croppedFile = await ImageCropper().cropImage( sourcePath: image!.path, uiSettings: [ AndroidUiSettings( toolbarTitle: 'Cropper'.tr, toolbarColor: AppColor.accentColor, toolbarWidgetColor: AppColor.redColor, 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(); await sendToAI(type, imageFile: File(image.path)); } } Future 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); 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(); } } Future 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 '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 '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 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 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 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']); } else if (idType == 'non_id_back') { responseNonIdCardBack = jsonDecode(responseData['content'][0]['text']); } update(); return responseData.toString(); } return responseIdCardDriverEgyptBack.toString(); } Future 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 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 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 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 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 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 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(); } }