File size: 11,042 Bytes
8f52c02
 
 
 
 
 
 
 
 
 
 
 
 
 
d5e6d72
 
 
 
131a9d1
8f52c02
 
 
 
131a9d1
 
 
 
 
 
8f52c02
 
 
 
 
 
131a9d1
 
 
 
 
8f52c02
 
 
131a9d1
 
 
 
 
8f52c02
 
131a9d1
 
 
 
8f52c02
 
 
 
 
 
 
 
 
131a9d1
 
 
8f52c02
 
131a9d1
8f52c02
131a9d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f52c02
 
131a9d1
8f52c02
131a9d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fcf547
131a9d1
6fcf547
131a9d1
 
6fcf547
131a9d1
 
 
 
 
 
 
 
 
6e4629a
131a9d1
8f52c02
 
6fcf547
8f52c02
 
 
6fcf547
8f52c02
6fcf547
6e4629a
 
123837d
 
 
 
 
 
 
 
 
 
 
8f52c02
123837d
8f52c02
6e4629a
8f52c02
d5e6d72
 
6e4629a
 
 
d214577
 
6e4629a
8f52c02
d214577
 
 
 
d5e6d72
 
d214577
 
 
 
 
d5e6d72
d214577
6e4629a
d214577
 
d5e6d72
d214577
 
 
 
d5e6d72
 
d214577
 
 
 
 
 
 
 
 
 
 
d5e6d72
 
d214577
6e4629a
d214577
 
 
 
 
 
 
 
 
 
 
 
d5e6d72
 
 
 
8f52c02
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
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.');
        }
}
});