-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
520 lines (457 loc) · 26.2 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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>📚Books Counter - 统计书中提到的书籍</title>
<meta name="description" content="上传文件,自动统计其中提到的其他书籍。快速了解一本书中引用的所有书籍。书中引用的书。书中关联的书">
<meta name="keywords" content="PDF统计,书籍引用,文献分析,阅读工具">
<meta name="author" content="BookInBook">
<link rel="canonical" href="https://www.bookinbook.top/">
<meta property="og:title" content="Books Counter - 统计书中提到的书籍">
<meta property="og:description" content="上传文件,自动统计其中提到的其他书籍。快速了解一本书中引用的所有书籍。">
<meta property="og:url" content="https://www.bookinbook.top/">
<meta property="og:type" content="website">
<meta property="og:image" content="https://www.bookinbook.top/path-to-your-image.jpg">
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/epubjs/dist/epub.min.js"></script>
</head>
<body class="bg-gray-100 text-gray-800 font-sans">
<div class="container mx-auto px-4 py-8 max-w-3xl" id="dropZone">
<h1 class="text-3xl font-bold text-blue-600 mb-6">🤓📚Books Counter </h1>
<p class="text-sm text-gray-500 mb-4">上传书籍统计其中提到的其他书,支持下载为表格</p>
<div class="mb-6">
<label for="bookFile" class="block mb-2 text-sm font-medium text-gray-400">选择PDF或EPUB文件</label>
<div class="flex items-center">
<label for="bookFile" class="cursor-pointer bg-gradient-to-r from-purple-500 to-orange-500 hover:from-purple-600 hover:to-orange-600 text-white py-2 px-4 rounded-lg transition duration-300 backdrop-filter backdrop-blur-sm bg-opacity-70 whitespace-nowrap">
<span id="fileLabel">选择查看的书</span>
<input type="file" id="bookFile" accept=".pdf,.epub" class="hidden" onchange="updateFileName()">
</label>
<span id="fileName" class="ml-3 text-sm text-gray-600"></span>
</div>
</div>
<div class="flex space-x-2">
<button onclick="processBook()" class="w-4/5 bg-gradient-to-r from-purple-500 to-orange-500 hover:from-purple-600 hover:to-orange-600 text-white py-2 px-4 rounded-lg transition duration-300 backdrop-filter backdrop-blur-sm bg-opacity-70 relative overflow-hidden">
<span class="relative z-10">查看书中提及的书籍</span>
<div class="absolute top-0 left-0 w-full h-full bg-gradient-to-r from-purple-500 to-orange-500 opacity-50 animate-gradient-x"></div>
</button>
<!-- 添加一个分享按钮 -->
<button onclick="shareResults()" class="w-1/5 bg-gradient-to-r from-purple-500 to-orange-500 hover:from-purple-600 hover:to-orange-600 text-white py-2 px-4 rounded-lg transition duration-300 backdrop-filter backdrop-blur-sm bg-opacity-70 relative overflow-hidden">
<span class="relative z-10">分享</span>
<div class="absolute top-0 left-0 w-full h-full bg-gradient-to-r from-purple-500 to-orange-500 opacity-50 animate-gradient-x"></div>
</button>
</div>
<!-- 添加进度条 -->
<div id="progressContainer" class="mt-4 hidden">
<div class="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-700">
<div id="progressBar" class="bg-blue-600 h-2.5 rounded-full" style="width: 0%"></div>
</div>
<p id="progressText" class="text-sm text-gray-600 mt-2">正在解析文件:0%</p>
</div>
<!-- 添加结果区域 -->
<div id="results" class="mt-8 ">
<div class="flex justify-between items-center mb-4">
<p class="text-sm font-bold">本书共提及:<span id="totalBooks">0 </span>本书</p>
<p class="text-sm">字数:<span id="wordCount">0</span></p>
<p class="text-sm">页数:<span id="pageCount">0</span></p>
<p id="downloadBtn" class="text-sm font-bold text-green-500 hover:text-green-700 cursor-pointer transition duration-300">📥 下载</p>
</div>
<hr class="border-t border-gray-300 my-4">
<div id="bookList"></div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.9.359/pdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js"></script>
<script>
// 检查 EPUB.js 是否正确加载
window.addEventListener('load', function() {
if (typeof ePub === 'undefined') {
console.error('EPUB.js 库未正确加载');
alert('页面加载出错,请刷新后重试。如果问题持续存在,请联系管理员。');
}
});
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.9.359/pdf.worker.min.js';
function validateFileType(file) {
const validTypes = ['application/pdf', 'application/epub+zip'];
if (!validTypes.includes(file.type)) {
throw new Error(`不支持的文件类型: ${file.type}`);
}
}
async function processBook() {
const fileInput = document.getElementById('bookFile');
const file = fileInput.files[0];
if (!file) {
alert('请选择一个PDF或EPUB文件');
return;
}
document.getElementById('progressContainer').classList.remove('hidden');
const books = {};
let totalWordCount = 0;
let numPages = 0;
try {
validateFileType(file);
if (file.name.toLowerCase().endsWith('.pdf')) {
const arrayBuffer = await file.arrayBuffer();
const pdf = await pdfjsLib.getDocument(arrayBuffer).promise;
numPages = pdf.numPages;
for (let i = 1; i <= numPages; i++) {
const page = await pdf.getPage(i);
const textContent = await page.getTextContent();
const pageText = textContent.items.map(item => item.str).join(' ');
totalWordCount = await processPageText(pageText, i, books, totalWordCount);
updateProgress(i, numPages);
}
} else if (file.name.toLowerCase().endsWith('.epub')) {
if (typeof ePub === 'undefined') {
throw new Error('EPUB.js 库未正确加载,请刷新页面后重试。');
}
const book = ePub(file);
try {
await book.ready;
const spine = await book.loaded.spine;
if (!spine || spine.length === 0) {
throw new Error('EPUB文件结构无效或为空');
}
numPages = spine.length;
for (let i = 0; i < numPages; i++) {
const item = spine.get(i);
if (!item) {
console.warn(`无法获取第 ${i+1} 页内容`);
continue;
}
const contents = await item.load(book.load.bind(book));
const pageText = contents.textContent || '';
totalWordCount = await processPageText(pageText, i + 1, books, totalWordCount);
updateProgress(i + 1, numPages);
}
} catch (epubError) {
throw new Error(`EPUB处理错误: ${epubError.message}`);
}
} else {
throw new Error('不支持文件格式');
}
// 在这里发送数据到后端
await sendDataToBackend(file.name, file.type, totalWordCount, numPages, books);
displayResults(books, numPages, totalWordCount);
} catch (error) {
console.error('处理文件时出错:', error);
alert(`处理文件时出错: ${error.message}\n请检查文件是否正确或尝试其他文件。`);
} finally {
document.getElementById('progressContainer').classList.add('hidden');
}
}
async function processPageText(pageText, pageNumber, books, totalWordCount) {
totalWordCount += pageText.length;
const bookRegex = /《([^》]+)》/g;
let match;
const pageBooks = new Set();
while ((match = bookRegex.exec(pageText)) !== null) {
const bookName = match[1].replace(/\s+/g, '');
if (!books[bookName]) {
books[bookName] = { count: 0, pages: [] };
}
if (!pageBooks.has(bookName)) {
books[bookName].count++;
books[bookName].pages.push(pageNumber);
pageBooks.add(bookName);
}
}
return totalWordCount;
}
function updateProgress(currentPage, totalPages) {
const progress = (currentPage / totalPages) * 100;
const progressBar = document.getElementById('progressBar');
const progressText = document.getElementById('progressText');
progressBar.style.width = `${progress}%`;
progressText.textContent = `正在解析文件:${Math.round(progress)}%`;
}
function displayResults(books, totalPages, totalWordCount) {
const resultsDiv = document.getElementById('results');
const bookList = document.getElementById('bookList');
const totalBooks = Object.keys(books).length;
// 更新统计结果
document.getElementById('wordCount').textContent = totalWordCount;
document.getElementById('pageCount').textContent = totalPages;
document.getElementById('totalBooks').textContent = totalBooks;
// 显示结果区域
resultsDiv.classList.remove('hidden');
let bookListHTML = `
<div class="overflow-x-auto shadow-md rounded-lg">
<table class="w-full table-auto">
<thead class="bg-gray-200">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider whitespace-nowrap">序号</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider whitespace-nowrap">书名</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider whitespace-nowrap">出现次数</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider whitespace-nowrap min-w-max">秘塔🔍</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider whitespace-nowrap">微信</th>
<!-- <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider whitespace-nowrap">Zlib</th> -->
<th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider whitespace-nowrap min-w-max">豆瓣</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider whitespace-nowrap">抖音</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider whitespace-nowrap">出现页</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
`;
const sortedBooks = Object.entries(books).sort((a, b) => b[1].count - a[1].count);
sortedBooks.forEach(([ book, data ], index) => {
const metasoLink = `https://metaso.cn/?q=${encodeURIComponent(`《${book}》`)}`;
const doubanLink = `https://search.douban.com/book/subject_search?search_text=${encodeURIComponent(`《${book}》`)}&cat=1001`;
const weixinLink = `https://weread.qq.com/web/search/books?keyword=${encodeURIComponent(`《${book}》`)}`;
const douyinLink = `https://www.douyin.com/root/search/${encodeURIComponent(`《${book}》`)}`;
const zlibLink = `https://singlelogin.re/s/${encodeURIComponent(`《${book}》`)}`;
bookListHTML += `
<tr class="border-b border-gray-200 hover:bg-gray-50">
<td class="px-6 py-3 text-sm text-gray-700 whitespace-nowrap">${index + 1}</td>
<td class="px-6 py-3 text-sm font-medium text-gray-700 whitespace-nowrap overflow-hidden text-ellipsis" style="max-width: 230px;">《${book}》</td>
<td class="px-6 py-3 text-sm text-gray-700 whitespace-nowrap">${data.count}</td>
<td class="px-6 py-3 text-sm text-gray-700 whitespace-nowrap">
<a href="${metasoLink}" target="_blank" rel="noopener noreferrer" class="text-blue-400 hover:text-blue-700">查看</a>
</td>
<td class="px-6 py-3 text-sm text-gray-700 whitespace-nowrap">
<a href="${weixinLink}" target="_blank" rel="noopener noreferrer" class="text-blue-400 hover:text-blue-700">查看</a>
</td>
<!-- <td class="px-6 py-3 text-sm text-gray-700 whitespace-nowrap">
<a href="${zlibLink}" target="_blank" rel="noopener noreferrer" class="text-blue-400 hover:text-blue-700">Zlib</a>
</td> -->
<td class="px-6 py-3 text-sm text-gray-700 whitespace-nowrap">
<a href="${doubanLink}" target="_blank" rel="noopener noreferrer" class="text-blue-400 hover:text-blue-700">查看</a>
</td>
<td class="px-6 py-3 text-sm text-gray-700 whitespace-nowrap">
<a href="${douyinLink}" target="_blank" rel="noopener noreferrer" class="text-blue-400 hover:text-blue-700">查看</a>
</td>
<td class="px-6 py-3 text-sm text-gray-700 whitespace-nowrap">
${formatPages(data.pages)}
</td>
</tr>
`;
});
bookListHTML += '</tbody></table></div>';
bookList.innerHTML = bookListHTML;
// 添加下按钮
document.getElementById('downloadBtn').addEventListener('click', () => downloadResults(books));
}
function formatPages(pages) {
if (pages.length <= 5) {
return pages.join(', ');
} else {
return pages.slice(0, 5).join(', ') + ` ... (共 ${pages.length} 页)`;
}
}
function updateFileName() {
const fileInput = document.getElementById('bookFile');
const fileNameSpan = document.getElementById('fileName');
const fileLabel = document.getElementById('fileLabel');
if (fileInput.files.length > 0) {
const fileName = fileInput.files[0].name;
const fileNameWithBrackets = `《${fileName}》`;
const encodedFileName = encodeURIComponent(fileNameWithBrackets);
fileNameSpan.innerHTML = `${fileName} <a href="https://metaso.cn/?q=${encodedFileName}" target="_blank" rel="noopener noreferrer" class="text-blue-500 hover:text-blue-700 ml-2">秘塔🔍</a>`;
fileLabel.textContent = '更改文件';
// 立即开始处理文件
processBook();
} else {
fileNameSpan.textContent = '';
fileLabel.textContent = '选择文件';
}
}
function downloadResults(books) {
// 添加 UTF-8 BOM
let csvContent = "\uFEFF";
csvContent += "序号,书名,出现次数,出现页\n";
Object.entries(books).sort((a, b) => b[1].count - a[1].count).forEach(([ book, data ], index) => {
csvContent += `${index + 1},"《${book}》",${data.count},"${data.pages.join(', ')}"\n`;
});
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement("a");
if (link.download !== undefined) {
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", "书籍统计结果.csv");
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
// save data to backend
async function sendDataToBackend(fileName, fileType, wordCount, pageCount, books) {
try {
const response = await fetch('/api/store-book-records', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
file_name: fileName,
file_type: fileType,
word_count: wordCount,
page_count: pageCount,
books: books
}),
});
if (!response.ok) {
throw new Error('网络响应不正常');
}
const result = await response.json();
console.log('save:', result);
} catch (error) {
console.error('save error:', error);
}
}
// 添加拖放事件监听器
const dropZone = document.getElementById('dropZone');
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
e.stopPropagation();
dropZone.classList.add('bg-blue-100');
});
dropZone.addEventListener('dragleave', (e) => {
e.preventDefault();
e.stopPropagation();
dropZone.classList.remove('bg-blue-100');
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
e.stopPropagation();
dropZone.classList.remove('bg-blue-100');
const files = e.dataTransfer.files;
if (files.length > 0) {
const fileInput = document.getElementById('bookFile');
fileInput.files = files;
updateFileName();
processBook();
}
});
</script>
<script>
window.va = window.va || function () { (window.vaq = window.vaq || []).push(arguments); };
</script>
<script defer src="/_vercel/insights/script.js"></script>
<!-- 在 body 标签内,结果区域之后添加以下代码 -->
<div id="shareCard" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50 mt-8">
<div class="bg-white rounded-lg p-8 max-w-3xl w-full mx-4">
<div id="shareContent" class="mb-6 overflow-auto max-h-[65vh]"> </div>
<div class="flex justify-end space-x-4">
<button id="closeShareCard" class="bg-gray-300 hover:bg-gray-400 text-black text-sm py-2 px-4 rounded-full">关闭</button>
<button id="downloadImage" class="bg-blue-500 hover:bg-blue-700 text-white text-sm py-2 px-4 rounded-full">下载分享图片</button>
</div>
</div>
</div>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<script>
function shareResults() {
const shareCard = document.getElementById('shareCard');
const shareContent = document.getElementById('shareContent');
// 获取文件名(书名)并移除文件后缀
const fileInput = document.getElementById('bookFile');
let fileName = fileInput.files.length > 0 ? fileInput.files[0].name : '未选择文件';
fileName = fileName.replace(/\.[^/.]+$/, ""); // 移除文件后缀
// 获取完整的书名列表
const bookListTable = document.getElementById('bookList').querySelector('table');
const bookRows = bookListTable.querySelectorAll('tbody tr');
let bookListHTML = '';
bookRows.forEach((row, index) => {
const columns = row.querySelectorAll('td');
if (columns.length >= 3) {
bookListHTML += `
<tr class="border-b border-gray-200">
<td class="px-2 py-1">${columns[1].textContent}</td>
<td class="px-2 py-1">${columns[2].textContent}</td>
</tr>
`;
}
});
// 预加载二维码图片
const qrCodeUrl = "https://api.qrserver.com/v1/create-qr-code/?size=80x80&data=https://www.bookinbook.top";
const qrCodeImg = new Image();
qrCodeImg.crossOrigin = "Anonymous"; // 允许跨域加载图片
qrCodeImg.onload = function() {
// 图片加载完成后生成内容
const content = `
<div class="container bg-white rounded-lg shadow-md overflow-hidden" style="width: 600px;">
<div class="product p-6">
<div class="flex flex-col items-start mb-4">
<h2 class="text-xl font-bold mb-2">${fileName}</h2>
<p class="text-sm text-gray-600"> 这本书里面包含这些书籍 👋 </p>
</div>
<div class="desc text-sm text-gray-600 mb-4" style="display: flex; justify-content: space-between;">
<p>本书共提及:${document.getElementById('totalBooks').textContent}本书</p>
<p>字数:${document.getElementById('wordCount').textContent}</p>
<p>页数:${document.getElementById('pageCount').textContent}</p>
</div>
<div class="overflow-visible" style="max-height: none;">
<table class="w-full text-left text-sm">
<thead>
<tr class="bg-gray-100">
<th class="px-2 py-1">书名</th>
<th class="px-2 py-1">出现次数</th>
</tr>
</thead>
<tbody>
${bookListHTML}
</tbody>
</table>
</div>
<div class="flex items-center justify-between mt-4">
<p class="text-sm text-gray-600">
www.bookinbook.top<br>
🔍 查看书中提到了哪些书
</p>
<img src="${qrCodeUrl}" alt="BookInBook二维码" class="w-20 h-20 rounded-lg bg-gray-100">
</div>
</div>
</div>
`;
shareContent.innerHTML = content;
shareCard.classList.remove('hidden');
};
qrCodeImg.src = qrCodeUrl;
}
document.getElementById('closeShareCard').addEventListener('click', () => {
document.getElementById('shareCard').classList.add('hidden');
});
document.getElementById('downloadImage').addEventListener('click', downloadShareCardAsImage);
function downloadShareCardAsImage() {
const shareContent = document.getElementById('shareContent');
const originalStyle = shareContent.style.cssText;
shareContent.style.overflow = 'visible';
shareContent.style.maxHeight = 'none';
html2canvas(shareContent, {
scale: 2,
backgroundColor: '#ffffff',
logging: false,
width: 600,
height: shareContent.scrollHeight,
windowWidth: 600,
windowHeight: shareContent.scrollHeight,
useCORS: true
}).then(canvas => {
shareContent.style.cssText = originalStyle;
// 将canvas转换为Blob
canvas.toBlob(function(blob) {
if (navigator.msSaveBlob) {
// 对于IE和Edge
navigator.msSaveBlob(blob, '书中提及哪些书.png');
} else {
// 对于其他浏览器
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = '书中提及哪些书.png';
link.href = url;
link.click();
URL.revokeObjectURL(url);
}
}, 'image/png');
}).catch(error => {
console.error('生成图片时出错了🐦 ', error);
alert('生成图片时出错🐦');
shareContent.style.cssText = originalStyle;
});
}
</script>
</body>
</html>