import React, { useState, useEffect } from 'react'; import { Card } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Upload, Image as ImageIcon } from 'lucide-react'; const ObjectDetector = () => { const [status, setStatus] = useState('Loading model...'); const [detections, setDetections] = useState([]); const [currentImage, setCurrentImage] = useState(null); const [detector, setDetector] = useState(null); // Initialize the model useEffect(() => { const initModel = async () => { try { const { pipeline, env } = await import('https://cdn.jsdelivr.net/npm/@xenova/transformers@2.10.1'); env.allowLocalModels = false; const model = await pipeline('object-detection', 'Xenova/detr-resnet-50'); setDetector(model); setStatus('Ready'); } catch (error) { console.error('Error loading model:', error); setStatus('Error loading model'); } }; initModel(); }, []); const handleFileUpload = (event) => { const file = event.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = (e) => { setCurrentImage(e.target.result); detectObjects(e.target.result); }; reader.readAsDataURL(file); }; const handleExampleImage = () => { const EXAMPLE_URL = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/city-streets.jpg'; setCurrentImage(EXAMPLE_URL); detectObjects(EXAMPLE_URL); }; const detectObjects = async (img) => { if (!detector) return; setStatus('Analyzing...'); try { const output = await detector(img, { threshold: 0.5, percentage: true, }); setDetections(output.map((det, index) => ({ ...det, id: index + 1 }))); setStatus(''); } catch (error) { console.error('Error detecting objects:', error); setStatus('Error analyzing image'); } }; return (
{status && (
{status}
)} {currentImage && (
Uploaded {detections.map((detection) => (
{detection.label} ({(detection.score * 100).toFixed(1)}%)
))}
)} {detections.length > 0 && (
{detections.map((detection) => ( ))}
Object Confidence Location
{detection.label} {(detection.score * 100).toFixed(1)}%
x: {detection.box.xmin.toFixed(1)}% - {detection.box.xmax.toFixed(1)}%
y: {detection.box.ymin.toFixed(1)}% - {detection.box.ymax.toFixed(1)}%
)}
); }; export default ObjectDetector;