Repository navigation
Expand file tree
/
Copy pathdata.py
More file actions
1432 lines (1222 loc) · 54.6 KB
/
Copy pathdata.py
File metadata and controls
1432 lines (1222 loc) · 54.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726<
8000
/div>
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
GLiNER2 Training Data Creation & Validation Module
This module provides intuitive classes for creating, validating, and managing
training data for GLiNER2 models.
Quick Examples
--------------
Create entity examples:
>>> example = InputExample(
... text="John works at Google in NYC.",
... entities={"person": ["John"], "company": ["Google"], "location": ["NYC"]}
... )
Create classification examples:
>>> example = InputExample(
... text="This movie is amazing!",
... classifications=[
... Classification(task="sentiment", labels=["positive", "negative"], true_label="positive")
... ]
... )
Create structured data examples:
>>> example = InputExample(
... text="iPhone 15 costs $999",
... structures=[
... Structure("product", name="iPhone 15", price="$999")
... ]
... )
Create relation examples:
>>> example = InputExample(
... text="Elon Musk founded SpaceX.",
... relations=[
... Relation("founded", head="Elon Musk", tail="SpaceX")
... ]
... )
Build and validate dataset:
>>> dataset = TrainingDataset(examples)
>>> dataset.validate() # Raises DataValidationError if invalid
>>> dataset.save("train.jsonl")
Load from JSONL:
>>> dataset = TrainingDataset.load("train.jsonl")
>>> # Or load multiple files
>>> dataset = TrainingDataset.load(["train1.jsonl", "train2.jsonl"])
"""
from __future__ import annotations
import json
import random
from dataclasses import dataclass, field
from pathlib import Path
from typing import (
Any, Dict, List, Mapping, Optional, Union, Tuple, Iterator, TYPE_CHECKING
)
from collections import Counter
from tqdm import tqdm
from gliner2.processing.surface import SurfaceSpan
if TYPE_CHECKING:
# Import-only (avoids a circular import with the trainer at runtime) so the
# ``'ExtractorDataset'`` forward reference in ``DataInput`` resolves for
# static type checkers / ``get_type_hints``.
from gliner2.training.trainer import ExtractorDataset
def _is_locatable(value: Any, text: str) -> bool:
# an absent field is not an annotation, so there is nothing to locate
if value is None or value == "":
return True
if isinstance(value, Mapping):
try:
span = SurfaceSpan.from_mapping(value)
except ValueError:
return False
return text[span.start : span.end] == span.text
if isinstance(value, list):
return all(_is_locatable(v, text) for v in value)
if isinstance(value, str):
return value.lower() in text.lower()
return False
class DataValidationError(Exception):
"""Raised when training data validation fails."""
def __init__(self, message: str, errors: List[str] = None):
super().__init__(message)
self.errors = errors or []
def __str__(self):
if self.errors:
error_list = "\n - ".join(self.errors[:10])
suffix = f"\n ... and {len(self.errors) - 10} more errors" if len(self.errors) > 10 else ""
return f"{self.args[0]}\n - {error_list}{suffix}"
return self.args[0]
_NO_TASK_ERROR = (
"Example must have at least one task (entities, classifications, structures, or relations). "
"A negative example still needs the labels it is negative for: declare them with empty "
"mention lists, e.g. entities={'person': [], 'company': []}, or pass them as "
"entity_descriptions."
)
# =============================================================================
# Data Format Detection & Loading
# =============================================================================
class DataFormat:
"""Enum-like class for supported data formats."""
JSONL = "jsonl"
JSONL_LIST = "jsonl_list"
INPUT_EXAMPLE_LIST = "input_example_list"
TRAINING_DATASET = "training_dataset"
DICT_LIST = "dict_list"
EXTRACTOR_DATASET = "extractor_dataset"
def detect_data_format(data: Any) -> str:
"""
Detect the format of input data.
Parameters
----------
data : Any
Input data in any supported format.
Returns
-------
str
The detected format name from DataFormat.
"""
# String path
if isinstance(data, str):
return DataFormat.JSONL
# Path object
if isinstance(data, Path):
return DataFormat.JSONL
# List types
if isinstance(data, list) and len(data) > 0:
first = data[0]
if isinstance(first, (str, Path)):
return DataFormat.JSONL_LIST
if isinstance(first, InputExample):
return DataFormat.INPUT_EXAMPLE_LIST
if isinstance(first, dict):
return DataFormat.DICT_LIST
# Empty list - default to dict list
if isinstance(data, list) and len(data) == 0:
return DataFormat.DICT_LIST
# TrainingDataset
if isinstance(data, TrainingDataset):
return DataFormat.TRAINING_DATASET
# ExtractorDataset (internal) - forward reference
if type(data).__name__ == 'ExtractorDataset':
return DataFormat.EXTRACTOR_DATASET
raise ValueError(f"Unsupported data format: {type(data)}")
class DataLoader_Factory:
"""
Factory for loading data from various formats into a unified internal format.
All loaders convert data to List[Dict] format where each dict has:
- "input": str (the text)
- "output": Dict (the schema/annotations)
Or alternatively:
- "text": str
- "schema": Dict
"""
@staticmethod
def load(
data: Any,
max_samples: int = -1,
shuffle: bool = True,
seed: int = 42,
validate: bool = False,
) -> List[Dict[str, Any]]:
"""
Load data from any supported format.
Parameters
----------
data : Any
Input data in any supported format.
max_samples : int, default=-1
Maximum samples to load (-1 = all).
shuffle : bool, default=True
Whether to shuffle the data.
seed : int, default=42
Random seed for shuffling.
validate : bool, default=False
Whether to validate the data. Validation is always strict:
checks that entity spans, relation values, and structure
field values exist in the text.
Returns
-------
List[Dict[str, Any]]
List of records in unified format.
"""
fmt = detect_data_format(data)
# Load based on format
if fmt == DataFormat.JSONL:
records = DataLoader_Factory._load_jsonl(data)
elif fmt == DataFormat.JSONL_LIST:
records = DataLoader_Factory._load_jsonl_list(data)
elif fmt == DataFormat.INPUT_EXAMPLE_LIST:
records = DataLoader_Factory._load_input_examples(data)
elif fmt == DataFormat.TRAINING_DATASET:
records = DataLoader_Factory._load_training_dataset(data)
elif fmt == DataFormat.DICT_LIST:
records = DataLoader_Factory._load_dict_list(data)
elif fmt == DataFormat.EXTRACTOR_DATASET:
records = data.data.copy()
else:
raise ValueError(f"Unsupported data format: {type(data)}")
# Validate if requested
if validate and records:
valid_indices, invalid_info = DataLoader_Factory._validate_records(records)
if invalid_info:
total_records = len(records)
num_invalid = len(invalid_info)
num_valid = len(valid_indices)
print(f"\nValidation: Found {num_invalid} invalid record(s) out of {total_records} total")
print("Removed invalid records:")
# Print first 5 invalid records
for idx, (record_idx, record, errors) in enumerate(invalid_info[:5]):
# Print first error for this record
error_msg = errors[0] if errors else "Unknown error"
print(f" Record {record_idx}: {error_msg}")
if num_invalid > 5:
print(f" ... and {num_invalid - 5} more invalid record(s)")
print(f"Kept {num_valid} valid record(s)\n")
# Filter records to keep only valid ones
records = [records[i] for i in valid_indices]
# Shuffle
if shuffle and records:
random.seed(seed)
random.shuffle(records)
# Limit samples
if max_samples > 0 and len(records) > max_samples:
records = records[:max_samples]
r
8BD0
eturn records
@staticmethod
def _load_jsonl(path: Union[str, Path]) -> List[Dict]:
"""Load from single JSONL file."""
path = Path(path)
if not path.exists():
raise FileNotFoundError(f"File not found: {path}")
records = []
with open(path, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
if line:
try:
records.append(json.loads(line))
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON in {path} line {line_num}: {e}")
return records
@staticmethod
def _load_jsonl_list(paths: List[Union[str, Path]]) -> List[Dict]:
"""Load from multiple JSONL files."""
records = []
for path in paths:
records.extend(DataLoader_Factory._load_jsonl(path))
return records
@staticmethod
def _load_input_examples(examples: List[InputExample]) -> List[Dict]:
"""Load from list of InputExample objects."""
return [ex.to_dict() for ex in examples]
@staticmethod
def _load_training_dataset(dataset: TrainingDataset) -> List[Dict]:
"""Load from TrainingDataset object."""
return dataset.to_records()
@staticmethod
def _load_dict_list(dicts: List[Dict]) -> List[Dict]:
"""Load from list of dicts."""
if not dicts:
return []
first = dicts[0]
# Check format
if "input" in first and "output" in first:
# Already in correct format
return dicts
elif "text" in first and "schema" in first:
# Alternative format - keep as is (handled in __getitem__)
return dicts
elif "text" in first:
# Maybe has entities/classifications at top level - try to convert
records = []
for d in dicts:
output = {}
if "entities" in d:
output["entities"] = d["entities"]
if "classifications" in d:
output["classifications"] = d["classifications"]
if "relations" in d:
output["relations"] = d["relations"]
if "json_structures" in d:
output["json_structures"] = d["json_structures"]
records.append({"input": d["text"], "output": output})
return records
else:
raise ValueError(
f"Unknown dict format. Expected keys like 'input'/'output', 'text'/'schema', "
f"or 'text' with annotation keys. Got: {list(first.keys())}"
)
@staticmethod
def _validate_records(records: List[Dict]) -> Tuple[List[int], List[Tuple[int, Dict, List[str]]]]:
"""
Validate and sanitize all records, removing only invalid parts.
Uses granular sanitization:
- Entities: Drop entity type if any mention not found
- Classifications: Drop individual invalid classifications
- Structures: Remove invalid fields, drop if all invalid
- Relations: Drop relation if any field invalid
- Record: Drop only if no valid tasks remain
Returns
-------
Tuple[List[int], List[Tuple[int, Dict, List[str]]]]
- First element: List of valid record indices (sanitized records replace originals)
- Second element: List of (index, original_record, warning_messages) for dropped records
"""
valid_indices = []
invalid_info = []
for i, record in tqdm(enumerate(records), total=len(records), desc="Validating records", unit="record"):
warnings = []
try:
example = InputExample.from_dict(record)
sanitize_warnings, is_valid = example.sanitize()
if is_valid:
# Replace record with sanitized version
records[i] = example.to_dict()
valid_indices.append(i)
if sanitize_warnings:
# Record was sanitized but still valid
warnings.extend(sanitize_warnings)
else:
# No valid content remains
warnings.extend(sanitize_warnings)
invalid_info.append((i, record, warnings))
except Exception as e:
warnings.append(f"Failed to parse - {e}")
invalid_info.append((i, record, warnings))
return valid_indices, invalid_info
# Type alias for flexible data input
TrainDataInput = Union[
str, # Single JSONL path
Path, # Single JSONL path
List[str], # Multiple JSONL paths
List[Path], # Multiple JSONL paths
List[Dict[str, Any]], # Raw records
'TrainingDataset', # TrainingDataset (forward reference)
'List[InputExample]', # List of InputExample (forward reference)
'ExtractorDataset', # Legacy dataset (forward reference)
]
# =============================================================================
# Training Data Classes
# =============================================================================
@dataclass
class Classification:
"""
A classification task definition.
Parameters
----------
task : str
Name of the classification task (e.g., "sentiment", "category").
labels : List[str]
All possible labels for this task.
true_label : str or List[str]
The correct label(s) for this example.
multi_label : bool, default=False
Whether multiple labels can be selected.
prompt : str, optional
Custom prompt for the task.
examples : List[Tuple[str, str]], optional
Few-shot examples as (input, output) pairs.
label_descriptions : Dict[str, str], optional
Descriptions for each label.
"""
task: str
labels: List[str]
true_label: Union[str, List[str]]
multi_label: bool = False
prompt: Optional[str] = None
examples: Optional[List[Tuple[str, str]]] = None
label_descriptions: Optional[Dict[str, str]] = None
def __post_init__(self):
if isinstance(self.true_label, str):
self._true_label_list = [self.true_label]
else:
self._true_label_list = list(self.true_label)
# Auto-infer multi_label=True when multiple true labels are provided
if len(self._true_label_list) > 1:
self.multi_label = True
def validate(self) -> List[str]:
"""Validate this classification and return list of errors."""
errors = []
if not self.task:
errors.append("Classification task name cannot be empty")
if not self.labels:
errors.append(f"Classification '{self.task}' has no labels")
for label in self._true_label_list:
if label not in self.labels:
errors.append(f"True label '{label}' not in labels list for task '{self.task}'")
if len(self._true_label_list) > 1 and not self.multi_label:
errors.append(f"Multiple true labels provided for '{self.task}' but multi_label=False")
if self.label_descriptions:
for key in self.label_descriptions:
if key not in self.labels:
errors.append(f"Label description key '{key}' not in labels for task '{self.task}'")
if self.examples:
for i, ex in enumerate(self.examples):
if not isinstance(ex, (list, tuple)) or len(ex) != 2:
errors.append(f"Example {i} for task '{self.task}' must be (input, output) pair")
return errors
def to_dict(self) -> Dict[str, Any]:
"""Convert to training format dictionary."""
result = {"task": self.task, "labels": self.labels, "true_label": self._true_label_list}
if self.multi_label:
result["multi_label"] = True
if self.prompt:
result["prompt"] = self.prompt
if self.examples:
result["examples"] = [list(ex) for ex in self.examples]
if self.label_descriptions:
result["label_descriptions"] = self.label_descriptions
return result
@dataclass
class ChoiceField:
"""
A field with predefined choices (classification within structure).
Parameters
----------
value : str
The selected value.
choices : List[str]
All possible choices.
"""
value: str
choices: List[str]
def validate(self, field_name: str) -> List[str]:
errors = []
if self.value not in self.choices:
errors.append(f"Choice value '{self.value}' not in choices {self.choices} for field '{field_name}'")
return errors
def to_dict(self) -> Dict[str, Any]:
return {"value": self.value, "choices": self.choices}
@dataclass
class Structure:
"""
A structured data extraction definition.
Parameters
----------
struct_name : str
Name of the structure (e.g., "product", "contact").
**fields : Any
Field names and values. Values can be:
- str: Single string value
- List[str]: Multiple values
- ChoiceField: Classification-style field with choices
Examples
--------
>>> struct = Structure("product", name="iPhone", price="$999")
>>> struct = Structure("contact", name="John", email="john@example.com")
"""
struct_name: str
_fields: Dict[str, Any] = field(default_factory=dict)
descriptions: Optional[Dict[str, str]] = None
def __init__(
self,
struct_name: str,
_descriptions: Dict[str, str] = None,
*,
mode: Optional[str] = "natural",
anchor: Optional[str] = None,
occurrence_policy: Optional[str] = None,
_field_values: Optional[Dict[str, Any]] = None,
**fields,
):
self.struct_name = struct_name
# JSONL structure fields can legitimately be named ``mode``, ``anchor``,
# or ``occurrence_policy``. ``InputExample.from_dict`` uses this private
# mapping path so those names remain ordinary data fields rather than
# colliding with boundary record metadata arguments.
if _field_values is not None:
if fields:
raise ValueError("_field_values cannot be combined with field keywords")
self._fields = dict(_field_values)
else:
self._fields = fields
self.descriptions = _descriptions
# Basic pre-boundary JSON structures use natural record formation by
# default. When no anchor is provided, get_record_metadata selects the
# first declared structure field.
self.mode = mode
self.anchor = anchor
self.occurrence_policy = occurrence_policy
def get_record_metadata(self) -> Optional[Dict[str, Any]]:
"""Return this structure's record-metadata entry, if any mode is set."""
if not self.mode:
return None
entry: Dict[str, Any] = {"mode": self.mode}
anchor = self.anchor
if self.mode == "natural" and not anchor:
# Default anchor = first declared field, in declaration order
# (kwargs order, captured before any training-time field shuffling).
anchor = next(iter(self._fields), None)
if anchor is not None:
entry["anchor"] = anchor
if self.occurrence_policy is not None:
entry["occurrence_policy"] = self.occurrence_policy
return {self.struct_name: entry}
def validate(self, text: str) -> List[str]:
"""
Validate this structure.
Parameters
----------
text : str
The text to validate against. Field values must exist in this text.
Returns
-------
List[str]
List of validation errors.
"""
errors = []
if not self.struct_name:
errors.append("Structure name cannot be empty")
if not self._fields:
errors.append(f"Structure '{self.struct_name}' has no fields")
for field_name, value in self._fields.items():
if isinstance(value, ChoiceField):
errors.extend(value.validate(f"{self.struct_name}.{field_name}"))
elif isinstance(value, list):
for i, v in enumerate(value):
if v is not None and not isinstance(v, (str, Mapping)):
errors.append(
f"List value at index {i} in "
f"'{self.struct_name}.{field_name}' must be a string or span"
)
elif not _is_locatable(v, text):
errors.append(f"List value '{v}' at index {i} in '{self.struct_name}.{field_name}' not found in text")
elif isinstance(value, (str, Mapping)):
if not _is_locatable(value, text):
errors.append(f"Value '{value}' for '{self.struct_name}.{field_name}' not found in text")
elif value is not None:
errors.append(
f"Value for '{self.struct_name}.{field_name}' must be a string, "
"span, list of them, or ChoiceField"
)
return errors
def to_dict(self) -> Dict[str, Dict[str, Any]]:
fields_dict = {}
for field_name, value in self._fields.items():
if isinstance(value, ChoiceField):
fields_dict[field_name] = value.to_dict()
else:
fields_dict[field_name] = value
return {self.struct_name: fields_dict}
def get_descriptions(self) -> Optional[Dict[str, Dict[str, str]]]:
if self.descriptions:
return {self.struct_name: self.descriptions}
return None
@dataclass
class Relation:
"""
A relation extraction definition.
Parameters
----------
name : str
Name of the relation (e.g., "works_for", "founded").
head : str, optional
The source/subject entity.
tail : str, optional
The target/object entity.
**fields : Any
Custom field names and values (use instead of head/tail).
"""
name: str
head: Optional[str] = None
tail: Optional[str] = None
_fields: Dict[str, str] = field(default_factory=dict)
def __init__(self, name: str, head: str = None, tail: str = None, **fields):
self.name = name
self.head = head
self.tail = tail
if fields:
self._fields = fields
elif head is not None and tail is not None:
self._fields = {"head": head, "tail": tail}
else:
self._fields = {}
if head is not None:
self._fields["head"] = head
if tail is not None:
self._fields["tail"] = tail
def validate(self, text: str) -> List[str]:
"""
Validate this relation.
Parameters
----------
text : str
The text to validate against. Field values must exist in this text.
Returns
-------
List[str]
List of validation errors.
"""
errors = []
if not self.name:
errors.append("Relation name cannot be empty")
if not self._fields:
errors.append(f"Relation '{self.name}' has no fields")
for field_name, value in self._fields.items():
if not _is_locatable(value, text):
errors.append(f"Relation value '{value}' for '{self.name}.{field_name}' not found in text")
return errors
def get_field_names(self) -> List[str]:
return list(self._fields.keys())
def to_dict(self) -> Dict[str, Dict[str, str]]:
return {self.name: self._fields}
@dataclass
class InputExample:
"""
A single training example for GLiNER2.
Parameters
----------
text : str
The input text for this example.
entities : Dict[str, List[str]], optional
Entity type to mentions mapping. A type mapped to an empty list is a
negative: the text is trained as containing no mention of that type.
entity_descriptions : Dict[str, str], optional
Descriptions for entity types. Every described type is part of this
example's label set, so a described type with no mentions is added to
``entities`` with an empty list and trained as a negative.
classifications : List[Classification], optional
Classification tasks for this example.
structures : List[Structure], optional
Structured data extractions for this example.
relations : List[Relation], optional
Relation extractions for this example.
Examples
--------
>>> example = InputExample(
... text="John Smith works at Google.",
... entities={"person": ["John Smith"], "company": ["Google"]}
... )
>>> negative = InputExample(
... text="The meeting moved to Tuesday.",
... entities={"person": [], "company": []}
... )
"""
text: str
entities: Optional[Dict[str, List[str]]] = None
entity_descriptions: Optional[Dict[str, str]] = None
classifications: Optional[List[Classification]] = None
structures: Optional[List[Structure]] = None
relations: Optional[List[Relation]] = None
def __post_init__(self):
if self.entities is None:
self.entities = {}
if self.classifications is None:
self.classifications = []
if self.structures is None:
self.structures = []
if self.relations is None:
self.relations = []
if self.entity_descriptions:
undeclared = [t for t in self.entity_descriptions if t not in self.entities]
if undeclared:
self.entities = {**self.entities, **{t: [] for t in undeclared}}
def validate(self) -> List[str]:
"""
Validate this example.
Validation is always strict: checks that entity mentions, relation values,
and structure field values exist in the text (case-insensitive).
Returns
-------
List[str]
List of validation errors. Empty list means valid.
"""
errors = []
if not self.text or not self.text.strip():
errors.append("Text cannot be empty")
return errors
if self.entities:
for entity_type, mentions in self.entities.items():
if not entity_type:
errors.append("Entity type cannot be empty")
for mention in mentions:
if not _is_locatable(mention, self.text):
errors.append(f"Entity '{mention}' (type: {entity_type}) not found in text")
for cls in self.classifications:
errors.extend(cls.validate())
for struct in self.structures:
errors.extend(struct.validate(self.text))
relation_fields = {}
for rel in self.relations:
errors.extend(rel.validate(self.text))
field_names = tuple(sorted(rel.get_field_names()))
if rel.name in relation_fields:
if relation_fields[rel.name] != field_names:
errors.append(f"Relation '{rel.name}' has inconsistent fields: {relation_fields[rel.name]} vs {field_names}")
else:
relation_fields[rel.name] = field_names
has_content = bool(self.entities) or bool(self.classifications) or bool(self.structures) or bool(self.relations)
if not has_content:
errors.append(_NO_TASK_ERROR)
return errors
def is_valid(self) -> bool:
"""Check if this example is valid."""
return len(self.validate()) == 0
def sanitize(self) -> Tuple[List[str], bool]:
"""
Remove invalid parts from this example, keeping only valid content.
Mutates self in-place.
Granular removal strategy:
- Entities: Drop entire entity type if ANY mention is not found in text
- Classifications: Drop individual classifications that have errors
- Structures: Remove invalid fields; drop structure only if ALL fields become invalid
- Relations: Drop the specific relation if ANY field has an error
- Example: Mark as invalid only if no valid tasks remain
Returns
-------
Tuple[List[str], bool]
- List of warning messages about what was removed
- bool: True if example still has valid content, False if should be dropped
"""
warnings = []
if not self.text or not self.text.strip():
warnings.append("Text is empty")
return warnings, False
# 1. Sanitize entities - drop entity type if any mention not found
if self.entities:
types_to_remove = []
for entity_type, mentions in self.entities.items():
if not entity_type:
types_to_remove.append(entity_type)
warnings.append("Entity type is empty")
continue
# Check if any mention is not in text
has_invalid = False
for mention in mentions:
if not _is_locatable(mention, self.text):
has_invalid = True
warnings.append(f"Entity '{mention}' (type: {entity_type}) not found in text - dropping entity type")
break
if has_invalid:
types_to_remove.append(entity_type)
# Remove invalid entity types
for entity_type in types_to_remove:
del self.entities[entity_type]
# Clean up entity descriptions for removed types
if self.entity_descriptions:
desc_to_remove = [desc_type for desc_type in self.entity_descriptions if desc_type not in self.entities]
for desc_type in desc_to_remove:
del self.entity_descriptions[desc_type]
# 2. Sanitize classifications - drop individual invalid ones
if self.classifications:
valid_classifications = []
for cls in self.classifications:
cls_errors = cls.validate()
if cls_errors:
warnings.append(f"Classification '{cls.task}' has errors - dropping: {cls_errors[0]}")
else:
valid_classifications.append(cls)
self.classifications = valid_classifications
# 3. Sanitize structures - remove invalid fields, drop if all invalid
if self.structures:
valid_structures = []
for struct in self.structures:
if not struct.struct_name:
warnings.append("Structure has empty name - dropping")
continue
if not struct._fields:
warnings.append(f"Structure '{struct.struct_name}' has no fields - dropping")
continue
# Filter out invalid fields
valid_fields = {}
for field_name, value in struct._fields.items():
is_valid = True
if isinstance(value, ChoiceField):
field_errors = value.validate(f"{struct.struct_name}.{field_name}")
if field_errors:
warnings.append(f"Field '{struct.struct_name}.{field_name}' invalid - dropping field")
is_valid = False
elif isinstance(value, list):
for v in value:
if not _is_locatable(v, self.text):
warnings.append(f"List value '{v}' in '{struct.struct_name}.{field_name}' not found - dropping field")
is_valid = False
break
elif isinstance(value, (str, Mapping)):
if not _is_locatable(value, self.text):
warnings.append(f"Value '{value}' for '{struct.struct_name}.{field_name}' not found - dropping field")
is_valid = False
if is_valid:
valid_fields[field_name] = value
# An anchored structure must keep the field its record metadata names.
#
# `record_metadata` is a DECLARATION -- it names the anchor field -- while
# the loop above edits GOLD. Dropping a field the declaration names leaves
8DBD
# a structure whose anchor points at nothing, and
# `compile_record_specs` then raises:
#
# record 'record' declares anchor 'type' but no matching field query
# was found in the layout
#
# aborting training in a DataLoader worker. It only bites when records are
# validated (`validate=True`), which is why it can lie dormant.
#
# The quieter case matters as much: `get_record_metadata` defaults a
# natural-mode anchor to the FIRST declared field, so reassigning
# `_fields` below would silently RE-POINT a defaulted anchor at whatever
# field now happens to be first -- no error, and the record trains against
# a different anchor than it declares.
#
# Resolve the anchor exactly as `get_record_metadata` will, before
# mutating, and drop the structure if that field did not survive.
anchor = struct.anchor
if struct.mode == "natural" and not anchor:
anchor = next(iter(struct._fields), None)
if struct.mode and anchor is not None and anchor not in valid_fields:
warnings.append(
f"Structure '{struct.struct_name}' lost its anchor field "
f"'{anchor}' during sanitization - dropping the whole structure"
)
continue
# Only keep structure if it has at least one valid field
if valid_fields:
struct._fields = valid_fields
valid_structures.append(struct)
else:
warnings.append(f"Structure '{struct.struct_name}' has no valid fields - dropping")
self.structures = valid_structures
# 4. Sanitize relations - drop entire relation if any field is invalid
if self.relations:
valid_relations = []
for rel in self.relations:
if not rel.name:
warnings.append("Relation has empty name - dropping")
continue
if not rel._fields:
warnings.append(f"Relation '{rel.name}' has no fields - dropping")
continue
# Check if any field value is invalid
has_invalid = False
for field_name, value in rel._fields.items():
if not _is_locatable(value, self.text):
warnings.append(f"Relation '{rel.name}' field '{field_name}' value '{value}' not found - dropping relation")
has_invalid = True
break
if not has_invalid:
valid_relations.append(rel)
self.relations = valid_relations
# Check if example still has any valid content
has_content = bool(self.entities) or bool(self.classifications) or bool(self.structures) or bool(self.relations)
if not has_content:
warnings.append("No valid tasks remain after sanitization")
return warnings, False
return warnings, True
def to_dict(self) -> Dict[str, Any]:
"""Convert to GLiNER2 training format."""
output = {}
if self.entities:
output["entities"] = self.entities
if self.entity_descriptions:
output["entity_descriptions"] = self.entity_descriptions
if self.classifications:
output["classifications"] = [cls.to_dict() for cls in self.classifications]
if self.structures:
output["json_structures"] = [struct.to_dict() for struct in self.structures]
all_descriptions = {}
record_metadata: Dict[str, Any] = {}
for struct in self.structures:
desc = struct.get_descriptions()
if desc:
all_descriptions.update(desc)
meta = struct.get_record_metadata()
if meta:
record_metadata.update(meta)