1010from typing import Optional
1111
1212import typer
13+ from pydantic import ValidationError
1314from ruamel .yaml import YAML
1415from typing_extensions import Annotated
1516
4748]
4849
4950AutoFixThresholdOption = 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"\n Wrote { 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+
307352def _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+
353407def _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