File size: 10,587 Bytes
7d81421
2e44909
 
7d81421
2e44909
7d81421
 
2e44909
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7d81421
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291

// AI Study Assistant Functions
document.addEventListener('DOMContentLoaded', function() {
    feather.replace();
    initializeEventListeners();
});

function initializeEventListeners() {
    // Initialize any necessary event listeners here
}

// File upload handling
function handleFileUpload(event, type) {
    const file = event.target.files[0];
    if (!file) return;

    const uploadLabel = event.target.nextElementSibling;
    uploadLabel.querySelector('span:first-child').textContent = file.name;
    
    const uploadProgress = uploadLabel.parentElement.querySelector('#upload-progress');
    uploadProgress.classList.remove('hidden');
    
    const progressBar = uploadProgress.querySelector('#progress-bar');
    const progressText = uploadProgress.querySelector('#progress-text');
    
    // Simulate upload progress
    let progress = 0;
    const interval = setInterval(() => {
        progress += 10;
        progressBar.style.width = `${progress}%`;
        
        if (progress >= 100) {
            clearInterval(interval);
            progressText.textContent = "Processing content...";
            processFileContent(file, type);
        }
    }, 300);
}

async function processFileContent(file, type) {
    try {
        let content = '';
        
        if (type.includes('pdf') || type.includes('document')) {
            content = await extractTextFromPDF(file);
        } else if (type.includes('image')) {
            content = await extractTextFromImage(file);
        } else if (type.includes('audio')) {
            content = await transcribeAudio(file);
        }
        
        generateStudyMaterials(content);
    } catch (error) {
        console.error('Error processing file:', error);
        showError("Failed to process file. Please try again.");
    }
}

async function processTextContent() {
    const text = document.getElementById('text-input').value;
    if (!text.trim()) {
        showError("Please enter some text to process");
        return;
    }
    generateStudyMaterials(text);
}

async function processUrlContent() {
    const url = document.getElementById('url-input').value;
    if (!url.trim()) {
        showError("Please enter a URL to process");
        return;
    }
    
    try {
        const response = await fetch(`/api/extract?url=${encodeURIComponent(url)}`);
        const data = await response.json();
        generateStudyMaterials(data.content);
    } catch (error) {
        console.error('Error processing URL:', error);
        showError("Failed to extract content from URL");
    }
}

async function generateStudyMaterials(content) {
    showLoading(true);
    
    try {
        // Call AI APIs to generate study materials
        const [summary, notes, flashcards, quiz] = await Promise.all([
            generateSummary(content),
            generateNotes(content),
            generateFlashcards(content),
            generateQuiz(content)
        ]);
        
        displayResults({ summary, notes, flashcards, quiz });
    } catch (error) {
        console.error('Error generating study materials:', error);
        showError("Failed to generate study materials");
    } finally {
        showLoading(false);
    }
}

// AI Processing Functions (would connect to real APIs in production)
async function extractTextFromPDF(file) {
    // In a real app, you would use a PDF text extraction library or API
    return "PDF extracted text would go here...";
}

async function extractTextFromImage(file) {
    // In a real app, you would use OCR API
    return "Image extracted text would go here...";
}

async function transcribeAudio(file) {
    // In a real app, you would use speech-to-text API
    return "Audio transcription would go here...";
}

async function generateSummary(content) {
    // In a real app, you would call an AI summarization API
    return {
        short: "Short summary of the content...",
        detailed: "Detailed summary of the content..."
    };
}

async function generateNotes(content) {
    // In a real app, you would call an AI notes generation API
    return ["Note 1", "Note 2", "Note 3"];
}

async function generateFlashcards(content) {
    // In a real app, you would call an AI flashcard generation API
    return [
        { question: "Question 1", answer: "Answer 1" },
        { question: "Question 2", answer: "Answer 2" }
    ];
}

async function generateQuiz(content) {
    // In a real app, you would call an AI quiz generation API
    return {
        questions: [
            {
                question: "Sample question?",
                options: ["Option 1", "Option 2", "Option 3"],
                answer: 0
            }
        ]
    };
}

// UI Helper Functions
function showLoading(show) {
    const loader = document.getElementById('global-loader');
    if (loader) loader.style.display = show ? 'block' : 'none';
}

