corp-extractor 0.2.11__py3-none-any.whl → 0.4.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: corp-extractor
3
- Version: 0.2.11
3
+ Version: 0.4.0
4
4
  Summary: Extract structured statements from text using T5-Gemma 2 and Diverse Beam Search
5
5
  Project-URL: Homepage, https://github.com/corp-o-rate/statement-extractor
6
6
  Project-URL: Documentation, https://github.com/corp-o-rate/statement-extractor#readme
@@ -24,19 +24,17 @@ Classifier: Topic :: Scientific/Engineering :: Information Analysis
24
24
  Classifier: Topic :: Text Processing :: Linguistic
25
25
  Requires-Python: >=3.10
26
26
  Requires-Dist: click>=8.0.0
27
+ Requires-Dist: gliner2
27
28
  Requires-Dist: numpy>=1.24.0
28
29
  Requires-Dist: pydantic>=2.0.0
30
+ Requires-Dist: sentence-transformers>=2.2.0
29
31
  Requires-Dist: torch>=2.0.0
30
32
  Requires-Dist: transformers>=5.0.0rc3
31
- Provides-Extra: all
32
- Requires-Dist: sentence-transformers>=2.2.0; extra == 'all'
33
33
  Provides-Extra: dev
34
34
  Requires-Dist: mypy>=1.0.0; extra == 'dev'
35
35
  Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
36
36
  Requires-Dist: pytest>=7.0.0; extra == 'dev'
37
37
  Requires-Dist: ruff>=0.1.0; extra == 'dev'
38
- Provides-Extra: embeddings
39
- Requires-Dist: sentence-transformers>=2.2.0; extra == 'embeddings'
40
38
  Description-Content-Type: text/markdown
41
39
 
42
40
  # Corp Extractor
@@ -51,40 +49,40 @@ Extract structured subject-predicate-object statements from unstructured text us
51
49
 
52
50
  - **Structured Extraction**: Converts unstructured text into subject-predicate-object triples
53
51
  - **Entity Type Recognition**: Identifies 12 entity types (ORG, PERSON, GPE, LOC, PRODUCT, EVENT, etc.)
54
- - **Quality Scoring** *(v0.2.0)*: Each triple scored for groundedness (0-1) based on source text
55
- - **Beam Merging** *(v0.2.0)*: Combines top beams for better coverage instead of picking one
56
- - **Embedding-based Dedup** *(v0.2.0)*: Uses semantic similarity to detect near-duplicate predicates
57
- - **Predicate Taxonomies** *(v0.2.0)*: Normalize predicates to canonical forms via embeddings
58
- - **Contextualized Matching** *(v0.2.2)*: Compares full "Subject Predicate Object" against source text for better accuracy
59
- - **Entity Type Merging** *(v0.2.3)*: Automatically merges UNKNOWN entity types with specific types during deduplication
60
- - **Reversal Detection** *(v0.2.3)*: Detects and corrects subject-object reversals using embedding comparison
61
- - **Command Line Interface** *(v0.2.4)*: Full-featured CLI for terminal usage
52
+ - **GLiNER2 Integration** *(v0.4.0)*: Uses GLiNER2 (205M params) for entity recognition and relation extraction
53
+ - **Predefined Predicates** *(v0.4.0)*: Optional `--predicates` list for GLiNER2 relation extraction mode
54
+ - **Entity-based Scoring** *(v0.4.0)*: Confidence combines semantic similarity (50%) + entity recognition scores (25% each)
55
+ - **Multi-Candidate Extraction**: Generates 3 candidates per statement (hybrid, GLiNER2-only, predicate-split)
56
+ - **Best Triple Selection**: Keeps only highest-scoring triple per source (use `--all-triples` to keep all)
57
+ - **Extraction Method Tracking**: Each statement includes `extraction_method` field (hybrid, gliner, split, model)
58
+ - **Beam Merging**: Combines top beams for better coverage instead of picking one
59
+ - **Embedding-based Dedup**: Uses semantic similarity to detect near-duplicate predicates
60
+ - **Predicate Taxonomies**: Normalize predicates to canonical forms via embeddings
61
+ - **Contextualized Matching**: Compares full "Subject Predicate Object" against source text for better accuracy
62
+ - **Entity Type Merging**: Automatically merges UNKNOWN entity types with specific types during deduplication
63
+ - **Reversal Detection**: Detects and corrects subject-object reversals using embedding comparison
64
+ - **Command Line Interface**: Full-featured CLI for terminal usage
62
65
  - **Multiple Output Formats**: Get results as Pydantic models, JSON, XML, or dictionaries
