CoolFace
Apppublic

hariprasanth0507/pythonconverter

sourceHugging Faceupdated 1y agoView on Hugging Face
1likes
index.js77 linesDownload Raw Back to root
1import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.4.1';2 3// Reference the elements that we will need4const status = document.getElementById('status');5const fileUpload = document.getElementById('upload');6const imageContainer = document.getElementById('container');7const example = document.getElementById('example');8 9const EXAMPLE_URL = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/city-streets.jpg';10 11// Create a new object detection pipeline12status.textContent = 'Loading model...';13const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');14status.textContent = 'Ready';15 16example.addEventListener('click', (e) => {17    e.preventDefault();18    detect(EXAMPLE_URL);19});20 21fileUpload.addEventListener('change', function (e) {22    const file = e.target.files[0];23    if (!file) {24        return;25    }26 27    const reader = new FileReader();28 29    // Set up a callback when the file is loaded30    reader.onload = e2 => detect(e2.target.result);31 32    reader.readAsDataURL(file);33});34 35 36// Detect objects in the image37async function detect(img) {38    imageContainer.innerHTML = '';39    imageContainer.style.backgroundImage = `url(${img})`;40 41    status.textContent = 'Analysing...';42    const output = await detector(img, {43        threshold: 0.5,44        percentage: true,45    });46    status.textContent = '';47    output.forEach(renderBox);48}49 50// Render a bounding box and label on the image51function renderBox({ box, label }) {52    const { xmax, xmin, ymax, ymin } = box;53 54    // Generate a random color for the box55    const color = '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, 0);56 57    // Draw the box58    const boxElement = document.createElement('div');59    boxElement.className = 'bounding-box';60    Object.assign(boxElement.style, {61        borderColor: color,62        left: 100 * xmin + '%',63        top: 100 * ymin + '%',64        width: 100 * (xmax - xmin) + '%',65        height: 100 * (ymax - ymin) + '%',66    })67 68    // Draw label69    const labelElement = document.createElement('span');70    labelElement.textContent = label;71    labelElement.className = 'bounding-box-label';72    labelElement.style.backgroundColor = color;73 74    boxElement.appendChild(labelElement);75    imageContainer.appendChild(boxElement);76}77