Skip to content

Commit 2fe6614

Browse files
authored
Merge pull request #160 from linkml/ccr-65a5480d-pb91sk
Grade fuzzy repairs by the configured thresholds, and count placed fixes
2 parents 7fcb8a8 + ea16598 commit 2fe6614

8 files changed

Lines changed: 466 additions & 47 deletions

File tree

‎docs/how-to/repair-validation-errors.md‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,18 @@ The repair command uses confidence thresholds to determine how to handle each er
9090
| **LOW** | 0.50-0.80 | Flag for manual review |
9191
| **VERY_LOW** | 0.00-0.50 | Recommend removal |
9292

93+
The score ranges are the defaults. A fuzzy match is graded by the repair
94+
config's `auto_fix_threshold`, `suggest_threshold` and `removal_threshold`, so
95+
raising `auto_fix_threshold` (or passing `--auto-fix-threshold`) turns
96+
borderline auto-fixes into suggestions, and lowering it does the reverse. The
97+
three must be in order, `removal <= suggest <= auto_fix`. A lower threshold
98+
you leave unset follows one you set below it (`auto_fix_threshold: 0.75` alone
99+
also lowers `suggest_threshold` to 0.75), and `--auto-fix-threshold` lowers the
100+
other two with it. Thresholds you set out of order are an error.
101+
The flag overrides the config file only when it is given. Character
102+
normalization and ellipsis repairs are not scored, so the thresholds do not
103+
apply to them.
104+
93105
## Repair Strategies
94106