63
66
 
64
67
  ## Installation
65
68
 
66
69
  ```bash
67
- # Recommended: include embedding support for smart deduplication
68
- pip install "corp-extractor[embeddings]"
69
-
70
- # Minimal installation (no embedding features)
71
70
  pip install corp-extractor
72
71
  ```
73
72
 
74
- **Note**: This package requires `transformers>=5.0.0` (pre-release) for T5-Gemma2 model support. Install with `--pre` flag if needed:
75
- ```bash
76
- pip install --pre "corp-extractor[embeddings]"
77
- ```
73
+ The GLiNER2 model (205M params) is downloaded automatically on first use.
74
+
75
+ **Note**: This package requires `transformers>=5.0.0` for T5-Gemma2 model support.
78
76
 
79
77
  **For GPU support**, install PyTorch with CUDA first:
80
78
  ```bash
81
79
  pip install torch --index-url https://download.pytorch.org/whl/cu121
82
- pip install "corp-extractor[embeddings]"
80
+ pip install corp-extractor
83
81
  ```
84
82
 
85
83
  **For Apple Silicon (M1/M2/M3)**, MPS acceleration is automatically detected:
86
84
  ```bash
87
- pip install "corp-extractor[embeddings]" # MPS used automatically
85
+ pip install corp-extractor # MPS used automatically
88
86
  ```
89
87
 
90
88
  ## Quick Start
@@ -182,6 +180,9 @@ Options:
182
180
  --no-dedup Disable deduplication
183
181
  --no-embeddings Disable embedding-based dedup (faster)
184
182
  --no-merge Disable beam merging
183
+ --no-gliner Disable GLiNER2 extraction (use raw model output)
184
+ --predicates TEXT Comma-separated predicate types for GLiNER2 relation extraction
185
+ --all-triples Keep all candidate triples (default: best per source)
185
186
  --dedup-threshold FLOAT Deduplication threshold (default: 0.65)
186
187
  --min-confidence FLOAT Min confidence filter (default: 0)
187
188
  --taxonomy PATH Load predicate taxonomy from file
@@ -284,7 +285,111 @@ for stmt in fixed_statements:
284
285
 
285
286
  During deduplication, reversed duplicates (e.g., "A -> P -> B" and "B -> P -> A") are now detected and merged, with the correct orientation determined by source text similarity.
286
287
 
