Solve - Verify

This commit is contained in:
Rizqika 2024-12-09 10:31:58 +07:00
parent 1b2cb719fc
commit 1abf8cc4ac

View File

@ -19,7 +19,7 @@ const Verify = () => {
const [thresholdError, setThresholdError] = useState(''); const [thresholdError, setThresholdError] = useState('');
const [selectedImageName, setSelectedImageName] = useState(''); const [selectedImageName, setSelectedImageName] = useState('');
const [resultImageLabel, setResultImageLabel] = useState(''); const [resultImageLabel, setResultImageLabel] = useState('');
const inputRef = useRef(null); const fileInputRef = useRef(null);
const [showResult, setShowResult] = useState(false); const [showResult, setShowResult] = useState(false);
const [applicationId, setApplicationId] = useState(''); const [applicationId, setApplicationId] = useState('');
const [thresholdId, setThresholdId] = useState(''); const [thresholdId, setThresholdId] = useState('');
@ -137,176 +137,156 @@ const Verify = () => {
const handleImageUpload = (file) => { const handleImageUpload = (file) => {
setShowResult(false);
if (!file) { if (!file) {
setImageError('Please select a file'); setImageError('Please select a file');
return; return;
} }
// Check file size (2MB = 2 * 1024 * 1024 bytes) const maxSize = 2 * 1024 * 1024; // 2MB
const maxSize = 2 * 1024 * 1024;
if (file.size > maxSize) { if (file.size > maxSize) {
setImageError('File size exceeds 2MB limit'); setImageError('File size exceeds 2MB limit');
setFile(null);
setSelectedImageName('');
return; return;
} }
// Check file type using both extension and MIME type
const fileExtension = file.name.split('.').pop().toLowerCase(); const fileExtension = file.name.split('.').pop().toLowerCase();
const validExtensions = ['jpg', 'jpeg']; const validExtensions = ['jpg', 'jpeg'];
const validMimeTypes = ['image/jpeg', 'image/jpg']; const validMimeTypes = ['image/jpeg', 'image/jpg'];
if (!validExtensions.includes(fileExtension) || !validMimeTypes.includes(file.type)) { if (!validExtensions.includes(fileExtension) || !validMimeTypes.includes(file.type)) {
setImageError('Only JPG/JPEG files are allowed'); setImageError('Only JPG/JPEG files are allowed');
setFile(null);
setSelectedImageName('');
return; return;
} }
// Check image dimensions const previewUrl = URL.createObjectURL(file);
const img = new Image(); const img = new Image();
const objectUrl = URL.createObjectURL(file);
img.onload = () => { 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); setFile(file);
setSelectedImageName(file.name);
setImageUrl(previewUrl);
setImageError(''); setImageError('');
}; };
img.onerror = () => { img.onerror = () => {
URL.revokeObjectURL(objectUrl); URL.revokeObjectURL(previewUrl);
setImageError('Invalid image file'); setImageError('Invalid image file');
setFile(null);
setSelectedImageName('');
}; };
img.src = objectUrl; img.src = previewUrl;
}; };
// Cancel image upload
const handleImageCancel = () => { const handleImageCancel = () => {
setSelectedImageName(''); setSelectedImageName('');
setFile(null); setFile(null);
if (inputRef.current) { if (fileInputRef.current) fileInputRef.current.value = '';
inputRef.current.value = '';
}
}; };
const handleCheckClick = async () => { const validateForm = () => {
// Reset previous error messages // Reset all error states
setErrorMessage(''); setErrorMessage('');
setApplicationError(''); setApplicationError('');
setSubjectError(''); setSubjectError('');
setThresholdError(''); setThresholdError('');
setUploadError(''); setUploadError('');
let hasError = false; // Track if any errors occur let isValid = true;
// Validate the applicationId // Validate applicationId
if (!applicationId) { if (!applicationId) {
setApplicationError('Please select an Application ID before enrolling.'); setApplicationError('Please select an Application ID before enrolling.');
hasError = true; // Mark that an error occurred isValid = false;
} }
// Validate the subjectId // Validate subjectId
if (!subjectId) { if (!subjectId) {
setSubjectError('Please enter a Subject ID before enrolling.'); 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; const selectedThreshold = thresholdIds.find(threshold => threshold.name === thresholdId)?.name;
if (!selectedThreshold) { if (!selectedThreshold) {
setThresholdError('Invalid threshold selected.'); setThresholdError('Invalid threshold selected.');
hasError = true; // Mark that an error occurred isValid = false;
} }
// Validate image upload // Validate image
if (!selectedImageName) { if (!selectedImageName || !file) {
setUploadError('Please upload a face photo before verifying.'); 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 return isValid;
if (hasError) { };
return;
}
// Log the input values for debugging const handleCheckClick = () => {
console.log('Selected Image Name:', selectedImageName); if (!validateForm()) {
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.');
return; return;
} }
setIsLoading(true); setIsLoading(true);
setErrorMessage('');
try { const formData = new FormData();
const response = await fetch(`${BASE_URL}/face_recognition/verifiy`, { formData.append('application_id', applicationId);
method: 'POST', formData.append('threshold', thresholdIds.find(t => t.name === thresholdId).name);
headers: { formData.append('subject_id', subjectId);
'accept': 'application/json', formData.append('file', file);
'x-api-key': API_KEY,
},
body: formData,
});
const data = await response.json(); // Log input values
console.log('📝 Request Data:', {
selectedImageName,
applicationId,
subjectId,
threshold: thresholdId
});
// Log the response data for debugging fetch(`${BASE_URL}/face_recognition/verifiy`, {
console.log('API Response Data:', data); method: 'POST',
headers: {
if (response.ok) { 'accept': 'application/json',
if (data.details && data.details.data && data.details.data.result) { 'x-api-key': API_KEY,
const result = data.details.data.result; },
body: formData,
// Update selectedQuota with the quota received from API })
setSelectedQuota(result.quota); .then(response => {
if (!response.ok) {
if (result.image_url) { return response.json().then(errorData => {
const imageFileName = result.image_url.split('/').pop(); throw new Error(errorData.detail || 'Verification failed, please try again');
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);
} }
} catch (error) { return response.json();
console.error('Error:', error); })
setErrorMessage('An error occurred while making the request.'); .then(result => {
} finally { 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); setIsLoading(false);
} });
}; };
const fetchImage = async (imageFileName) => { const fetchImage = async (imageFileName) => {
setIsLoading(true); setIsLoading(true);
try { try {
@ -799,7 +779,7 @@ const Verify = () => {
> >
Browse Browse
</span> </span>
<p className="text-muted">Recommended size: 300x300 (Max File Size: 2MB)</p> <p className="text-muted">Recommended size: 320x200 (Max File Size: 2MB)</p>
<p className="text-muted">Supported file types: JPG, JPEG</p> <p className="text-muted">Supported file types: JPG, JPEG</p>
</div> </div>
} }