-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
320 lines (289 loc) · 14.4 KB
/
index.html
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
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
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Text Summarizer</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
dark: {
100: '#1E293B',
200: '#334155',
300: '#475569'
}
}
}
}
}
</script>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/universal-sentence-encoder"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
</head>
<body class="dark:bg-dark-100 min-h-screen overflow-x-hidden" x-data="summarizer">
<!-- Three.js Background -->
<canvas id="bgCanvas" class="fixed top-0 left-0 w-full h-full -z-10"></canvas>
<div class="container mx-auto px-4 py-8 max-w-6xl relative">
<div class="text-center mb-12 relative">
<h1 class="text-4xl font-bold mb-2 dark:text-white">Browser-Based Text Summarizer</h1>
<p class="dark:text-gray-300">Advanced Natural Language Processing in Your Browser</p>
<button @click="toggleTheme" class="absolute right-0 top-0 p-2 text-xl dark:text-white">
<i :class="isDark ? 'bi-sun' : 'bi-moon'"></i>
</button>
</div>
<div class="grid md:grid-cols-2 gap-8">
<!-- Input Section -->
<div class="backdrop-blur-sm bg-white/80 dark:bg-dark-200/80 rounded-xl shadow-lg p-6 border border-gray-200 dark:border-dark-300">
<div class="flex justify-between items-center mb-4">
<h2 class="text-2xl font-semibold dark:text-white">Input Text</h2>
<div class="flex gap-2">
<span class="text-sm dark:text-gray-300" x-text="'Words: ' + wordCount"></span>
<button @click="clearText" class="dark:text-gray-300 hover:text-gray-700 transition-colors">
<i class="bi bi-trash"></i>
</button>
</div>
</div>
<textarea
x-model="inputText"
@input="updateWordCount"
class="w-full h-64 p-4 border rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white/50 dark:bg-dark-300/50 dark:text-white backdrop-blur-sm"
placeholder="Enter your text here to summarize..."
></textarea>
<div class="mt-4 space-y-4">
<div class="flex gap-4">
<input type="file" @change="handleFileUpload" accept=".txt" class="hidden" id="fileInput">
<button
@click="document.getElementById('fileInput').click()"
class="flex-1 py-2 px-4 bg-white/50 dark:bg-dark-300/50 hover:bg-white/70 dark:hover:bg-dark-300/70 rounded-lg flex items-center justify-center gap-2 transition-all duration-300 dark:text-white"
>
<i class="bi bi-file-text"></i>
Upload Text
</button>
<button
@click="generateSummary"
class="flex-1 bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 flex items-center justify-center gap-2 transition-all duration-300"
:disabled="isProcessing || !inputText.trim()"
>
<template x-if="!isProcessing">
<i class="bi bi-magic"></i>
</template>
<template x-if="isProcessing">
<i class="bi bi-hourglass-split animate-spin"></i>
</template>
Summarize
</button>
</div>
</div>
</div>
<!-- Output Section -->
<div class="backdrop-blur-sm bg-white/80 dark:bg-dark-200/80 rounded-xl shadow-lg p-6 border border-gray-200 dark:border-dark-300">
<div class="flex justify-between items-center mb-4">
<h2 class="text-2xl font-semibold dark:text-white">Summary</h2>
<div class="flex gap-3">
<button @click="copyToClipboard" class="dark:text-gray-300 hover:text-gray-700 transition-colors">
<i class="bi bi-clipboard"></i>
</button>
<button @click="downloadSummary" class="dark:text-gray-300 hover:text-gray-700 transition-colors">
<i class="bi bi-download"></i>
</button>
</div>
</div>
<div class="h-64 overflow-y-auto p-4 border rounded-lg bg-white/50 dark:bg-dark-300/50 backdrop-blur-sm">
<template x-if="!summaryText">
<p class="text-gray-500 dark:text-gray-400 italic">Your summary will appear here...</p>
</template>
<template x-if="summaryText">
<p class="dark:text-white" x-text="summaryText"></p>
</template>
</div>
<div class="mt-6">
<h3 class="text-sm font-medium mb-2 dark:text-white">Summary Settings</h3>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="text-sm dark:text-gray-300 mb-1 block">Compression Rate</label>
<select
x-model="compressionRate"
class="w-full p-2 border rounded-lg bg-white/50 dark:bg-dark-300/50 dark:text-white backdrop-blur-sm"
>
<option class="bg-red-500" value="0.3">High (30%)</option>
<option class="bg-yellow-500" value="0.5">Medium (50%)</option>
<option class="bg-green-500" value="0.7">Low (70%)</option>
</select>
</div>
<div>
<label class="text-sm dark:text-gray-300 mb-1 block">Algorithm</label>
<select
x-model="algorithm"
class="w-full p-2 border rounded-lg bg-white/50 dark:bg-dark-300/50 dark:text-white backdrop-blur-sm"
>
<option value="extractive">Extractive</option>
<option value="frequency">Frequency-based</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('summarizer', () => ({
inputText: '',
summaryText: '',
isProcessing: false,
compressionRate: 0.5,
algorithm: 'extractive',
wordCount: 0,
isDark: true,
model: null,
async init() {
try {
// If you want to load the model from a local path, adjust it here
const model = await tf.loadLayersModel('./model.json')
console.log('Model loaded successfully!');
} catch (error) {
console.error('Error loading model:', error);
}
},
toggleTheme() {
this.isDark = !this.isDark;
document.documentElement.classList.toggle('dark');
},
updateWordCount() {
this.wordCount = this.inputText.trim().split(/\s+/).length;
},
async generateSummary() {
if (!this.inputText.trim()) {
alert('Please enter some text to summarize');
return;
}
this.isProcessing = true;
try {
if (this.algorithm === 'extractive') {
this.summaryText = await this.extractiveSummarization(this.inputText);
} else {
this.summaryText = await this.frequencyBasedSummarization(this.inputText);
}
} catch (error) {
console.error('Error generating summary:', error);
alert('Error generating summary. Please try again.');
} finally {
this.isProcessing = false;
}
},
async extractiveSummarization(text) {
const sentences = text.match(/[^.!?]+[.!?]+/g) || [];
if (sentences.length === 0) return text;
try {
const encodedSentences = await this.model.embed(sentences);
const sentenceEmbeddings = await encodedSentences.array();
const sentenceScores = [];
for (let i = 0; i < sentenceEmbeddings.length; i++) {
let score = 0;
for (let j = 0; j < sentenceEmbeddings.length; j++) {
if (i !== j) {
score += this.cosineSimilarity(sentenceEmbeddings[i], sentenceEmbeddings[j]);
}
}
sentenceScores.push(score);
}
const numSentences = Math.max(1, Math.floor(sentences.length * this.compressionRate));
const topSentences = sentenceScores
.map((score, idx) => ({ score, idx }))
.sort((a, b) => b.score - a.score)
.slice(0, numSentences)
.sort((a, b) => a.idx - b.idx)
.map(item => sentences[item.idx]);
return topSentences.join(' ');
} catch (error) {
console.error('Error in extractive summarization:', error);
return this.frequencyBasedSummarization(text); // Fallback to frequency-based
}
},
cosineSimilarity(a, b) {
const dotProduct = a.reduce((sum, val, i) => sum + val * b[i], 0);
const normA = Math.sqrt(a.reduce((sum, val) => sum + val * val, 0));
const normB = Math.sqrt(b.reduce((sum, val) => sum + val * val, 0));
return dotProduct / (normA * normB);
},
async frequencyBasedSummarization(text) {
const sentences = text.match(/[^.!?]+[.!?]+/g) || [text];
if (sentences.length === 0) return text;
const wordFreq = {};
const words = text.toLowerCase().match(/\b\w+\b/g) || [];
words.forEach(word => {
wordFreq[word] = (wordFreq[word] || 0) + 1;
});
const sentenceScores = sentences.map(sentence => {
const sentenceWords = sentence.toLowerCase().match(/\b\w+\b/g) || [];
return sentenceWords.reduce((score, word) => score + wordFreq[word], 0) / sentenceWords.length;
});
const numSentences = Math.max(1, Math.floor(sentences.length * this.compressionRate));
const topSentences = sentenceScores
.map((score, idx) => ({ score, idx }))
.sort((a, b) => b.score - a.score)
.slice(0, numSentences)
.sort((a, b) => a.idx - b.idx)
.map(item => sentences[item.idx]);
return topSentences.join(' ');
},
async handleFileUpload(event) {
const file = event.target.files[0];
if (!file) return;
try {
const text = await file.text();
this.inputText = text;
this.updateWordCount();
} catch (error) {
console.error('Error reading file:', error);
alert('Error reading file. Please try again.');
}
event.target.value = '';
},
clearText() {
if (confirm('Are you sure you want to clear all content?')) {
this.inputText = '';
this.summaryText = '';
this.wordCount = 0;
}
},
async copyToClipboard() {
if (!this.summaryText) {
alert('No summary to copy');
return;
}
try {
await navigator.clipboard.writeText(this.summaryText);
alert('Summary copied to clipboard!');
} catch (err) {
console.error('Failed to copy:', err);
alert('Failed to copy text. Please try again.');
}
},
downloadSummary() {
if (!this.summaryText) {
alert('No summary to download');
return;
}
const blob = new Blob([this.summaryText], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `summary-${new Date().toISOString().slice(0, 10)}.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
}));
});
</script>
</body>
</html>