File size: 16,578 Bytes
09726f9
dac2ca2
 
 
 
 
 
 
 
 
 
09726f9
dac2ca2
09726f9
dac2ca2
09726f9
dac2ca2
 
09726f9
56b51ea
39e321e
dac2ca2
56b51ea
dac2ca2
09726f9
b7fbb29
09726f9
dac2ca2
09726f9
 
 
 
dac2ca2
d3655e4
fb915bd
 
 
 
 
ae3a71a
fb915bd
 
 
 
da87c58
 
fb915bd
 
 
 
dac2ca2
fb915bd
 
 
 
 
dac2ca2
09726f9
 
 
 
dac2ca2
a6c9213
 
 
 
 
 
 
dac2ca2
09726f9
b7fbb29
09726f9
 
 
 
 
 
 
 
 
 
 
 
18e5423
 
 
 
dac2ca2
18e5423
 
 
 
 
 
 
 
 
 
 
09726f9
 
 
18e5423
 
09726f9
18e5423
 
 
09726f9
 
 
 
dac2ca2
09726f9
 
 
 
ae3a71a
 
09726f9
 
 
 
 
dac2ca2
09726f9
 
 
 
b7fbb29
09726f9
 
 
 
 
 
dac2ca2
1778128
dac2ca2
 
 
 
 
 
 
 
 
09726f9
dac2ca2
441a3b0
09726f9
 
 
 
 
dac2ca2
 
09726f9
441a3b0
09726f9
 
 
 
 
 
dac2ca2
 
 
 
09726f9
 
 
 
 
 
 
dac2ca2
441a3b0
 
09726f9
 
 
 
dac2ca2
 
b7fbb29
09726f9
 
 
 
 
6d0140e
 
 
 
 
 
 
09726f9
 
 
 
 
 
 
dac2ca2
441a3b0
 
 
dac2ca2
 
b7fbb29
09726f9
 
b7fbb29
09726f9
ae3a71a
09726f9
 
dac2ca2
09726f9
 
 
 
dac2ca2
09726f9
 
 
 
f563661
09726f9
fb915bd
 
dac2ca2
 
fb915bd
dac2ca2
fb915bd
 
 
 
09726f9
 
 
 
 
 
 
 
 
56b51ea
 
