vomebook commited on
Commit
a124605
·
1 Parent(s): 1610b91

Broaden Reader format compatibility

Browse files
scripts/copy_reader_vendor.mjs CHANGED
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
  import { mkdirSync, writeFileSync } from "node:fs";
3
  import { get } from "node:https";
4
  import { dirname, join } from "node:path";
 
5
 
6
  const output = process.argv[2] || "static/vendor";
7
  mkdirSync(output, { recursive: true });
@@ -39,14 +40,25 @@ async function downloadWithRetry(url) {
39
  }
40
 
41
  async function main() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  for (const [url, target, expected] of [
43
  ["https://cdn.jsdelivr.net/npm/pdfjs-dist@6.2.108/build/pdf.min.mjs", "pdf.min.mjs", "e0be3863c23c8af2305b16548febd58e7f8874a460253317d7771cddbc1c0f6d"],
44
  ["https://cdn.jsdelivr.net/npm/pdfjs-dist@6.2.108/build/pdf.worker.min.mjs", "pdf.worker.min.mjs", "0613f41490dd6aaceed7a93fbbd38c85e6d6aa60474b6588c6e7709cfbe18cb3"],
45
- ["https://cdn.jsdelivr.net/npm/pdfjs-dist@6.2.108/wasm/jbig2.wasm", "wasm/jbig2.wasm", "e6bee67724a7b5436fe8162638e3708cfc8d52b6342db69a49715e30ff27cfdc"],
46
- ["https://cdn.jsdelivr.net/npm/pdfjs-dist@6.2.108/wasm/jbig2_nowasm_fallback.js", "wasm/jbig2_nowasm_fallback.js", "04c795a6657a4553a64b781ea3e85256203d913c3b71b72b85fa3ce00622f458"],
47
- ["https://cdn.jsdelivr.net/npm/pdfjs-dist@6.2.108/wasm/openjpeg.wasm", "wasm/openjpeg.wasm", "004a0e62db930ba9ff2a22212f4554d0bb57a0635a8287caf70f98117cee14ba"],
48
- ["https://cdn.jsdelivr.net/npm/pdfjs-dist@6.2.108/wasm/openjpeg_nowasm_fallback.js", "wasm/openjpeg_nowasm_fallback.js", "0f998419819da4491d8302222aa9e2ff2494685641aa2a6c21c3760c29f3e319"],
49
- ["https://cdn.jsdelivr.net/npm/pdfjs-dist@6.2.108/wasm/qcms_bg.wasm", "wasm/qcms_bg.wasm", "663d86126d5f5fcb1c61490f94353e2a8375660b8c5498ab3ebab5a34b08800e"],
50
  ["https://cdn.jsdelivr.net/npm/epubjs@0.3.93/dist/epub.min.js", "epub.min.js", "06eae15745107b4aa508c95538275251f69bfb9f1175621fc458d9f42ed082d4"],
51
  ["https://cdn.jsdelivr.net/npm/marked@18.0.10/lib/marked.umd.js", "marked.min.js", "eaccee2fb9fb3b2c09e873a5504da82507850d9e677bd720122ac49e2a03982a"],
52
  ["https://cdn.jsdelivr.net/npm/dompurify@3.4.14/dist/purify.min.js", "purify.min.js", "c2f26ea4fc0d88141c9aa430eb515ac86fce59418ceebd85fa475b87a8d6c3e6"],
 
2
  import { mkdirSync, writeFileSync } from "node:fs";
3
  import { get } from "node:https";
4
  import { dirname, join } from "node:path";
5
+ import { gunzipSync } from "node:zlib";
6
 
7
  const output = process.argv[2] || "static/vendor";
8
  mkdirSync(output, { recursive: true });
 
40
  }
41
 
42
  async function main() {
43
+ const pdfArchive = await downloadWithRetry("https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-6.2.108.tgz");
44
+ const pdfArchiveHash = createHash("sha256").update(pdfArchive).digest("hex");
45
+ if (pdfArchiveHash !== "b3e68d5cda70551a90b3f771419d379e20fc788ce056fa32de73608e01df47f4") throw new Error(`pdfjs-dist archive SHA-256 ${pdfArchiveHash} does not match`);
46
+ const tar = gunzipSync(pdfArchive);
47
+ for (let offset = 0; offset + 512 <= tar.length;) {
48
+ const header = tar.subarray(offset, offset + 512), name = header.subarray(0, 100).toString().replace(/\0.*$/, "");
49
+ if (!name) break;
50
+ const size = parseInt(header.subarray(124, 136).toString().replace(/\0.*$/, "").trim() || "0", 8);
51
+ const relative = name.replace(/^package\//, "");
52
+ if ((relative.startsWith("cmaps/") || relative.startsWith("standard_fonts/") || relative.startsWith("wasm/")) && !relative.endsWith("/")) {
53
+ const target = join(output, relative);
54
+ mkdirSync(dirname(target), { recursive: true });
55
+ writeFileSync(target, tar.subarray(offset + 512, offset + 512 + size));
56
+ }
57
+ offset += 512 + Math.ceil(size / 512) * 512;
58
+ }
59
  for (const [url, target, expected] of [
60
  ["https://cdn.jsdelivr.net/npm/pdfjs-dist@6.2.108/build/pdf.min.mjs", "pdf.min.mjs", "e0be3863c23c8af2305b16548febd58e7f8874a460253317d7771cddbc1c0f6d"],
61
  ["https://cdn.jsdelivr.net/npm/pdfjs-dist@6.2.108/build/pdf.worker.min.mjs", "pdf.worker.min.mjs", "0613f41490dd6aaceed7a93fbbd38c85e6d6aa60474b6588c6e7709cfbe18cb3"],
 
 
 
 
 
62
  ["https://cdn.jsdelivr.net/npm/epubjs@0.3.93/dist/epub.min.js", "epub.min.js", "06eae15745107b4aa508c95538275251f69bfb9f1175621fc458d9f42ed082d4"],
63
  ["https://cdn.jsdelivr.net/npm/marked@18.0.10/lib/marked.umd.js", "marked.min.js", "eaccee2fb9fb3b2c09e873a5504da82507850d9e677bd720122ac49e2a03982a"],
64
  ["https://cdn.jsdelivr.net/npm/dompurify@3.4.14/dist/purify.min.js", "purify.min.js", "c2f26ea4fc0d88141c9aa430eb515ac86fce59418ceebd85fa475b87a8d6c3e6"],
static/reader.html CHANGED
@@ -4,7 +4,7 @@
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
  <meta name="theme-color" content="#181a1d">
7
- <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https://huggingface.co https://hf-mirror.com https://*.huggingface.co https://*.hf.co https://*.xethub.hf.co; connect-src 'self' blob: https://huggingface.co https://hf-mirror.com https://*.huggingface.co https://*.hf.co https://*.xethub.hf.co; worker-src 'self' blob:; frame-src 'self' blob:; font-src 'self' data:; base-uri 'none'; form-action 'none'; object-src 'none'">
8
  <title>VoiceOfML Reader</title>
9
  <link rel="preconnect" href="https://huggingface.co" crossorigin>
10
  <link rel="stylesheet" href="/static/reader.css">
 
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
  <meta name="theme-color" content="#181a1d">
7
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https://huggingface.co https://hf-mirror.com https://*.huggingface.co https://*.hf.co https://*.xethub.hf.co; connect-src 'self' blob: https://huggingface.co https://hf-mirror.com https://*.huggingface.co https://*.hf.co https://*.xethub.hf.co; worker-src 'self' blob:; frame-src 'self' blob:; font-src 'self' data:; base-uri 'none'; form-action 'none'; object-src 'none'">
8
  <title>VoiceOfML Reader</title>
9
  <link rel="preconnect" href="https://huggingface.co" crossorigin>
10
  <link rel="stylesheet" href="/static/reader.css">
static/reader.js CHANGED
@@ -1,6 +1,8 @@
1
  const PDFJS_URL = "/static/vendor/pdf.min.e0be3863c23c.mjs";
2
  const PDFJS_WORKER_URL = "/static/pdf-worker-wrapper.mjs";
3
  const PDFJS_WASM_URL = "/static/vendor/wasm/";
 
 
4
  const EPUB_URL = "/static/vendor/epub.min.06eae1574510.js";
5
  const MARKED_URL = "/static/vendor/marked.min.eaccee2fb9fb.js";
6
  const PURIFY_URL = "/static/vendor/purify.min.c2f26ea4fc0d.js";
@@ -237,6 +239,7 @@ async function renderPdfShell(shell, force = false, priority = false) {
237
  shell.dataset.renderState = "idle";
238
  console.warn(`PDF page ${shell.dataset.page} render failed`, error);
239
  const retries = Number(shell.dataset.renderRetries || 0);
 
240
  if (retries < 3) { shell.dataset.renderRetries = String(retries + 1); setTimeout(() => renderPdfShell(shell, true), 400 * (retries + 1)); }
241
  } finally { releasePdfRenderSlot(); finishRender(); delete shell._renderPromise; }
242
  }
@@ -289,7 +292,8 @@ async function renderText(markdown, prepared) {
289
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
290
  if (!markdown) await renderPlainText(response);
291
  else {
292
- const text = await response.text();
 
293
  await prepared.engines;
294
  const article = document.createElement("article"); article.className = "reader-markdown";
295
  article.innerHTML = DOMPurify.sanitize(marked.parse(text), { USE_PROFILES: { html: true } }); content.appendChild(article);
@@ -304,15 +308,27 @@ async function renderPlainText(response) {
304
  textNode.data = new TextDecoder(detectTextEncoding(bytes, title)).decode(bytes);
305
  return;
306
  }
307
- const reader = response.body.getReader();
308
- const first = await reader.read();
309
- const sample = first.value || new Uint8Array();
310
- let streamDone = first.done;
 
 
 
 
 
 
 
 
 
 
 
 
311
  const decoder = new TextDecoder(detectTextEncoding(sample, title));
312
  let pending = "", frame = 0;
313
  const flush = () => { frame = 0; if (pending) { textNode.appendData(pending); pending = ""; } };
314
  const scheduleFlush = () => { if (!frame) frame = requestAnimationFrame(flush); };
315
- pending = decoder.decode(sample, { stream: !streamDone });
316
  scheduleFlush();
317
  while (!streamDone) {
318
  const { value, done } = await reader.read();
@@ -332,7 +348,7 @@ function detectTextEncoding(bytes, hint = "") {
332
  const oddNulls = bytes.filter((value, index) => !value && index % 2 === 1).length;
333
  if (oddNulls > bytes.length / 8 && oddNulls > evenNulls * 4) return "utf-16le";
334
  if (evenNulls > bytes.length / 8 && evenNulls > oddNulls * 4) return "utf-16be";
335
- try { new TextDecoder("utf-8", { fatal: true }).decode(bytes, { stream: true }); return "utf-8"; } catch (_) {}
336
  if (/[\u0400-\u04ff]/.test(hint)) return "windows-1251";
337
  const candidates = ["gb18030", "big5", "windows-1251", "windows-1252"];
338
  let best = "gb18030", bestScore = -Infinity;
@@ -360,7 +376,9 @@ async function renderEpub(prepared) {
360
  async function displayEpub(url, frame) {
361
  const book = ePub(url); epubRendition = book.renderTo(frame, { width: "100%", height: "100%", spread: "none", flow: "scrolled-doc" });
362
  epubRendition.on("relocated", (location) => { epubLocation = location && location.start ? location.start.cfi : ""; scheduleSave(); });
363
- await epubRendition.display(restoredEntry && restoredEntry.epubLocation || undefined);
 
 
364
  }
365
  async function renderDocx(prepared) {
366
  const [response] = await prepared;
@@ -375,6 +393,7 @@ async function renderDocx(prepared) {
375
  renderHeaders: true, renderFooters: true, renderFootnotes: true, renderEndnotes: true,
376
  renderChanges: false, renderComments: false, renderAltChunks: false, debug: false,
377
  });
 
378
  for (const link of body.querySelectorAll("a[href]")) {
379
  const href = link.getAttribute("href") || "";
380
  if (!href.startsWith("#") && !/^https?:\/\//i.test(href)) link.removeAttribute("href");
@@ -405,7 +424,7 @@ async function start() {
405
  } catch (error) { console.error(error); fail("原文件加载失败,请检查网络后重试,或下载原文件。"); }
406
  }
407
  function prepareDocument() {
408
- if (capability.mode === "pdf") return import(PDFJS_URL).then((pdfjs) => { pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL; const options = (url) => ({ url, wasmUrl: PDFJS_WASM_URL, withCredentials: false }); return pdfjs.getDocument(options(contentUrl)).promise.catch(() => pdfjs.getDocument(options(sourceUrl)).promise); });
409
  if (capability.mode === "markdown") return Promise.all([fetch(contentUrl), Promise.all([loadScript(MARKED_URL), loadScript(PURIFY_URL)])]).then(([response, engines]) => ({ response, engines }));
410
  if (capability.mode === "text") return fetch(contentUrl).then((response) => ({ response }));
411
  if (capability.mode === "epub") return Promise.all([fetch(contentUrl), loadScript(JSZIP_URL).then(() => loadScript(EPUB_URL))]);
 
1
  const PDFJS_URL = "/static/vendor/pdf.min.e0be3863c23c.mjs";
2
  const PDFJS_WORKER_URL = "/static/pdf-worker-wrapper.mjs";
3
  const PDFJS_WASM_URL = "/static/vendor/wasm/";
4
+ const PDFJS_CMAP_URL = "/static/vendor/cmaps/";
5
+ const PDFJS_STANDARD_FONT_URL = "/static/vendor/standard_fonts/";
6
  const EPUB_URL = "/static/vendor/epub.min.06eae1574510.js";
7
  const MARKED_URL = "/static/vendor/marked.min.eaccee2fb9fb.js";
8
  const PURIFY_URL = "/static/vendor/purify.min.c2f26ea4fc0d.js";
 
239
  shell.dataset.renderState = "idle";
240
  console.warn(`PDF page ${shell.dataset.page} render failed`, error);
241
  const retries = Number(shell.dataset.renderRetries || 0);
242
+ if (priority) throw error;
243
  if (retries < 3) { shell.dataset.renderRetries = String(retries + 1); setTimeout(() => renderPdfShell(shell, true), 400 * (retries + 1)); }
244
  } finally { releasePdfRenderSlot(); finishRender(); delete shell._renderPromise; }
245
  }
 
292
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
293
  if (!markdown) await renderPlainText(response);
294
  else {
295
+ const bytes = new Uint8Array(await response.arrayBuffer());
296
+ const text = new TextDecoder(detectTextEncoding(bytes, title)).decode(bytes);
297
  await prepared.engines;
298
  const article = document.createElement("article"); article.className = "reader-markdown";
299
  article.innerHTML = DOMPurify.sanitize(marked.parse(text), { USE_PROFILES: { html: true } }); content.appendChild(article);
 
308
  textNode.data = new TextDecoder(detectTextEncoding(bytes, title)).decode(bytes);
309
  return;
310
  }
311
+ const reader = response.body.getReader(), chunks = [];
312
+ let sampleSize = 0, displayedSampleSize = 0, streamDone = false;
313
+ while (!streamDone && sampleSize < 65536) {
314
+ const { value, done } = await reader.read();
315
+ streamDone = done;
316
+ if (value && value.length) {
317
+ chunks.push(value); sampleSize += value.length;
318
+ if (displayedSampleSize === sampleSize - value.length) {
319
+ let asciiLength = 0; while (asciiLength < value.length && value[asciiLength] < 128) asciiLength++;
320
+ if (asciiLength) { textNode.appendData(new TextDecoder("utf-8").decode(value.subarray(0, asciiLength))); displayedSampleSize += asciiLength; }
321
+ }
322
+ }
323
+ }
324
+ const sample = new Uint8Array(sampleSize);
325
+ let sampleOffset = 0;
326
+ for (const chunk of chunks) { sample.set(chunk, sampleOffset); sampleOffset += chunk.length; }
327
  const decoder = new TextDecoder(detectTextEncoding(sample, title));
328
  let pending = "", frame = 0;
329
  const flush = () => { frame = 0; if (pending) { textNode.appendData(pending); pending = ""; } };
330
  const scheduleFlush = () => { if (!frame) frame = requestAnimationFrame(flush); };
331
+ pending = decoder.decode(sample.subarray(displayedSampleSize), { stream: !streamDone });
332
  scheduleFlush();
333
  while (!streamDone) {
334
  const { value, done } = await reader.read();
 
348
  const oddNulls = bytes.filter((value, index) => !value && index % 2 === 1).length;
349
  if (oddNulls > bytes.length / 8 && oddNulls > evenNulls * 4) return "utf-16le";
350
  if (evenNulls > bytes.length / 8 && evenNulls > oddNulls * 4) return "utf-16be";
351
+ try { new TextDecoder("utf-8", { fatal: true }).decode(bytes); return "utf-8"; } catch (_) {}
352
  if (/[\u0400-\u04ff]/.test(hint)) return "windows-1251";
353
  const candidates = ["gb18030", "big5", "windows-1251", "windows-1252"];
354
  let best = "gb18030", bestScore = -Infinity;
 
376
  async function displayEpub(url, frame) {
377
  const book = ePub(url); epubRendition = book.renderTo(frame, { width: "100%", height: "100%", spread: "none", flow: "scrolled-doc" });
378
  epubRendition.on("relocated", (location) => { epubLocation = location && location.start ? location.start.cfi : ""; scheduleSave(); });
379
+ const restoredLocation = restoredEntry && restoredEntry.epubLocation;
380
+ try { await epubRendition.display(restoredLocation || undefined); }
381
+ catch (error) { if (!restoredLocation) throw error; epubLocation = ""; await epubRendition.display(); }
382
  }
383
  async function renderDocx(prepared) {
384
  const [response] = await prepared;
 
393
  renderHeaders: true, renderFooters: true, renderFootnotes: true, renderEndnotes: true,
394
  renderChanges: false, renderComments: false, renderAltChunks: false, debug: false,
395
  });
396
+ if (!(body.textContent || "").trim() && !body.querySelector("img, table, svg, canvas")) throw new Error("DOCX rendered no supported content");
397
  for (const link of body.querySelectorAll("a[href]")) {
398
  const href = link.getAttribute("href") || "";
399
  if (!href.startsWith("#") && !/^https?:\/\//i.test(href)) link.removeAttribute("href");
 
424
  } catch (error) { console.error(error); fail("原文件加载失败,请检查网络后重试,或下载原文件。"); }
425
  }
426
  function prepareDocument() {
427
+ if (capability.mode === "pdf") return import(PDFJS_URL).then((pdfjs) => { pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL; const options = (url) => ({ url, wasmUrl: PDFJS_WASM_URL, cMapUrl: PDFJS_CMAP_URL, cMapPacked: true, standardFontDataUrl: PDFJS_STANDARD_FONT_URL, withCredentials: false }); return pdfjs.getDocument(options(contentUrl)).promise.catch(() => pdfjs.getDocument(options(sourceUrl)).promise); });
428
  if (capability.mode === "markdown") return Promise.all([fetch(contentUrl), Promise.all([loadScript(MARKED_URL), loadScript(PURIFY_URL)])]).then(([response, engines]) => ({ response, engines }));
429
  if (capability.mode === "text") return fetch(contentUrl).then((response) => ({ response }));
430
  if (capability.mode === "epub") return Promise.all([fetch(contentUrl), loadScript(JSZIP_URL).then(() => loadScript(EPUB_URL))]);