function showError(message) {
    // Create or show error message in UI
    const errorElement = document.getElementById('error-message') || createErrorElement();
    errorElement.textContent = message;
    errorElement.classList.remove('hidden');
    setTimeout(() => errorElement.classList.add('hidden'), 5000);
}

function createErrorElement() {
    const errorElement = document.createElement('div');
    errorElement.id = 'error-message';
    errorElement.className = 'fixed top-4 right-4 bg-red-500 text-white px-4 py-2 rounded-md shadow-lg hidden';
    document.body.appendChild(errorElement);
    return errorElement;
}

function displayResults(results) {
    // Create a modal or section to display the results
    const resultsContainer = document.getElementById('results-container') || createResultsContainer();
    
    // Populate with actual results
    resultsContainer.innerHTML = `
        <div class="bg-white rounded-lg shadow-lg p-6 max-w-4xl mx-auto">
            <h2 class="text-2xl font-bold mb-4">Your Study Materials</h2>
            
            <div class="mb-6">
                <h3 class="text-xl font-semibold mb-2">Summary</h3>
                <p class="text-gray-700">${results.summary.detailed}</p>
            </div>
            
            <div class="mb-6">
                <h3 class="text-xl font-semibold mb-2">Key Notes</h3>
                <ul class="list-disc pl-5 space-y-1">
                    ${results.notes.map(note => `<li>${note}</li>`).join('')}
                </ul>
            </div>
            
            <div class="mb-6">
                <h3 class="text-xl font-semibold mb-2">Flashcards</h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    ${results.flashcards.map(card => `
                        <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <p class="font-medium">Q: ${card.question}</p>
                            <p class="text-gray-600 mt-1">A: ${card.answer}</p>
                        </div>
                    `).join('')}
                </div>
            </div>
            
            <div>
                <h3 class="text-xl font-semibold mb-2">Quiz</h3>
                <div class="space-y-4">
                    ${results.quiz.questions.map((q, i) => `
                        <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <p class="font-medium">${i+1}. ${q.question}</p>
                            <div class="mt-2 space-y-2">
                                ${q.options.map((opt, j) => `
                                    <div class="flex items-center">
                                        <input type="radio" id="q${i}-opt${j}" name="q${i}" value="${j}" 
                                               class="mr-2" ${j === q.answer ? 'checked' : ''}>
                                        <label for="q${i}-opt${j}">${opt}</label>
                                    </div>
                                `).join('')}
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
            
            <div class="mt-6 flex justify-end space-x-3">
                <button onclick="exportAsPDF(${JSON.stringify(results)})" 
                        class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                    Export as PDF
                </button>
                <button onclick="exportAsText(${JSON.stringify(results)})" 
                        class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700">
                    Export as Text
                </button>
            </div>
        </div>
    `;
    
    resultsContainer.classList.remove('hidden');
    window.scrollTo({ top: resultsContainer.offsetTop, behavior: 'smooth' });
}

function createResultsContainer() {
    const container = document.createElement('div');
    container.id = 'results-container';
    container.className = 'hidden py-12 px-4 md:px-8 lg:px-16';
    document.body.insertBefore(container, document.querySelector('custom-footer'));
    return container;
}
// Simple text summarization function (placeholder for actual AI implementation)
function summarizeText(text) {
    // This is a placeholder - in a real implementation, you would use a proper summarization algorithm
    const sentences = text.split('.');
    const importantSentences = sentences.filter((_, index) => index % 3 === 0);
    return importantSentences.join('. ') + (importantSentences.length ? '.' : '');
}

// Generate flashcards from text (placeholder)
function generateFlashcards(text) {
    // Placeholder - real implementation would use question generation algorithms
    const sentences = text.split('.');
    return sentences.slice(0, 5).map((sentence, index) => ({
        question: `What is the main idea of this point? (Card ${index + 1})`,
        answer: sentence.trim()
    }));
}

// Export functions
function exportAsPDF(content, filename = 'study-material') {
    // Placeholder - real implementation would use a PDF generation library
    console.log(`Exporting as PDF: ${filename}`, content);
    alert(`Exporting as PDF: ${filename}`);
}

function exportAsText(content, filename = 'study-material') {
    // Placeholder - real implementation would create a downloadable text file
    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${filename}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}