span-aligner 0.1.2__py3-none-any.whl → 0.2.0__py3-none-any.whl

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.
@@ -0,0 +1,283 @@
1
+ Metadata-Version: 2.4
2
+ Name: span-aligner
3
+ Version: 0.2.0
4
+ Summary: A utility for aligning and mapping text spans between different text representations.
5
+ License: MIT
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: numpy<3,>=1.26
10
+ Requires-Dist: scipy<2,>=1.13
11
+ Requires-Dist: networkx<4,>=3.3
12
+ Requires-Dist: rapidfuzz<4,>=3.13
13
+ Requires-Dist: regex>=2024.9
14
+ Requires-Dist: transformers<6,>=4.41
15
+ Requires-Dist: torch<3,>=2.5
16
+ Requires-Dist: scikit-learn<2,>=1.7
17
+ Requires-Dist: requests<3,>=2.32
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # Span Projecting & Alignment
23
+
24
+ A utility for aligning and mapping text spans between different text representations, and projecting annotations across languages using semantic alignment.
25
+
26
+ ## Features
27
+
28
+ - **Span Alignment**: Sanitize boundaries, fuzzy match segments, map spans between text versions.
29
+ - **Span Projection**: Project annotations from a source text (e.g., English) to a target text (e.g., Dutch) using embeddings.
30
+
31
+ ## Installation
32
+
33
+ Install dependencies:
34
+
35
+ ```bash
36
+ pip install span-aligner
37
+ ```
38
+
39
+ ## Usage
40
+
41
+ The package `span_aligner` provides two main classes: `SpanAligner` and `SpanProjector`.
42
+
43
+ * **`SpanAligner`**:
44
+ Uses regex and fuzzy search. It is highly efficient but restricted to **monolingual** tasks (same language). It serves as a strong baseline for correcting boundary offsets or mapping annotations between slightly different versions of a text.
45
+
46
+ * **`SpanProjector`**:
47
+ Uses **word embeddings** (Transformers) to align tokens semantically. It supports **cross-lingual** projection and handles significant paraphrasing. However, it is computationally more expensive.
48
+ * *Complexity*: The default `mwmf` (Max Weight Matching) algorithm has a complexity of **O(n³)**, meaning execution time increases exponentially with text length.
49
+ * *Use Case*: Use when languages differ or when textual differences are too great for fuzzy matching.
50
+
51
+ ## Optimization & Best Practices
52
+
53
+ To achieve the best results while managing computational cost, follow these guidelines:
54
+
55
+ ### 1. Choose the Right Tool for the Job
56
+ If the source and target texts are in the same language, **always start with `SpanAligner`**. It is significantly faster and creates precise splits. Only switch to `SpanProjector` if fuzzy matching fails due to low textual overlap.
57
+
58
+ ### 2. Manage Text Length (Chunking)
59
+ The `SpanProjector` (specifically with `mwmf`) struggles with very long sequences.
60
+ * **Split Texts**: Break documents into logical segments (e.g., paragraphs, decisions, list items) before projection.
61
+ * **Project Locally**: Align spans within their corresponding segments rather than projecting a small span against an entire document.
62
+
63
+ ### 3. Select the Appropriate Algorithm
64
+ * **`mwmf`** (Max Weight Matching): The gold standard. Finds the globally optimal alignment but is slow. Use for final, high-quality output on segmented text.
65
+ * **`inter`** (Intersection): Much faster. Works excellently for **short, distinct spans** (e.g., named entities like persons, locations, dates) where context is less critical.
66
+ * **`itermax`**: A balanced heuristic that offers better speed than `mwmf` with comparable quality for many tasks.
67
+
68
+ ### 4. Translation-Assisted Projection (Hybrid Approach)
69
+ If direct cross-lingual projection yields subpar results, consider an intermediate translation step to simplify the alignment task:
70
+
71
+ 1. **Translate Source**: Use an LLM or NMT model to translate the annotated source text (or just the spans) into the target language.
72
+ 2. **Align Locally**: Use `SpanAligner` (or `SpanProjector` with `inter`) to map the *translated* spans onto the *actual* target text.
73
+
74
+ **Tip**: The translation should mimic the vocabulary of the target text as closely as possible.
75
+ * *Workflow*: `annotated_source` + `target_text` → **LLM** → `rough_translated_source` → **SpanAligner** → `final_annotated_target`
76
+
77
+
78
+
79
+ ### Span Aligner
80
+
81
+ Utilities for exact and fuzzy span mapping.
82
+
83
+ #### Get Annotations from Tagged Text
84
+
85
+ Extract structured spans and entities from a string with inline tags.
86
+
87
+ ```python
88
+ from span_aligner import SpanAligner
89
+
90
+ tagged_input = "<administrative_body>Environmental Committee</administrative_body> discussed the <impact_location>central park</impact_location> renovation on <publication_date>2025-12-15</publication_date>."
91
+
92
+ ner_map = {
93
+ "administrative_body": "ADMINISTRATIVE BODY",
94
+ "publication_date": "PUBLICATION DATE",
95
+ "impact_location": "PRIMARY LOCATION"
96
+ }
97
+
98
+ span_map ={
99
+ "motivation" : "MOTIVATION"
100
+ }
101
+
102
+ annotations = SpanAligner.get_annotations_from_tagged_text(
103
+ tagged_input,
104
+ ner_map=ner_map,
105
+ span_map=span_map
106
+ )
107
+
108
+ print(annotations["entities"])
109
+ # Output:
110
+ #[
111
+ # {'start': 0, 'end': 23, 'text': 'Environmental Committee', 'labels': ['ADMINISTRATIVE BODY']},
112
+ # {'start': 38, 'end': 50, 'text': 'central park', 'labels': ['PRIMARY LOCATION']},
113
+ # {'start': 65, 'end': 75, 'text': '2025-12-15', 'labels': ['PUBLICATION DATE']}
114
+ #]
115
+ ```
116
+
117
+ #### Rebuild Tagged Text
118
+
119
+ Reconstruct a string with XML-like tags from raw text and span/entity lists.
120
+
121
+ ```python
122
+ from span_aligner import SpanAligner
123
+
124
+ text = "On 2026-01-12, the Budget Committee finalized the annual report."
125
+ # Entities corresponding to 'ADMINISTRATIVE BODY' label (indices skip "the ")
126
+ entities = [{"start": 19, "end": 35, "labels": ["administrative_body"]}]
127
+
128
+ tagged, stats = SpanAligner.rebuild_tagged_text(text, entities=entities)
129
+ print(tagged)
130
+ # Output: On 2026-01-12, the <administrative_body>Budget Committee</administrative_body> finalized the annual report.
131
+ ```
132
+
133
+ #### Map Tags to Original
134
+
135
+ Align annotated spans from a tagged string back to their positions in the original text, allowing for noisy text or translation differences.
136
+
137
+ ```python
138
+ from span_aligner import SpanAligner
139
+
140
+ original_text = "Budget Committee met on 2026-01-12 to view\n\n the central park prject."
141
+ tagged_text = "<administrative_body>Budget Committee</administrative_body> met on <publication_date>2026-01-12</publication_date> to review the <impact_location>central park</impact_location> project."
142
+
143
+ mapped_tagged_text = SpanAligner.map_tags_to_original(
144
+ original_text=original_text,
145
+ tagged_text=tagged_text,
146
+ min_ratio=0.7
147
+ )
148
+ print(mapped_tagged_text)
149
+ # Output preserves original text errors:
150
+ # "<administrative_body>Budget Committee</administrative_body> met on <publication_date>2026-01-12</publication_date> to view
151
+ # the <impact_location>central park</impact_location> prject."
152
+ ```
153
+
154
+ ### Span Projector
155
+
156
+ Project annotations from one text to another using semantic alignment (e.g., cross-lingual projection).
157
+
158
+ The process begins by generating embeddings for both source and target texts, creating a similarity matrix, and finding the optimal set of alignment pairs. Several algorithms are implemented for this matching phase, including `mwmf`, `inter`, `itermax`, `fwd`, `rev`, `greedy`, and `threshold`.
159
+
160
+
161
+
162
+ #### Project En -> En (Identity/Paraphrase)
163
+
164
+ Project annotations to a similar text in the same language. Functions similar to the `spanAligner` with improved fuzzy matching.
165
+
166
+ ```python
167
+ from span_aligner import SpanProjector
168
+
169
+ # Initialize projector (uses BERT embeddings by default)
170
+ projector = SpanProjector(src_lang="en", tgt_lang="en")
171
+
172
+ src_text = "The <ent>cat</ent> \n\n sat. on the mat."
173
+ tgt_text = "The cat sat on the mat."
174
+
175
+ tagged_tgt, spans = projector.project_tagged_text(src_text, tgt_text)
176
+ print(tagged_tgt)
177
+ # Output: The <ent>cat</ent> sat on the mat.
178
+ ```
179
+
180
+ #### Project En -> Nl (Cross-Lingual)
181
+
182
+ Project annotations from an English source text to a Dutch target translation.
183
+
184
+ ```python
185
+ from span_aligner import SpanProjector
186
+
187
+ # Initialize projector
188
+ projector = SpanProjector(src_lang="en", tgt_lang="nl")
189
+
190
+ src_text = """DECISION LIST <contextual_location>Municipality of Zele</contextual_location>
191
+ <administrative_body>Standing Committee</administrative_body> | <contextual_date>June 28, 2021</contextual_date>
192
+ <title>1. Acceptance of candidacies for the examination procedure coordinator of Welfare</title>
193
+ <decision>Acceptance of candidacies for the examination procedure coordinator of Welfare</decision>
194
+ <title>2. Establishment of valuation rules for the integrated entity Municipality and Public Social Welfare Center (OCMW)</title>
195
+ <decision>Establishment of valuation rules for the integrated entity Municipality and OCMW</decision>"""
196
+
197
+ tgt_text = """BESLUITENLIJST Gemeente Zele Vast bureau | 28 juni 20211.
198
+ 1. Aanvaarden kandidaturen examenprocedure coördinator Welzijn
199
+ Aanvaarden kandidaturen examenprocedure coördinator Welzijn
200
+ 2. Vaststelling waarderingsregels geïntegreerde entiteit Gemeente en OCMW
201
+ Vaststelling waarderingsregels geïntegreerde entiteit Gemeente en OCMW"""
202
+
203
+ tagged_tgt, spans = projector.project_tagged_text(src_text, tgt_text)
204
+ print(tagged_tgt)
205
+ # Output: BESLUITENLIJST <contextual_location>Gemeente Zele</contextual_location>
206
+ # <administrative_body>Vast bureau</administrative_body> <contextual_date>| 28 juni 20211</contextual_date>.
207
+ # <title>1. Aanvaarden kandidaturen examenprocedure coördinator Welzijn
208
+ # Aanvaarden kandidaturen examenprocedure coördinator</title> Welzijn
209
+ # <title>2. Vaststelling waarderingsregels geïntegreerde entiteit Gemeente en OCMW</title>
210
+ # <decision>Vaststelling waarderingsregels geïntegreerde entiteit Gemeente en OCMW</decision>
211
+
212
+ ```
213
+
214
+ ### Sentence Aligner
215
+
216
+ Low-level class for aligning tokens between two texts (sentences or paragraphs) using transformer embeddings. Based on the work of `simalign` but optimized for span mapping (partial alignment instead of full text) and customized for different embedding providers (Ollama, SaaS providers, Transformers, Sentence-Transformers).
217
+
218
+ #### Initialize Aligner
219
+
220
+ ```python
221
+ from span_aligner import SentenceAligner
222
+
223
+ # Use bert embeddings (default) with BPE tokenization
224
+ aligner = SentenceAligner(model="bert", token_type="bpe")
225
+
226
+ text_src = "This is a simple test sentence for alignment."
227
+ text_tgt = "Dit is een eenvoudige testzin voor uitlijning."
228
+ ```
229
+
230
+ #### Get Text Embeddings
231
+
232
+ Retrieve tokens and embedding vectors for a string.
233
+
234
+ ```python
235
+ tokens_src, vecs_src = aligner.get_text_embeddings(text_src)
236
+ print(f"Src tokens: {len(tokens_src)}, Vectors: {vecs_src.shape}")
237
+ # Output: Src tokens: 9, Vectors: (10, 768)
238
+ ```
239
+
240
+ #### Align Partial Substring
241
+
242
+ Find the alignment of a specific substring from source to target.
243
+
244
+ ```python
245
+ # Align "simple test"
246
+ res_sub = aligner.align_texts_partial_substring(text_src, text_tgt, "simple test")
247
+ print(f"Src tokens in result: {[t.text for t in res_sub.src_tokens]}")
248
+ # Output: Src tokens in result: ['simple', 'test']
249
+ ```
250
+
251
+ ## Configuration & Advanced Usage
252
+
253
+ ### Embedding Models
254
+
255
+ The `model` parameter supports common transformer models:
256
+
257
+ - `"bert"`: `bert-base-multilingual-cased` (Default, robust multilingual performance)
258
+ - `"xlmr"`: `xlm-roberta-base` (Strong cross-lingual transfer)
259
+ - `"xlmr-large"`: `xlm-roberta-large` (Higher accuracy, more resource intensive)
260
+
261
+ ```python
262
+ # Use xlm-roberta-base
263
+ projector = SpanProjector(model="xlmr")
264
+ ```
265
+
266
+ ### Matching Algorithms
267
+
268
+ The `matching_method` parameter controls how the token similarity matrix is converted into an alignment.
269
+
270
+ - `"mwmf"` (**Max Weight Matching**): Finds the global optimal independent edge set. Best quality, O(n³) complexity.
271
+ - `"inter"` (**Intersection**): Intersection of forward and backward attention. High precision, lower recall, very fast.
272
+ - `"itermax"` (**Iterative Max**): Heuristic iterative maximization. Good speed/quality balance.
273
+ - `"greedy"` (**Greedy**): Selects best matches greedily. Fast but local optimum.
274
+
275
+ ```python
276
+ # Trade accuracy for speed with 'inter'
277
+ projector = SpanProjector(matching_method="inter")
278
+ ```
279
+
280
+ ### Tokenization: BPE vs Word
281
+
282
+ - `token_type="bpe"` (Recommended): Uses the transformer's subword tokenizer (e.g. WordPiece). Handles rare words better and aligns closer to the model's internal representation.
283
+ - `token_type="word"`: Splits by whitespace/punctuation. Simpler, but can result in `[UNK]` tokens for transformers.
@@ -0,0 +1,10 @@
1
+ span_aligner/__init__.py,sha256=yNtN5dOoDBg_rRJtdN8L8G0zpvrCtT8xNZ7cNwqWZeg,129
2
+ span_aligner/aligner.py,sha256=e50HqfhSSlkFywnDxjMBnmiKZdX1r1ho-T-58f7jJQc,47881
3
+ span_aligner/sentence_aligner.py,sha256=d2I5X2NxtJz5O87TEUkmR9pq1jfg47x5KmVzJc1-mH8,29555
4
+ span_aligner/span_aligner.py,sha256=EAmPBQzP7esCIb25Z6diiwVBhuhbMRLl6w5JZWL2hiI,49622
5
+ span_aligner/span_projector.py,sha256=gb2vHQy3bcot5f7_DRUzqFJvtS21YhijfFVn-7wyfFw,26448
6
+ span_aligner-0.2.0.dist-info/licenses/LICENSE,sha256=TqCZNrAXPrgWq9k95te7bOOyXztjxjxWQWnsHSqT8SM,1096
7
+ span_aligner-0.2.0.dist-info/METADATA,sha256=vdri1q_7CtqA-i90-Vmg7la0CDqlduTBY6JDWf-LVq8,12372
8
+ span_aligner-0.2.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
9
+ span_aligner-0.2.0.dist-info/top_level.txt,sha256=syADug30Z0JSDJXnan6CIBWuI4mCdpghyDa48kj69VY,13
10
+ span_aligner-0.2.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.9.0)
2
+ Generator: setuptools (80.10.2)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,169 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: span-aligner
3
- Version: 0.1.2
4
- Summary: A utility for aligning and mapping text spans between different text representations.
5
- License: MIT
6
- Requires-Python: >=3.8
7
- Description-Content-Type: text/markdown
8
- License-File: LICENSE
9
- Requires-Dist: rapidfuzz>=3.0.0
10
- Provides-Extra: dev
11
- Requires-Dist: pytest>=7.0.0; extra == "dev"
12
- Dynamic: license-file
13
-
14
- # Span Aligner
15
-
16
- A utility for aligning and mapping text spans between different text representations, particularly useful for Label Studio annotation compatibility.
17
-
18
- ## Features
19
-
20
- - Sanitize span boundaries to avoid special characters.
21
- - Find exact and fuzzy matches of text segments in original documents.
22
- - Map spans from one text representation to another.
23
- - Rebuild tagged text with nested annotations.
24
- - Merge result objects containing span annotations.
25
-
26
- ## Installation
27
-
28
- Install from source:
29
-
30
- ```bash
31
- pip install span-aligner
32
- ```
33
-
34
-
35
- ## Usage
36
-
37
-
38
- ### Get Annotations from Tagged Text
39
-
40
- Extract structured spans and entities from a string with inline tags.
41
-
42
- ```python
43
- tagged_input = "<administrative_body>Environmental Committee</administrative_body> discussed the <impact_location>central park</impact_location> renovation on <publication_date>2025-12-15</publication_date>."
44
-
45
- ner_map = {
46
- "administrative_body": "ADMINISTRATIVE BODY",
47
- "publication_date": "PUBLICATION DATE",
48
- "impact_location": "PRIMARY LOCATION"
49
- }
50
-
51
- span_map ={
52
- "motivation" : "MOTIVATION"
53
- }
54
-
55
- annotations = SpanAligner.get_annotations_from_tagged_text(
56
- tagged_input,
57
- ner_map=ner_map,
58
- span_map=span_map
59
- )
60
-
61
- print(annotations["entities"])
62
- # Output:
63
- #[
64
- # {'start': 0, 'end': 23, 'text': 'Environmental Committee', 'labels': ['ADMINISTRATIVE BODY']},
65
- # {'start': 38, 'end': 50, 'text': 'central park', 'labels': ['PRIMARY LOCATION']},
66
- # {'start': 65, 'end': 75, 'text': '2025-12-15', 'labels': ['PUBLICATION DATE']}
67
- #]
68
-
69
- print(annotations["spans"])
70
- # Output:
71
- #[
72
- # {'start': 0, 'end': 76, 'text': 'Environmental Committee discussed the central park renovation on 2025-12-15.', 'labels': ['MOTIVATION']}
73
- #]
74
-
75
-
76
- print(annotations["plain_text"])
77
- # Output: "Environmental Committee discussed the central park renovation on 2025-12-15."
78
- ```
79
-
80
- ### Rebuild Tagged Text
81
-
82
- Reconstruct a string with XML-like tags from raw text and span/entity lists.
83
-
84
- ```python
85
- text = "On 2026-01-12, the Budget Committee finalized the annual report."
86
- # Spans corresponding to 'MOTIVATION' label, mapped to 'motivation' tag
87
- spans = [{"start": 0, "end": 64, "labels": ["motivation"]}]
88
- # Entities corresponding to 'ADMINISTRATIVE BODY' label, mapped to 'administrative_body' tag
89
- entities = [{"start": 15, "end": 35, "labels": ["administrative_body"]}]
90
-
91
- tagged, stats = SpanAligner.rebuild_tagged_text(text, spans, entities)
92
- print(tagged)
93
- # Output: <motivation>On 2026-01-12, the <administrative_body>Budget Committee</administrative_body> finalized the annual report.</motivation>
94
- ```
95
-
96
- ### Rebuild Tagged Text from Task
97
-
98
- Generate tagged text directly from a Label Studio task object.
99
-
100
- ```python
101
- # Assuming 'task' is a Label Studio task object (or similar structure)
102
- # with .data['text'] and .annotations attributes
103
- mapping = {
104
- "DECISION": "decision",
105
- "LEGAL FRAMEWORK": "legal_framework",
106
- "EXPIRATION DATE": "expiry_date"
107
- }
108
-
109
- tagged_output = SpanAligner.rebuild_tagged_text_from_task(task, mapping)
110
- print(tagged_output)
111
- ```
112
-
113
- ### Map Tags to Original
114
-
115
- Align annotated spans from a tagged string back to their positions in the original text, keeping the mistakes and text as written in the original.
116
-
117
- ```python
118
- original_text = "Budget Budget Committee met on 2026-01-12 to view\n\n the central park prject."
119
- # Imagine the text was slightly modified or translated, but tags are present
120
- tagged_text = "<administrative_body>Budget Committee</administrative_body> met on <publication_date>2026-01-12</publication_date> to review the <impact_location>central park</impact_location> project."
121
-
122
- mapped_tagged_text = SpanAligner.map_tags_to_original(
123
- original_text=original_text,
124
- tagged_text=tagged_text,
125
- min_ratio=0.7
126
- )
127
- print(mapped_tagged_text)
128
- # Output might look like: "Budget <administrative_body>Budget Committee</administrative_body> met on <publication_date>2026-01-12</publication_date> to view\n\n the <impact_location>central park</impact_location> prject."
129
- ```
130
-
131
-
132
-
133
- ### Map Tags to Original and Get Positions
134
-
135
- Combine mapping tags to original text and extracting entities with correct labels.
136
-
137
- ```python
138
- original_text = "Legal basis: Art. 5. The Env. Committee met on 2026-01-12."
139
- tagged_text = "Legal basis: <article>Art. 5</article>. The <administrative_body>Environmental Committee</administrative_body> met on <session_date>2026-01-12</session_date>."
140
-
141
- # 1. Map tags to the noisy original text
142
- mapped_tagged_text = SpanAligner.map_tags_to_original(
143
- original_text=original_text,
144
- tagged_text=tagged_text,
145
- min_ratio=0.7
146
- )
147
-
148
- # 2. Extract annotations using the mapping
149
- ner_label_mapping = {
150
- "administrative_body": "ADMINISTRATIVE BODY",
151
- "session_date": "SESSION DATE",
152
- "article": "ARTICLE"
153
- }
154
-
155
- annotations = SpanAligner.get_annotations_from_tagged_text(
156
- mapped_tagged_text,
157
- ner_map=ner_label_mapping
158
- )
159
-
160
- print(annotations["entities"])
161
- # Output:
162
- # [
163
- # {'start': 13, 'end': 19, 'text': 'Art. 5', 'labels': ['ARTICLE']},
164
- # {'start': 47, 'end': 57, 'text': '2026-01-12', 'labels': ['SESSION DATE']}
165
- # ]
166
- ```
167
-
168
-
169
-
@@ -1,7 +0,0 @@
1
- span_aligner/__init__.py,sha256=ERLPBS6aad_17IPcoMDkVqi7lrSJxuHgqrdh69EN9xI,63
2
- span_aligner/aligner.py,sha256=e50HqfhSSlkFywnDxjMBnmiKZdX1r1ho-T-58f7jJQc,47881
3
- span_aligner-0.1.2.dist-info/licenses/LICENSE,sha256=TqCZNrAXPrgWq9k95te7bOOyXztjxjxWQWnsHSqT8SM,1096
4
- span_aligner-0.1.2.dist-info/METADATA,sha256=Di18JARjRmxjiDXHrOpHrLFioe9QejtnrFVOfrU30cU,5564
5
- span_aligner-0.1.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
6
- span_aligner-0.1.2.dist-info/top_level.txt,sha256=syADug30Z0JSDJXnan6CIBWuI4mCdpghyDa48kj69VY,13
7
- span_aligner-0.1.2.dist-info/RECORD,,