@knaw-huc/text-annotation-segmenter 0.1.1 → 0.3.0

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 CHANGED
@@ -15,15 +15,18 @@ A special case is the marker: an annotation of zero width marking a position in
15
15
 
16
16
  ## API
17
17
 
18
- - [`segment<T>(text, annotations): TextSegment<T>[]`](./src/segment.ts) <br /> Split a text into TextSegments with char offsets to the text and a list of applying annotations.
19
- - [`AnnotationSegment<T>`](./src/Model.ts) <br /> Input list of objects linking annotations to the text using character offsets.
20
- - [`TextSegment<T>`](./src/Model.ts) <br /> Output list of segments with character offsets and the annotations that apply.
21
- - [`groupSegments<T>(segments, predicate): Group<T>[]`](./src/groupSegments.ts) <br /> Group segments into higher-level units (e.g., words, sentences, entities) by collecting all segments that share a matching annotation.
22
- - [`Group<T>`](./src/groupSegments.ts) <br /> Output group of segments matching the same predicate result.
18
+ - [`segment<T>(text, annotations, getOffsets): TextSegment<T>[]`](./src/segment.ts) <br /> Split a text into TextSegments with char offsets to the text and a list of applying annotations.
19
+ - [`TextSegment<T>`](./src/Model.ts) <br /> Start and end offsets of text segment (excluding last character), plus the annotations that apply.
20
+ - [`groupSegments<T>(segments, isGroup, getId): SegmentGroup<T>[]`](src/groupSegments.ts) <br /> Recursively group segments into higher-level units (e.g., words, paragraphs, divs) by collecting all segments that share a matching annotation.
21
+ - [`SegmentGroup<T>`](src/groupSegments.ts) <br /> A `Group<T>` (with annotation and recursive children) or `Ungrouped<T>` (with plain segments).
22
+ - [`findSegmentOffsets<T>(segments): Map<T, SegmentOffsets>`](src/findSegmentOffsets.ts) <br /> For each annotation, collect the first and last segment index it appears in, keyed by object reference.
23
+ - [`SegmentOffsets`](src/findSegmentOffsets.ts) <br /> Start and end segment index of an annotation (excluding end segment).
23
24
 
24
25
  ## Example
25
26
 
26
- Given the text `"abc"` with two overlapping annotations:
27
+ ### Create text segments
28
+
29
+ A text 'abc' with two overlapping annotations at 'ab' and 'bc' will be split up in three segments:
27
30
 
28
31
  ```txt
29
32
  text: abc
@@ -32,24 +35,67 @@ annotation bc: __
32
35
  ```
33
36
 
34
37
  ```ts
35
- import { segment } from "text-annotation-segmenter";
38
+ import { segment } from "@knaw-huc/text-annotation-segmenter";
36
39
 
37
40
  const text = 'abc';
38
- const ab = {id: 'ab'};
39
- const bc = {id: 'bc'};
41
+ const ab = {id: 'ab', begin: 0, end: 2};
42
+ const bc = {id: 'bc', begin: 1, end: 3};
40
43
 
41
- const segments = segment(text, [
42
- {begin: 0, end: 2, body: ab},
43
- {begin: 1, end: 3, body: bc},
44
- ]);
44
+ const segments = segment(text, [ab, bc], (a) => a);
45
45
 
46
46
  expect(segments).toEqual([
47
- {id: '0', begin: 0, end: 1, annotations: [ab]},
48
- {id: '1', begin: 1, end: 2, annotations: [ab, bc]},
49
- {id: '2', begin: 2, end: 3, annotations: [bc]},
47
+ {index: 0, begin: 0, end: 1, body: 'a', annotations: [ab]},
48
+ {index: 1, begin: 1, end: 2, body: 'ab', annotations: [ab, bc]},
49
+ {index: 2, begin: 2, end: 3, body: 'c', annotations: [bc]},
50
+ ]);
51
+ ```
52
+
53
+ ### Group segments
54
+
55
+ We can use segments to build up a hierachy of elements:
56
+
57
+ Given the text 'ab' with a section spanning the whole text and a paragraph spanning the first half:
58
+
59
+ ```txt
60
+ text: aabb
61
+ section: ____
62
+ paragraph: __
63
+ ```
64
+
65
+ ```ts
66
+ import {segment, groupSegments} from "@knaw-huc/text-annotation-segmenter";
67
+
68
+ const text = 'aabb';
69
+ const section = {id: 'section', type: 'section', begin: 0, end: 4};
70
+ const paragraph = {id: 'paragraph', type: 'paragraph', begin: 0, end: 2};
71
+
72
+ const segments = segment(text, [section, paragraph], (a) => a);
73
+
74
+ const isGroup = a => a.type === 'section' || a.type === 'paragraph';
75
+ const getId = a => a.id;
76
+
77
+ const groups = groupSegments(
78
+ segments,
79
+ isGroup,
80
+ getId,
81
+ );
82
+
83
+ expect(groups).toEqual([
84
+ {
85
+ isGroup: true, annotation: section, children: [
86
+ {
87
+ isGroup: true, annotation: paragraph, children: [
88
+ {isGroup: false, segments: [segments[0]]}
89
+ ]
90
+ },
91
+ {isGroup: false, segments: [segments[1]]},
92
+ ]
93
+ }
50
94
  ]);
51
95
  ```
