vomebook commited on
Commit ·
9ae8ec6
1
Parent(s): 0232c8f
feat: support additional Reader formats
Browse filesFiles changed (12)
1632 unmodified lines16331634163516361637163816391632 unmodified lines"css": "text/css", "jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png","gif": "image/gif", "bmp": "image/bmp", "webp": "image/webp", "jxl": "image/jxl", "svg": "image/svg+xml", "ttf": "font/ttf","otf": "font/otf", "woff": "font/woff", "woff2": "font/woff2", "mp3": "audio/mpeg","mp4": "video/mp4", "gz": "application/gzip",}def initialize_reader_bucket_state(target_app: FastAPI) -> None:target_app.state.reader_bucket_cache = OrderedDict()1632 unmodified lines163316341635163616371638163916401632 unmodified lines"css": "text/css", "jpg": "image/jpeg", "jpeg": "image/jpeg", "png": "image/png","gif": "image/gif", "bmp": "image/bmp", "webp": "image/webp", "jxl": "image/jxl", "svg": "image/svg+xml", "ttf": "font/ttf","otf": "font/otf", "woff": "font/woff", "woff2": "font/woff2", "mp3": "audio/mpeg","wav": "audio/wav", "m4a": "audio/mp4", "flac": "audio/flac", "mpga": "audio/mpeg","mp4": "video/mp4", "mov": "video/quicktime", "swf": "application/x-shockwave-flash", "gz": "application/gzip",}def initialize_reader_bucket_state(target_app: FastAPI) -> None:target_app.state.reader_bucket_cache = OrderedDict()
16 unmodified lines1718192021222324252627282916 unmodified lines"t": {"document.txt"},"k": {"document.md"},"i": {"document.webp", "document.jpg", "document.jpeg", "document.png", "document.gif", "document.bmp"},"a": {"audio.mp3"},"v": {"video.mp4"},}READER_BUCKET_PATH_RE = re.compile(r"^(?:objects/[0-9a-f]{2}/[0-9a-f]{64}/[0-9a-f]{16}/(?:page-manifest\.json|ocr-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl)|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))|"r"ebook-chapters/objects/[0-9a-f]{2}/[0-9a-f]{64}/[a-z0-9-]+/[a-z0-9-]+-epub-chapters-v[0-9]+-bucket/epub-chapters/(?:chapter-manifest\.json|chapters/chapter-[0-9]{4}\.xhtml|resources/(?!\.{1,2}(?:/|$))[^/]+(?:/(?!\.{1,2}(?:/|$))[^/]+)*|epub-search-index\.json\.gz)|"r"objects/[0-9a-f]{2}/[0-9a-f]{64}/(?:[0-9a-f]{16}/)?(?:[a-z0-9-]+/)?document\.(?:epub|mobi|azw|azw3|fb2|docx|html|txt|md|webp|jpg|jpeg|png|gif|bmp))$")READER_EBOOK_BUCKET = "vomebook/pdf-pages"16 unmodified lines171819202122232425262728293016 unmodified lines"t": {"document.txt"},"k": {"document.md"},"i": {"document.webp", "document.jpg", "document.jpeg", "document.png", "document.gif", "document.bmp"},"a": {"audio.mp3", "audio.wav", "audio.m4a", "audio.flac", "audio.mpga"},"v": {"video.mp4", "video.mov"},"f": {"document.swf"},}READER_BUCKET_PATH_RE = re.compile(r"^(?:objects/[0-9a-f]{2}/[0-9a-f]{64}/[0-9a-f]{16}/(?:page-manifest\.json|ocr-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl)|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))|"r"ebook-chapters/objects/[0-9a-f]{2}/[0-9a-f]{64}/[a-z0-9-]+/[a-z0-9-]+-epub-chapters-v[0-9]+-bucket/epub-chapters/(?:chapter-manifest\.json|chapters/chapter-[0-9]{4}\.xhtml|resources/(?!\.{1,2}(?:/|$))[^/]+(?:/(?!\.{1,2}(?:/|$))[^/]+)*|epub-search-index\.json\.gz)|"r"objects/[0-9a-f]{2}/[0-9a-f]{64}/(?:[0-9a-f]{16}/)?(?:[a-z0-9-]+/)?(?:document\.(?:epub|mobi|azw|azw3|fb2|docx|html|txt|md|webp|jpg|jpeg|png|gif|bmp|swf)|audio\.(?:mp3|wav|m4a|flac|mpga)|video\.(?:mp4|mov)))$")READER_EBOOK_BUCKET = "vomebook/pdf-pages"
5 unmodified lines678910111269 unmodified lines828384858687885 unmodified linesREADER_ASSET_MODES = {"p": "pdf", "e": "epub", "d": "docx", "h": "html","t": "txt", "k": "md", "i": "webp", "a": "audio", "v": "video",}READER_NATIVE_FOLIATE_EXTENSIONS = frozenset({"epub", "mobi", "azw", "azw3", "fb2"})READER_ASSETS_BASE = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/"69 unmodified linesand raw_path.endswith("/page-manifest.json")):return "https://huggingface.co/buckets/vomebook/pdf-pages/resolve/" + pathif (bucket == "vomebook/pdf-pages" and raw_path.startswith("objects/")and re.search(r"/document\.(?:docx|html|txt|md|webp|jpg|jpeg|png|gif|bmp)$", raw_path)):return "https://huggingface.co/buckets/vomebook/pdf-pages/resolve/" + pathif bucket == "vomebook/pdf-pages":return "/api/reader-bucket-resource?path=" + path5 unmodified lines678910111269 unmodified lines82838485868788895 unmodified linesREADER_ASSET_MODES = {"p": "pdf", "e": "epub", "d": "docx", "h": "html","t": "txt", "k": "md", "i": "webp", "a": "audio", "v": "video", "f": "swf",}READER_NATIVE_FOLIATE_EXTENSIONS = frozenset({"epub", "mobi", "azw", "azw3", "fb2"})READER_ASSETS_BASE = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/"69 unmodified linesand raw_path.endswith("/page-manifest.json")):return "https://huggingface.co/buckets/vomebook/pdf-pages/resolve/" + pathif (bucket == "vomebook/pdf-pages" and raw_path.startswith("objects/")and re.search(r"/(?:document\.(?:docx|html|txt|md|webp|jpg|jpeg|png|gif|bmp|swf)"r"|audio\.(?:mp3|wav|m4a|flac|mpga)|video\.(?:mp4|mov))$", raw_path)):return "https://huggingface.co/buckets/vomebook/pdf-pages/resolve/" + pathif bucket == "vomebook/pdf-pages":return "/api/reader-bucket-resource?path=" + path
6 unmodified lines789101112136 unmodified lines2021222324252627283033 unmodified lines306230633064306530663067306816 unmodified lines30853086308730883089309030916 unmodified lines"jpg", "jpeg", "png", "gif", "bmp", "tif", "psd","html", "htm", "mht", "vcf","mp3", "wav", "m4a", "flac", "mpga", "wma", "ape", "amr","mp4", "mov", "flv", "f4v", "rm", "rmvb", "mkv", "avi", "mpg", "mts", "wmv", "asx", "swf",];const FILE_ICON_MAP = {pdf: "pdf",6 unmodified linesbmp: "image", webp: "image", svg: "image",html: "code", htm: "code", aspx: "code", css: "code", js: "code", xml: "code",json: "code", ini: "code", bat: "code",mp4: "video", flv: "video", swf: "video", rm: "video", rmvb: "video",wmv: "video", mpg: "video", mts: "video", f4v: "video", asx: "video",mp3: "audio", wav: "audio", wma: "audio", ape: "audio", m4a: "audio", mpga: "audio",iso: "archive", msi: "archive", dat: "archive",exe: "file",db: "database", itf: "database",3033 unmodified lines<button class="result-action-btn" data-action="copy" data-link="${escapeHTML(getCopyableLink(recordLink))}">复制链接</button><button class="result-action-btn primary" data-action="download" data-filename="${escapeHTML(rec.File + (rec.Extension ? '.' + rec.Extension : ''))}" data-link="${escapeHTML(recordLink)}">下载</button><a href="${escapeHTML(getPreviewLink(recordPath))}" class="result-action-btn" target="_blank" rel="noopener noreferrer">仓库查看</a>${readerActionUrl ? `<button class="result-action-btn" data-action="read" data-reader-url="${escapeHTML(readerActionUrl)}">${["audio", "video"].includes(VoiceOfMLReader.capability(readerActionRecord.ReaderExtension || readerActionRecord.Extension).mode) ? "在线播放" : "在线阅读"}</button>` : ""}</div>`;}16 unmodified linesVSCROLL.measuredRowKeys[index] = null;}button.dataset.readerUrl = getReaderLink(actionRecord);const label = ["audio", "video"].includes(VoiceOfMLReader.capability(actionRecord.ReaderExtension || actionRecord.Extension).mode) ? "在线播放" : "在线阅读";if (button.textContent !== label) { button.textContent = label; VSCROLL.measuredRowKeys[index] = null; }}VSCROLL.measuredWindowKey = "";6 unmodified lines789101112136 unmodified lines2021222324252627283033 unmodified lines306230633064306530663067306816 unmodified lines30853086308730883089309030916 unmodified lines"jpg", "jpeg", "png", "gif", "bmp", "tif", "psd","html", "htm", "mht", "vcf","mp3", "wav", "m4a", "flac", "mpga", "wma", "ape", "amr","mp4", "mov", "flv", "f4v", "rm", "rmvb", "mkv", "avi", "mpg", "mts", "ts", "wmv", "asx", "swf",];const FILE_ICON_MAP = {pdf: "pdf",6 unmodified linesbmp: "image", webp: "image", svg: "image",html: "code", htm: "code", aspx: "code", css: "code", js: "code", xml: "code",json: "code", ini: "code", bat: "code",mp4: "video", mov: "video", flv: "video", swf: "video", asx: "video", rm: "video", rmvb: "video",wmv: "video", mpg: "video", mts: "video", f4v: "video", asx: "video",mp3: "audio", wav: "audio", wma: "audio", ape: "audio", m4a: "audio", flac: "audio", mpga: "audio",iso: "archive", msi: "archive", dat: "archive",exe: "file",db: "database", itf: "database",3033 unmodified lines<button class="result-action-btn" data-action="copy" data-link="${escapeHTML(getCopyableLink(recordLink))}">复制链接</button><button class="result-action-btn primary" data-action="download" data-filename="${escapeHTML(rec.File + (rec.Extension ? '.' + rec.Extension : ''))}" data-link="${escapeHTML(recordLink)}">下载</button><a href="${escapeHTML(getPreviewLink(recordPath))}" class="result-action-btn" target="_blank" rel="noopener noreferrer">仓库查看</a>${readerActionUrl ? `<button class="result-action-btn" data-action="read" data-reader-url="${escapeHTML(readerActionUrl)}">${["audio", "video", "swf"].includes(VoiceOfMLReader.capability(readerActionRecord.ReaderExtension || readerActionRecord.Extension).mode) ? "在线播放" : "在线阅读"}</button>` : ""}</div>`;}16 unmodified linesVSCROLL.measuredRowKeys[index] = null;}button.dataset.readerUrl = getReaderLink(actionRecord);const label = ["audio", "video", "swf"].includes(VoiceOfMLReader.capability(actionRecord.ReaderExtension || actionRecord.Extension).mode) ? "在线播放" : "在线阅读";if (button.textContent !== label) { button.textContent = label; VSCROLL.measuredRowKeys[index] = null; }}VSCROLL.measuredWindowKey = "";
104 unmodified lines10510610710810911011171 unmodified lines18318418518618718820 unmodified lines2092102112122132142153 unmodified lines2192202212222232242255 unmodified lines231232233234235236237104 unmodified linesaudio: "audio",mp4: "video",mov: "video",video: "video"});const articleExtensions = Object.freeze(Object.keys(modes));const features = Object.freeze({71 unmodified linesbookmarks: true,pagination: false,media: true}});20 unmodified linesconst assetVersion = String.raw`(?:[0-9a-f]{16}/)?`;const assetPages = String.raw`(?:page-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl))`;const assetOcr = String.raw`(?:ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))`;const assetDocument = String.raw`(?:linearized\.pdf|document\.(?:pdf|epub|mobi|azw|azw3|fb2|docx|html|txt|md|webp)|book\.epub|audio\.mp3|video\.mp4)`;const assetChapters = String.raw`(?:chapter-manifest\.json|epub-chapters/(?:chapter-manifest\.json|chapters/chapter-[0-9]{4}\.xhtml|resources/[A-Za-z0-9._~%+\-/]+|epub-search-index\.json\.gz))`;const ebookBucketPathPattern = new RegExp(`^ebook-chapters/${assetRoot}[a-z0-9-]+/[a-z0-9-]+-epub-chapters-v[0-9]+-bucket/epub-chapters/(?:chapter-manifest\\.json|chapters/chapter-[0-9]{4}\\.xhtml|resources/(?!\\.{1,2}(?:/|$))[^/]+(?:/(?!\\.{1,2}(?:/|$))[^/]+)*|epub-search-index\\.json\\.gz)$`);const assetPrimaryPattern = new RegExp(3 unmodified lines`^(?:pdf_manifest\\.json|${assetRoot}${assetVersion}(?:${assetPages}|${assetOcr}|(?:[a-z0-9-]+/)?(?:${assetDocument}|${assetChapters})))$`);const bucketPathPattern = new RegExp(`^${assetRoot}${assetVersion}(?:${assetPages}|${assetOcr})$`);const staticBucketPathPattern = new RegExp(`^${assetRoot}(?:[0-9a-f]{16}/)?(?:[a-z0-9-]+/)?document\\.(?:docx|html|txt|md|webp|jpg|jpeg|png|gif|bmp)$`);const versionedBucketPathPattern = new RegExp(`^${assetRoot}[0-9a-f]{16}/(?:${assetPages}|${assetOcr})$`);const assetBase = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/";const assetModes = Object.freeze({5 unmodified linesk: "md",i: "webp",a: "audio",v: "video"});function isBucketPath(path, versioned = false, bucket = "vomebook/pdf-pages") {104 unmodified lines10510610710810911011111271 unmodified lines18418518618718818919019119219319419519619720 unmodified lines2182192202212222232243 unmodified lines2282292302312322332345 unmodified lines240241242243244245246247104 unmodified linesaudio: "audio",mp4: "video",mov: "video",video: "video",swf: "swf"});const articleExtensions = Object.freeze(Object.keys(modes));const features = Object.freeze({71 unmodified linesbookmarks: true,pagination: false,media: true},swf: {toc: false,search: false,zoom: false,bookmarks: true,pagination: false,media: true}});20 unmodified linesconst assetVersion = String.raw`(?:[0-9a-f]{16}/)?`;const assetPages = String.raw`(?:page-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl))`;const assetOcr = String.raw`(?:ocr-manifest\.json|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz))`;const assetDocument = String.raw`(?:linearized\.pdf|document\.(?:pdf|epub|mobi|azw|azw3|fb2|docx|html|txt|md|webp|swf)|book\.epub|audio\.(?:mp3|wav|m4a|flac|mpga)|video\.(?:mp4|mov))`;const assetChapters = String.raw`(?:chapter-manifest\.json|epub-chapters/(?:chapter-manifest\.json|chapters/chapter-[0-9]{4}\.xhtml|resources/[A-Za-z0-9._~%+\-/]+|epub-search-index\.json\.gz))`;const ebookBucketPathPattern = new RegExp(`^ebook-chapters/${assetRoot}[a-z0-9-]+/[a-z0-9-]+-epub-chapters-v[0-9]+-bucket/epub-chapters/(?:chapter-manifest\\.json|chapters/chapter-[0-9]{4}\\.xhtml|resources/(?!\\.{1,2}(?:/|$))[^/]+(?:/(?!\\.{1,2}(?:/|$))[^/]+)*|epub-search-index\\.json\\.gz)$`);const assetPrimaryPattern = new RegExp(3 unmodified lines`^(?:pdf_manifest\\.json|${assetRoot}${assetVersion}(?:${assetPages}|${assetOcr}|(?:[a-z0-9-]+/)?(?:${assetDocument}|${assetChapters})))$`);const bucketPathPattern = new RegExp(`^${assetRoot}${assetVersion}(?:${assetPages}|${assetOcr})$`);const staticBucketPathPattern = new RegExp(`^${assetRoot}(?:[0-9a-f]{16}/)?(?:[a-z0-9-]+/)?(?:document\\.(?:docx|html|txt|md|webp|jpg|jpeg|png|gif|bmp|swf)|audio\\.(?:mp3|wav|m4a|flac|mpga)|video\\.(?:mp4|mov))$`);const versionedBucketPathPattern = new RegExp(`^${assetRoot}[0-9a-f]{16}/(?:${assetPages}|${assetOcr})$`);const assetBase = "https://huggingface.co/datasets/vomebook/Reader-Assets/resolve/main/";const assetModes = Object.freeze({5 unmodified linesk: "md",i: "webp",a: "audio",v: "video",f: "swf"});function isBucketPath(path, versioned = false, bucket = "vomebook/pdf-pages") {
30 unmodified lines31323334353630 unmodified linesurl: "https://cdn.jsdelivr.net/npm/docx-preview@0.4.0/dist/docx-preview.min.js",file: "docx-preview.min.js",sha256: "051ef503f2677d53159a388b7384e950eda41ea4e47a103e5e36f124d7faea40"}};for (const vendor of Object.values(vendors)) {30 unmodified lines313233343536373839404130 unmodified linesurl: "https://cdn.jsdelivr.net/npm/docx-preview@0.4.0/dist/docx-preview.min.js",file: "docx-preview.min.js",sha256: "051ef503f2677d53159a388b7384e950eda41ea4e47a103e5e36f124d7faea40"},ruffle: {url: "https://unpkg.com/@ruffle-rs/ruffle@0.6.0/ruffle.js",file: "ruffle.js",sha256: "a686a305345b06542dddedada71869104916a61e393f174687571528ac4225f5"}};for (const vendor of Object.values(vendors)) {
4 unmodified lines5678910114 unmodified lines<meta name="viewport" content="width=device-width, initial-scale=1" /><metahttp-equiv="Content-Security-Policy"content="default-src 'self'; base-uri 'self' blob:; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline' blob:; img-src 'self' data: blob: https:; media-src 'self' https://voiceofml-search.hf.space https://hf-mirror.com https://huggingface.co https://*.hf.co https://*.huggingface.co; connect-src 'self' blob: https://huggingface.co https://*.hf.co https://*.huggingface.co https://voiceofml-search.hf.space https://hf-mirror.com; frame-src 'self' blob:;"/><title>VoiceOfML Reader</title><script>4 unmodified lines5678910114 unmodified lines<meta name="viewport" content="width=device-width, initial-scale=1" /><metahttp-equiv="Content-Security-Policy"content="default-src 'self'; base-uri 'self' blob:; script-src 'self' https://unpkg.com 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline' blob:; img-src 'self' data: blob: https:; media-src 'self' https://voiceofml-search.hf.space https://hf-mirror.com https://huggingface.co https://*.hf.co https://*.huggingface.co; connect-src 'self' blob: https://unpkg.com https://huggingface.co https://*.hf.co https://*.huggingface.co https://voiceofml-search.hf.space https://hf-mirror.com; frame-src 'self' blob:;"/><title>VoiceOfML Reader</title><script>
17 unmodified lines181920212223531 unmodified lines5555565575585595603980 unmodified lines454145424543454445454546143 unmodified lines46904691469246934694469543 unmodified lines47394740474147424743474417 unmodified linesconst PURIFY_URL = VoiceOfMLReaderResources.vendorUrl("purify", "/static/");const JSZIP_URL = VoiceOfMLReaderResources.vendorUrl("jszip", "/static/");const DOCX_PREVIEW_URL = VoiceOfMLReaderResources.vendorUrl("docx", "/static/");const READER_PROXY_TIMEOUT_MS = 120000;const readerRequestManager = VoiceOfMLReaderRequests.createReaderRequestManager();const readerRuntime = VoiceOfMLReaderRuntime.createReaderRuntime();531 unmodified lineslet pageNavigationLockUntil = 0;let pendingBookmarkSnapshot = null;let mediaElement = null;function nextReaderGeneration(name) {return readerRuntime.nextGeneration(name);}3980 unmodified linesstatus.textContent = "图片";}function disposeFormatResources(mode) {if (["pdf", "pdf-pages"].includes(mode)) {pdfDocument = null;pdfPageManifest = null;143 unmodified linesdocx: [loadDocxDocument, renderDocx],audio: [loadMediaDocument, () => renderMedia("audio")],video: [loadMediaDocument, () => renderMedia("video")],foliate: [loadMediaDocument, renderFoliate]};for (const [mode, [open, render]] of Object.entries(formats))43 unmodified linescontent.appendChild(media);status.textContent = mode === "audio" ? "音频" : "视频";}// Resolve once, then keep source URLs, capability, and presentation in sync.async function resolveReaderSource() {if (!readerId || sourceUrl) return;17 unmodified lines18192021222324531 unmodified lines5565575585595605615623980 unmodified lines4543454445454546454745484549455045514552143 unmodified lines469646974698469947004701470243 unmodified lines474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477017 unmodified linesconst PURIFY_URL = VoiceOfMLReaderResources.vendorUrl("purify", "/static/");const JSZIP_URL = VoiceOfMLReaderResources.vendorUrl("jszip", "/static/");const DOCX_PREVIEW_URL = VoiceOfMLReaderResources.vendorUrl("docx", "/static/");const RUFFLE_URL = VoiceOfMLReaderResources.vendors.ruffle.url;const READER_PROXY_TIMEOUT_MS = 120000;const readerRequestManager = VoiceOfMLReaderRequests.createReaderRequestManager();const readerRuntime = VoiceOfMLReaderRuntime.createReaderRuntime();531 unmodified lineslet pageNavigationLockUntil = 0;let pendingBookmarkSnapshot = null;let mediaElement = null;let swfPlayer = null;function nextReaderGeneration(name) {return readerRuntime.nextGeneration(name);}3980 unmodified linesstatus.textContent = "图片";}function disposeFormatResources(mode) {if (mode === "swf") {swfPlayer?.remove();swfPlayer = null;}if (["pdf", "pdf-pages"].includes(mode)) {pdfDocument = null;pdfPageManifest = null;143 unmodified linesdocx: [loadDocxDocument, renderDocx],audio: [loadMediaDocument, () => renderMedia("audio")],video: [loadMediaDocument, () => renderMedia("video")],swf: [loadSwfDocument, renderSwf],foliate: [loadMediaDocument, renderFoliate]};for (const [mode, [open, render]] of Object.entries(formats))43 unmodified linescontent.appendChild(media);status.textContent = mode === "audio" ? "音频" : "视频";}async function loadSwfDocument() {await loadScript(RUFFLE_URL);const response = await fetchReaderResponse();return new Uint8Array(await response.arrayBuffer());}async function renderSwf(data) {assertReaderActive();const factory = window.RufflePlayer?.newest?.();if (!factory) throw Object.assign(new Error("Ruffle 未加载"), { code: "READER_SWF_ENGINE" });const player = factory.createPlayer();player.className = "reader-swf";player.setAttribute("aria-label", `${documentState.title} Flash 内容`);player.style.width = "100%";player.style.minHeight = "360px";content.appendChild(player);swfPlayer = player;await player.ruffle().load({ data });status.textContent = "Flash 内容";}// Resolve once, then keep source URLs, capability, and presentation in sync.async function resolveReaderSource() {if (!readerId || sourceUrl) return;
166 unmodified lines1671681691701711722 unmodified lines17517617717817918036 unmodified lines217218219220221222166 unmodified lines"s": 2, "m": "p", "p": OBJECT + "/1234567890abcdef/page-manifest.json","b": "vomebook/pdf-pages",}decoded = app.decode_reader_assets(gzip.compress(json.dumps({"v": 1, "f": files}).encode()))["f"]self.assertEqual(set(decoded), set(files))self.assertEqual(decoded["ebook-chapters"]["cb"], "vomebook/pdf-pages")2 unmodified lines"https://huggingface.co/buckets/vomebook/pdf-pages/resolve/"+ OBJECT + "/1234567890abcdef/page-manifest.json",)for entry in decoded.values():if entry.get("b"):self.assertIsNotNone(app.READER_BUCKET_PATH_RE.fullmatch(entry["p"]))36 unmodified linesapp.app.state.http_session = sessionreturn sessionasync def content(self, upstream, method="GET"):self.session(upstream)return await app.api_reader_content(SimpleNamespace(method=method, headers={}), SOURCE, None)166 unmodified lines1671681691701711721731741751762 unmodified lines17918018118218318418518618718818919019136 unmodified lines228229230231232233234235236237238239240166 unmodified lines"s": 2, "m": "p", "p": OBJECT + "/1234567890abcdef/page-manifest.json","b": "vomebook/pdf-pages",}files["native-audio-bucket"] = {"s": 2, "m": "a", "p": OBJECT + "/native-media-cdn-v1/audio.flac","b": "vomebook/pdf-pages",}decoded = app.decode_reader_assets(gzip.compress(json.dumps({"v": 1, "f": files}).encode()))["f"]self.assertEqual(set(decoded), set(files))self.assertEqual(decoded["ebook-chapters"]["cb"], "vomebook/pdf-pages")2 unmodified lines"https://huggingface.co/buckets/vomebook/pdf-pages/resolve/"+ OBJECT + "/1234567890abcdef/page-manifest.json",)self.assertEqual(app.reader_asset_url(decoded["native-audio-bucket"]),"https://huggingface.co/buckets/vomebook/pdf-pages/resolve/"+ OBJECT + "/native-media-cdn-v1/audio.flac",)self.assertEqual(app.READER_RESOURCE_TYPES["flac"], "audio/flac")self.assertEqual(app.reader_extension_for_asset(decoded["native-audio-bucket"], "flac"), "audio")for entry in decoded.values():if entry.get("b"):self.assertIsNotNone(app.READER_BUCKET_PATH_RE.fullmatch(entry["p"]))36 unmodified linesapp.app.state.http_session = sessionreturn sessionasync def test_bucket_audio_resource_uses_audio_mime_type(self):path = OBJECT + "/native-media-cdn-v1/audio.flac"with patch.object(app, "get_reader_bucket_resource", AsyncMock(return_value=b"flac")):response = await app.api_reader_bucket_resource(path)self.assertEqual(response.media_type, "audio/flac")self.assertEqual(response.body, b"flac")async def content(self, upstream, method="GET"):self.session(upstream)return await app.api_reader_content(SimpleNamespace(method=method, headers={}), SOURCE, None)
123456117 unmodified lines124125126127128129"""Local Reader behavior regressions; all document/network fixtures stay offline."""import ioimport gzipimport hashlibimport json117 unmodified linesself.assertTrue(image.evaluate("image => image.complete && image.naturalWidth > 0"))self.assertTrue(self.page.locator("#full-search-toggle").evaluate("node => node.hidden"))def test_saved_native_pdf_opens_target_page_first(self):store = support.STORE_SCRIPT.replace("get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300)),",1234567117 unmodified lines125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""Local Reader behavior regressions; all document/network fixtures stay offline."""import ioimport base64import gzipimport hashlibimport json117 unmodified linesself.assertTrue(image.evaluate("image => image.complete && image.naturalWidth > 0"))self.assertTrue(self.page.locator("#full-search-toggle").evaluate("node => node.hidden"))def test_native_spreadsheet_html_keeps_cells_selectable_and_zoomable(self):chart = support.IMAGE_FIXTURES["webp"][1]chart_data = "data:image/webp;base64," + base64.b64encode(chart).decode()document = ('<!doctype html><html><head><meta charset="utf-8"><style>''body{width:max-content;min-width:100%;margin:0;padding:12px}''.sheet{width:max-content;min-width:100%}table{border-collapse:collapse}''td{min-width:900px;height:80px;border:1px solid #444}''</style></head><body><section class="sheet"><h2>工作表 1</h2>'f'<table><tr><td id="cell">完整单元格文字<img src="{chart_data}"></td></tr></table>''</section></body></html>')self.serve(document, "text/html")self.open(self.reader_url("html", "table"))frame_element = self.page.locator("iframe.html-frame")frame_element.wait_for()frame = frame_element.element_handle().content_frame()self.assertEqual(frame.locator("#cell").text_content().strip(), "完整单元格文字")self.assertGreater(frame.locator("img").evaluate("image => image.naturalWidth"), 0)before = frame.locator("table").evaluate("node => node.getBoundingClientRect().width")self.page.locator("#zoom-in").click(click_count=5)self.assertGreater(frame.locator("table").evaluate("node => node.getBoundingClientRect().width"), before,)def test_saved_native_pdf_opens_target_page_first(self):store = support.STORE_SCRIPT.replace("get: () => new Promise((resolve) => setTimeout(() => resolve(null), 300)),",
57 unmodified lines58596061626357 unmodified lines'/api/reader-bucket-resource?path=' + encodeURIComponent(bucket))assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: bucket, b: 'vomebook/pdf-pages'}, '/api/reader-bucket-resource').ReaderLink,'/api/reader-bucket-resource?path=' + encodeURIComponent(bucket))const optimized = assetRoot + 'pdf-range-v1-document/document.pdf'assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: optimized, b: 'vomebook/pdf-optimized'}), null)assert.strictEqual(assets.isAssetSourcePath(sourcePrefix + 'pdf_manifest.json'), true)57 unmodified lines58596061626364656667686970717273747557 unmodified lines'/api/reader-bucket-resource?path=' + encodeURIComponent(bucket))assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: bucket, b: 'vomebook/pdf-pages'}, '/api/reader-bucket-resource').ReaderLink,'/api/reader-bucket-resource?path=' + encodeURIComponent(bucket))const nativeMediaPath = assetRoot + 'native-media-cdn-v1/audio.flac'const nativeMedia = assets.assetFields({s: 2, m: 'a', p: nativeMediaPath, b: 'vomebook/pdf-pages'}, '/api/reader-bucket-resource')assert.strictEqual(nativeMedia.ReaderExtension, 'audio')assert.strictEqual(nativeMedia.ReaderLink,'https://huggingface.co/buckets/vomebook/pdf-pages/resolve/' + nativeMediaPath)assert.strictEqual(assets.isAssetSourcePath(sourcePrefix + nativeMediaPath), true)const swfPath = assetRoot + 'native-swf-ruffle-v1/document.swf'const swf = assets.assetFields({s: 2, m: 'f', p: swfPath, b: 'vomebook/pdf-pages'}, '/api/reader-bucket-resource')assert.strictEqual(swf.ReaderExtension, 'swf')assert.strictEqual(assets.capability('swf').mode, 'swf')assert.strictEqual(swf.ReaderLink,'https://huggingface.co/buckets/vomebook/pdf-pages/resolve/' + swfPath)const optimized = assetRoot + 'pdf-range-v1-document/document.pdf'assert.strictEqual(assets.assetFields({s: 2, m: 'p', p: optimized, b: 'vomebook/pdf-optimized'}), null)assert.strictEqual(assets.isAssetSourcePath(sourcePrefix + 'pdf_manifest.json'), true)
8 unmodified lines91011121314158 unmodified linesALLOWED_DOWNLOAD_HOST_SUFFIXES = (".hf.co", ".huggingface.co", ".xethub.hf.co")MAX_REDIRECTS = 5READER_ASSET_PATH_RE = re.compile(r"objects/[0-9a-f]{2}/[0-9a-f]{64}/(?:[0-9a-f]{16}/)?(?:page-manifest\.json|ocr-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl)|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)|(?:[a-z0-9-]+/)?(?:linearized\.pdf|chapter-manifest\.json|document\.(?:pdf|epub|mobi|azw|azw3|fb2|docx|html|txt|md|webp|jpg|jpeg|png|gif|bmp)|book\.epub|audio\.mp3|video\.mp4|epub-chapters/(?:chapter-manifest\.json|chapters/chapter-[0-9]{4}\.xhtml|resources/[A-Za-z0-9._~%+\-/]+|epub-search-index\.json\.gz)))")READER_ASSET_SOURCE_RE = re.compile(r"/datasets/vomebook/Reader-Assets/resolve/main/(?:pdf_manifest\.json|" + READER_ASSET_PATH_RE.pattern + r")"8 unmodified lines91011121314158 unmodified linesALLOWED_DOWNLOAD_HOST_SUFFIXES = (".hf.co", ".huggingface.co", ".xethub.hf.co")MAX_REDIRECTS = 5READER_ASSET_PATH_RE = re.compile(r"objects/[0-9a-f]{2}/[0-9a-f]{64}/(?:[0-9a-f]{16}/)?(?:page-manifest\.json|ocr-manifest\.json|pages/page-[0-9]{6}\.(?:webp|jxl)|ocr/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz)|(?:[a-z0-9-]+/)?(?:linearized\.pdf|chapter-manifest\.json|document\.(?:pdf|epub|mobi|azw|azw3|fb2|docx|html|txt|md|webp|jpg|jpeg|png|gif|bmp|swf)|book\.epub|audio\.(?:mp3|wav|m4a|flac|mpga)|video\.(?:mp4|mov)|epub-chapters/(?:chapter-manifest\.json|chapters/chapter-[0-9]{4}\.xhtml|resources/[A-Za-z0-9._~%+\-/]+|epub-search-index\.json\.gz)))")READER_ASSET_SOURCE_RE = re.compile(r"/datasets/vomebook/Reader-Assets/resolve/main/(?:pdf_manifest\.json|" + READER_ASSET_PATH_RE.pattern + r")"
app.py+2-1
reader_assets.py+4-3
record_metadata.py+3-2
static/app.js+5-5
static/reader-contract.js+14-4
static/reader-resources.js+5
static/reader.html+1-1
static/reader.js+26
tests/test_reader_backend.py+18
tests/test_reader_refactor.py+26
tests/test_reader_regression.js+12
upstream_http.py+1-1