ochre-sdk 1.3.32 → 1.3.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -9
- package/dist/fetchers/item-ocr-data.d.mts +20 -16
- package/dist/fetchers/item-ocr-data.mjs +154 -63
- package/dist/index.d.mts +2 -2
- package/dist/ocr.d.mts +18 -7
- package/dist/ocr.mjs +22 -10
- package/dist/query.mjs +2 -2
- package/dist/schemas.d.mts +1 -0
- package/dist/schemas.mjs +2 -1
- package/dist/types/index.d.mts +33 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -57,8 +57,7 @@ present and `error` is `null`; on failure, the parsed value is `null` and
|
|
|
57
57
|
`category` lets the XQuery search only the matching OCHRE collection.
|
|
58
58
|
- `fetchItemLinks(uuid, options)` fetches items linked from a source item and
|
|
59
59
|
parses them as embedded OCHRE items.
|
|
60
|
-
- `fetchItemOcrData(uuid, value, options)`
|
|
61
|
-
an item that match a search value, for drawing hit boxes over a scanned page.
|
|
60
|
+
- `fetchItemOcrData(uuid, value, options)` searches the OCR text of an item and returns each match with its page, the positioned words you need to draw hit boxes over the scanned page, and, if you ask for it, the words around the match for a result snippet.
|
|
62
61
|
- `fetchGallery(params, options)` fetches paginated resource galleries with an
|
|
63
62
|
optional label filter.
|
|
64
63
|
- `fetchWebsite(abbreviation, options)` fetches an OCHRE website presentation
|
|
@@ -221,23 +220,34 @@ Set item projections do not carry the OCR layer, so an `ocr` leaf is resolved by
|
|
|
221
220
|
|
|
222
221
|
## OCR Data
|
|
223
222
|
|
|
224
|
-
A Resource
|
|
223
|
+
A Resource can carry an `<ocr>` layer with the positioned output of an OCR run, and a multi-page document usually keeps one layer on each of its child Resources, one per page. The node hierarchy inside a layer is irregular and is not parsed, but any word node within it, at any depth, is read as one positioned OCR string. A word node is any element named `String` or `string` in any namespace, and its text comes from the `CONTENT` attribute rather than from the element's text content.
|
|
225
224
|
|
|
226
225
|
```ts
|
|
227
226
|
import { fetchItemOcrData } from "ochre-sdk";
|
|
228
227
|
|
|
229
|
-
const result = await fetchItemOcrData("<item-uuid>", "
|
|
230
|
-
|
|
228
|
+
const result = await fetchItemOcrData("<item-uuid>", "Madeline", {
|
|
229
|
+
contextWordCount: 8,
|
|
231
230
|
});
|
|
232
231
|
|
|
233
|
-
for (const
|
|
234
|
-
console.log(
|
|
232
|
+
for (const match of result.ocrMatches ?? []) {
|
|
233
|
+
console.log(
|
|
234
|
+
match.pageNumber,
|
|
235
|
+
match.context?.before,
|
|
236
|
+
match.text,
|
|
237
|
+
match.context?.after,
|
|
238
|
+
);
|
|
235
239
|
}
|
|
236
240
|
```
|
|
237
241
|
|
|
238
|
-
|
|
242
|
+
Because a word node holds a single OCR word, matching runs against each word, which defaults to case-insensitive `includes`, and the search value is split on whitespace and matched as a phrase. A match is a run of consecutive words in which the first word matches the first term, the second word matches the second term, and so on. With `includes`, each word only has to contain its term, so searching for `"whitman madeline"` finds `Whitman, Madeline` despite the comma, while `exact` requires each word to equal its term. Searching for `"Chicago University"` does not match `University of Chicago`, and a single-term search matches every word that matches the term, each as its own match. Matches come back in document order, and an item with no OCR layer, or with no matches, returns an empty array, though requesting an item that does not exist is an error.
|
|
239
243
|
|
|
240
|
-
|
|
244
|
+
`resourceUuid` names the Resource that owns the page's OCR layer, which differs from the requested item when the OCR lives on a child Resource, and `pageNumber` gives the 1-based position of that Resource among its sibling Resources. You can use `resourceUuid` to navigate to the page and `pageNumber` to label it.
|
|
245
|
+
|
|
246
|
+
Pass `contextWordCount` to get that many words on either side of each match in `context.before` and `context.after`. The context crosses lines and blocks but never leaves the page, and `context.isTruncatedBefore` and `context.isTruncatedAfter` tell you whether the page has more words beyond it, so you know when to draw an ellipsis. The context is counted in whole words, and if you need snippets of an even length, you can trim it to a character budget in your UI. Without `contextWordCount`, `context` is null and the search skips the extra work.
|
|
247
|
+
|
|
248
|
+
`strings` holds the positioned words of the match, and `x` and `y` come from `HPOS` and `VPOS` and give the top-left corner of each box, `width` and `height` give its size, and `vertices` comes from `VERTICES` and is its full bounding polygon, which is not always rectangular. Each geometry field is null when the source attribute is absent or unparseable, in which case `vertices` is empty.
|
|
249
|
+
|
|
250
|
+
A word hyphenated across two lines is matched by its whole form from `SUBS_CONTENT`, so it counts as one word in both a phrase and the context, and searching for `"He conceived of"` finds `He con-` at the end of one line and `ceived of` at the start of the next, with the match holding both halves in `strings` (one box on each line) and its `text` and context showing the word whole.
|
|
241
251
|
|
|
242
252
|
## Helpers And Types
|
|
243
253
|
|
|
@@ -1,37 +1,41 @@
|
|
|
1
1
|
import { OchreRequestOptions } from "./request.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { OcrMatch } from "../types/index.mjs";
|
|
3
3
|
/**
|
|
4
|
-
Fetches
|
|
4
|
+
Fetches the OCR matches of an OCHRE item for a search value
|
|
5
5
|
|
|
6
6
|
Resources may carry an `<ocr>` layer whose internal hierarchy is irregular
|
|
7
|
-
and therefore not parsed. Only its word nodes are
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
`
|
|
7
|
+
and therefore not parsed. Only its word nodes are read, wherever they occur
|
|
8
|
+
in that subtree. A word node is any element named `String` or `string` in
|
|
9
|
+
any namespace, and matching reads its `CONTENT` attribute, or its
|
|
10
|
+
`SUBS_CONTENT` attribute when the word is hyphenated across two lines.
|
|
11
11
|
|
|
12
|
-
Each word node holds a single OCR word, so
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
12
|
+
Each word node holds a single OCR word, so the search value is split on
|
|
13
|
+
whitespace and read as a phrase: a match is a run of consecutive words in
|
|
14
|
+
which each word matches its term, so a single-term search matches every word
|
|
15
|
+
that matches the term. Every OCR layer is one page, and nested child Resources are
|
|
16
|
+
searched too, with `resourceUuid` and `pageNumber` naming the page each
|
|
17
|
+
match is on. Matches are returned in document order.
|
|
16
18
|
|
|
17
19
|
@param uuid - The UUID of the OCHRE item to read the OCR layer of
|
|
18
|
-
@param value - The search value
|
|
20
|
+
@param value - The search value, matched as a phrase of whitespace-separated terms
|
|
19
21
|
@param options - Options for the fetch
|
|
20
|
-
@param options.matchMode - Whether
|
|
22
|
+
@param options.matchMode - Whether each term has to be contained in its word ("includes", the default) or equal it ("exact")
|
|
21
23
|
@param options.isCaseSensitive - Whether matching is case sensitive, defaulting to false
|
|
24
|
+
@param options.contextWordCount - The number of words of context to return on either side of each match, within its page, defaulting to 0 for no context
|
|
22
25
|
@param options.fetch - The fetch function to use
|
|
23
|
-
@returns The
|
|
24
|
-
|
|
26
|
+
@returns The OCR matches, an empty array when the item has no OCR layer or
|
|
27
|
+
nothing matches, and a null output on fetch/parse errors
|
|
25
28
|
*/
|
|
26
29
|
export declare function fetchItemOcrData(uuid: string, value: string, options?: OchreRequestOptions & {
|
|
27
30
|
matchMode?: "includes" | "exact";
|
|
28
31
|
isCaseSensitive?: boolean;
|
|
32
|
+
contextWordCount?: number;
|
|
29
33
|
}): Promise<{
|
|
30
|
-
|
|
34
|
+
ocrMatches: Array<OcrMatch>;
|
|
31
35
|
error: null;
|
|
32
36
|
detailedError: null;
|
|
33
37
|
} | {
|
|
34
|
-
|
|
38
|
+
ocrMatches: null;
|
|
35
39
|
error: string;
|
|
36
40
|
detailedError: string;
|
|
37
41
|
}>;
|
|
@@ -1,16 +1,15 @@
|
|
|
1
1
|
import { getErrorOutput } from "../errors.mjs";
|
|
2
2
|
import { requestOchre } from "./request.mjs";
|
|
3
|
-
import { buildOcrWordPath } from "../ocr.mjs";
|
|
3
|
+
import { buildOcrLayerPath, buildOcrWordPath } from "../ocr.mjs";
|
|
4
4
|
import { itemOcrDataParametersSchema } from "../schemas.mjs";
|
|
5
5
|
import { OCHRE_RESPONSE_PADDING, stringLiteral } from "../xquery.mjs";
|
|
6
6
|
import * as v from "valibot";
|
|
7
7
|
// src/fetchers/item-ocr-data.ts
|
|
8
8
|
const OCR_STRING_VERTEX_REGEX = /\(\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*\)/g;
|
|
9
9
|
/**
|
|
10
|
-
Schema for a single
|
|
10
|
+
Schema for a single OCR string of a match in the OCHRE API response
|
|
11
11
|
*/
|
|
12
12
|
const ocrStringSchema = v.object({
|
|
13
|
-
resourceUuid: v.optional(v.string(), ""),
|
|
14
13
|
content: v.optional(v.string(), ""),
|
|
15
14
|
x: v.optional(v.string(), ""),
|
|
16
15
|
y: v.optional(v.string(), ""),
|
|
@@ -19,11 +18,24 @@ const ocrStringSchema = v.object({
|
|
|
19
18
|
vertices: v.optional(v.string(), "")
|
|
20
19
|
});
|
|
21
20
|
/**
|
|
21
|
+
Schema for a single OCR match in the OCHRE API response
|
|
22
|
+
*/
|
|
23
|
+
const ocrMatchSchema = v.object({
|
|
24
|
+
resourceUuid: v.optional(v.string(), ""),
|
|
25
|
+
pageNumber: v.optional(v.string(), ""),
|
|
26
|
+
text: v.optional(v.string(), ""),
|
|
27
|
+
before: v.optional(v.string(), ""),
|
|
28
|
+
after: v.optional(v.string(), ""),
|
|
29
|
+
isTruncatedBefore: v.optional(v.string(), "false"),
|
|
30
|
+
isTruncatedAfter: v.optional(v.string(), "false"),
|
|
31
|
+
ocrString: v.optional(v.union([v.array(ocrStringSchema), ocrStringSchema]))
|
|
32
|
+
});
|
|
33
|
+
/**
|
|
22
34
|
Schema for the item OCR data OCHRE API response
|
|
23
35
|
*/
|
|
24
|
-
const responseSchema = v.object({ result: v.object({ ochre: v.object({
|
|
36
|
+
const responseSchema = v.object({ result: v.object({ ochre: v.object({ ocrMatches: v.object({
|
|
25
37
|
found: v.optional(v.string(), "false"),
|
|
26
|
-
|
|
38
|
+
ocrMatch: v.optional(v.union([v.array(ocrMatchSchema), ocrMatchSchema]))
|
|
27
39
|
}) }) }) });
|
|
28
40
|
function getSearchTerms(parameters) {
|
|
29
41
|
const { value, isCaseSensitive } = parameters;
|
|
@@ -31,7 +43,7 @@ function getSearchTerms(parameters) {
|
|
|
31
43
|
for (const term of value.split(/\s+/u)) if (term !== "") terms.push(isCaseSensitive ? term : term.toLocaleLowerCase("en-US"));
|
|
32
44
|
return terms;
|
|
33
45
|
}
|
|
34
|
-
function
|
|
46
|
+
function parseOcrNumber(value) {
|
|
35
47
|
const trimmedValue = value.trim();
|
|
36
48
|
if (trimmedValue === "") return null;
|
|
37
49
|
const numericValue = Number(trimmedValue);
|
|
@@ -49,74 +61,138 @@ function parseOcrStringVertices(value) {
|
|
|
49
61
|
}
|
|
50
62
|
return vertices;
|
|
51
63
|
}
|
|
64
|
+
function toArray(value) {
|
|
65
|
+
if (value == null) return [];
|
|
66
|
+
return Array.isArray(value) ? value : [value];
|
|
67
|
+
}
|
|
52
68
|
/**
|
|
53
|
-
Build an XQuery string to fetch
|
|
69
|
+
Build an XQuery string to fetch the OCR matches of an item from the OCHRE API
|
|
54
70
|
|
|
55
71
|
The `<ocr>` layer is marked supplemental, so it is deliberately read without
|
|
56
72
|
the supplemental stripping the other fetchers apply. Word nodes are projected
|
|
57
73
|
at any depth, because OCHRE does not guarantee the shape of the surrounding
|
|
58
74
|
hierarchy.
|
|
59
75
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
76
|
+
Each layer is one page. A layer is skipped unless every term occurs somewhere
|
|
77
|
+
in its joined word text, which is a superset of every phrase match, so pages
|
|
78
|
+
without a match never pay for word-by-word matching. On the remaining pages
|
|
79
|
+
the words are read into a sequence once, a phrase is matched only from the
|
|
80
|
+
words matching its first term, and the context is sliced out of the sequence
|
|
81
|
+
by position rather than walked along the `preceding` and `following` axes.
|
|
82
|
+
|
|
83
|
+
A hyphenated word is split over two word nodes that both carry the whole
|
|
84
|
+
form in `SUBS_CONTENT`. The two nodes are read as one word, so a phrase
|
|
85
|
+
spanning a hyphenated word still lines up term by term, and the hyphenation
|
|
86
|
+
check only runs on pages that carry a `SUBS_TYPE` at all.
|
|
64
87
|
|
|
65
|
-
The matches are wrapped in an `<
|
|
88
|
+
The matches are wrapped in an `<ocrMatches>` element carrying a `found`
|
|
66
89
|
flag, which tells "no such item" apart from "no matches".
|
|
67
90
|
@param parameters - The parameters for the fetch
|
|
68
91
|
@param parameters.uuid - The UUID of the OCHRE item to read the OCR layer of
|
|
69
|
-
@param parameters.terms - The
|
|
70
|
-
@param parameters.matchMode - Whether a term has to be contained in
|
|
92
|
+
@param parameters.terms - The search terms to match, in phrase order, already lowercased for case-insensitive matching
|
|
93
|
+
@param parameters.matchMode - Whether a term has to be contained in its word or equal it
|
|
71
94
|
@param parameters.isCaseSensitive - Whether matching is case sensitive
|
|
95
|
+
@param parameters.contextWordCount - The number of words of context to return on either side of a match, or 0 for none
|
|
72
96
|
@returns An XQuery string
|
|
73
97
|
*/
|
|
74
98
|
function buildXQuery(parameters) {
|
|
75
|
-
const { uuid, terms, matchMode, isCaseSensitive } = parameters;
|
|
76
|
-
const
|
|
77
|
-
const
|
|
78
|
-
const matchExpression = matchMode === "exact" ?
|
|
99
|
+
const { uuid, terms, matchMode, isCaseSensitive, contextWordCount } = parameters;
|
|
100
|
+
const fold = (expression) => isCaseSensitive ? expression : `lower-case(${expression})`;
|
|
101
|
+
const keyExpression = matchMode === "exact" ? `normalize-space(${fold("$text")})` : fold("$text");
|
|
102
|
+
const matchExpression = matchMode === "exact" ? "$keys[$index + $offset - 1] eq $terms[$offset]" : "contains($keys[$index + $offset - 1], $terms[$offset])";
|
|
103
|
+
const contextAttributes = contextWordCount > 0 ? `
|
|
104
|
+
before="{string-join(subsequence($texts, max(($index - ${contextWordCount}, 1)), min(($index - 1, ${contextWordCount}))), " ")}"
|
|
105
|
+
after="{string-join(subsequence($texts, $last + 1, ${contextWordCount}), " ")}"
|
|
106
|
+
isTruncatedBefore="{$index - ${contextWordCount} gt 1}"
|
|
107
|
+
isTruncatedAfter="{$last + ${contextWordCount} lt $textCount}"` : "";
|
|
79
108
|
return `xquery version "1.0-ml";
|
|
80
109
|
|
|
81
|
-
declare variable $terms := (${
|
|
110
|
+
declare variable $terms := (${terms.map((term) => stringLiteral(term)).join(", ")});
|
|
111
|
+
declare variable $termCount := count($terms);
|
|
112
|
+
|
|
113
|
+
declare function local:joins-previous($words as element()*, $index as xs:integer) as xs:boolean {
|
|
114
|
+
let $word := $words[$index]
|
|
115
|
+
let $previous := $words[$index - 1]
|
|
116
|
+
let $whole := string($word/@SUBS_CONTENT)
|
|
117
|
+
return $whole ne ""
|
|
118
|
+
and string($word/@SUBS_TYPE) eq "HypPart2"
|
|
119
|
+
and string($previous/@SUBS_TYPE) eq "HypPart1"
|
|
120
|
+
and string($previous/@SUBS_CONTENT) eq $whole
|
|
121
|
+
};
|
|
82
122
|
|
|
83
123
|
let $ochre := doc(${stringLiteral(uuid)})/ochre
|
|
84
|
-
let $
|
|
85
|
-
for $
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
124
|
+
let $ocrMatches :=
|
|
125
|
+
for $layer in ${buildOcrLayerPath("$ochre")}
|
|
126
|
+
let $words := ${buildOcrWordPath("$layer")}
|
|
127
|
+
let $layerText := ${fold("string-join(($words/@CONTENT, $words/@SUBS_CONTENT), \" \")")}
|
|
128
|
+
where (every $term in $terms satisfies contains($layerText, $term))
|
|
129
|
+
return
|
|
130
|
+
let $wordCount := count($words)
|
|
131
|
+
let $heads :=
|
|
132
|
+
if (exists($words/@SUBS_TYPE))
|
|
133
|
+
then
|
|
134
|
+
for $index in (1 to $wordCount)
|
|
135
|
+
where not(local:joins-previous($words, $index))
|
|
136
|
+
return $index
|
|
137
|
+
else (1 to $wordCount)
|
|
138
|
+
let $texts :=
|
|
139
|
+
for $head in $heads
|
|
140
|
+
let $word := $words[$head]
|
|
141
|
+
return string(($word/@SUBS_CONTENT[. ne ""], $word/@CONTENT)[1])
|
|
142
|
+
let $keys := for $text in $texts return ${keyExpression}
|
|
143
|
+
let $textCount := count($texts)
|
|
144
|
+
let $owner := $layer/ancestor::*[local-name(.) = "resource"][1]
|
|
145
|
+
let $pageNumber :=
|
|
146
|
+
if (exists($owner))
|
|
147
|
+
then count($owner/preceding-sibling::*[local-name(.) = "resource"]) + 1
|
|
148
|
+
else ()
|
|
149
|
+
for $index in (1 to $textCount - $termCount + 1)
|
|
150
|
+
where (every $offset in (1 to $termCount) satisfies ${matchExpression})
|
|
151
|
+
return
|
|
152
|
+
let $last := $index + $termCount - 1
|
|
153
|
+
let $firstWord := $heads[$index]
|
|
154
|
+
let $lastWord := if ($last lt $textCount) then $heads[$last + 1] - 1 else $wordCount
|
|
155
|
+
return <ocrMatch
|
|
156
|
+
resourceUuid="{string($owner/@uuid)}"
|
|
157
|
+
pageNumber="{$pageNumber}"
|
|
158
|
+
text="{string-join(subsequence($texts, $index, $termCount), " ")}"${contextAttributes}>{
|
|
159
|
+
for $string in subsequence($words, $firstWord, $lastWord - $firstWord + 1)
|
|
160
|
+
return <ocrString
|
|
161
|
+
content="{string($string/@CONTENT)}"
|
|
162
|
+
x="{string($string/@HPOS)}"
|
|
163
|
+
y="{string($string/@VPOS)}"
|
|
164
|
+
width="{string($string/@WIDTH)}"
|
|
165
|
+
height="{string($string/@HEIGHT)}"
|
|
166
|
+
vertices="{string($string/@VERTICES)}"/>
|
|
167
|
+
}</ocrMatch>
|
|
95
168
|
|
|
96
|
-
return <ochre>${OCHRE_RESPONSE_PADDING}<
|
|
169
|
+
return <ochre>${OCHRE_RESPONSE_PADDING}<ocrMatches found="{exists($ochre)}">{$ocrMatches}</ocrMatches></ochre>`;
|
|
97
170
|
}
|
|
98
171
|
/**
|
|
99
|
-
Fetches
|
|
172
|
+
Fetches the OCR matches of an OCHRE item for a search value
|
|
100
173
|
|
|
101
174
|
Resources may carry an `<ocr>` layer whose internal hierarchy is irregular
|
|
102
|
-
and therefore not parsed. Only its word nodes are
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
`
|
|
175
|
+
and therefore not parsed. Only its word nodes are read, wherever they occur
|
|
176
|
+
in that subtree. A word node is any element named `String` or `string` in
|
|
177
|
+
any namespace, and matching reads its `CONTENT` attribute, or its
|
|
178
|
+
`SUBS_CONTENT` attribute when the word is hyphenated across two lines.
|
|
106
179
|
|
|
107
|
-
Each word node holds a single OCR word, so
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
180
|
+
Each word node holds a single OCR word, so the search value is split on
|
|
181
|
+
whitespace and read as a phrase: a match is a run of consecutive words in
|
|
182
|
+
which each word matches its term, so a single-term search matches every word
|
|
183
|
+
that matches the term. Every OCR layer is one page, and nested child Resources are
|
|
184
|
+
searched too, with `resourceUuid` and `pageNumber` naming the page each
|
|
185
|
+
match is on. Matches are returned in document order.
|
|
111
186
|
|
|
112
187
|
@param uuid - The UUID of the OCHRE item to read the OCR layer of
|
|
113
|
-
@param value - The search value
|
|
188
|
+
@param value - The search value, matched as a phrase of whitespace-separated terms
|
|
114
189
|
@param options - Options for the fetch
|
|
115
|
-
@param options.matchMode - Whether
|
|
190
|
+
@param options.matchMode - Whether each term has to be contained in its word ("includes", the default) or equal it ("exact")
|
|
116
191
|
@param options.isCaseSensitive - Whether matching is case sensitive, defaulting to false
|
|
192
|
+
@param options.contextWordCount - The number of words of context to return on either side of each match, within its page, defaulting to 0 for no context
|
|
117
193
|
@param options.fetch - The fetch function to use
|
|
118
|
-
@returns The
|
|
119
|
-
|
|
194
|
+
@returns The OCR matches, an empty array when the item has no OCR layer or
|
|
195
|
+
nothing matches, and a null output on fetch/parse errors
|
|
120
196
|
*/
|
|
121
197
|
async function fetchItemOcrData(uuid, value, options) {
|
|
122
198
|
try {
|
|
@@ -124,42 +200,57 @@ async function fetchItemOcrData(uuid, value, options) {
|
|
|
124
200
|
uuid,
|
|
125
201
|
value,
|
|
126
202
|
matchMode: options?.matchMode,
|
|
127
|
-
isCaseSensitive: options?.isCaseSensitive
|
|
128
|
-
|
|
129
|
-
const terms = getSearchTerms({
|
|
130
|
-
value: parameters.value,
|
|
131
|
-
isCaseSensitive: parameters.isCaseSensitive
|
|
203
|
+
isCaseSensitive: options?.isCaseSensitive,
|
|
204
|
+
contextWordCount: options?.contextWordCount
|
|
132
205
|
});
|
|
133
206
|
const xquery = buildXQuery({
|
|
134
207
|
uuid: parameters.uuid,
|
|
135
|
-
terms
|
|
208
|
+
terms: getSearchTerms({
|
|
209
|
+
value: parameters.value,
|
|
210
|
+
isCaseSensitive: parameters.isCaseSensitive
|
|
211
|
+
}),
|
|
136
212
|
matchMode: parameters.matchMode,
|
|
137
|
-
isCaseSensitive: parameters.isCaseSensitive
|
|
213
|
+
isCaseSensitive: parameters.isCaseSensitive,
|
|
214
|
+
contextWordCount: parameters.contextWordCount
|
|
138
215
|
});
|
|
139
|
-
const { found,
|
|
216
|
+
const { found, ocrMatch } = (await requestOchre({
|
|
140
217
|
xquery,
|
|
141
218
|
schema: responseSchema,
|
|
142
219
|
label: "OCHRE item OCR data",
|
|
143
220
|
options
|
|
144
|
-
})).result.ochre.
|
|
221
|
+
})).result.ochre.ocrMatches;
|
|
145
222
|
if (found !== "true") throw new Error(`No OCHRE item found for UUID: ${parameters.uuid}`, { cause: parameters.uuid });
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
resourceUuid: parsedOcrString.resourceUuid !== "" ? parsedOcrString.resourceUuid : null,
|
|
223
|
+
const ocrMatches = [];
|
|
224
|
+
for (const parsedOcrMatch of toArray(ocrMatch)) {
|
|
225
|
+
const strings = Array.from(toArray(parsedOcrMatch.ocrString), (parsedOcrString) => ({
|
|
150
226
|
content: parsedOcrString.content,
|
|
151
|
-
x:
|
|
152
|
-
y:
|
|
153
|
-
width:
|
|
154
|
-
height:
|
|
227
|
+
x: parseOcrNumber(parsedOcrString.x),
|
|
228
|
+
y: parseOcrNumber(parsedOcrString.y),
|
|
229
|
+
width: parseOcrNumber(parsedOcrString.width),
|
|
230
|
+
height: parseOcrNumber(parsedOcrString.height),
|
|
155
231
|
vertices: parseOcrStringVertices(parsedOcrString.vertices)
|
|
156
|
-
}))
|
|
232
|
+
}));
|
|
233
|
+
ocrMatches.push({
|
|
234
|
+
resourceUuid: parsedOcrMatch.resourceUuid !== "" ? parsedOcrMatch.resourceUuid : null,
|
|
235
|
+
pageNumber: parseOcrNumber(parsedOcrMatch.pageNumber),
|
|
236
|
+
text: parsedOcrMatch.text,
|
|
237
|
+
strings,
|
|
238
|
+
context: parameters.contextWordCount > 0 ? {
|
|
239
|
+
before: parsedOcrMatch.before,
|
|
240
|
+
after: parsedOcrMatch.after,
|
|
241
|
+
isTruncatedBefore: parsedOcrMatch.isTruncatedBefore === "true",
|
|
242
|
+
isTruncatedAfter: parsedOcrMatch.isTruncatedAfter === "true"
|
|
243
|
+
} : null
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
return {
|
|
247
|
+
ocrMatches,
|
|
157
248
|
error: null,
|
|
158
249
|
detailedError: null
|
|
159
250
|
};
|
|
160
251
|
} catch (error) {
|
|
161
252
|
return {
|
|
162
|
-
|
|
253
|
+
ocrMatches: null,
|
|
163
254
|
...getErrorOutput(error, "Failed to fetch item OCR data")
|
|
164
255
|
};
|
|
165
256
|
}
|
package/dist/index.d.mts
CHANGED
|
@@ -16,6 +16,6 @@ import { flattenItemProperties } from "./helpers.mjs";
|
|
|
16
16
|
import { OCHRE_LANGUAGES, OchreLanguage, OchreLanguageCode, OchreLanguageKind, OchreLanguageStandard, getOchreLanguage, getOchreLanguageCode, isOchreLanguageCode } from "./languages.mjs";
|
|
17
17
|
import { defineLanguages } from "./parsers/languages.mjs";
|
|
18
18
|
import { MultilingualOptions, MultilingualString, MultilingualStringEntries, MultilingualStringEntry, MultilingualStringInput, MultilingualStringJSON, MultilingualStringObject, MultilingualStringText } from "./parsers/multilingual.mjs";
|
|
19
|
-
import { AnyBibliography, AnyConcept, AnyItem, AnyPeriod, AnyPerson, AnyPropertyValue, AnyPropertyVariable, AnyResource, AnySet, AnySpatialUnit, AnyText, AnyTree, BaseItem, BaseItemLink, BelongsTo, Bibliography, BibliographyEntryInfo, BibliographyItemLink, BibliographySourceDocument, Concept, ConceptItemLink, ContainedItemCategory, ContainedItemCategoryFromOption, ContainedItemCategoryOption, Context, ContextItem, ContextItemCategory, ContextNode, Coordinates, CoordinatesSource, DictionaryUnitItemLink, DownloadOption, EmbeddedBibliography, EmbeddedConcept, EmbeddedItem, EmbeddedPeriod, EmbeddedPerson, EmbeddedPropertyValue, EmbeddedPropertyVariable, EmbeddedResource, EmbeddedSet, EmbeddedSpatialUnit, EmbeddedText, EmbeddedTree, Event, Gallery, Heading, HeadingItemCategory, Identification, Image, ImageMap, ImageMapArea, Interpretation, Item, ItemCategory, ItemCategoryFromOption, ItemCategoryOption, ItemCategoryWithEmbeddedItems, ItemContainerCategory, ItemLink, ItemLinkCategory, ItemLinks, ItemLocation, ItemPayloadKind, ItemProperty, ItemWithoutEmbeddedItems, LanguageCodes, License, MapLayer, Metadata, Note, Observation, OcrString, PartialDate, PartialDateBound, PartialDateQualifier, PartialDateSeason, PartialDateValue, Period, PeriodItemLink, Person, PersonItemLink, Property, PropertyLike, PropertyRelation, PropertyValue, PropertyValueContent, PropertyValueDataType, PropertyValueItemLink, PropertyValueQueryItem, PropertyVariable, PropertyVariableItemLink, Query, QueryGroup, QueryLeaf, QueryablePropertyValueDataType, RecursiveItemCategory, Resource, ResourceItemLink, Section, Set, SetAttributeValueQueryItem, SetBibliography, SetConcept, SetItem, SetItemCategory, SetItemLink, SetItemProperty, SetItemSimplifiedProperty, SetItemsSort, SetItemsSortDirection, SetPeriod, SetResource, SetSpatialUnit, SetStyle, SetStyleProperty, SetTree, SimplifiedProperty, SpatialUnit, SpatialUnitItemLink, Text, TextItemLink, TopLevelItem, Tree, TreeItemCategory, TreeItemLink } from "./types/index.mjs";
|
|
19
|
+
import { AnyBibliography, AnyConcept, AnyItem, AnyPeriod, AnyPerson, AnyPropertyValue, AnyPropertyVariable, AnyResource, AnySet, AnySpatialUnit, AnyText, AnyTree, BaseItem, BaseItemLink, BelongsTo, Bibliography, BibliographyEntryInfo, BibliographyItemLink, BibliographySourceDocument, Concept, ConceptItemLink, ContainedItemCategory, ContainedItemCategoryFromOption, ContainedItemCategoryOption, Context, ContextItem, ContextItemCategory, ContextNode, Coordinates, CoordinatesSource, DictionaryUnitItemLink, DownloadOption, EmbeddedBibliography, EmbeddedConcept, EmbeddedItem, EmbeddedPeriod, EmbeddedPerson, EmbeddedPropertyValue, EmbeddedPropertyVariable, EmbeddedResource, EmbeddedSet, EmbeddedSpatialUnit, EmbeddedText, EmbeddedTree, Event, Gallery, Heading, HeadingItemCategory, Identification, Image, ImageMap, ImageMapArea, Interpretation, Item, ItemCategory, ItemCategoryFromOption, ItemCategoryOption, ItemCategoryWithEmbeddedItems, ItemContainerCategory, ItemLink, ItemLinkCategory, ItemLinks, ItemLocation, ItemPayloadKind, ItemProperty, ItemWithoutEmbeddedItems, LanguageCodes, License, MapLayer, Metadata, Note, Observation, OcrMatch, OcrString, PartialDate, PartialDateBound, PartialDateQualifier, PartialDateSeason, PartialDateValue, Period, PeriodItemLink, Person, PersonItemLink, Property, PropertyLike, PropertyRelation, PropertyValue, PropertyValueContent, PropertyValueDataType, PropertyValueItemLink, PropertyValueQueryItem, PropertyVariable, PropertyVariableItemLink, Query, QueryGroup, QueryLeaf, QueryablePropertyValueDataType, RecursiveItemCategory, Resource, ResourceItemLink, Section, Set, SetAttributeValueQueryItem, SetBibliography, SetConcept, SetItem, SetItemCategory, SetItemLink, SetItemProperty, SetItemSimplifiedProperty, SetItemsSort, SetItemsSortDirection, SetPeriod, SetResource, SetSpatialUnit, SetStyle, SetStyleProperty, SetTree, SimplifiedProperty, SpatialUnit, SpatialUnitItemLink, Text, TextItemLink, TopLevelItem, Tree, TreeItemCategory, TreeItemLink } from "./types/index.mjs";
|
|
20
20
|
import { AccordionWebBlock, ContextTree, ContextTreeFilterLevel, ContextTreeFilterVariant, ContextTreeLevel, ContextTreeLevelItem, ProtectedWebsite, ResponsiveStyles, Scope, Style, StylesheetCategory, StylesheetItem, WebAccordionItem, WebBlock, WebBlockByLayout, WebBlockItem, WebBlockLayout, WebCollectionVariant, WebElement, WebElementComponent, WebElementComponentName, WebElementComponentOf, WebElementOf, WebIiifViewer, WebImage, WebLoadingVariant, WebOptions, WebRelationVariant, WebSectionDisplay, WebSectionVariant, WebSidebar, WebTitle, Webpage, Website, WebsiteMetadata, WebsitePrivacy, WebsitePropertyQuery, WebsitePropertyQueryNode, WebsiteSegment, WebsiteType } from "./types/website.mjs";
|
|
21
|
-
export { type AccordionWebBlock, type AnyBibliography, type AnyConcept, type AnyItem, type AnyPeriod, type AnyPerson, type AnyPropertyValue, type AnyPropertyVariable, type AnyResource, type AnySet, type AnySpatialUnit, type AnyText, type AnyTree, type BaseItem, type BaseItemLink, type BelongsTo, type Bibliography, type BibliographyEntryInfo, type BibliographyItemLink, type BibliographySourceDocument, type Concept, type ConceptItemLink, type ContainedItemCategory, type ContainedItemCategoryFromOption, type ContainedItemCategoryOption, type Context, type ContextItem, type ContextItemCategory, type ContextNode, type ContextTree, type ContextTreeFilterLevel, type ContextTreeFilterVariant, type ContextTreeLevel, type ContextTreeLevelItem, type Coordinates, type CoordinatesSource, DEFAULT_PAGE_SIZE, type DictionaryUnitItemLink, type DownloadOption, type EmbeddedBibliography, type EmbeddedConcept, type EmbeddedItem, type EmbeddedPeriod, type EmbeddedPerson, type EmbeddedPropertyValue, type EmbeddedPropertyVariable, type EmbeddedResource, type EmbeddedSet, type EmbeddedSpatialUnit, type EmbeddedText, type EmbeddedTree, type Event, type Gallery, type Heading, type HeadingItemCategory, type Identification, type Image, type ImageMap, type ImageMapArea, type Interpretation, type Item, type ItemCategory, type ItemCategoryFromOption, type ItemCategoryOption, type ItemCategoryWithEmbeddedItems, type ItemContainerCategory, type ItemLink, type ItemLinkCategory, type ItemLinks, type ItemLocation, type ItemPayloadKind, type ItemProperty, type ItemWithoutEmbeddedItems, type LanguageCodes, type License, type MapLayer, type Metadata, type MultilingualOptions, MultilingualString, type MultilingualStringEntries, type MultilingualStringEntry, type MultilingualStringInput, type MultilingualStringJSON, type MultilingualStringObject, type MultilingualStringText, type Note, OCHRE_LANGUAGES, type Observation, type OchreLanguage, type OchreLanguageCode, type OchreLanguageKind, type OchreLanguageStandard, type OcrString, type PartialDate, type PartialDateBound, type PartialDateQualifier, type PartialDateSeason, type PartialDateValue, type Period, type PeriodItemLink, type Person, type PersonItemLink, type Property, type PropertyLike, type PropertyOptions, type PropertyRelation, type PropertySelector, type PropertyValue, type PropertyValueContent, type PropertyValueDataType, type PropertyValueItemLink, type PropertyValueQueryItem, type PropertyVariable, type PropertyVariableItemLink, type ProtectedWebsite, type Query, type QueryGroup, type QueryLeaf, type QueryablePropertyValueDataType, type RecursiveItemCategory, type Resource, type ResourceItemLink, type ResponsiveStyles, type Scope, type Section, type Set, type SetAttributeValueQueryItem, type SetBibliography, type SetConcept, type SetItem, type SetItemCategory, type SetItemLink, type SetItemProperty, type SetItemSimplifiedProperty, type SetItemsSort, type SetItemsSortDirection, type SetPeriod, type SetResource, type SetSpatialUnit, type SetStyle, type SetStyleProperty, type SetTree, type SimplifiedProperty, type SpatialUnit, type SpatialUnitItemLink, type Style, type StylesheetCategory, type StylesheetItem, type Text, type TextItemLink, type TopLevelItem, type Tree, type TreeItemCategory, type TreeItemLink, type WebAccordionItem, type WebBlock, type WebBlockByLayout, type WebBlockItem, type WebBlockLayout, type WebCollectionVariant, type WebElement, type WebElementComponent, type WebElementComponentName, type WebElementComponentOf, type WebElementOf, type WebIiifViewer, type WebImage, type WebLoadingVariant, type WebOptions, type WebRelationVariant, type WebSectionDisplay, type WebSectionVariant, type WebSidebar, type WebTitle, type Webpage, type Website, type WebsiteMetadata, type WebsitePrivacy, type WebsitePropertyQuery, type WebsitePropertyQueryNode, type WebsiteSegment, type WebsiteType, defineLanguages, fetchGallery, fetchItem, fetchItemChildren, fetchItemLinks, fetchItemLocations, fetchItemOcrData, fetchMapLayers, fetchSetItems, fetchSetPropertyValues, fetchTreeItems, fetchWebsite, fetchWebsiteMetadata, flattenItemProperties, getLeafPropertyValues, getOchreLanguage, getOchreLanguageCode, getProperty, getPropertyValue, getPropertyValues, getUniqueProperties, getUniquePropertyVariableLabels, isOchreLanguageCode, isPropertyMatchingFilter, normalizePropertyVariableLabel };
|
|
21
|
+
export { type AccordionWebBlock, type AnyBibliography, type AnyConcept, type AnyItem, type AnyPeriod, type AnyPerson, type AnyPropertyValue, type AnyPropertyVariable, type AnyResource, type AnySet, type AnySpatialUnit, type AnyText, type AnyTree, type BaseItem, type BaseItemLink, type BelongsTo, type Bibliography, type BibliographyEntryInfo, type BibliographyItemLink, type BibliographySourceDocument, type Concept, type ConceptItemLink, type ContainedItemCategory, type ContainedItemCategoryFromOption, type ContainedItemCategoryOption, type Context, type ContextItem, type ContextItemCategory, type ContextNode, type ContextTree, type ContextTreeFilterLevel, type ContextTreeFilterVariant, type ContextTreeLevel, type ContextTreeLevelItem, type Coordinates, type CoordinatesSource, DEFAULT_PAGE_SIZE, type DictionaryUnitItemLink, type DownloadOption, type EmbeddedBibliography, type EmbeddedConcept, type EmbeddedItem, type EmbeddedPeriod, type EmbeddedPerson, type EmbeddedPropertyValue, type EmbeddedPropertyVariable, type EmbeddedResource, type EmbeddedSet, type EmbeddedSpatialUnit, type EmbeddedText, type EmbeddedTree, type Event, type Gallery, type Heading, type HeadingItemCategory, type Identification, type Image, type ImageMap, type ImageMapArea, type Interpretation, type Item, type ItemCategory, type ItemCategoryFromOption, type ItemCategoryOption, type ItemCategoryWithEmbeddedItems, type ItemContainerCategory, type ItemLink, type ItemLinkCategory, type ItemLinks, type ItemLocation, type ItemPayloadKind, type ItemProperty, type ItemWithoutEmbeddedItems, type LanguageCodes, type License, type MapLayer, type Metadata, type MultilingualOptions, MultilingualString, type MultilingualStringEntries, type MultilingualStringEntry, type MultilingualStringInput, type MultilingualStringJSON, type MultilingualStringObject, type MultilingualStringText, type Note, OCHRE_LANGUAGES, type Observation, type OchreLanguage, type OchreLanguageCode, type OchreLanguageKind, type OchreLanguageStandard, type OcrMatch, type OcrString, type PartialDate, type PartialDateBound, type PartialDateQualifier, type PartialDateSeason, type PartialDateValue, type Period, type PeriodItemLink, type Person, type PersonItemLink, type Property, type PropertyLike, type PropertyOptions, type PropertyRelation, type PropertySelector, type PropertyValue, type PropertyValueContent, type PropertyValueDataType, type PropertyValueItemLink, type PropertyValueQueryItem, type PropertyVariable, type PropertyVariableItemLink, type ProtectedWebsite, type Query, type QueryGroup, type QueryLeaf, type QueryablePropertyValueDataType, type RecursiveItemCategory, type Resource, type ResourceItemLink, type ResponsiveStyles, type Scope, type Section, type Set, type SetAttributeValueQueryItem, type SetBibliography, type SetConcept, type SetItem, type SetItemCategory, type SetItemLink, type SetItemProperty, type SetItemSimplifiedProperty, type SetItemsSort, type SetItemsSortDirection, type SetPeriod, type SetResource, type SetSpatialUnit, type SetStyle, type SetStyleProperty, type SetTree, type SimplifiedProperty, type SpatialUnit, type SpatialUnitItemLink, type Style, type StylesheetCategory, type StylesheetItem, type Text, type TextItemLink, type TopLevelItem, type Tree, type TreeItemCategory, type TreeItemLink, type WebAccordionItem, type WebBlock, type WebBlockByLayout, type WebBlockItem, type WebBlockLayout, type WebCollectionVariant, type WebElement, type WebElementComponent, type WebElementComponentName, type WebElementComponentOf, type WebElementOf, type WebIiifViewer, type WebImage, type WebLoadingVariant, type WebOptions, type WebRelationVariant, type WebSectionDisplay, type WebSectionVariant, type WebSidebar, type WebTitle, type Webpage, type Website, type WebsiteMetadata, type WebsitePrivacy, type WebsitePropertyQuery, type WebsitePropertyQueryNode, type WebsiteSegment, type WebsiteType, defineLanguages, fetchGallery, fetchItem, fetchItemChildren, fetchItemLinks, fetchItemLocations, fetchItemOcrData, fetchMapLayers, fetchSetItems, fetchSetPropertyValues, fetchTreeItems, fetchWebsite, fetchWebsiteMetadata, flattenItemProperties, getLeafPropertyValues, getOchreLanguage, getOchreLanguageCode, getProperty, getPropertyValue, getPropertyValues, getUniqueProperties, getUniquePropertyVariableLabels, isOchreLanguageCode, isPropertyMatchingFilter, normalizePropertyVariableLabel };
|
package/dist/ocr.d.mts
CHANGED
|
@@ -21,15 +21,26 @@ narrowing misses is a document the search silently drops.
|
|
|
21
21
|
*/
|
|
22
22
|
export declare const OCR_WORD_QNAMES: string;
|
|
23
23
|
/**
|
|
24
|
-
Build an XQuery path selecting every OCR
|
|
24
|
+
Build an XQuery path selecting every OCR layer beneath a node
|
|
25
25
|
|
|
26
|
-
Matches
|
|
27
|
-
rather than a name test, because a name test silently matches nothing when
|
|
28
|
-
OCHRE varies the casing or serves the elements in a namespace. Word elements
|
|
29
|
-
are selected at any depth, because the hierarchy between the layer and its
|
|
30
|
-
words is irregular and is not parsed.
|
|
26
|
+
Matches on `local-name()` so that a layer is selected in any namespace.
|
|
31
27
|
@param rootExpression - The XQuery expression to select from
|
|
32
28
|
@returns The XQuery path
|
|
33
29
|
@internal
|
|
34
30
|
*/
|
|
35
|
-
export declare function
|
|
31
|
+
export declare function buildOcrLayerPath(rootExpression: string): string;
|
|
32
|
+
/**
|
|
33
|
+
Build an XQuery path selecting every OCR word element beneath an OCR layer
|
|
34
|
+
|
|
35
|
+
Matches on `local-name()` so that both the ALTO-namespaced and the
|
|
36
|
+
unnamespaced elements are selected, against exactly the local names
|
|
37
|
+
{@link OCR_WORD_QNAMES} narrows on, so the path and the narrowing always
|
|
38
|
+
agree. Comparing against a literal list measures around three times faster
|
|
39
|
+
than case-folding every element name. Word elements are selected at any
|
|
40
|
+
depth, because the hierarchy between the layer and its words is irregular
|
|
41
|
+
and is not parsed.
|
|
42
|
+
@param layerExpression - The XQuery expression selecting the OCR layers, as built by {@link buildOcrLayerPath}
|
|
43
|
+
@returns The XQuery path
|
|
44
|
+
@internal
|
|
45
|
+
*/
|
|
46
|
+
export declare function buildOcrWordPath(layerExpression: string): string;
|
package/dist/ocr.mjs
CHANGED
|
@@ -10,7 +10,6 @@ of them: an `xs:QName("String")` narrowing matches 2 of the 18,446 documents
|
|
|
10
10
|
carrying an OCR layer, while the ALTO-namespaced `String` matches 14,650.
|
|
11
11
|
*/
|
|
12
12
|
const OCR_WORD_LOCAL_NAMES = ["String", "string"];
|
|
13
|
-
const OCR_WORD_CASE_FOLDED_LOCAL_NAME = "string";
|
|
14
13
|
/**
|
|
15
14
|
The name of the element wrapping an OCR layer inside an OCHRE document
|
|
16
15
|
@internal
|
|
@@ -34,18 +33,31 @@ narrowing misses is a document the search silently drops.
|
|
|
34
33
|
*/
|
|
35
34
|
const OCR_WORD_QNAMES = `(${[...OCR_WORD_LOCAL_NAMES.map((localName) => `fn:QName(${stringLiteral(ALTO_NAMESPACE)}, ${stringLiteral(localName)})`), ...OCR_WORD_LOCAL_NAMES.map((localName) => `xs:QName(${stringLiteral(localName)})`)].join(", ")})`;
|
|
36
35
|
/**
|
|
37
|
-
Build an XQuery path selecting every OCR
|
|
36
|
+
Build an XQuery path selecting every OCR layer beneath a node
|
|
38
37
|
|
|
39
|
-
Matches
|
|
40
|
-
rather than a name test, because a name test silently matches nothing when
|
|
41
|
-
OCHRE varies the casing or serves the elements in a namespace. Word elements
|
|
42
|
-
are selected at any depth, because the hierarchy between the layer and its
|
|
43
|
-
words is irregular and is not parsed.
|
|
38
|
+
Matches on `local-name()` so that a layer is selected in any namespace.
|
|
44
39
|
@param rootExpression - The XQuery expression to select from
|
|
45
40
|
@returns The XQuery path
|
|
46
41
|
@internal
|
|
47
42
|
*/
|
|
48
|
-
function
|
|
49
|
-
return `${rootExpression}//*[
|
|
43
|
+
function buildOcrLayerPath(rootExpression) {
|
|
44
|
+
return `${rootExpression}//*[local-name(.) = ${stringLiteral("ocr")}]`;
|
|
50
45
|
}
|
|
51
|
-
|
|
46
|
+
/**
|
|
47
|
+
Build an XQuery path selecting every OCR word element beneath an OCR layer
|
|
48
|
+
|
|
49
|
+
Matches on `local-name()` so that both the ALTO-namespaced and the
|
|
50
|
+
unnamespaced elements are selected, against exactly the local names
|
|
51
|
+
{@link OCR_WORD_QNAMES} narrows on, so the path and the narrowing always
|
|
52
|
+
agree. Comparing against a literal list measures around three times faster
|
|
53
|
+
than case-folding every element name. Word elements are selected at any
|
|
54
|
+
depth, because the hierarchy between the layer and its words is irregular
|
|
55
|
+
and is not parsed.
|
|
56
|
+
@param layerExpression - The XQuery expression selecting the OCR layers, as built by {@link buildOcrLayerPath}
|
|
57
|
+
@returns The XQuery path
|
|
58
|
+
@internal
|
|
59
|
+
*/
|
|
60
|
+
function buildOcrWordPath(layerExpression) {
|
|
61
|
+
return `${layerExpression}//*[local-name(.) = (${OCR_WORD_LOCAL_NAMES.map((localName) => stringLiteral(localName)).join(", ")})][@${OCR_WORD_CONTENT_ATTRIBUTE}]`;
|
|
62
|
+
}
|
|
63
|
+
export { OCR_LAYER_ELEMENT_NAME, OCR_WORD_CONTENT_ATTRIBUTE, OCR_WORD_QNAMES, buildOcrLayerPath, buildOcrWordPath };
|
package/dist/query.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BELONGS_TO_COLLECTION_UUID } from "./constants.mjs";
|
|
2
|
-
import { OCR_WORD_CONTENT_ATTRIBUTE, OCR_WORD_QNAMES, buildOcrWordPath } from "./ocr.mjs";
|
|
2
|
+
import { OCR_WORD_CONTENT_ATTRIBUTE, OCR_WORD_QNAMES, buildOcrLayerPath, buildOcrWordPath } from "./ocr.mjs";
|
|
3
3
|
import { OCHRE_RESPONSE_PADDING, compileOchreQuery, stringLiteral } from "./xquery.mjs";
|
|
4
4
|
// src/query.ts
|
|
5
5
|
const CTS_INCLUDES_STOP_WORDS = /* @__PURE__ */ new Set([
|
|
@@ -580,7 +580,7 @@ function registerOcrPhraseHelper(context) {
|
|
|
580
580
|
context.helperNamesByKey.set(helperName, helperName);
|
|
581
581
|
context.helperDeclarations.push(`declare function ${helperName}($resource as node(), $terms as xs:string*, $isCaseSensitive as xs:boolean) as xs:boolean {
|
|
582
582
|
let $contents :=
|
|
583
|
-
for $word in ${buildOcrWordPath("$resource")}
|
|
583
|
+
for $word in ${buildOcrWordPath(buildOcrLayerPath("$resource"))}
|
|
584
584
|
return if ($isCaseSensitive) then string($word/@${OCR_WORD_CONTENT_ATTRIBUTE}) else lower-case(string($word/@${OCR_WORD_CONTENT_ATTRIBUTE}))
|
|
585
585
|
let $needles :=
|
|
586
586
|
for $term in $terms
|
package/dist/schemas.d.mts
CHANGED
|
@@ -72,6 +72,7 @@ export declare const itemOcrDataParametersSchema: v.ObjectSchema<{
|
|
|
72
72
|
readonly value: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "A search value is required">]>;
|
|
73
73
|
readonly matchMode: v.OptionalSchema<v.PicklistSchema<["includes", "exact"], undefined>, "includes">;
|
|
74
74
|
readonly isCaseSensitive: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
|
|
75
|
+
readonly contextWordCount: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, "Context word count must be an integer">, v.MinValueAction<number, 0, "Context word count must not be negative">]>, 0>;
|
|
75
76
|
}, undefined>;
|
|
76
77
|
export declare const setItemsParametersSchema: v.ObjectSchema<{
|
|
77
78
|
readonly belongsToCollectionScopeUuids: v.OptionalSchema<v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Invalid pseudo-UUID">]>, undefined>, readonly []>;
|
package/dist/schemas.mjs
CHANGED
|
@@ -268,7 +268,8 @@ const itemOcrDataParametersSchema = v.object({
|
|
|
268
268
|
uuid: uuidSchema,
|
|
269
269
|
value: v.pipe(v.string(), v.check((value) => value.trim() !== "", "A search value is required")),
|
|
270
270
|
matchMode: v.optional(v.picklist(["includes", "exact"]), "includes"),
|
|
271
|
-
isCaseSensitive: defaultFalseSchema
|
|
271
|
+
isCaseSensitive: defaultFalseSchema,
|
|
272
|
+
contextWordCount: v.optional(v.pipe(v.number(), v.integer("Context word count must be an integer"), v.minValue(0, "Context word count must not be negative")), 0)
|
|
272
273
|
});
|
|
273
274
|
/**
|
|
274
275
|
Schema for validating Set items parameters
|
package/dist/types/index.d.mts
CHANGED
|
@@ -335,7 +335,7 @@ Positioned OCR string in OCHRE
|
|
|
335
335
|
|
|
336
336
|
OCHRE gives no guarantee about the node hierarchy inside a Resource's
|
|
337
337
|
`<ocr>` layer, so only its word nodes are parsed, at whatever depth they
|
|
338
|
-
occur. A word node is any element named `string` in any
|
|
338
|
+
occur. A word node is any element named `String` or `string` in any
|
|
339
339
|
namespace, and its text is read from the `CONTENT` attribute.
|
|
340
340
|
|
|
341
341
|
`x` and `y` come from `HPOS` and `VPOS` and locate the top-left corner of
|
|
@@ -343,12 +343,8 @@ the word's box, while `vertices` comes from `VERTICES` and is its full
|
|
|
343
343
|
bounding polygon, which is not necessarily rectangular. Every geometry
|
|
344
344
|
attribute is optional in the source, so each one is null when absent or
|
|
345
345
|
unparseable, and `vertices` is then empty.
|
|
346
|
-
|
|
347
|
-
`resourceUuid` is the Resource that owns the OCR layer, which differs from
|
|
348
|
-
the requested item when the OCR lives on a child Resource.
|
|
349
346
|
*/
|
|
350
347
|
export type OcrString = {
|
|
351
|
-
resourceUuid: string | null;
|
|
352
348
|
content: string;
|
|
353
349
|
x: number | null;
|
|
354
350
|
y: number | null;
|
|
@@ -360,6 +356,38 @@ export type OcrString = {
|
|
|
360
356
|
}>;
|
|
361
357
|
};
|
|
362
358
|
/**
|
|
359
|
+
OCR search match in OCHRE
|
|
360
|
+
|
|
361
|
+
A match is one occurrence of the search phrase on one page: a run of
|
|
362
|
+
consecutive words in which each word matches its term. `strings` holds the
|
|
363
|
+
positioned words of the run, and a word hyphenated across two lines
|
|
364
|
+
contributes both halves.
|
|
365
|
+
|
|
366
|
+
`text` is the run as it reads, with hyphenated words rejoined from their
|
|
367
|
+
`SUBS_CONTENT`, which also count as one word in the phrase and in the
|
|
368
|
+
context. `context` holds the words on either side, within the same
|
|
369
|
+
page, and is null unless context was requested. Its `isTruncatedBefore` and
|
|
370
|
+
`isTruncatedAfter` flags are true when the page has more words beyond the
|
|
371
|
+
context.
|
|
372
|
+
|
|
373
|
+
`resourceUuid` is the Resource that owns the page's OCR layer, which differs
|
|
374
|
+
from the requested item when the OCR lives on a child Resource.
|
|
375
|
+
`pageNumber` is the 1-based position of that Resource among its sibling
|
|
376
|
+
Resources, which is the page order of a multi-page document.
|
|
377
|
+
*/
|
|
378
|
+
export type OcrMatch = {
|
|
379
|
+
resourceUuid: string | null;
|
|
380
|
+
pageNumber: number | null;
|
|
381
|
+
text: string;
|
|
382
|
+
strings: Array<OcrString>;
|
|
383
|
+
context: {
|
|
384
|
+
before: string;
|
|
385
|
+
after: string;
|
|
386
|
+
isTruncatedBefore: boolean;
|
|
387
|
+
isTruncatedAfter: boolean;
|
|
388
|
+
} | null;
|
|
389
|
+
};
|
|
390
|
+
/**
|
|
363
391
|
Note in OCHRE
|
|
364
392
|
*/
|
|
365
393
|
export type Note<T extends LanguageCodes = LanguageCodes> = {
|