52
96
 
97
+ ---
98
+
53
99
  More examples:
54
100
 
55
101
  - For edge cases, see: [segment.spec.ts](./src/segment.spec.ts).
@@ -0,0 +1 @@
1
+ export type GetId<T> = (annotation: T) => string;
@@ -0,0 +1,2 @@
1
+ import { Offsets } from './Model.ts';
2
+ export type GetOffsets<T> = (annotation: T) => Offsets;
package/dist/Model.d.ts CHANGED
@@ -1,18 +1,16 @@
1
1
  /**
2
- * Input: object linking annotation to the text using character offsets.
2
+ * Start and end character, end excluding last character
3
3
  */
4
- export type AnnotationOffsets<T = unknown> = {
4
+ export type Offsets = {
5
5
  begin: number;
6
6
  end: number;
7
- body: T;
8
7
  };
9
8
  /**
10
- * Output: segment of text and the annotations that apply.
9
+ * Output: start and end offsets of text segment (excluding last character), plus the annotations that apply.
11
10
  */
12
- export type TextSegment<T = unknown> = {
13
- id: SegmentId;
14
- begin: number;
15
- end: number;
11
+ export type TextSegment<T> = Offsets & {
12
+ index: SegmentIndex;
13
+ body: string;
16
14
  annotations: T[];
17
15
  };
18
- export type SegmentId = string;
16
+ export type SegmentIndex = number;
@@ -0,0 +1,13 @@
1
+ import { TextSegment } from './Model';
2
+ export type SegmentOffsets = {
3
+ beginSegment: number;
4
+ /**
5
+ * Excluding last segment
6
+ */
7
+ endSegment: number;
8
+ };
9
+ /**
10
+ * For each annotation, collect the first and last segment index
11
+ * it appears in, keyed by object reference.
12
+ */
13
+ export declare function findSegmentOffsets<T>(segments: TextSegment<T>[]): Map<T, SegmentOffsets>;
@@ -1,10 +1,23 @@
1
- import { TextSegment } from './Model.ts';
1
+ import { TextSegment } from './Model';
2
+ import { GetId } from './GetId.ts';
3
+ export type SegmentGroup<T> = Group<T> | Ungrouped<T>;
2
4
  export type Group<T> = {
5
+ isGroup: true;
3
6
  annotation: T;
7
+ children: SegmentGroup<T>[];
8
+ };
9
+ export type Ungrouped<T> = {
10
+ isGroup: false;
4
11
  segments: TextSegment<T>[];
5
12
  };
6
13
  /**
7
- * Group segments into higher-level units (e.g. words, sentences, entities)
8
- * by grouping all segments that share a matching annotation.
14
+ * Recursively group a list of segments into higher-level units (e.g. words,
15
+ * paragraphs or divs) by segments that share a matching annotation.
16
+ *
17
+ * Example: text "aabb" with section (0–4) and paragraph (0–2) produces:
18
+ * [group(section): [group(paragraph("aa")), ungrouped("bb")]]
19
+ *
20
+ * Note: annotations are assumed to be ordered by nesting depth
21
+ * in each segment's annotations array, outer-first.
9
22
  */
10
- export declare function groupSegments<T>(segments: TextSegment<T>[], predicate: (annotation: T) => boolean): Group<T>[];
23
+ export declare function groupSegments<T>(segments: TextSegment<T>[], isGroup: (annotation: T) => boolean, getId: GetId<T>): SegmentGroup<T>[];
package/dist/index.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  export { segment } from './segment.ts';
2
2
  export type { AnnotationSegmentsByChar } from './segment.ts';
3
+ export { findSegmentOffsets } from './findSegmentOffsets.ts';
4
+ export type { SegmentOffsets } from './findSegmentOffsets.ts';
3
5
  export { groupSegments } from './groupSegments.ts';
4
- export type { Group } from './groupSegments.ts';
5
- export type { AnnotationOffsets, TextSegment, SegmentId, } from './Model.ts';
6
+ export type { Group, SegmentGroup } from './groupSegments.ts';
7
+ export type { Offsets, TextSegment, SegmentIndex, } from './Model.ts';
8
+ export type { GetOffsets } from './GetOffsets.ts';
package/dist/index.js CHANGED
@@ -1,21 +1,17 @@
1
- function segment(text, annotations) {
1
+ function segment(text, annotations, getOffsets) {
2
2
  const segments = [];
3
- let segmentCounter = 0;
3
+ let segmentCounter = -1;
4
4
  const offsetMap = /* @__PURE__ */ new Map(), getOrCreateOffset = (charIndex) => {
5
5
  let offset = offsetMap.get(charIndex);
6
6
  return offset || (offset = { charIndex, starting: [], ending: [] }, offsetMap.set(charIndex, offset)), offset;
7
7
  };
8
8
  getOrCreateOffset(0), getOrCreateOffset(text.length);
9
9
  for (const annotation of annotations) {
10
- if (annotation.begin >= text.length || annotation.end <= 0)
10
+ const offsets = getOffsets(annotation), isMarker = offsets.begin === offsets.end;
11
+ if (isMarker && (offsets.end < 0 || offsets.begin > text.length) || !isMarker && (offsets.end <= 0 || offsets.begin >= text.length))
11
12
  continue;
12
- const needsClamping = annotation.begin < 0 || annotation.end > text.length;
13
- let clamped = annotation;
14
- needsClamping && (clamped = {
15
- ...annotation,
16
- begin: Math.max(0, annotation.begin),
17
- end: Math.min(text.length, annotation.end)
18
- }), getOrCreateOffset(clamped.begin).starting.push(clamped), getOrCreateOffset(clamped.end).ending.push(clamped);
13
+ const begin = Math.max(0, offsets.begin), end = Math.min(text.length, offsets.end);
14
+ getOrCreateOffset(begin).starting.push(annotation), getOrCreateOffset(end).ending.push(annotation);
19
15
  }
20
16
  const sortedOffsets = [...offsetMap.values()].sort(
21
17
  (a, b) => a.charIndex - b.charIndex
@@ -23,11 +19,12 @@ function segment(text, annotations) {
23
19
  let lastOffset = 0;
24
20
  for (const offset of sortedOffsets) {
25
21
  if (offset.charIndex > lastOffset) {
26
- const id = `${segmentCounter++}`;
22
+ const index = ++segmentCounter;
27
23
  segments.push({
28
- id,
24
+ index,
29
25
  begin: lastOffset,
30
26
  end: offset.charIndex,
27
+ body: text.slice(lastOffset, offset.charIndex),
31
28
  annotations: [...activeAnnotations]
32
29
  });
33
30
  }
@@ -35,37 +32,73 @@ function segment(text, annotations) {
35
32
  let hasMarkers = !1;
36
33
  const markerSegmentAnnotations = [];
37
34
  for (const a of offset.starting)
38
- offset.ending.includes(a) ? (hasMarkers = !0, markerSegmentAnnotations.push(a.body)) : activeAnnotations.add(a.body);
39
- for (const a of offset.ending)
40
- activeAnnotations.delete(a.body);
35
+ offset.ending.includes(a) ? (hasMarkers = !0, markerSegmentAnnotations.push(a)) : activeAnnotations.add(a);
36
+ for (const annotation of offset.ending)
37
+ activeAnnotations.delete(annotation);
41
38
  if (hasMarkers) {
42
39
  markerSegmentAnnotations.push(...activeAnnotations);
43
- const segment2 = `${segmentCounter++}`;
40
+ const index = ++segmentCounter;
44
41
  segments.push({
45
- id: segment2,
42
+ index,
46
43
  begin: offset.charIndex,
47
44
  end: offset.charIndex,
45
+ body: "",
48
46
  annotations: markerSegmentAnnotations
49
47
  });
50
48
  }
51
49
  }
52
50
  return segments;
53
51
  }
54
- function groupSegments(segments, predicate) {
55
- const groups = /* @__PURE__ */ new Map();
56
- for (const segment2 of segments) {
57
- const match = segment2.annotations.find(predicate);
58
- if (match) {
59
- let list = groups.get(match);
60
- list || (list = [], groups.set(match, list)), list.push(segment2);
52
+ function findSegmentOffsets(segments) {
53
+ const offsets = /* @__PURE__ */ new Map();
54
+ for (let i = 0; i < segments.length; i++)
55
+ for (const annotation of segments[i].annotations) {
56
+ const existing = offsets.get(annotation);
57
+ existing ? existing.endSegment = i + 1 : offsets.set(annotation, { beginSegment: i, endSegment: i + 1 });
61
58
  }
59
+ return offsets;
60
+ }
61
+ function groupSegments(segments, isGroup, getId) {
62
+ return group(segments, isGroup, getId, 0);
63
+ }
64
+ function group(segments, isGroup, getId, depth) {
65
+ return groupByAnnotation(segments, isGroup, getId, depth).map(
66
+ (group2) => group2.annotation ? createGroup(group2.annotation, group2.segments, isGroup, getId, depth) : createUngrouped(group2.segments)
67
+ );
68
+ }
69
+ function groupByAnnotation(segments, isGroup, getId, depth) {
70
+ const groups = [];
71
+ let currentId, currentGroup;
72
+ for (const segment2 of segments) {
73
+ const annotation = getGroupAnnotation(segment2, isGroup, depth), id = annotation ? getId(annotation) : void 0;
74
+ !currentGroup || id !== currentId ? (currentGroup = annotation ? { annotation, segments: [segment2] } : { segments: [segment2] }, groups.push(currentGroup), currentId = id) : currentGroup.segments.push(segment2);
62
75
  }
63
- return [...groups.entries()].map(([annotation, segments2]) => ({
76
+ return groups;
77
+ }
78
+ function getGroupAnnotation(segment2, isGroup, depth) {
79
+ let groupIndex = 0;
80
+ for (const annotation of segment2.annotations)
81
+ if (isGroup(annotation)) {
82
+ if (groupIndex === depth)
83
+ return annotation;
84
+ groupIndex++;
85
+ }
86
+ }
87
+ function createGroup(annotation, segments, isGroup, getId, depth) {
88
+ return {
89
+ isGroup: !0,
64
90
  annotation,
65
- segments: segments2
66
- }));
91
+ children: group(segments, isGroup, getId, depth + 1)
92
+ };
93
+ }
94
+ function createUngrouped(segments) {
95
+ return {
96
+ isGroup: !1,
97
+ segments
98
+ };
67
99
  }
68
100
  export {
101
+ findSegmentOffsets,
69
102
  groupSegments,
70
103
  segment
71
104
  };
package/dist/segment.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- import { AnnotationOffsets, TextSegment } from './Model';
1
+ import { TextSegment } from './Model';
2
+ import { GetOffsets } from './GetOffsets.ts';
2
3
  /**
3
4
  * Split a text into {@link TextSegment}s with character offsets and a list of applying annotations.
4
5
  */
5
- export declare function segment<T>(text: string, annotations: AnnotationOffsets<T>[]): TextSegment<T>[];
6
- export type AnnotationSegmentsByChar<T = unknown> = {
6
+ export declare function segment<T>(text: string, annotations: T[], getOffsets: GetOffsets<T>): TextSegment<T>[];
7
+ export type AnnotationSegmentsByChar<T> = {
7
8
  charIndex: number;
8
- starting: AnnotationOffsets<T>[];
9
- ending: AnnotationOffsets<T>[];
9
+ starting: T[];
10
+ ending: T[];
10
11
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@knaw-huc/text-annotation-segmenter",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/knaw-huc/text-annotation-segmenter.git"
@@ -19,7 +19,7 @@
19
19
  ],
20
20
  "scripts": {
21
21
  "dev:build": "vite build --watch",
22
- "build": "vite build",
22
+ "build": "npm run test && vite build",
23
23
  "test": "vitest run",
24
24
  "bench": "vitest bench",
25
25
  "prepublishOnly": "npm run build"
package/README.html DELETED
@@ -1,41 +0,0 @@
1
- <h1 id="knaw-huctext-annotation-segmenter"><span class="citation" data-cites="knaw-huc/text-annotation-segmenter">@knaw-huc/text-annotation-segmenter</span></h1>
2
- <p>Utility functions to help render overlapping annotations in a text.</p>
3
- <p>Annotations on a text have a non-hierarchical nature, i.e., they can overlap:</p>
4
- <pre class="text"><code>Aa&lt;bc&gt;bb&lt;cd&gt;cc&lt;/bc&gt;dd&lt;cd&gt;ee.</code></pre>
5
- <p>However, HTML is hierarchical. How to display these kinds of annotations that do not live inside or next to each other, but cut across each other?</p>
6
- <p>The <code>segment</code> function creates an array of segments: a flat, non-overlapping list where each segment links to both the text and all the annotations that apply. Each segment translates into a single DOM element. Elements linked to multiple overlapping annotations can now be decorated with their own styling, classes and callbacks.</p>
7
- <p>A special case is the marker: an annotation of zero width marking a position in the text. Markers result in zero-width segments, also linking all annotations that start at, end at, or span across that position.</p>
8
- <h2 id="api">API</h2>
9
- <ul>
10
- <li><a href="./src/segment.ts"><code>segment&lt;T&gt;(text, annotations): TextSegment&lt;T&gt;[]</code></a> <br /> Split a text into TextSegments with char offsets to the text and a list of applying annotations.</li>
11
- <li><a href="./src/Model.ts"><code>AnnotationSegment&lt;T&gt;</code></a> <br /> Input list of objects linking annotations to the text using character offsets.</li>
12
- <li><a href="./src/Model.ts"><code>TextSegment&lt;T&gt;</code></a> <br /> Output list of segments with character offsets and the annotations that apply.</li>
13
- <li><a href="./src/groupSegments.ts"><code>groupSegments&lt;T&gt;(segments, predicate): Group&lt;T&gt;[]</code></a> <br /> Group segments into higher-level units (e.g., words, sentences, entities) by collecting all segments that share a matching annotation.</li>
14
- <li><a href="./src/groupSegments.ts"><code>Group&lt;T&gt;</code></a> <br /> Output group of segments matching the same predicate result.</li>
15
- </ul>
16
- <h2 id="example">Example</h2>
17
- <p>Given the text <code>"abc"</code> with two overlapping annotations:</p>
18
- <div class="sourceCode" id="cb2"><pre class="sourceCode txt"><code class="sourceCode default"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true"></a> text: abc</span>
19
- <span id="cb2-2"><a href="#cb2-2" aria-hidden="true"></a>annotation ab: __</span>
20
- <span id="cb2-3"><a href="#cb2-3" aria-hidden="true"></a>annotation bc: __</span></code></pre></div>
21
- <div class="sourceCode" id="cb3"><pre class="sourceCode ts"><code class="sourceCode typescript"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true"></a><span class="im">import</span> { segment } from <span class="st">&quot;text-annotation-segmenter&quot;</span><span class="op">;</span></span>
22
- <span id="cb3-2"><a href="#cb3-2" aria-hidden="true"></a></span>
23
- <span id="cb3-3"><a href="#cb3-3" aria-hidden="true"></a>const text <span class="op">=</span> <span class="st">&#39;abc&#39;</span><span class="op">;</span></span>
24
- <span id="cb3-4"><a href="#cb3-4" aria-hidden="true"></a>const ab <span class="op">=</span> {id<span class="op">:</span> <span class="st">&#39;ab&#39;</span>}<span class="op">;</span></span>
25
- <span id="cb3-5"><a href="#cb3-5" aria-hidden="true"></a>const bc <span class="op">=</span> {id<span class="op">:</span> <span class="st">&#39;bc&#39;</span>}<span class="op">;</span></span>
26
- <span id="cb3-6"><a href="#cb3-6" aria-hidden="true"></a></span>
27
- <span id="cb3-7"><a href="#cb3-7" aria-hidden="true"></a>const segments <span class="op">=</span> <span class="fu">segment</span>(text<span class="op">,</span> [</span>
28
- <span id="cb3-8"><a href="#cb3-8" aria-hidden="true"></a> {begin<span class="op">:</span> <span class="dv">0</span><span class="op">,</span> end<span class="op">:</span> <span class="dv">2</span><span class="op">,</span> body<span class="op">:</span> ab}<span class="op">,</span></span>
29
- <span id="cb3-9"><a href="#cb3-9" aria-hidden="true"></a> {begin<span class="op">:</span> <span class="dv">1</span><span class="op">,</span> end<span class="op">:</span> <span class="dv">3</span><span class="op">,</span> body<span class="op">:</span> bc}<span class="op">,</span></span>
30
- <span id="cb3-10"><a href="#cb3-10" aria-hidden="true"></a>])<span class="op">;</span></span>
31
- <span id="cb3-11"><a href="#cb3-11" aria-hidden="true"></a></span>
32
- <span id="cb3-12"><a href="#cb3-12" aria-hidden="true"></a><span class="fu">expect</span>(segments)<span class="op">.</span><span class="fu">toEqual</span>([</span>
33
- <span id="cb3-13"><a href="#cb3-13" aria-hidden="true"></a> {id<span class="op">:</span> <span class="st">&#39;0&#39;</span><span class="op">,</span> begin<span class="op">:</span> <span class="dv">0</span><span class="op">,</span> end<span class="op">:</span> <span class="dv">1</span><span class="op">,</span> annotations<span class="op">:</span> [ab]}<span class="op">,</span></span>
34
- <span id="cb3-14"><a href="#cb3-14" aria-hidden="true"></a> {id<span class="op">:</span> <span class="st">&#39;1&#39;</span><span class="op">,</span> begin<span class="op">:</span> <span class="dv">1</span><span class="op">,</span> end<span class="op">:</span> <span class="dv">2</span><span class="op">,</span> annotations<span class="op">:</span> [ab<span class="op">,</span> bc]}<span class="op">,</span></span>
35
- <span id="cb3-15"><a href="#cb3-15" aria-hidden="true"></a> {id<span class="op">:</span> <span class="st">&#39;2&#39;</span><span class="op">,</span> begin<span class="op">:</span> <span class="dv">2</span><span class="op">,</span> end<span class="op">:</span> <span class="dv">3</span><span class="op">,</span> annotations<span class="op">:</span> [bc]}<span class="op">,</span></span>
36
- <span id="cb3-16"><a href="#cb3-16" aria-hidden="true"></a>])<span class="op">;</span></span></code></pre></div>
37
- <p>More examples:</p>
38
- <ul>
39
- <li>For edge cases, see: <a href="./src/segment.spec.ts">segment.spec.ts</a>.</li>
40
- <li>For benchmarks, see <a href="./src/segment.bench.ts">segment.bench.ts</a>.</li>
41
- </ul>