Spaces:
Running
Running
Download script.js from mikeqaqw/pixelperfect-ai-wizard: direct link, hf CLI and curl.
- Browser
- Download file 16.3 kB
-
https://huggingface.co/spaces/mikeqaqw/pixelperfect-ai-wizard/resolve/main/script.js
- Command line
-
hf download hf://spaces/mikeqaqw/pixelperfect-ai-wizard/script.js
-
curl -L -o script.js https://huggingface.co/spaces/mikeqaqw/pixelperfect-ai-wizard/resolve/main/script.js
16.3 kB
| import * as faceapi from 'https://cdn.jsdelivr.net/npm/@vladmandic/face-api@1.7.5/+esm'; | |
| // DOM Elements | |
| const canvas = document.getElementById('canvas'); | |
| const ctx = canvas.getContext('2d'); | |
| const overlay = document.getElementById('overlay'); | |
| const overlayCtx = overlay.getContext('2d'); | |
| const dropzone = document.getElementById('dropzone'); | |
| const fileInput = document.getElementById('fileInput'); | |
| const uploadBtn = document.getElementById('uploadBtn'); | |
| const imageContainer = document.getElementById('imageContainer'); | |
| // Expression Controls | |
| const smileRange = document.getElementById('smileRange'); | |
| const eyeRange = document.getElementById('eyeRange'); | |
| const eyebrowRange = document.getElementById('eyebrowRange'); | |
| const mouthRange = document.getElementById('mouthRange'); | |
| const faceWidthRange = document.getElementById('faceWidthRange'); | |
| const jawRange = document.getElementById('jawRange'); | |
| const showLandmarksSwitch = document.getElementById('showLandmarks'); | |
| const modelStatus = document.getElementById('modelStatus'); | |
| // State | |
| let originalImage = null; | |
| let currentImage = null; | |
| let detection = null; | |
| let expressions = { | |
| smile: 0, | |
| eyeOpenness: 0, | |
| eyebrowPosition: 0, | |
| mouthOpenness: 0, | |
| faceWidth: 0, | |
| jawDefinition: 0 | |
| }; | |
| // Initialize | |
| async function init() { | |
| // Load face-api models | |
| try { | |
| const modelPath = 'https://cdn.jsdelivr.net/npm/@vladmandic/face-api@1.7.5/model'; | |
| await Promise.all([ | |
| faceapi.nets.tinyFaceDetector.load(modelPath), | |
| faceapi.nets.faceLandmark68Net.load(modelPath), | |
| faceapi.nets.faceRecognitionNet.load(modelPath) | |
| ]); | |
| console.log('Face detection models loaded'); | |
| if (modelStatus) { | |
| modelStatus.innerHTML = '<sl-icon name="check-circle" style="color: var(--sl-color-success-600);"></sl-icon><span>AI models ready</span>'; | |
| setTimeout(() => modelStatus.style.display = 'none', 2000); | |
| } | |
| } catch (error) { | |
| console.error('Failed to load models:', error); | |
| if (modelStatus) { | |
| modelStatus.innerHTML = '<span style="color: var(--sl-color-danger-600);">Failed to load models</span>'; | |
| } | |
| } | |
| // Event listeners | |
| uploadBtn.addEventListener('click', () => fileInput.click()); | |
| fileInput.addEventListener('change', handleFileSelect); | |
| dropzone.addEventListener('click', () => fileInput.click()); | |
| // Drag & drop handlers | |
| dropzone.addEventListener('dragover', (e) => { | |
| e.preventDefault(); | |
| dropzone.classList.add('dragover'); | |
| e.dataTransfer.dropEffect = 'copy'; | |
| }); | |
| dropzone.addEventListener('dragleave', (e) => { | |
| e.preventDefault(); | |
| dropzone.classList.remove('dragover'); | |
| }); | |
| dropzone.addEventListener('drop', (e) => { | |
| e.preventDefault(); | |
| e.stopPropagation(); | |
| dropzone.classList.remove('dragover'); | |
| const files = e.dataTransfer.files; | |
| if (files.length > 0) { | |
| const file = files[0]; | |
| if (file.type.match('image.*')) { | |
| const dataTransfer = new DataTransfer(); | |
| dataTransfer.items.add(file); | |
| fileInput.files = dataTransfer.files; | |
| handleFileSelect({ target: fileInput }); | |
| } else { | |
| showToast('Please select an image file', 'danger'); | |
| } | |
| } | |
| }); | |
| // Expression control listeners | |
| smileRange.addEventListener('sl-change', (e) => { | |
| expressions.smile = parseInt(e.target.value); | |
| updateExpression(); | |
| }); | |
| eyeRange.addEventListener('sl-change', (e) => { | |
| expressions.eyeOpenness = parseInt(e.target.value); | |
| updateExpression(); | |
| }); | |
| eyebrowRange.addEventListener('sl-change', (e) => { | |
| expressions.eyebrowPosition = parseInt(e.target.value); | |
| updateExpression(); | |
| }); | |
| mouthRange.addEventListener('sl-change', (e) => { | |
| expressions.mouthOpenness = parseInt(e.target.value); | |
| updateExpression(); | |
| }); | |
| faceWidthRange.addEventListener('sl-change', (e) => { | |
| expressions.faceWidth = parseInt(e.target.value); | |
| updateExpression(); | |
| }); | |
| jawRange.addEventListener('sl-change', (e) => { | |
| expressions.jawDefinition = parseInt(e.target.value); | |
| updateExpression(); | |
| }); | |
| showLandmarksSwitch.addEventListener('sl-change', (e) => { | |
| if (e.target.checked) { | |
| drawLandmarks(); | |
| } else { | |
| overlayCtx.clearRect(0, 0, overlay.width, overlay.height); | |
| } | |
| }); | |
| // Preset buttons | |
| document.querySelectorAll('.preset-btn').forEach(btn => { | |
| btn.addEventListener('click', () => applyPreset(btn.dataset.preset)); | |
| }); | |
| // Reset and Download | |
| document.getElementById('resetBtn').addEventListener('click', resetExpressions); | |
| document.getElementById('downloadBtn').addEventListener('click', downloadImage); | |
| } | |
| // Handle file selection | |
| async function handleFileSelect(event) { | |
| const file = event.target.files[0]; | |
| if (!file) return; | |
| try { | |
| if (!file.type.match('image.*')) { | |
| throw new Error('Please select an image file (JPEG, PNG, etc.)'); | |
| } | |
| if (file.size > 5 * 1024 * 1024) { | |
| throw new Error('Image size must be less than 5MB'); | |
| } | |
| showLoading(true); | |
| const image = await loadImage(file); | |
| originalImage = image; | |
| currentImage = image; | |
| await displayImage(image); | |
| await detectFace(); | |
| showToast('Face detected! You can now edit expressions.', 'success'); | |
| } catch (error) { | |
| console.error('Upload error:', error); | |
| showToast(error.message, 'danger'); | |
| } finally { | |
| showLoading(false); | |
| fileInput.value = ''; | |
| } | |
| } | |
| function loadImage(file) { | |
| return new Promise((resolve, reject) => { | |
| const reader = new FileReader(); | |
| reader.onload = (e) => { | |
| const img = new Image(); | |
| img.onload = () => resolve(img); | |
| img.onerror = () => reject(new Error('Failed to load image')); | |
| img.src = e.target.result; | |
| }; | |
| reader.onerror = () => reject(new Error('Failed to read file')); | |
| reader.readAsDataURL(file); | |
| }); | |
| } | |
| async function displayImage(img) { | |
| canvas.hidden = false; | |
| overlay.hidden = false; | |
| dropzone.hidden = true; | |
| // Calculate dimensions | |
| const maxWidth = imageContainer.clientWidth - 40; | |
| const maxHeight = imageContainer.clientHeight - 40; | |
| let width = img.width; | |
| let height = img.height; | |
| const ratio = Math.min(maxWidth / width, maxHeight / height); | |
| width *= ratio; | |
| height *= ratio; | |
| canvas.width = width; | |
| canvas.height = height; | |
| overlay.width = width; | |
| overlay.height = height; | |
| ctx.drawImage(img, 0, 0, width, height); | |
| } | |
| async function detectFace() { | |
| if (!currentImage) return; | |
| try { | |
| const detections = await faceapi.detectAllFaces(canvas, new faceapi.TinyFaceDetectorOptions()) | |
| .withFaceLandmarks(); | |
| if (detections.length > 0) { | |
| detection = detections[0]; | |
| drawLandmarks(); | |
| } else { | |
| showToast('No face detected. Please try another image.', 'warning'); | |
| } | |
| } catch (error) { | |
| console.error('Face detection error:', error); | |
| showToast('Face detection failed. Please try again.', 'danger'); | |
| } | |
| } | |
| function drawLandmarks() { | |
| if (!detection || !showLandmarksSwitch.checked) return; | |
| overlayCtx.clearRect(0, 0, overlay.width, overlay.height); | |
| const landmarks = detection.landmarks; | |
| const positions = landmarks.getPositions(); | |
| // Draw face outline | |
| overlayCtx.strokeStyle = '#4f46e5'; | |
| overlayCtx.lineWidth = 2; | |
| overlayCtx.beginPath(); | |
| const jawOutline = landmarks.getJawOutline(); | |
| jawOutline.forEach((point, i) => { | |
| if (i === 0) overlayCtx.moveTo(point.x, point.y); | |
| else overlayCtx.lineTo(point.x, point.y); | |
| }); | |
| overlayCtx.stroke(); | |
| // Draw key points | |
| overlayCtx.fillStyle = '#4f46e5'; | |
| positions.forEach(point => { | |
| overlayCtx.beginPath(); | |
| overlayCtx.arc(point.x, point.y, 2, 0, 2 * Math.PI); | |
| overlayCtx.fill(); | |
| }); | |
| // Highlight expression control points | |
| const leftEye = landmarks.getLeftEye(); | |
| const rightEye = landmarks.getRightEye(); | |
| const mouth = landmarks.getMouth(); | |
| const leftEyebrow = landmarks.getLeftEyebrow(); | |
| const rightEyebrow = landmarks.getRightEyebrow(); | |
| overlayCtx.fillStyle = '#ef4444'; | |
| [leftEye[0], rightEye[0]].forEach(point => { | |
| overlayCtx.beginPath(); | |
| overlayCtx.arc(point.x, point.y, 4, 0, 2 * Math.PI); | |
| overlayCtx.fill(); | |
| }); | |
| overlayCtx.fillStyle = '#10b981'; | |
| mouth.forEach(point => { | |
| overlayCtx.beginPath(); | |
| overlayCtx.arc(point.x, point.y, 3, 0, 2 * Math.PI); | |
| overlayCtx.fill(); | |
| }); | |
| } | |
| function updateExpression() { | |
| if (!originalImage || !detection) return; | |
| // Clear and redraw original | |
| ctx.clearRect(0, 0, canvas.width, canvas.height); | |
| ctx.drawImage(originalImage, 0, 0, canvas.width, canvas.height); | |
| // Apply expression modifications based on sliders | |
| // This is a simulation using canvas transformations | |
| // In a full implementation, this would use a GAN or diffusion model | |
| const landmarks = detection.landmarks; | |
| // Create temporary canvas for manipulation | |
| const tempCanvas = document.createElement('canvas'); | |
| tempCanvas.width = canvas.width; | |
| tempCanvas.height = canvas.height; | |
| const tempCtx = tempCanvas.getContext('2d'); | |
| tempCtx.drawImage(originalImage, 0, 0, canvas.width, canvas.height); | |
| // Apply region-based adjustments | |
| ctx.globalCompositeOperation = 'source-over'; | |
| // Smile effect (mouth region manipulation) | |
| if (expressions.smile !== 0) { | |
| const mouth = landmarks.getMouth(); | |
| const centerX = mouth.map(p => p.x).reduce((a, b) => a + b) / mouth.length; | |
| const centerY = mouth.map(p => p.y).reduce((a, b) => a + b) / mouth.length; | |
| ctx.save(); | |
| ctx.translate(centerX, centerY); | |
| ctx.rotate((expressions.smile / 100) * 0.2); | |
| ctx.translate(-centerX, -centerY); | |
| // Draw mouth region with slight transformation | |
| const mouthBounds = getBounds(mouth); | |
| ctx.drawImage(tempCanvas, | |
| mouthBounds.minX - 10, mouthBounds.minY - 10, | |
| mouthBounds.maxX - mouthBounds.minX + 20, mouthBounds.maxY - mouthBounds.minY + 20, | |
| mouthBounds.minX - 10, mouthBounds.minY - 10, | |
| mouthBounds.maxX - mouthBounds.minX + 20, mouthBounds.maxY - mouthBounds.minY + 20 | |
| ); | |
| ctx.restore(); | |
| } | |
| // Eye openness (scale eyes vertically) | |
| if (expressions.eyeOpenness !== 0) { | |
| const leftEye = landmarks.getLeftEye(); | |
| const rightEye = landmarks.getRightEye(); | |
| [leftEye, rightEye].forEach(eye => { | |
| const center = getCenter(eye); | |
| const scale = 1 + (expressions.eyeOpenness / 200); | |
| ctx.save(); | |
| ctx.translate(center.x, center.y); | |
| ctx.scale(1, scale); | |
| ctx.translate(-center.x, -center.y); | |
| const bounds = getBounds(eye); | |
| ctx.clearRect(bounds.minX - 5, bounds.minY - 5, bounds.maxX - bounds.minX + 10, bounds.maxY - bounds.minY + 10); | |
| ctx.drawImage(tempCanvas, | |
| bounds.minX - 5, bounds.minY - 5, | |
| bounds.maxX - bounds.minX + 10, bounds.maxY - bounds.minY + 10, | |
| bounds.minX - 5, bounds.minY - 5, | |
| bounds.maxX - bounds.minX + 10, bounds.maxY - bounds.minY + 10 | |
| ); | |
| ctx.restore(); | |
| }); | |
| } | |
| // Eyebrow position | |
| if (expressions.eyebrowPosition !== 0) { | |
| const eyebrows = [...landmarks.getLeftEyebrow(), ...landmarks.getRightEyebrow()]; | |
| const bounds = getBounds(eyebrows); | |
| const offsetY = expressions.eyebrowPosition / 5; | |
| ctx.drawImage(tempCanvas, | |
| bounds.minX - 5, bounds.minY - 5 + offsetY, | |
| bounds.maxX - bounds.minX + 10, bounds.maxY - bounds.minY + 10, | |
| bounds.minX - 5, bounds.minY - 5, | |
| bounds.maxX - bounds.minX + 10, bounds.maxY - bounds.minY + 10 | |
| ); | |
| } | |
| drawLandmarks(); | |
| } | |
| function getBounds(points) { | |
| return { | |
| minX: Math.min(...points.map(p => p.x)), | |
| maxX: Math.max(...points.map(p => p.x)), | |
| minY: Math.min(...points.map(p => p.y)), | |
| maxY: Math.max(...points.map(p => p.y)) | |
| }; | |
| } | |
| function getCenter(points) { | |
| return { | |
| x: points.map(p => p.x).reduce((a, b) => a + b) / points.length, | |
| y: points.map(p => p.y).reduce((a, b) => a + b) / points.length | |
| }; | |
| } | |
| function applyPreset(preset) { | |
| switch(preset) { | |
| case 'happy': | |
| smileRange.value = 80; | |
| eyeRange.value = 20; | |
| eyebrowRange.value = 20; | |
| mouthRange.value = 30; | |
| break; | |
| case 'sad': | |
| smileRange.value = -60; | |
| eyeRange.value = -20; | |
| eyebrowRange.value = 40; | |
| mouthRange.value = 0; | |
| break; | |
| case 'surprised': | |
| smileRange.value = 0; | |
| eyeRange.value = 80; | |
| eyebrowRange.value = 80; | |
| mouthRange.value = 60; | |
| break; | |
| case 'angry': | |
| smileRange.value = -40; | |
| eyeRange.value = -30; | |
| eyebrowRange.value = -60; | |
| mouthRange.value = 0; | |
| break; | |
| case 'wink': | |
| // Asymmetric - would need more complex handling | |
| smileRange.value = 40; | |
| eyeRange.value = -100; // Squint one eye | |
| eyebrowRange.value = 20; | |
| mouthRange.value = 0; | |
| break; | |
| case 'neutral': | |
| default: | |
| smileRange.value = 0; | |
| eyeRange.value = 0; | |
| eyebrowRange.value = 0; | |
| mouthRange.value = 0; | |
| } | |
| expressions.smile = parseInt(smileRange.value); | |
| expressions.eyeOpenness = parseInt(eyeRange.value); | |
| expressions.eyebrowPosition = parseInt(eyebrowRange.value); | |
| expressions.mouthOpenness = parseInt(mouthRange.value); | |
| updateExpression(); | |
| showToast(`Applied ${preset} expression`, 'success'); | |
| } | |
| function resetExpressions() { | |
| smileRange.value = 0; | |
| eyeRange.value = 0; | |
| eyebrowRange.value = 0; | |
| mouthRange.value = 0; | |
| faceWidthRange.value = 0; | |
| jawRange.value = 0; | |
| expressions = { | |
| smile: 0, | |
| eyeOpenness: 0, | |
| eyebrowPosition: 0, | |
| mouthOpenness: 0, | |
| faceWidth: 0, | |
| jawDefinition: 0 | |
| }; | |
| if (originalImage) { | |
| ctx.clearRect(0, 0, canvas.width, canvas.height); | |
| ctx.drawImage(originalImage, 0, 0, canvas.width, canvas.height); | |
| drawLandmarks(); | |
| } | |
| showToast('Reset to original', 'neutral'); | |
| } | |
| function downloadImage() { | |
| if (!currentImage) { | |
| showToast('No image to download', 'warning'); | |
| return; | |
| } | |
| const link = document.createElement('a'); | |
| link.download = 'expression-edited-photo.png'; | |
| link.href = canvas.toDataURL(); | |
| link.click(); | |
| showToast('Image downloaded!', 'success'); | |
| } | |
| function showLoading(show) { | |
| let loadingDiv = document.querySelector('.loading'); | |
| if (!loadingDiv && show) { | |
| loadingDiv = document.createElement('div'); | |
| loadingDiv.className = 'loading'; | |
| loadingDiv.innerHTML = '<sl-spinner style="font-size: 3rem;"></sl-spinner><p>Processing...</p>'; | |
| imageContainer.appendChild(loadingDiv); | |
| } else if (loadingDiv && !show) { | |
| loadingDiv.remove(); | |
| } | |
| } | |
| function showToast(message, variant) { | |
| const toast = Object.assign(document.createElement('sl-alert'), { | |
| variant, | |
| closable: true, | |
| duration: 3000, | |
| innerHTML: message | |
| }); | |
| document.body.appendChild(toast); | |
| toast.toast(); | |
| } | |
| // Initialize the app | |
| document.addEventListener('DOMContentLoaded', init); |