Spaces:
Running
Running
File size: 7,378 Bytes
ee7b2b5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 |
let apiKey = localStorage.getItem('rapidapi-key');
let uploadCount = parseInt(localStorage.getItem('upload-count') || '0');
let currentImageUrl = null; // Store the current image URL
// Initialize the app
document.addEventListener('DOMContentLoaded', () => {
updateUploadCount();
updateApiStatus();
// Load API key if exists
if (apiKey) {
document.getElementById('apiKey').value = apiKey;
}
// Event listener for image URL input
const imageUrlInput = document.getElementById('imageUrlInput');
imageUrlInput.addEventListener('input', (e) => {
currentImageUrl = e.target.value.trim();
updateApiStatus(); // Re-evaluate check button state after URL input
});
});
function updateUploadCount() {
document.getElementById('uploadCount').textContent = uploadCount;
}
function updateApiStatus() {
const statusIndicator = document.getElementById('apiStatus');
const statusDot = statusIndicator.querySelector('.status-dot');
const statusText = statusIndicator.querySelector('.status-text');
const checkBtn = document.getElementById('checkBtn');
const imageUrlProvided = currentImageUrl && isValidUrl(currentImageUrl);
if (apiKey) {
statusDot.classList.add('active');
statusText.textContent = 'API Key Configured';
// Only enable check button if an image URL is also provided and valid
checkBtn.disabled = !imageUrlProvided;
} else {
statusDot.classList.remove('active');
statusText.textContent = 'API Key Required';
checkBtn.disabled = true;
}
}
function saveApiKey() {
const input = document.getElementById('apiKey');
const btn = input.nextElementSibling;
if (!input.value.trim()) {
showNotification('Please enter a valid API key', 'error');
return;
}
btn.classList.add('loading');
// Simulate API key validation
setTimeout(() => {
apiKey = input.value.trim();
localStorage.setItem('rapidapi-key', apiKey);
btn.classList.remove('loading');
updateApiStatus();
showNotification('API key saved successfully!', 'success');
}, 1000);
}
function clearAll() {
document.getElementById('imageUrlInput').value = '';
currentImageUrl = null;
document.getElementById('resultSection').style.display = 'none';
updateApiStatus(); // Update check button state after clearing
}
function isValidUrl(string) {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}
async function checkAuthenticity() {
const checkBtn = document.getElementById('checkBtn');
if (!currentImageUrl || !isValidUrl(currentImageUrl)) {
showNotification('Please enter a valid image URL to analyze', 'error');
return;
}
if (!apiKey) {
showNotification('Please save your RapidAPI key first.', 'error');
return;
}
checkBtn.classList.add('loading');
try {
const response = await fetch('https://product-authentication-api-fake-vs-real-item-detector.p.rapidapi.com/check', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-rapidapi-host': 'product-authentication-api-fake-vs-real-item-detector.p.rapidapi.com',
'x-rapidapi-key': apiKey
},
body: JSON.stringify({
image_url: currentImageUrl // Send the provided image URL to the API
})
});
if (!response.ok) {
throw new Error(`API Error: ${response.status}`);
}
const result = await response.json();
displayResult(result);
// Update upload count
uploadCount++;
localStorage.setItem('upload-count', uploadCount.toString());
updateUploadCount();
} catch (error) {
console.error('Error:', error);
showNotification('Authentication check failed. Please try again.', 'error');
// For demo purposes, show a mock result even on error
const mockResult = {
status: 'fake', // Changed to fake for an example of error result
brand: 'Unknown',
description: 'Could not verify authenticity. Please try another image or check the URL.'
};
displayResult(mockResult);
} finally {
checkBtn.classList.remove('loading');
}
}
function displayResult(result) {
const resultSection = document.getElementById('resultSection');
const resultBadge = document.getElementById('resultBadge');
const resultImage = document.getElementById('resultImage');
const resultBrand = document.getElementById('resultBrand');
const resultStatus = document.getElementById('resultStatus');
const resultDescription = document.getElementById('resultDescription');
// Update badge
resultBadge.className = `result-badge ${result.status}`;
resultBadge.querySelector('.badge-text').textContent = result.status === 'real' ? 'Authentic' : 'Fake';
// Update image - use the URL stored in currentImageUrl
resultImage.src = currentImageUrl;
// Update details
resultBrand.textContent = result.brand || 'Unknown';
resultStatus.textContent = result.status === 'real' ? 'Authentic Product' : 'Counterfeit Product';
resultDescription.textContent = result.description || 'No description available';
// Show result section with animation
resultSection.style.display = 'block';
setTimeout(() => {
resultSection.scrollIntoView({ behavior: 'smooth' });
}, 100);
showNotification(`Product analyzed: ${result.status === 'real' ? 'Authentic' : 'Counterfeit'}`, result.status === 'real' ? 'success' : 'warning');
}
function showNotification(message, type = 'info') {
// Create notification element
const notification = document.createElement('div');
notification.className = `notification ${type}`;
notification.textContent = message;
// Style the notification
Object.assign(notification.style, {
position: 'fixed',
top: '20px',
right: '20px',
padding: '1rem 1.5rem',
borderRadius: '12px',
fontWeight: '600',
fontSize: '0.875rem',
zIndex: '1000',
transform: 'translateX(400px)',
transition: 'transform 0.3s ease',
maxWidth: '300px',
boxShadow: '0 10px 25px rgba(0,0,0,0.1)'
});
// Set colors based on type
const colors = {
success: { bg: '#10B981', color: 'white' },
error: { bg: '#EF4444', color: 'white' },
warning: { bg: '#F59E0B', color: 'white' },
info: { bg: '#3B82F6', color: 'white' }
};
notification.style.backgroundColor = colors[type].bg;
notification.style.color = colors[type].color;
document.body.appendChild(notification);
// Animate in
setTimeout(() => {
notification.style.transform = 'translateX(0)';
}, 10);
// Remove after delay
setTimeout(() => {
notification.style.transform = 'translateX(400px)';
setTimeout(() => {
if (notification.parentNode) {
notification.parentNode.removeChild(notification);
}
}, 300);
}, 3000);
} |