95107
### 1. Character Normalization (High Confidence)
@@ -267,7 +279,7 @@ linkml-reference-validator repair data <DATA_FILE> --schema <SCHEMA> [OPTIONS]
267279
- `--schema PATH` - Path to LinkML schema (required)
268280
- `--target-class CLASS` - Target class to validate
269281
- `--dry-run / --no-dry-run` - Show changes without applying (default: dry-run)
270-
- `--auto-fix-threshold FLOAT` - Minimum similarity for auto-fixes (default: 0.95)
282+
- `--auto-fix-threshold FLOAT` - Minimum similarity for auto-fixes (default: the config file's `auto_fix_threshold`, else 0.95)
271283
- `--output PATH` - Output file path (default: overwrite the input, keeping a `.bak` backup). When given with `--no-dry-run`, it is always written, as an unchanged copy of the input when there is nothing to fix, and the input itself is not touched, so no backup is made
272284
- `--config PATH` - Path to repair configuration file
273285
- `--cache-dir PATH` - Directory for caching references

‎docs/reference/cli.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ linkml-reference-validator repair text [OPTIONS] TEXT REFERENCE_ID
467467
- `--cache-dir PATH, -c PATH` - Directory for caching references
468468
- `--config PATH` - Path to configuration file (.yaml)
469469
- `--verbose, -v` - Verbose output with detailed logging
470-
- `--auto-fix-threshold FLOAT, -a FLOAT` - Minimum similarity for auto-fixes (default: 0.95)
470+
- `--auto-fix-threshold FLOAT, -a FLOAT` - Minimum similarity for auto-fixes (default: the config file's `auto_fix_threshold`, else 0.95)
471471
- `--help` - Show help message
472472

473473
### Examples
@@ -542,7 +542,7 @@ linkml-reference-validator repair data [OPTIONS] DATA_FILE
542542
- `--schema PATH, -s PATH` (required) - Path to LinkML schema file
543543
- `--target-class TEXT, -t TEXT` - Target class to validate
544544
- `--dry-run / --no-dry-run, -n / -N` - Show changes without applying (default: dry-run)
545-
- `--auto-fix-threshold FLOAT, -a FLOAT` - Minimum similarity for auto-fixes (default: 0.95)
545+
- `--auto-fix-threshold FLOAT, -a FLOAT` - Minimum similarity for auto-fixes (default: the config file's `auto_fix_threshold`, else 0.95)
546546
- `--output PATH, -o PATH` - Output file path (default: overwrite the input, keeping a `.bak` backup). When given with `--no-dry-run`, it is always written, as an unchanged copy of the input when there is nothing to fix, and the input itself is not touched, so no backup is made
547547
- `--config PATH` - Path to configuration file (.yaml)
548548
- `--cache-dir PATH, -c PATH` - Directory for caching references

‎src/linkml_reference_validator/cli/repair.py‎

Lines changed: 78 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from typing import Optional
1111

1212
import typer
13+
from pydantic import ValidationError
1314
from ruamel.yaml import YAML
1415
from typing_extensions import Annotated
1516

@@ -47,11 +48,14 @@
4748
]
4849

4950
AutoFixThresholdOption = Annotated[
50-
float,
51+
Optional[float],
5152
typer.Option(
5253
"--auto-fix-threshold",
5354
"-a",
54-
help="Minimum similarity for automatic fixes (0.0-1.0, default: 0.95)",
55+
help=(
56+
"Minimum similarity for automatic fixes (0.0-1.0). Default: the "
57+
"config file's auto_fix_threshold, else 0.95"
58+
),
5559
),
5660
]
5761

@@ -77,7 +81,7 @@ def data_command(
7781
typer.Option("--target-class", "-t", help="Target class to validate"),
7882
] = None,
7983
dry_run: DryRunOption = True,
80-
auto_fix_threshold: AutoFixThresholdOption = 0.95,
84+
auto_fix_threshold: AutoFixThresholdOption = None,
8185
output: OutputOption = None,
8286
cache_dir: CacheDirOption = None,
8387
verbose: VerboseOption = False,
@@ -115,8 +119,7 @@ def data_command(
115119
raise typer.Exit(1)
116120

117121
# Load repair config from file if provided
118-
repair_config = _load_repair_config(config_file)
119-
repair_config.auto_fix_threshold = auto_fix_threshold
122+
repair_config = _repair_config_with(config_file, auto_fix_threshold)
120123
repair_config.dry_run = dry_run
121124

122125
# Set up validation config
@@ -135,7 +138,7 @@ def data_command(
135138
else:
136139
typer.echo(f"Repairing {data_file}")
137140
typer.echo(f" Schema: {schema_file}")
138-
typer.echo(f" Auto-fix threshold: {auto_fix_threshold}")
141+
typer.echo(f" Auto-fix threshold: {repair_config.auto_fix_threshold}")
139142
typer.echo(f" Cache directory: {val_config.cache_dir}")
140143
typer.echo("")
141144

@@ -164,10 +167,18 @@ def data_command(
164167

165168
# Apply repairs if not dry run
166169
if not dry_run:
167-
changes_made = report.auto_fixed_count > 0 and _apply_repairs_to_data(
168-
data, report, target_class
170+
placed = (
171+
_apply_repairs_to_data(data, report, target_class)
172+
if report.auto_fixed_count > 0
173+
else 0
169174
)
170-
if changes_made:
175+
unplaced = report.auto_fixed_count - placed
176+
if unplaced > 0:
177+
typer.echo(
178+
f"\n! {unplaced} of {report.auto_fixed_count} auto-fix(es) could "
179+
"not be placed back in the data"
180+
)
181+
if placed:
171182
output_path = output or data_file
172183
# A backup only matters when the input itself is overwritten.
173184
if repair_config.create_backup and _same_file(output_path, data_file):
@@ -177,13 +188,8 @@ def data_command(
177188
with open(output_path, 'w') as f:
178189
yaml.dump(data, f)
179190
typer.echo(f"\n✓ Wrote {output_path}")
180-
typer.echo(f" Applied {report.auto_fixed_count} auto-fix(es)")
191+
typer.echo(f" Applied {placed} auto-fix(es)")
181192
else:
182-
if report.auto_fixed_count > 0:
183-
typer.echo(
184-
f"\n! {report.auto_fixed_count} auto-fix(es) could not be "
185-
"placed back in the data"
186-
)
187193
_copy_unchanged(data_file, output)
188194

189195
# Exit with appropriate code
@@ -207,7 +213,7 @@ def text_command(
207213
reference_id: Annotated[str, typer.Argument(help="Reference ID (e.g., PMID:12345678 or DOI:10.1234/example)")],
208214
cache_dir: CacheDirOption = None,
209215
verbose: VerboseOption = False,
210-
auto_fix_threshold: AutoFixThresholdOption = 0.95,
216+
auto_fix_threshold: AutoFixThresholdOption = None,
211217
config_file: ConfigFileOption = None,
212218
):
213219
"""Attempt to repair a single supporting text quote.
@@ -229,7 +235,7 @@ def text_command(
229235
if cache_dir:
230236
val_config.cache_dir = cache_dir
231237

232-
repair_config = RepairConfig(auto_fix_threshold=auto_fix_threshold)
238+
repair_config = _repair_config_with(config_file, auto_fix_threshold)
233239
repairer = SupportingTextRepairer(
234240
validation_config=val_config,
235241
repair_config=repair_config,
@@ -304,6 +310,45 @@ def _copy_unchanged(data_file: Path, output: Optional[Path]) -> None:
304310
typer.echo(f"\nWrote {output} (no changes)")
305311

306312

313+
def _repair_config_with(
314+
config_file: Optional[Path], auto_fix_threshold: Optional[float]
315+
) -> RepairConfig:
316+
"""The repair config from the file, with ``--auto-fix-threshold`` on top.
317+
318+
The flag overrides the file only when given, so a threshold set in the
319+
config file is not replaced by the flag's default (#127). There is no flag
320+
for the lower thresholds, so a flag below them lowers them with it: every
321+
match at or above it is auto-fixed, rather than the flag being an error.
322+
323+
Examples:
324+
>>> _repair_config_with(None, None).auto_fix_threshold
325+
0.95
326+
>>> config = _repair_config_with(None, 0.7)
327+
>>> (config.auto_fix_threshold, config.suggest_threshold, config.removal_threshold)
328+
(0.7, 0.7, 0.5)
329+
"""
330+
repair_config = _load_repair_config(config_file)
331+
if auto_fix_threshold is None:
332+
return repair_config
333+
suggest = min(repair_config.suggest_threshold, auto_fix_threshold)
334+
try: # user input: report an out-of-range value, not a traceback
335+
return RepairConfig.model_validate({
336+
**repair_config.model_dump(),
337+
"auto_fix_threshold": auto_fix_threshold,
338+
"suggest_threshold": suggest,
339+
"removal_threshold": min(repair_config.removal_threshold, suggest),
340+
})
341+
except ValidationError as e:
342+
typer.echo(f"Error: invalid --auto-fix-threshold: {_first_error(e)}", err=True)
343+
raise typer.Exit(1)
344+
345+
346+
def _first_error(error: ValidationError) -> str:
347+
"""The first problem pydantic found, without its help URL."""
348+
first = error.errors()[0]
349+
return first["msg"].removeprefix("Value error, ")
350+
351+
307352
def _load_repair_config(config_file: Optional[Path]) -> RepairConfig:
308353
"""Load repair configuration from file.
309354
@@ -340,16 +385,25 @@ def _load_repair_config(config_file: Optional[Path]) -> RepairConfig:
340385
if "repair" in config_data:
341386
repair_data = config_data.get("repair")
342387
if isinstance(repair_data, dict):
343-
return RepairConfig(**repair_data)
388+
return _repair_config_from(repair_data, config_file)
344389
return RepairConfig()
345390

346391
repair_keys = set(RepairConfig.model_fields.keys())
347392
if repair_keys.intersection(config_data.keys()):
348-
return RepairConfig(**config_data)
393+
return _repair_config_from(config_data, config_file)
349394

350395
return RepairConfig()
351396

352397

398+
def _repair_config_from(data: dict, config_file: Path) -> RepairConfig:
399+
"""Build the repair config from a file's settings, or exit with a clean error."""
400+
try: # user input: a bad value is reported, not a traceback
401+
return RepairConfig(**data)
402+
except ValidationError as e:
403+
typer.echo(f"Error: invalid repair config in {config_file}: {_first_error(e)}", err=True)
404+
raise typer.Exit(1)
405+
406+
353407
def _excerpt_keys(d: dict) -> list[str]:
354408
"""Return every key holding an excerpt on this evidence item.
355409
@@ -463,7 +517,7 @@ def _apply_repairs_to_data(
463517
data: dict,
464518
report,
465519
target_class: Optional[str],
466-
) -> bool:
520+
) -> int:
467521
"""Apply auto-fixes from repair report to data.
468522
469523
Args:
@@ -472,9 +526,9 @@ def _apply_repairs_to_data(
472526
target_class: Target class (for future use)
473527
474528
Returns:
475-
True if any changes were made
529+
How many fixes were placed, so the caller can report any that were not
476530
"""
477-
changes_made = False
531+
placed: set[str] = set()
478532

479533
# Build a map of paths to repairs
480534
repairs_by_path = {}
@@ -486,8 +540,6 @@ def _apply_repairs_to_data(
486540
break
487541

488542
def _apply_to_dict(d: dict, path: str = ""):
489-
nonlocal changes_made
490-
491543
if isinstance(d, dict):
492544
# Check if this item needs repair
493545
# Keyed by the same path extraction reported, which names the
@@ -498,7 +550,7 @@ def _apply_to_dict(d: dict, path: str = ""):
498550
key_path = f"{path}.{text_key}" if path else text_key
499551
if key_path in repairs_by_path:
500552
d[text_key] = repairs_by_path[key_path]
501-
changes_made = True
553+
placed.add(key_path)
502554

503555
# Recurse
504556
for key in ["evidence", "supporting_evidence", "annotations"]:
@@ -523,4 +575,4 @@ def _apply_to_dict(d: dict, path: str = ""):
523575
elif isinstance(data, dict):
524576
_apply_to_dict(data)
525577

526-
return changes_made
578+
return len(placed)

0 commit comments

Comments
 (0)