fb915bd
56b51ea
fb915bd
09726f9
56b51ea
09726f9
 
 
dac2ca2
09726f9
 
 
b7fbb29
09726f9
 
 
 
 
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
// Transport is supplied by the Reader's cancellation/deadline-owned request manager.
/** @typedef {import('../../../typings/reader-v3-strict').Resource} Resource */
/** @typedef {import('../../../typings/reader-v3-strict').DatasetPrimary} DatasetPrimary */
/** @typedef {import('../../../typings/reader-v3-strict').Partition} Partition */
/** @typedef {import('../../../typings/reader-v3-strict').TextEntry} TextEntry */
/** @typedef {import('../../../typings/reader-v3-strict').TextLayer} TextLayer */
/** @typedef {import('../../../typings/reader-v3-strict').TextIndex} TextIndex */
/** @typedef {import('../../../typings/reader-v3-strict').TextPartition} TextPartition */
/** @typedef {import('../../../typings/reader-v3-strict').ReadingManifest} ReadingManifest */
/** @typedef {import('../../../typings/reader-v3-strict').PageMap} PageMap */
/** @param {unknown} value */
const sha = value => typeof value === "string" && /^[0-9a-f]{64}$/.test(value);
/** @param {number} value */
const positive = value => Number.isFinite(value) && value > 0;
/** @param {number} value */
const integer = value => Number.isSafeInteger(value) && value > 0;
/** @returns {never} */
function invalid() { throw new Error("PDF_V3_INVALID"); }
const modes = new Set(["auto", "horizontal-ltr", "horizontal-rtl", "vertical-rl", "vertical-lr"]);
const pathPattern = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/[0-9a-f]{16}\/(?:reading-manifest\.json|page-map\.json\.gz|text-layer-manifest\.json|text-review-manifest\.json|text\/(?:page-[0-9]{6}\.json\.gz|book-text\.json\.gz|search-[0-9]{6}-[0-9]{6}\.json\.gz|partition-[0-9]{6}-[0-9]{6}-manifest\.json)|preview\/(?:page-[0-9]{6}\.(?:png|webp|jpeg|svg|jxl)|partition-[0-9]{6}-[0-9]{6}-manifest\.json))$/;
const sharedPagePattern = /^objects\/[0-9a-f]{2}\/[0-9a-f]{64}\/[0-9a-f]{16}\/pages\/page-[0-9]{6}\.(?:jxl|png)$/;
/** @param {unknown} path */
export const isV3Path = path => typeof path === "string" && (pathPattern.test(path) || sharedPagePattern.test(path));
/** @param {Resource} ref @param {string} [source] */
export function validateResource(ref, source = "") {
  if (!ref || typeof ref.path !== "string" || !["vomebook/pdf-pages-v2", "vomebook/reader-assets-v2"].includes(ref.bucket) ||
      ref.role !== "runtime" || !sha(ref.sha256) || !integer(ref.bytes) ||
      !(/** @type {typeof globalThis & {VoiceOfMLReader: {isBucketPath(path: string, runtime: boolean, bucket: string): boolean}}} */ (globalThis)).VoiceOfMLReader.isBucketPath(ref.path, true, ref.bucket)) invalid();
  if (isV3Path(ref.path) && (ref.bucket !== "vomebook/pdf-pages-v2" ||
      (source && !ref.path.startsWith(`objects/${source.slice(0, 2)}/${source}/`)))) invalid();
  return ref;
}
/** @param {DatasetPrimary} ref @param {string} [sourceKey] @param {string} [sourceSha] @param {string} [expectedKind] */
function validateDatasetPrimary(ref, sourceKey, sourceSha, expectedKind) {
  const keys = ["kind", "repo", "path", "revision", "sha256", "bytes", "role"];
  if (!ref || typeof ref !== "object" || Array.isArray(ref) ||
      Object.keys(ref).length !== keys.length || keys.some(key => !Object.hasOwn(ref, key)) ||
      ref.kind !== "dataset-source" || ref.role !== "runtime" ||
      typeof ref.repo !== "string" || !/^VoiceOfML\/[A-Za-z0-9._-]+$/.test(ref.repo) ||
      [".", ".."].includes(ref.repo.slice("VoiceOfML/".length)) ||
      typeof ref.path !== "string" || !ref.path || ref.path.startsWith("/") ||
      ref.path.split("/").some(part => !part || part === "." || part === "..") ||
      /[\\%?#\x00-\x1f\x7f\p{Cs}]/u.test(ref.path) || !/\.(?:pdf|djvu)$/i.test(ref.path) ||
      typeof ref.revision !== "string" || !/^[0-9a-f]{40}$/.test(ref.revision) ||
      !sha(ref.sha256) || !integer(ref.bytes) ||
      ref.bytes > (/\.pdf$/i.test(ref.path) ? 2 * 1024 * 1024 * 1024 : 512 * 1024 * 1024) ||
      (sourceKey !== undefined && sourceKey !== ref.repo + "\0" + ref.path) ||
      (sourceSha !== undefined && sourceSha !== ref.sha256) ||
      (expectedKind !== undefined && !ref.path.toLowerCase().endsWith("." + expectedKind))) invalid();
}
/** @param {DatasetPrimary} ref */
export function datasetPrimaryUrl(ref) {
  validateDatasetPrimary(ref);
  return `https://huggingface.co/datasets/${ref.repo}/resolve/${ref.revision}/` +
    ref.path.split("/").map(encodeURIComponent).join("/");
}
/** @param {unknown} b */
function validBox(b) {
  return Array.isArray(b) && b.length === 4 && b.every(v => Number.isFinite(v) && v >= 0 && v <= 1) &&
    b[0] < b[2] && b[1] < b[3];
}
/** @param {unknown} quad */
function validQuad(quad) {
  if (!Array.isArray(quad) || quad.length !== 4 || quad.some(point =>
      !Array.isArray(point) || point.length !== 2 || point.some(v => !Number.isFinite(v) || v < 0 || v > 1))) return false;
  let area = 0;
  for (let i = 0; i < 4; i++) area += quad[i][0] * quad[(i + 1) % 4][1] - quad[(i + 1) % 4][0] * quad[i][1];
  return Math.abs(area) > 2e-9;
}
/** @param {TextLayer} layer @param {TextEntry} entry @param {string} source */
export function validateTextLayer(layer, entry, source) {
  if (!entry || !layer || layer.version !== 1 || layer.kind !== "pdf-text-layer" || layer.source_sha256 !== source ||
      layer.page !== entry.page || !sha(layer.generation) || layer.generation !== entry.generation ||
      !sha(layer.raw_sha256) || !sha(layer.page_identity) || layer.page_identity !== entry.page_identity ||
      layer.offset_unit !== "unicode-codepoint" || typeof layer.text !== "string" ||
      !["raw", "accepted"].includes(layer.revision) || !["unreviewed", "partially-reviewed"].includes(layer.quality) ||
      !["processed", "processed-empty"].includes(layer.processing) ||
      layer.quality !== entry.quality || layer.processing !== entry.processing ||
      !positive(layer.geometry?.width) || !positive(layer.geometry?.height) ||
      layer.geometry.coordinate_space !== "normalized-page" || !Array.isArray(layer.regions) ||
      layer.regions.length > 10000) invalid();
  if ((layer.revision === "raw" && layer.quality !== "unreviewed") ||
      (layer.revision === "accepted" && (layer.quality !== "partially-reviewed" ||
        !sha(layer.parent_generation) || !Array.isArray(layer.acceptances) || !layer.acceptances.length))) invalid();
  const ids = new Set(), text = layer.text;
  // Regions are ordered and non-overlapping in code points. Keep one forward
  // UTF-16 cursor instead of allocating an array for every point on the page.
  let end = 0, unit = 0;
  /** @param {number} target */
  const advance = target => {
    while (end < target && unit < text.length) {
      const high = text.charCodeAt(unit++);
      if (high >= 0xd800 && high <= 0xdbff && unit < text.length) {
        const low = text.charCodeAt(unit);
        if (low >= 0xdc00 && low <= 0xdfff) unit++;
      }
      end++;
    }
    return end === target;
  };
  for (const [order, region] of layer.regions.entries()) {
    if (!region || typeof region.id !== "string" || ids.has(region.id) || region.order !== order ||
        !Number.isSafeInteger(region.start) || !Number.isSafeInteger(region.end) || region.start < end ||
        region.end <= region.start || typeof region.text !== "string" || !validBox(region.box) ||
        !validQuad(region.quad) ||
        !modes.has(region.writing_mode) || !["ltr", "rtl", "mixed", "neutral"].includes(region.direction)) invalid();
    if (!advance(region.start)) invalid();
    const begin = unit;
    if (!advance(region.end) || text.slice(begin, unit) !== region.text) invalid();
    ids.add(region.id);
  }
  return layer;
}
/** @param {Partition[]} partitions @param {number} page */
export function partitionFor(partitions, page) {
  let low = 0, high = partitions.length;
  while (low < high) {
    const mid = (low + high) >> 1;
    const part = partitions[mid];
    if (part && part.start <= page) low = mid + 1;
    else high = mid;
  }
  const part = partitions[low - 1];
  return part && page <= part.end ? part : null;
}
/** @param {Partition[]} values @param {number} count @param {boolean} complete @param {string} source */
function partitions(values, count, complete, source) {
  if (!Array.isArray(values)) invalid();
  let end = 0;
  for (const part of values) {
    if (!part || !integer(part.start) || !integer(part.end) || part.start <= end || part.end < part.start ||
        part.end > count || (complete && part.start !== end + 1)) invalid();
    validateResource(part.resource, source);
    end = part.end;
  }
  if (complete && end !== count) invalid();
}
/** @param {import('../../../typings/reader-v3-strict').RepositoryOptions} options */
export function createV3Repository({ readJson, resourceUrl, signal, pageCount, sourceSha }) {
  /** @type {Map<string, {value: unknown, size: number}>} */
  const cache = new Map();
  /** @type {Map<string, Promise<unknown>>} */
  const pending = new Map();
  /** @type {TextIndex | null} */
  let index = null;
  /** @type {Promise<TextIndex> | null} */
  let textPending = null;
  let bytes = 0, disposed = false, indexKey = "";
  const active = () => { if (disposed || signal?.aborted) throw new DOMException("Reader closed", "AbortError"); };
  /** @param {Resource} ref @param {string} [source] */
  async function read(ref, source = sourceSha) {
    active();
    validateResource(ref, source);
    const key = ref.bucket + ":" + ref.path + ":" + ref.sha256;
    const cached = cache.get(key);
    if (cached) { cache.delete(key); cache.set(key, cached); return cached.value; }
    const existing = pending.get(key);
    if (existing) return existing;
    if (pending.size >= 8) throw new Error("PDF_V3_BUSY");
    const task = Promise.resolve().then(() => readJson(resourceUrl(ref), ref)).then(value => {
      active();
      const size = JSON.stringify(value).length * 2;
      if (size <= 2 * 1024 * 1024) {
        cache.set(key, { value, size }); bytes += size;
        while (cache.size > 4 || bytes > 2 * 1024 * 1024) {
          const oldest = cache.keys().next().value;
          if (oldest === undefined) break;
          const evicted = cache.get(oldest);
          if (evicted) bytes -= evicted.size;
          cache.delete(oldest);
        }
      }
      return value;
    }).finally(() => pending.delete(key));
    pending.set(key, task);
    return task;
  }
  /** @param {Resource} ref */
  async function textIndex(ref) {
    active(); validateResource(ref, sourceSha);
    const key = ref.bucket + ":" + ref.path + ":" + ref.sha256;
    if (indexKey && indexKey !== key) throw new Error("PDF_V3_GENERATION_CHANGED");
    indexKey = key;
    if (index) return index;
    if (!textPending) textPending = read(ref).then(payload => {
      const value = /** @type {TextIndex} */ (payload);
      if (!value || value.version !== 1 || value.kind !== "pdf-text-layer-index" || value.complete !== true ||
          value.source_sha256 !== sourceSha || value.page_count !== pageCount || !sha(value.generation) ||
          !["raw", "effective"].includes(value.revision) || value.offset_unit !== "unicode-codepoint") invalid();
      partitions(value.partitions, pageCount, true, sourceSha);
      validateResource(value.book_text, sourceSha);
      if (!value.book_text.path.endsWith("/text/book-text.json.gz")) invalid();
      if (value.search_partitions !== undefined) {
        partitions(value.search_partitions, pageCount, true, sourceSha);
        for (const part of value.search_partitions) {
          if (part.end - part.start >= 32 || !part.resource.path.endsWith(
            `/text/search-${String(part.start).padStart(6, "0")}-${String(part.end).padStart(6, "0")}.json.gz`)) invalid();
        }
      }
      active(); index = value; return value;
    }).catch(error => { textPending = null; throw error; });
    return textPending;
  }
  return {
    read,
    textIndex,
    /** @param {Resource} ref @param {number} page */
    async textPage(ref, page) {
      if (!integer(page) || page > pageCount) invalid();
      const root = await textIndex(ref), part = partitionFor(root.partitions, page);
      if (!part) invalid();
      const value = /** @type {TextPartition} */ (await read(part.resource));
      if (!value || value.version !== 1 || value.kind !== "pdf-text-partition" || value.source_sha256 !== sourceSha ||
          value.generation !== root.generation || value.start !== part.start || value.end !== part.end ||
          !Array.isArray(value.pages) || value.pages.length !== part.end - part.start + 1 ||
          value.pages.some((p, i) => !p || p.page !== part.start + i)) invalid();
      const entry = value.pages[page - part.start];
      if (!entry) invalid();
      validateResource(entry.resource, sourceSha);
      if (!entry.resource.path.endsWith(`/text/page-${String(page).padStart(6, "0")}.json.gz`)) invalid();
      return validateTextLayer(/** @type {TextLayer} */ (await read(entry.resource)), entry, sourceSha);
    },
    dispose() { disposed = true; cache.clear(); bytes = 0; index = null; }
  };
}
/** @param {ReadingManifest} manifest @param {number} maxPages */
export function validateReadingManifest(manifest, maxPages) {
  if (!manifest || manifest.version !== 3 || manifest.kind !== "pdf-reading" ||
      !sha(manifest.source_sha256) || !sha(manifest.generation) || !integer(manifest.page_count) ||
      manifest.page_count > maxPages || typeof manifest.source_key !== "string" ||
      !["pdf", "djvu"].includes(manifest.primary?.kind) || manifest.primary.status !== "ready" ||
      typeof manifest.preview?.complete !== "boolean" || manifest.preview.page_count !== manifest.page_count) invalid();
  const primary = manifest.primary.resource;
  const dataset = primary?.kind === "dataset-source";
  if (dataset) validateDatasetPrimary(/** @type {DatasetPrimary} */ (primary), manifest.source_key, manifest.source_sha256, manifest.primary.kind);
  else validateResource(/** @type {Resource} */ (primary));
  if (manifest.primary.kind === "djvu" && (manifest.page_count > 10000 ||
      (!dataset && ((/** @type {Resource} */ (primary)).bucket !== "vomebook/pdf-pages-v2" || primary.sha256 !== manifest.source_sha256 ||
        primary.bytes > 512 * 1024 * 1024 ||
        !primary.path.startsWith(`objects/${manifest.source_sha256.slice(0, 2)}/${manifest.source_sha256}/`) ||
        !primary.path.endsWith("/document.djvu"))))) invalid();
  if (manifest.primary.kind === "pdf" && !dataset && !primary.path.endsWith(".pdf")) invalid();
  validateResource(manifest.page_map, manifest.source_sha256);
  if (!manifest.page_map.path.endsWith("/page-map.json.gz")) invalid();
  partitions(manifest.preview.partitions, manifest.page_count, manifest.preview.complete, manifest.source_sha256);
  if (!Number.isSafeInteger(manifest.preview.ready_pages) || manifest.preview.ready_pages < 0 ||
      manifest.preview.ready_pages > manifest.page_count ||
      (manifest.preview.complete && manifest.preview.ready_pages !== manifest.page_count)) invalid();
  if (manifest.preview.complete && manifest.preview.partitions.some(p => p.complete !== true)) invalid();
  if (manifest.text_layer) validateResource(manifest.text_layer, manifest.source_sha256);
  if (manifest.text_layer && !manifest.text_layer.path.endsWith("/text-layer-manifest.json")) invalid();
  const skipped = manifest.preview.status === "skipped";
  if (manifest.preview.status !== undefined && !skipped) invalid();
  if (skipped && (manifest.preview.complete ||
      manifest.preview.ready_pages !== 0 || manifest.preview.partitions.length !== 0)) invalid();
  if (manifest.primary.kind === "djvu" && !skipped) throw new Error("DJVU_LEGACY_READING_UNSUPPORTED");
  if (manifest.components?.document !== "ready" ||
      manifest.components.preview !== (skipped ? "skipped" : manifest.preview.complete ? "ready" : "pending") ||
      manifest.components.text !== (manifest.text_layer ? "ready" : "pending")) invalid();
  return manifest;
}
/** @param {PageMap} map @param {ReadingManifest} manifest */
export function validatePageMap(map, manifest) {
  if (!map || map.version !== 1 || map.kind !== "pdf-page-map" || map.source_sha256 !== manifest.source_sha256 ||
      !Array.isArray(map.pages) || map.pages.length !== manifest.page_count || map.pages.some((p, i) =>
        !p || p.page !== i + 1 || !sha(p.identity) || !positive(p.width) || !positive(p.height) ||
        ![0, 90, 180, 270].includes(p.rotation) || !Array.isArray(p.crop_box) || p.crop_box.length !== 4 ||
        !Array.isArray(p.media_box) || p.media_box.length !== 4 ||
        [...p.crop_box, ...p.media_box].some(v => !Number.isFinite(v)))) invalid();
  return map;
}