287
- ## Disable Embeddings (Faster, No Extra Dependencies)
288
+ ## New in v0.4.0: GLiNER2 Integration
289
+
290
+ v0.4.0 replaces spaCy with **GLiNER2** (205M params) for entity recognition and relation extraction. GLiNER2 is a unified model that handles NER, text classification, structured data extraction, and relation extraction with CPU-optimized inference.
291
+
292
+ ### Why GLiNER2?
293
+
294
+ The T5-Gemma model excels at:
295
+ - **Triple isolation** - identifying that a relationship exists
296
+ - **Coreference resolution** - resolving pronouns to named entities
297
+
298
+ GLiNER2 now handles:
299
+ - **Entity recognition** - refining subject/object boundaries
300
+ - **Relation extraction** - when predefined predicates are provided
301
+ - **Entity scoring** - scoring how "entity-like" subjects/objects are
302
+
303
+ ### Two Extraction Modes
304
+
305
+ **Mode 1: With Predicate List** (GLiNER2 relation extraction)
306
+ ```python
307
+ from statement_extractor import extract_statements, ExtractionOptions
308
+
309
+ options = ExtractionOptions(predicates=["works_for", "founded", "acquired", "headquartered_in"])
310
+ result = extract_statements("John works for Apple Inc. in Cupertino.", options)
311
+ ```
312
+
313
+ Or via CLI:
314
+ ```bash
315
+ corp-extractor "John works for Apple Inc." --predicates "works_for,founded,acquired"
316
+ ```
317
+
318
+ **Mode 2: Without Predicate List** (entity-refined extraction)
319
+ ```python
320
+ result = extract_statements("Apple announced a new iPhone.")
321
+ # Uses GLiNER2 for entity extraction to refine boundaries
322
+ # Extracts predicate from source text using T5-Gemma's hint
323
+ ```
324
+
325
+ ### Three Candidate Extraction Methods
326
+
327
+ For each statement, three candidates are generated and the best is selected:
328
+
329
+ | Method | Description |
330
+ |--------|-------------|
331
+ | `hybrid` | Model subject/object + GLiNER2/extracted predicate |
332
+ | `gliner` | All components refined by GLiNER2 |
333
+ | `split` | Source text split around the predicate |
334
+
335
+ ```python
336
+ for stmt in result:
337
+ print(f"{stmt.subject.text} --[{stmt.predicate}]--> {stmt.object.text}")
338
+ print(f" Method: {stmt.extraction_method}") # hybrid, gliner, split, or model
339
+ print(f" Confidence: {stmt.confidence_score:.2f}")
340
+ ```
341
+
342
+ ### Combined Quality Scoring
343
+
344
+ Confidence scores combine **semantic similarity** and **entity recognition**:
345
+
346
+ | Component | Weight | Description |
347
+ |-----------|--------|-------------|
348
+ | Semantic similarity | 50% | Cosine similarity between source text and reassembled triple |
349
+ | Subject entity score | 25% | How entity-like the subject is (via GLiNER2) |
350
+ | Object entity score | 25% | How entity-like the object is (via GLiNER2) |
351
+
352
+ **Entity scoring (via GLiNER2):**
353
+ - Recognized entity with high confidence: 1.0
354
+ - Recognized entity with moderate confidence: 0.8
355
+ - Partially recognized: 0.6
356
+ - Not recognized: 0.2
357
+
358
+ ### Extraction Method Tracking
359
+
360
+ Each statement includes an `extraction_method` field:
361
+ - `hybrid` - Model subject/object + GLiNER2 predicate
362
+ - `gliner` - All components refined by GLiNER2
363
+ - `split` - Subject/object from splitting source text around predicate
364
+ - `model` - All components from T5-Gemma model (only when `--no-gliner`)
365
+
366
+ ### Best Triple Selection
367
+
368
+ By default, only the **highest-scoring triple** is kept for each source sentence.
369
+
370
+ To keep all candidate triples:
371
+ ```python
372
+ options = ExtractionOptions(all_triples=True)
373
+ result = extract_statements(text, options)
374
+ ```
375
+
376
+ Or via CLI:
377
+ ```bash
378
+ corp-extractor "Your text" --all-triples --verbose
379
+ ```
380
+
381
+ **Disable GLiNER2 extraction** to use only model output:
382
+ ```python
383
+ options = ExtractionOptions(use_gliner_extraction=False)
384
+ result = extract_statements(text, options)
385
+ ```
386
+
387
+ Or via CLI:
388
+ ```bash
389
+ corp-extractor "Your text" --no-gliner
390
+ ```
391
+
392
+ ## Disable Embeddings
288
393
 
