From 1abf8cc4ac58edb13ac0c5839eb7192c4ad9a3e5 Mon Sep 17 00:00:00 2001 From: Rizqika Date: Mon, 9 Dec 2024 10:31:58 +0700 Subject: [PATCH] Solve - Verify --- .../FaceRecognition/Section/Verify.jsx | 186 ++++++++---------- 1 file changed, 83 insertions(+), 103 deletions(-) diff --git a/src/screens/Biometric/FaceRecognition/Section/Verify.jsx b/src/screens/Biometric/FaceRecognition/Section/Verify.jsx index 9189fe3..96134b1 100644 --- a/src/screens/Biometric/FaceRecognition/Section/Verify.jsx +++ b/src/screens/Biometric/FaceRecognition/Section/Verify.jsx @@ -19,7 +19,7 @@ const Verify = () => { const [thresholdError, setThresholdError] = useState(''); const [selectedImageName, setSelectedImageName] = useState(''); const [resultImageLabel, setResultImageLabel] = useState(''); - const inputRef = useRef(null); + const fileInputRef = useRef(null); const [showResult, setShowResult] = useState(false); const [applicationId, setApplicationId] = useState(''); const [thresholdId, setThresholdId] = useState(''); @@ -137,176 +137,156 @@ const Verify = () => { const handleImageUpload = (file) => { + setShowResult(false); if (!file) { setImageError('Please select a file'); return; } - // Check file size (2MB = 2 * 1024 * 1024 bytes) - const maxSize = 2 * 1024 * 1024; + const maxSize = 2 * 1024 * 1024; // 2MB if (file.size > maxSize) { setImageError('File size exceeds 2MB limit'); - setFile(null); - setSelectedImageName(''); return; } - // Check file type using both extension and MIME type const fileExtension = file.name.split('.').pop().toLowerCase(); const validExtensions = ['jpg', 'jpeg']; const validMimeTypes = ['image/jpeg', 'image/jpg']; - + if (!validExtensions.includes(fileExtension) || !validMimeTypes.includes(file.type)) { setImageError('Only JPG/JPEG files are allowed'); - setFile(null); - setSelectedImageName(''); return; } - // Check image dimensions + const previewUrl = URL.createObjectURL(file); const img = new Image(); - const objectUrl = URL.createObjectURL(file); - img.onload = () => { - URL.revokeObjectURL(objectUrl); - - if (img.width > 300 || img.height > 300) { - setImageError('Image dimensions must not exceed 300x300 pixels'); - setFile(null); - setSelectedImageName(''); - return; - } - - // All validations passed - setSelectedImageName(file.name); setFile(file); + setSelectedImageName(file.name); + setImageUrl(previewUrl); setImageError(''); }; img.onerror = () => { - URL.revokeObjectURL(objectUrl); + URL.revokeObjectURL(previewUrl); setImageError('Invalid image file'); - setFile(null); - setSelectedImageName(''); }; - img.src = objectUrl; + img.src = previewUrl; }; - + // Cancel image upload const handleImageCancel = () => { - setSelectedImageName(''); - setFile(null); - if (inputRef.current) { - inputRef.current.value = ''; - } + setSelectedImageName(''); + setFile(null); + if (fileInputRef.current) fileInputRef.current.value = ''; }; - const handleCheckClick = async () => { - // Reset previous error messages + const validateForm = () => { + // Reset all error states setErrorMessage(''); setApplicationError(''); setSubjectError(''); setThresholdError(''); setUploadError(''); - let hasError = false; // Track if any errors occur + let isValid = true; - // Validate the applicationId + // Validate applicationId if (!applicationId) { setApplicationError('Please select an Application ID before enrolling.'); - hasError = true; // Mark that an error occurred + isValid = false; } - // Validate the subjectId + // Validate subjectId if (!subjectId) { setSubjectError('Please enter a Subject ID before enrolling.'); - hasError = true; // Mark that an error occurred + isValid = false; } - // Validate thresholdId + // Validate threshold const selectedThreshold = thresholdIds.find(threshold => threshold.name === thresholdId)?.name; if (!selectedThreshold) { setThresholdError('Invalid threshold selected.'); - hasError = true; // Mark that an error occurred + isValid = false; } - // Validate image upload - if (!selectedImageName) { + // Validate image + if (!selectedImageName || !file) { setUploadError('Please upload a face photo before verifying.'); - hasError = true; // Mark that an error occurred + isValid = false; } - // If there are any errors, stop the function - if (hasError) { - return; - } + return isValid; + }; - // Log the input values for debugging - console.log('Selected Image Name:', selectedImageName); - console.log('Application ID:', applicationId); - console.log('Subject ID:', subjectId); - console.log('Selected Threshold:', selectedThreshold); - - // Prepare FormData for the API request - const formData = new FormData(); - formData.append('application_id', applicationId); - formData.append('threshold', selectedThreshold); - formData.append('subject_id', subjectId); - - if (file) { - formData.append('file', file, file.name); - } else { - setUploadError('Please upload an image file.'); + const handleCheckClick = () => { + if (!validateForm()) { return; } setIsLoading(true); + setErrorMessage(''); - try { - const response = await fetch(`${BASE_URL}/face_recognition/verifiy`, { - method: 'POST', - headers: { - 'accept': 'application/json', - 'x-api-key': API_KEY, - }, - body: formData, - }); + const formData = new FormData(); + formData.append('application_id', applicationId); + formData.append('threshold', thresholdIds.find(t => t.name === thresholdId).name); + formData.append('subject_id', subjectId); + formData.append('file', file); - const data = await response.json(); + // Log input values + console.log('📝 Request Data:', { + selectedImageName, + applicationId, + subjectId, + threshold: thresholdId + }); - // Log the response data for debugging - console.log('API Response Data:', data); - - if (response.ok) { - if (data.details && data.details.data && data.details.data.result) { - const result = data.details.data.result; - - // Update selectedQuota with the quota received from API - setSelectedQuota(result.quota); - - if (result.image_url) { - const imageFileName = result.image_url.split('/').pop(); - await fetchImage(imageFileName); - } - - setShowResult(true); - setVerified(result.verified); - setResultImageLabel(selectedImageName); - } - } else { - const errorMessage = data.message || data.detail || data.details?.message || 'An unknown error occurred.'; - setErrorMessage(errorMessage); + fetch(`${BASE_URL}/face_recognition/verifiy`, { + method: 'POST', + headers: { + 'accept': 'application/json', + 'x-api-key': API_KEY, + }, + body: formData, + }) + .then(response => { + if (!response.ok) { + return response.json().then(errorData => { + throw new Error(errorData.detail || 'Verification failed, please try again'); + }); } - } catch (error) { - console.error('Error:', error); - setErrorMessage('An error occurred while making the request.'); - } finally { + return response.json(); + }) + .then(result => { + console.log('📡 API Response:', result); + + if (result.details?.data?.result) { + const { result: verificationResult } = result.details.data; + + setSelectedQuota(verificationResult.quota); + setShowResult(true); + setVerified(verificationResult.verified); + setResultImageLabel(selectedImageName); + + if (verificationResult.image_url) { + const imageFileName = verificationResult.image_url.split('/').pop(); + return fetchImage(imageFileName); + } + } + }) + .catch(error => { + console.error('🔥 Request Failed:', error); + setErrorMessage(error.message); + setShowResult(false); + }) + .finally(() => { setIsLoading(false); - } + }); }; + const fetchImage = async (imageFileName) => { setIsLoading(true); try { @@ -799,7 +779,7 @@ const Verify = () => { > Browse -

Recommended size: 300x300 (Max File Size: 2MB)

+

Recommended size: 320x200 (Max File Size: 2MB)

Supported file types: JPG, JPEG

}