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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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Missing Data Extractor</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
</head>
<body class="bg-gray-50 min-h-screen">
    <custom-header></custom-header>
    
    <main class="container mx-auto px-4 py-8">
        <div class="bg-white rounded-xl shadow-md p-6 max-w-6xl mx-auto">
            <h1 class="text-3xl font-bold text-gray-800 mb-4">Missing Data Extractor</h1>
            <p class="text-gray-600 mb-6">
                Extract missing Article Titles and Keywords from article URLs
            </p>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                <div class="bg-blue-50 p-4 rounded-lg">
                    <div class="flex items-center mb-2">
                        <i data-feather="upload" class="text-blue-500 mr-2"></i>
                        <h2 class="text-xl font-semibold text-blue-800">Input Requirements</h2>
                    </div>
                    <ul class="text-gray-700 space-y-1">
                        <li>Excel spreadsheet with article metadata</li>
                        <li>Must include article URLs column</li>
                        <li>Columns: Name of the study, Authors, Year, Reads, Citations, Keywords, Complete abstract</li>
                        <li>Missing data will be extracted from URLs</li>
                    </ul>
                </div>
                
                <div class="bg-green-50 p-4 rounded-lg">
                    <div class="flex items-center mb-2">
                        <i data-feather="download" class="text-green-500 mr-2"></i>
                        <h2 class="text-xl font-semibold text-green-800">Extraction Scope</h2>
                    </div>
                    <ul class="text-gray-700 space-y-1">
                        <li>Article Titles (only if missing)</li>
                        <li>Keywords (each as separate row)</li>
                        <li>Preserves existing data</li>
                        <li>1-3 second delay between requests</li>
                    </ul>
                </div>
            </div>
            
            <div class="mb-8">
                <h2 class="text-2xl font-semibold text-gray-800 mb-4">Upload Spreadsheet</h2>
                <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
                    <input type="file" id="spreadsheetFile" accept=".xlsx,.xls" class="hidden">
                    <div id="uploadArea" class="cursor-pointer">
                        <i data-feather="file" class="text-gray-400 mx-auto mb-2" style="width: 48px; height: 48px;"></i>
                        <p class="text-gray-500 mb-2">Drag & drop your Excel spreadsheet here</p>
                        <p class="text-gray-400 text-sm">or click to browse</p>
                    </div>
                </div>
            </div>
            
            <div class="flex flex-col sm:flex-row gap-4 mb-8">
                <button id="startExtraction" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg font-medium flex items-center justify-center disabled:opacity-50" disabled>
                    <i data-feather="play" class="mr-2"></i>
                    Start Data Extraction
                </button>
                <button id="downloadResults" class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-6 py-3 rounded-lg font-medium flex items-center justify-center disabled:opacity-50" disabled>
                    <i data-feather="download" class="mr-2"></i>
                    Download Results
                </button>
            </div>
        </div>
        
        <div id="progressContainer" class="bg-white rounded-xl shadow-md p-6 max-w-6xl mx-auto mt-6 hidden">
            <h2 class="text-2xl font-semibold text-gray-800 mb-4">Extraction Progress</h2>
            
            <div class="mb-6">
                <div class="flex justify-between mb-1">
                    <span class="text-gray-700">Current progress</span>
                    <span id="progressPercent" class="text-gray-700">0%</span>
                </div>
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                    <div id="progressBar" class="bg-blue-600 h-2.5 rounded-full" style="width: 0%"></div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
                <div class="bg-white border border-gray-200 rounded-lg p-4">
                    <h3 class="text-sm font-medium text-gray-500">Total Articles</h3>
                    <p id="totalArticles" class="text-2xl font-semibold text-gray-800">0</p>
                </div>
                <div class="bg-white border border-gray-200 rounded-lg p-4">
                    <h3 class="text-sm font-medium text-gray-500">Titles Found</h3>
                    <p id="titlesFound" class="text-2xl font-semibold text-green-600">0</p>
                </div>
                <div class="bg-white border border-gray-200 rounded-lg p-4">
                    <h3 class="text-sm font-medium text-gray-500">Keywords Found</h3>
                    <p id="keywordsFound" class="text-2xl font-semibold text-green-600">0</p>
                </div>
                <div class="bg-white border border-gray-200 rounded-lg p-4">
                    <h3 class="text-sm font-medium text-gray-500">Skipped</h3>
                    <p id="articlesSkipped" class="text-2xl font-semibold text-red-600">0</p>
                </div>
            </div>
            
            <div class="bg-gray-50 p-4 rounded-lg">
                <h3 class="text-lg font-medium text-gray-800 mb-2">Extraction Log</h3>
                <div id="logMessages" class="h-64 overflow-y-auto space-y-2 text-sm text-gray-700">
                    <!-- Log messages will appear here -->
                </div>
            </div>
        </div>
    </main>
    
    <custom-footer></custom-footer>
    
    <script src="components/header.js"></script>
    <script src="components/footer.js"></script>
    <script src="script.js"></script>
    <script>
        feather.replace();
        
        // Missing data extraction functionality
        document.addEventListener('DOMContentLoaded', function() {
            const uploadArea = document.getElementById('uploadArea');
            const fileInput = document.getElementById('spreadsheetFile');
            const startButton = document.getElementById('startExtraction');
            const downloadButton = document.getElementById('downloadResults');
            const progressContainer = document.getElementById('progressContainer');
            const progressBar = document.getElementById('progressBar');
            const progressPercent = document.getElementById('progressPercent');
            const totalArticles = document.getElementById('totalArticles');
            const titlesFound = document.getElementById('titlesFound');
            const keywordsFound = document.getElementById('keywordsFound');
            const articlesSkipped = document.getElementById('articlesSkipped');
            const logMessages = document.getElementById('logMessages');
            
            let spreadsheetData = [];
            let currentArticleIndex = 0;
            let titlesExtracted = 0;
            let keywordsExtracted = 0;
            let skippedArticles = 0;
            
            // File upload handling
            uploadArea.addEventListener('click', () => fileInput.click());
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.classList.add('border-blue-400', 'bg-blue-50');
            });
            uploadArea.addEventListener('dragleave', () => {
                uploadArea.classList.remove('border-blue-400', 'bg-blue-50');
            });
            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.classList.remove('border-blue-400', 'bg-blue-50');
                const files = e.dataTransfer.files;
                if (files.length > 0 && (files[0].name.endsWith('.xlsx') || files[0].name.endsWith('.xls'))) {
                    handleFileUpload(files[0]);
                }
            });
            
            fileInput.addEventListener('change', (e) => {
                if (e.target.files.length > 0) {
                    handleFileUpload(e.target.files[0]);
                }
            });
            
            function handleFileUpload(file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    try {
                        const data = new Uint8Array(e.target.result);
                        const workbook = XLSX.read(data, { type: 'array' });
                        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                        const jsonData = XLSX.utils.sheet_to_json(firstSheet);
                        
                        if (jsonData.length > 0) {
                            spreadsheetData = jsonData;
                            totalArticles.textContent = jsonData.length;
                            startButton.disabled = false;
                            addLogMessage(`Successfully loaded spreadsheet with ${jsonData.length} articles`);
                        } else {
                            addLogMessage('Error: No data found in spreadsheet');
                        }
                    } catch (error) {
                        addLogMessage(`Error reading spreadsheet: ${error.message}`);
                    }
                };
                reader.readAsArrayBuffer(file);
            }
            
            startButton.addEventListener('click', async function() {
                progressContainer.classList.remove('hidden');
                startButton.disabled = true;
                
                // Reset counters
                currentArticleIndex = 0;
                titlesExtracted = 0;
                keywordsExtracted = 0;
                skippedArticles = 0;
                progressBar.style.width = '0%';
                progressPercent.textContent = '0%';
                logMessages.innerHTML = '';
                
                addLogMessage('Starting missing data extraction...');
                
                processArticles();
            });
            
            async function processArticles() {
                for (let i = 0; i < spreadsheetData.length; i++) {
                    currentArticleIndex = i;
                    const article = spreadsheetData[i];
                    
                    // Check if URL exists
                    if (!article.URL && !article.url) {
                        addLogMessage(`Skipping article ${i + 1}: No URL provided`);
                        skippedArticles++;
                        articlesSkipped.textContent = skippedArticles;
                        updateProgress();
                        continue;
                    }
                    
                    const url = article.URL || article.url;
                    const needsTitle = !article['Name of the study'] || article['Name of the study'].trim() === '';
                    const needsKeywords = !article.Keywords || article.Keywords.trim() === '';
                    
                    if (!needsTitle && !needsKeywords) {
                        addLogMessage(`Article ${i + 1}: No missing data found`);
                        updateProgress();
                        continue;
                    }
                    
                    addLogMessage(`Processing article ${i + 1}: ${url}`);
                    
                    try {
                        // Add delay between requests (1-3 seconds)
                        await new Promise(resolve => setTimeout(resolve, 1000 + Math.random() * 2000));
                        
                        // Use CORS proxy to avoid CORS issues
                        const proxyUrl = 'https://cors-anywhere.herokuapp.com/';
                        const response = await fetch(proxyUrl + url);
                        
                        if (response.ok) {
                            const html = await response.text();
                            const parser = new DOMParser();
                            const doc = parser.parseFromString(html, 'text/html');
                            
                            let titleFound = false;
                            let keywordsFound = false;
                            
                            // Extract title if missing
                            if (needsTitle) {
                                const title = extractArticleTitle(doc);
                                if (title) {
                                    article['Name of the study'] = title;
                                    titlesExtracted++;
                                    titlesFound.textContent = titlesExtracted;
                                    titleFound = true;
                                }
                            }
                            
                            // Extract keywords if missing
                            if (needsKeywords) {
                                const keywords = extractKeywords(doc);
                                if (keywords.length > 0) {
                                    article.Keywords = keywords.join(', ');
                                    keywordsExtracted += keywords.length;
                                    keywordsFound.textContent = keywordsExtracted;
                                    keywordsFound = true;
                                }
                            }
                            
                            if (titleFound || keywordsFound) {
                                addLogMessage(`✓ Successfully extracted data for article ${i + 1}`);
                            } else {
                                addLogMessage(`✗ No data extracted for article ${i + 1}`);
                                skippedArticles++;
                                articlesSkipped.textContent = skippedArticles;
                            }
                        } else {
                            addLogMessage(`✗ Failed to fetch article ${i + 1}: ${response.status}`);
                            skippedArticles++;
                            articlesSkipped.textContent = skippedArticles;
                        }
                    } catch (error) {
                        addLogMessage(`✗ Error processing article ${i + 1}: ${error.message}`);
                        skippedArticles++;
                        articlesSkipped.textContent = skippedArticles;
                    }
                    
                    updateProgress();
                }
                
                // Generate exports
                downloadButton.disabled = false;
                addLogMessage('Extraction completed!');
                addLogMessage(`Summary: ${titlesExtracted} titles found, ${keywordsExtracted} keywords found, ${skippedArticles} articles skipped');
            }
            
            function extractArticleTitle(doc) {
                // Try multiple selectors for article title
                const selectors = [
                    'h1.article-title',
                    'h1.title',
                    'h1',
                    '.article-title',
                    '.title',
                    'title'
                ];
                
                for (const selector of selectors) {
                    const element = doc.querySelector(selector);
                    if (element && element.textContent.trim()) {
                        return element.textContent.trim();
                    }
                }
                
                return null;
            }
            
            function extractKeywords(doc) {
                const keywords = [];
                
                // Try multiple selectors for keywords
                const selectors = [
                    '.keywords',
                    '.keyword',
                    '[class*="keyword"]',
                    'meta[name="keywords"]',
                    'meta[name="Keywords"]'
                ];
                
                for (const selector of selectors) {
                    const elements = doc.querySelectorAll(selector);
                    elements.forEach(element => {
                        if (element.tagName === 'META') {
                            const content = element.getAttribute('content');
                            if (content) {
                                keywords.push(...content.split(',').map(k => k.trim()).filter(k => k));
                        } else if (element.textContent) {
                            const text = element.textContent.trim();
                            if (text.toLowerCase().includes('keyword')) {
                                // Extract keywords from text like "Keywords: word1, word2, word3"
                                const match = text.match(/keywords?:\s*(.+)/i);
                                if (match) {
                                    keywords.push(...match[1].split(',').map(k => k.trim()).filter(k => k));
                                } else {
                                    keywords.push(text);
                                }
                            }
                        }
                    });
                }
                
                return [...new Set(keywords)]; // Remove duplicates
            }
            
            function updateProgress() {
                const progress = ((currentArticleIndex + 1) / spreadsheetData.length) * 100;
                progressBar.style.width = `${progress}%`;
                progressPercent.textContent = `${Math.round(progress)}%`;
            }
            
            function addLogMessage(message) {
                const now = new Date();
                const timeString = now.toLocaleTimeString();
                const messageElement = document.createElement('div');
                messageElement.innerHTML = `<span class="text-gray-500">[${timeString}]</span> ${message}`;
                logMessages.appendChild(messageElement);
                logMessages.scrollTop = logMessages.scrollHeight;
            }
            
            downloadButton.addEventListener('click', function() {
                if (spreadsheetData.length === 0) return;
                
                // Create updated workbook
                const wb = XLSX.utils.book_new();
                const ws = XLSX.utils.json_to_sheet(spreadsheetData);
                XLSX.utils.book_append_sheet(wb, ws, 'Updated Articles');
                
                // Download Excel file
                XLSX.writeFile(wb, 'updated_articles_data.xlsx');
                
                // Generate keywords CSV
                const keywordsData = [];
                spreadsheetData.forEach(article => {
                    if (article.Keywords && article.Keywords.trim() !== '') {
                        const keywords = article.Keywords.split(',').map(k => k.trim());
                        keywords.forEach(keyword => {
                            keywordsData.push({
                                'Article URL': article.URL || article.url,
                                'Name of the study': article['Name of the study'],
                                'Keyword': keyword
                            });
                        });
                    }
                });
                
                if (keywordsData.length > 0) {
                    const keywordsWS = XLSX.utils.json_to_sheet(keywordsData);
                    const keywordsWB = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(keywordsWB, keywordsWS, 'Keywords');
                    XLSX.writeFile(keywordsWB, 'keywords_export.csv');
                }
                
                addLogMessage('Files downloaded successfully!');
            });
        });
    </script>
</body>
</html>