289
394
  ```python
290
395
  options = ExtractionOptions(
@@ -353,21 +458,23 @@ for text in texts:
353
458
  This library uses the T5-Gemma 2 statement extraction model with **Diverse Beam Search** ([Vijayakumar et al., 2016](https://arxiv.org/abs/1610.02424)):
354
459
 
355
460
  1. **Diverse Beam Search**: Generates 4+ candidate outputs using beam groups with diversity penalty
356
- 2. **Quality Scoring** *(v0.2.0)*: Each triple scored for groundedness in source text
357
- 3. **Beam Merging** *(v0.2.0)*: Top beams combined for better coverage
358
- 4. **Embedding Dedup** *(v0.2.0)*: Semantic similarity removes near-duplicate predicates
359
- 5. **Predicate Normalization** *(v0.2.0)*: Optional taxonomy matching via embeddings
360
- 6. **Contextualized Matching** *(v0.2.2)*: Full statement context used for canonicalization and dedup
361
- 7. **Entity Type Merging** *(v0.2.3)*: UNKNOWN types merged with specific types during dedup
362
- 8. **Reversal Detection** *(v0.2.3)*: Subject-object reversals detected and corrected via embedding comparison
461
+ 2. **Quality Scoring**: Each triple scored for groundedness in source text
462
+ 3. **Beam Merging**: Top beams combined for better coverage
463
+ 4. **Embedding Dedup**: Semantic similarity removes near-duplicate predicates
464
+ 5. **Predicate Normalization**: Optional taxonomy matching via embeddings
465
+ 6. **Contextualized Matching**: Full statement context used for canonicalization and dedup
466
+ 7. **Entity Type Merging**: UNKNOWN types merged with specific types during dedup
467
+ 8. **Reversal Detection**: Subject-object reversals detected and corrected via embedding comparison
468
+ 9. **GLiNER2 Extraction** *(v0.4.0)*: Entity recognition and relation extraction for improved accuracy
363
469
 
364
470
  ## Requirements
365
471
 
366
472
  - Python 3.10+
367
473
  - PyTorch 2.0+
368
- - Transformers 4.35+
474
+ - Transformers 5.0+
369
475
  - Pydantic 2.0+
370
- - sentence-transformers 2.2+ *(optional, for embedding features)*
476
+ - sentence-transformers 2.2+
477
+ - GLiNER2 (model downloaded automatically on first use)
371
478
  - ~2GB VRAM (GPU) or ~4GB RAM (CPU)
372
479
 
373
480
  ## Links
@@ -0,0 +1,12 @@
1
+ statement_extractor/__init__.py,sha256=KwZfWnTB9oevTLw0TrNlYFu67qIYO-34JqDtcpjOhZI,3013
2
+ statement_extractor/canonicalization.py,sha256=ZMLs6RLWJa_rOJ8XZ7PoHFU13-zeJkOMDnvK-ZaFa5s,5991
3
+ statement_extractor/cli.py,sha256=FOkkihVfoROc-Biu8ICCzlLJeDScYYNLLJHnv0GCGGM,9507
4
+ statement_extractor/extractor.py,sha256=d0HnCeCPybw-4jDxH_ffZ4LY9Klvqnza_wa90Bd4Q18,40074
5
+ statement_extractor/gliner_extraction.py,sha256=KNs3n5-fnoUwY1wvbPwZL8j-3YVstmioJlcjp2k1FmY,10491
6
+ statement_extractor/models.py,sha256=cyCQc3vlYB3qlg6-uL5Vt4odIiulKtHzz1Cyrf0lEAU,12198
7
+ statement_extractor/predicate_comparer.py,sha256=jcuaBi5BYqD3TKoyj3pR9dxtX5ihfDJvjdhEd2LHCwc,26184
8
+ statement_extractor/scoring.py,sha256=s_8nhavBNzPPFmGf2FyBummH4tgP7YGpXoMhl2Jh3Xw,16650
9
+ corp_extractor-0.4.0.dist-info/METADATA,sha256=8f2CDtZG757kaB6XMfbBVdNSRMyS5-4Lflc_LoZCC_8,17725
10
+ corp_extractor-0.4.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
11
+ corp_extractor-0.4.0.dist-info/entry_points.txt,sha256=i0iKFqPIusvb-QTQ1zNnFgAqatgVah-jIhahbs5TToQ,115
12
+ corp_extractor-0.4.0.dist-info/RECORD,,
@@ -29,12 +29,13 @@ Example:
29
29
  >>> data = extract_statements_as_dict("Some text...")
30
30
  """
31
31
 
32
- __version__ = "0.2.5"
32
+ __version__ = "0.3.0"
33
33
 
34
34
  # Core models
35
35
  from .models import (
36
36
  Entity,
37
37
  EntityType,
38
+ ExtractionMethod,
38
39
  ExtractionOptions,
39
40
  ExtractionResult,
40
41
  Statement,
@@ -73,6 +74,7 @@ __all__ = [
73
74
  # Core models
74
75
  "Entity",
75
76
  "EntityType",
77
+ "ExtractionMethod",
76
78
  "ExtractionOptions",
77
79
  "ExtractionResult",
78
80
  "Statement",
@@ -34,6 +34,7 @@ def _configure_logging(verbose: bool) -> None:
34
34
  "statement_extractor.scoring",
35
35
  "statement_extractor.predicate_comparer",
36
36
  "statement_extractor.canonicalization",
37
+ "statement_extractor.gliner_extraction",
37
38
  ]:
38
39
  logging.getLogger(logger_name).setLevel(level)
39
40
 
@@ -65,6 +66,9 @@ from .models import (
65
66
  @click.option("--no-dedup", is_flag=True, help="Disable deduplication")
66
67
  @click.option("--no-embeddings", is_flag=True, help="Disable embedding-based deduplication (faster)")
67
68
  @click.option("--no-merge", is_flag=True, help="Disable beam merging (select single best beam)")
69
+ @click.option("--no-gliner", is_flag=True, help="Disable GLiNER2 extraction (use raw model output)")
70
+ @click.option("--predicates", type=str, help="Comma-separated list of predicate types for GLiNER2 relation extraction")
71
+ @click.option("--all-triples", is_flag=True, help="Keep all candidate triples instead of selecting best per source")
68
72
  @click.option("--dedup-threshold", type=float, default=0.65, help="Similarity threshold for deduplication (default: 0.65)")
69
73
  # Quality options
70
74
  @click.option("--min-confidence", type=float, default=0.0, help="Minimum confidence threshold 0-1 (default: 0)")
@@ -89,6 +93,9 @@ def main(
89
93
  no_dedup: bool,
90
94
  no_embeddings: bool,
91
95
  no_merge: bool,
96
+ no_gliner: bool,
97
+ predicates: Optional[str],
98
+ all_triples: bool,
92
99
  dedup_threshold: float,
93
100
  min_confidence: float,
94
101
  taxonomy: Optional[str],
@@ -152,6 +159,13 @@ def main(
152
159
  # Configure scoring
153
160
  scoring_config = ScoringConfig(min_confidence=min_confidence)
154
161
 
162
+ # Parse predicates if provided
163
+ predicate_list = None
164
+ if predicates:
165
+ predicate_list = [p.strip() for p in predicates.split(",") if p.strip()]
166
+ if not quiet:
167
+ click.echo(f"Using predicate list: {predicate_list}", err=True)
168
+
155
169
  # Configure extraction options
156
170
  options = ExtractionOptions(
157
171
  num_beams=beams,
@@ -160,6 +174,9 @@ def main(
160
174
  deduplicate=not no_dedup,
161
175
  embedding_dedup=not no_embeddings,
162
176
  merge_beams=not no_merge,
177
+ use_gliner_extraction=not no_gliner,
178
+ predicates=predicate_list,
179
+ all_triples=all_triples,
163
180
  predicate_taxonomy=predicate_taxonomy,
164
181
  predicate_config=predicate_config,
165
182
  scoring_config=scoring_config,
@@ -225,6 +242,9 @@ def _print_table(result, verbose: bool):
225
242
  click.echo(f" {stmt.object.text}{object_type}")
226
243
 
227
244
  if verbose:
245
+ # Always show extraction method
246
+ click.echo(f" Method: {stmt.extraction_method.value}")
247
+
228
248
  if stmt.confidence_score is not None:
229
249
  click.echo(f" Confidence: {stmt.confidence_score:.2f}")
230
250