Download script.js from normalguy5/pdf-cheat-sheet-generator-pro: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/spaces/normalguy5/pdf-cheat-sheet-generator-pro/resolve/main/script.js
- Command line
-
hf download hf://spaces/normalguy5/pdf-cheat-sheet-generator-pro/script.js
-
curl -L -o script.js https://huggingface.co/spaces/normalguy5/pdf-cheat-sheet-generator-pro/resolve/main/script.js
11 kB
| document.addEventListener('DOMContentLoaded', function() { | |
| // DOM elements | |
| const uploadBtn = document.getElementById('upload-btn'); | |
| const pdfUpload = document.getElementById('pdf-upload'); | |
| const processingSection = document.getElementById('processing-section'); | |
| const resultsSection = document.getElementById('results-section'); | |
| const keyPointsContainer = document.getElementById('key-points-container'); | |
| const exportPdfBtn = document.getElementById('export-pdf'); | |
| // Event listeners | |
| uploadBtn.addEventListener('click', () => pdfUpload.click()); | |
| pdfUpload.addEventListener('change', handleFileUpload); | |
| exportPdfBtn.addEventListener('click', exportToPDF); | |
| // Initialize jsPDF | |
| if (typeof window.jspdf === 'undefined') { | |
| console.error('jsPDF not loaded'); | |
| } | |
| // Handle PDF file upload | |
| async function handleFileUpload(event) { | |
| const file = event.target.files[0]; | |
| if (!file) return; | |
| // Validate file type | |
| if (file.type !== 'application/pdf') { | |
| alert('Please upload a valid PDF file.'); | |
| return; | |
| } | |
| // Show processing state | |
| processingSection.classList.remove('hidden'); | |
| resultsSection.classList.add('hidden'); | |
| keyPointsContainer.innerHTML = ''; | |
| try { | |
| // Check file size (limit to 10MB) | |
| if (file.size > 10 * 1024 * 1024) { | |
| throw new Error('File size exceeds 10MB limit'); | |
| } | |
| // Extract text from PDF | |
| const text = await extractTextFromPDF(file); | |
| if (!text || text.trim().length === 0) { | |
| throw new Error('No text could be extracted from the PDF'); | |
| } | |
| // Process text to find key points | |
| const keyPoints = extractKeyPoints(text); | |
| if (!keyPoints || keyPoints.length === 0) { | |
| throw new Error('No key points could be extracted'); | |
| } | |
| // Display results | |
| displayKeyPoints(keyPoints); | |
| // Hide processing and show results | |
| processingSection.classList.add('hidden'); | |
| resultsSection.classList.remove('hidden'); | |
| } catch (error) { | |
| console.error('Error processing PDF:', error); | |
| processingSection.classList.add('hidden'); | |
| alert(`Error: ${error.message || 'Failed to process PDF. Please try again with a different file.'}`); | |
| // Reset file input | |
| pdfUpload.value = ''; | |
| } | |
| } | |
| // Extract text from PDF using PDF.js with better error handling | |
| async function extractTextFromPDF(file) { | |
| try { | |
| const arrayBuffer = await file.arrayBuffer(); | |
| // Initialize PDF.js with error handling | |
| const loadingTask = pdfjsLib.getDocument(arrayBuffer); | |
| const pdf = await loadingTask.promise; | |
| let fullText = ''; | |
| // Process each page with timeout protection | |
| for (let i = 1; i <= pdf.numPages; i++) { | |
| const page = await pdf.getPage(i); | |
| const textContent = await page.getTextContent(); | |
| const text = textContent.items.map(item => item.str).join(' '); | |
| fullText += text + '\n'; | |
| // Early exit if text is getting too large | |
| if (fullText.length > 500000) { | |
| console.warn('Text extraction stopped early due to size limits'); | |
| break; | |
| } | |
| } | |
| return fullText; | |
| } catch (error) { | |
| console.error('PDF text extraction failed:', error); | |
| throw new Error('Failed to read PDF content. The file may be corrupted or password protected.'); | |
| } | |
| } | |
| // Extract key points optimized for compact exam cheat sheets with better fallbacks | |
| function extractKeyPoints(text) { | |
| try { | |
| // First, split the text into sentences or logical chunks | |
| const sentences = text.split(/\.\s+|;\s+|\n+/).filter(s => s.length > 10); | |
| // Enhanced patterns for academic content with character limits | |
| const formulas = text.match(/([A-Za-z0-9]+\s?[=ββ <>β€β₯]\s?.{1,80})|([A-Za-z0-9]+\s?\(.+\)\s?[=ββ <>β€β₯]\s?.{1,80})/g) || []; | |
| const definitions = text.match(/([A-Za-z-]+\s?[:β’-]\s?.{1,80}?(?=[A-Z][a-z]|$|\n))/g) || []; | |
| const theorems = text.match(/(Theorem|Lemma|Corollary|Proposition)\s.{1,80}?(?=Proof|$|\n))/g) || []; | |
| const numberedItems = text.match(/(\d+[.)]\s?.{1,80}?(?=\n|$))/g) || []; | |
| const importantPhrases = sentences.filter(s => | |
| s.includes('important') || s.includes('note') || s.includes('must') || | |
| s.includes('key') || s.includes('critical') || s.includes('essential') || | |
| s.includes('definition') || s.includes('formula') || s.includes('equation') | |
| ); | |
| // Fallback if no matches found - use first sentences | |
| if (formulas.length + definitions.length + theorems.length + numberedItems.length + importantPhrases.length === 0) { | |
| return sentences | |
| .slice(0, 100) | |
| .map(s => truncateText(s.trim().replace(/\s+/g, ' '), 80)); | |
| } | |
| // Process and format for maximum density with character limits | |
| const allPoints = [ | |
| ...formulas.map(f => `π ${truncateText(f.trim().replace(/\s+/g, ' '), 80)}`), | |
| ...definitions.map(d => `π ${truncateText(d.trim().replace(/\s+/g, ' ').replace(/[:β’-]\s?/, ': '), 80)}`), | |
| ...theorems.map(t => `π§ ${truncateText(t.trim().replace(/\s+/g, ' '), 80)}`), | |
| ...numberedItems.map(n => `# ${truncateText(n.trim().replace(/\s+/g, ' '), 80)}`), | |
| ...importantPhrases.map(p => `β ${truncateText(p.trim().replace(/\s+/g, ' '), 80)}`) | |
| ]; | |
| // Remove duplicates and sort by length (shorter first) | |
| return [...new Set(allPoints)] | |
| .sort((a, b) => a.length - b.length) | |
| .slice(0, 100); // More items but each is shorter | |
| } catch (error) { | |
| console.error('Key point extraction failed:', error); | |
| // Fallback to simple text chunks | |
| return text.split('\n') | |
| .filter(line => line.trim().length > 10) | |
| .slice(0, 100) | |
| .map(line => truncateText(line.trim(), 80)); | |
| } | |
| } | |
| // Helper function to truncate long text with better handling | |
| function truncateText(text, maxLength) { | |
| if (!text) return ''; | |
| text = text.toString().trim(); | |
| if (text.length <= maxLength) return text; | |
| // Try to truncate at word boundary | |
| const truncated = text.substring(0, maxLength - 3); | |
| const lastSpace = truncated.lastIndexOf(' '); | |
| if (lastSpace > 0 && (maxLength - lastSpace) < 20) { | |
| return truncated.substring(0, lastSpace) + '...'; | |
| } | |
| return truncated + '...'; | |
| } | |
| // Display extracted key points in ultra-compact format | |
| function displayKeyPoints(points) { | |
| keyPointsContainer.innerHTML = ''; | |
| keyPointsContainer.className = 'grid grid-cols-4 gap-1 text-xxxs'; // More columns, smaller text | |
| points.forEach((point, index) => { | |
| const pointElement = document.createElement('div'); | |
| pointElement.className = 'key-point-item bg-gray-50 p-1 rounded border border-gray-200 font-mono cursor-pointer hover:bg-blue-50 transition-colors'; | |
| pointElement.innerHTML = ` | |
| <p class="text-gray-700 leading-none">${point}</p> | |
| `; | |
| pointElement.addEventListener('click', () => { | |
| navigator.clipboard.writeText(point) | |
| .then(() => { | |
| pointElement.classList.add('bg-green-50', 'border-green-200'); | |
| setTimeout(() => { | |
| pointElement.classList.remove('bg-green-50', 'border-green-200'); | |
| }, 1000); | |
| }) | |
| .catch(err => { | |
| console.error('Failed to copy text: ', err); | |
| }); | |
| }); | |
| keyPointsContainer.appendChild(pointElement); | |
| }); | |
| } | |
| // Export key points to PDF in ultra-compact format | |
| function exportToPDF() { | |
| try { | |
| const { jsPDF } = window.jspdf; | |
| const doc = new jsPDF({ | |
| orientation: 'portrait', | |
| unit: 'mm', | |
| format: 'a4', | |
| compress: true | |
| }); | |
| // Ultra-compact styling | |
| doc.setFont('Helvetica', 'normal'); | |
| doc.setFontSize(6); | |
| doc.setTextColor(20); | |
| const points = Array.from(keyPointsContainer.querySelectorAll('p')).map(p => p.textContent); | |
| const margin = 5; | |
| const pageWidth = doc.internal.pageSize.width - (margin * 2); | |
| const colWidth = pageWidth / 4 - 2; // 4 columns with small gap | |
| const lineHeight = 3; | |
| let y = margin; | |
| // Create 4 columns for maximum density | |
| for (let i = 0; i < points.length; i++) { | |
| const col = i % 4; | |
| const xPos = margin + (col * (colWidth + 2)); | |
| // Add new page if needed with tighter margins | |
| if (y > doc.internal.pageSize.height - margin) { | |
| doc.addPage('a4', 'portrait'); | |
| y = margin; | |
| } | |
| // Optimize text splitting | |
| const lines = doc.splitTextToSize(points[i].replace(/\s+/g, ' '), colWidth); | |
| // Skip empty lines | |
| if (lines.length === 0) continue; | |
| // Add text with minimal spacing | |
| doc.text(lines, xPos, y, { | |
| maxWidth: colWidth, | |
| lineHeightFactor: 0.9 | |
| }); | |
| // Update y position for next item | |
| y += (lines.length * lineHeight); | |
| } | |
| // Compact PDF output | |
| doc.setProperties({ | |
| title: 'Compact Cheat Sheet', | |
| subject: 'Exam Cheat Sheet', | |
| creator: 'PDF Nugget Miner' | |
| }); | |
| // Save with optimized name and compression | |
| doc.save(`cheat-sheet-${new Date().toISOString().slice(0,10)}.pdf`, { | |
| compression: true | |
| }); | |
| } catch (error) { | |
| console.error('PDF Export Error:', error); | |
| alert('Failed to generate PDF. Please try again.'); | |
| } | |
| } | |
| }); |