Spaces:
Running
Running
Update index.js
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.7.6';// Reference the elements that we will needconst status = document.getElementById('status');const fileUpload = document.getElementById('upload');const imageContainer = document.getElementById('container');const example = document.getElementById('example');const EXAMPLE_URL = 'https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/city-streets.jpg';// Create a new object detection pipelinestatus.textContent = 'Loading model...';const detector = await pipeline('object-detection', 'Xenova/detr-resnet-50');status.textContent = 'Ready';example.addEventListener('click', (e) => {e.preventDefault();detect(EXAMPLE_URL);});fileUpload.addEventListener('change', function (e) {const file = e.target.files[0];if (!file) {return;}const reader = new FileReader();// Set up a callback when the file is loadedreader.onload = e2 => detect(e2.target.result);reader.readAsDataURL(file);});// Detect objects in the imageasync function detect(img) {imageContainer.innerHTML = '';imageContainer.style.backgroundImage = `url(${img})`;status.textContent = 'Analysing...';const output = await detector(img, {threshold: 0.5,percentage: true,});status.textContent = '';output.forEach(renderBox);}// Render a bounding box and label on the imagefunction renderBox({ box, label }) {const { xmax, xmin, ymax, ymin } = box;// Generate a random color for the boxconst color = '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, 0);// Draw the boxconst boxElement = document.createElement('div');boxElement.className = 'bounding-box';Object.assign(boxElement.style, {borderColor: color,left: 100 * xmin + '%',top: 100 * ymin + '%',width: 100 * (xmax - xmin) + '%',height: 100 * (ymax - ymin) + '%',})// Draw labelconst labelElement = document.createElement('span');labelElement.textContent = label;labelElement.className = 'bounding-box-label';labelElement.style.backgroundColor = color;boxElement.appendChild(labelElement);imageContainer.appendChild(boxElement);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.7.6';// DOM elementsconst videoUrlInput = document.getElementById('video-url');const languageSelect = document.getElementById('language-select');const summarizeBtn = document.getElementById('summarize-btn');const statusDiv = document.getElementById('status');const outputDiv = document.getElementById('output');const outputContainer = document.getElementById('output-container');const statsDiv = document.getElementById('stats');// YouTube Transcript API function (using proxy)async function getYouTubeTranscript(videoId, language = 'en') {try {// Using a CORS proxy to fetch transcript// You can also use: https://yt-api.com/api/transcript?videoId=${videoId}&lang=${language}const response = await fetch(`https://yt-api.com/api/transcript?videoId=${videoId}&lang=${language}`,{headers: {'Accept': 'application/json',}});if (!response.ok) {const errorData = await response.json();throw new Error(errorData.error || 'Failed to fetch transcript');}const data = await response.json();if (!data.transcript || data.transcript.length === 0) {throw new Error('No transcript found for this video');}// Combine all text partsconst transcriptText = data.transcript.map(item => item.text).join(' ');return transcriptText;} catch (error) {// Fallback to alternate APItry {const response = await fetch(`https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${videoId}&format=json`);// This doesn't give transcript, just checking if video existsif (!response.ok) {throw new Error('Video not found');}throw new Error('Transcript not available for this video. Try another one.');} catch (fallbackError) {throw new Error(error.message || 'Failed to fetch transcript');}}}// Extract video ID from URLfunction extractVideoId(url) {if (!url) return null;url = url.trim();// Handle youtu.be formatif (url.includes('youtu.be')) {const videoId = url.split('/').pop().split('?')[0];return videoId;}// Handle youtube.com formatif (url.includes('youtube.com')) {// watch?v= formatif (url.includes('watch?v=')) {const videoId = url.split('watch?v=')[1].split('&')[0];return videoId;}// embed formatif (url.includes('/embed/')) {const videoId = url.split('/embed/')[1].split('?')[0];return videoId;}// Short URL formatif (url.includes('/v/')) {const videoId = url.split('/v/')[1].split('?')[0];return videoId;}}// If it's just the video ID (11 characters)if (/^[a-zA-Z0-9_-]{11}$/.test(url)) {return url;}return null;}// Summarize text using Transformers.jslet summarizer = null;async function loadSummarizer() {try {statusDiv.textContent = 'π Loading summarization model...';statusDiv.className = 'status loading';// Using a smaller model for better performance in browsersummarizer = await pipeline('summarization','Xenova/distilbart-cnn-6-6');statusDiv.textContent = 'β Model loaded! Ready to summarize.';statusDiv.className = 'status';return true;} catch (error) {console.error('Error loading model:', error);statusDiv.textContent = 'β Failed to load model. Please refresh and try again.';statusDiv.className = 'status error';return false;}}async function summarizeText(text) {if (!summarizer) {throw new Error('Summarizer not loaded');}// Check if text is long enoughconst words = text.split(/\s+/);if (words.length < 20) {return { summary: text, originalLength: words.length };}// Adjust max length based on inputconst maxLength = Math.min(150, Math.max(30, Math.floor(words.length / 2)));const minLength = Math.min(20, Math.floor(maxLength / 2));try {const result = await summarizer(text, {max_length: maxLength,min_length: minLength,do_sample: false,});return {summary: result[0].summary_text,originalLength: words.length};} catch (error) {console.error('Summarization error:', error);throw new Error('Failed to summarize text');}}// Main function to process videoasync function processVideo() {const url = videoUrlInput.value.trim();const language = languageSelect.value;if (!url) {outputDiv.innerHTML = `<div class="error-message">β οΈ Please enter a YouTube URL or video ID.</div>`;return;}// Extract video IDconst videoId = extractVideoId(url);if (!videoId) {outputDiv.innerHTML = `<div class="error-message">β Invalid YouTube URL or video ID.<br>Please use formats like:<br>β’ https://www.youtube.com/watch?v=VIDEO_ID<br>β’ https://youtu.be/VIDEO_ID<br>β’ Just the 11-character video ID</div>`;return;}// Disable button and show loadingsummarizeBtn.disabled = true;summarizeBtn.textContent = 'β³ Processing...';outputContainer.className = 'loading';statusDiv.textContent = 'π Fetching transcript...';statusDiv.className = 'status loading';try {// Fetch transcriptconst transcriptText = await getYouTubeTranscript(videoId, language);if (!transcriptText || transcriptText.trim().length === 0) {throw new Error('No transcript available');}statusDiv.textContent = 'π Generating summary...';// Summarizeconst result = await summarizeText(transcriptText);// Display resultsoutputDiv.innerHTML = `<div class="success-message"><strong>π Summary</strong><p style="margin-top: 10px;">${result.summary}</p></div>`;// Show statsstatsDiv.style.display = 'block';statsDiv.innerHTML = `π Original: ${result.originalLength} words`;statusDiv.textContent = 'β Summary generated successfully!';statusDiv.className = 'status';} catch (error) {console.error('Error:', error);outputDiv.innerHTML = `<div class="error-message">β ${error.message || 'An unexpected error occurred'}<br><br>π‘ Tips:<br>β’ Make sure the video has captions available<br>β’ Try selecting a different language<br>β’ Try a different video</div>`;statsDiv.style.display = 'none';statusDiv.textContent = 'β Error processing video';statusDiv.className = 'status error';} finally {// Re-enable buttonsummarizeBtn.disabled = false;summarizeBtn.textContent = 'π― Generate Summary';outputContainer.className = '';}}// Event listenerssummarizeBtn.addEventListener('click', processVideo);videoUrlInput.addEventListener('keypress', (e) => {if (e.key === 'Enter') {processVideo();}});// Example buttonsdocument.querySelectorAll('.example-btn').forEach(btn => {btn.addEventListener('click', () => {videoUrlInput.value = btn.dataset.url;processVideo();});});// Initialize appasync function init() {// Load the modelconst loaded = await loadSummarizer();if (loaded) {// Auto-process the example videosetTimeout(() => processVideo(), 500);}}// Start the appinit();// Handle errors globallywindow.addEventListener('error', (event) => {console.error('Global error:', event.error);statusDiv.textContent = 'β An error occurred. Please check the console for details.';statusDiv.className = 'status error';});
index.js+257-60