Download code/numeric_target_scoring.py from dfdu233/MeningiomaBench: direct link, hf CLI and curl.
- Browser
- Download file 3.97 kB
-
https://huggingface.co/datasets/dfdu233/MeningiomaBench/resolve/main/code/numeric_target_scoring.py
- Command line
-
hf download hf://datasets/dfdu233/MeningiomaBench/code/numeric_target_scoring.py
-
curl -L -o numeric_target_scoring.py https://huggingface.co/datasets/dfdu233/MeningiomaBench/resolve/main/code/numeric_target_scoring.py
3.97 kB
| """Experimental typed numeric contract only; no whole-question or clinical validity claim.""" | |
| from decimal import Decimal, InvalidOperation | |
| import re | |
| N = r'[+-]?\d+(?:,\d{3})*(?:\.\d+)?' | |
| U = r'%|[A-Za-z][A-Za-z ]*' | |
| SEP = r'(?:-|–|—|\bto\b)' | |
| def number(value): | |
| try: | |
| result = Decimal(str(value).replace(',', '')) | |
| return result if result.is_finite() else None | |
| except InvalidOperation: | |
| return None | |
| def unit(value): | |
| if not isinstance(value, str): | |
| return None | |
| normalized = value.strip().lower() | |
| return {'percent': '%', 'percentage': '%', 'year': 'years', 'month': 'months', | |
| 'patient': 'patients', 'case': 'cases', 'sample': 'samples'}.get(normalized, normalized) | |
| def parse_answer(text, expected_kind): | |
| """Parse concise answers only. Never search for target numbers inside arbitrary prose.""" | |
| if not isinstance(text, str): | |
| return None | |
| text = text.strip().replace('−', '-') | |
| if expected_kind == 'estimate_with_ci': | |
| pattern = (rf'(?P<value>{N})\s*(?P<unit>{U})\s*\(\s*' | |
| rf'(?:(?P<confidence_level>{N})\s*%\s*(?:CI|confidence interval)\s*:?\s*)?' | |
| rf'(?P<lower>{N})\s*{SEP}\s*(?P<upper>{N})\s*(?P<bounds_unit>{U})?\s*\)') | |
| m = re.fullmatch(pattern, text, re.I) | |
| if m: | |
| data = {k: v for k, v in m.groupdict().items() if v is not None} | |
| if data.get('bounds_unit') and unit(data['bounds_unit']) != unit(data['unit']): | |
| return None | |
| data.pop('bounds_unit', None) | |
| return {'kind': 'estimate_with_ci', **data} | |
| if expected_kind == 'range': | |
| m = re.fullmatch(rf'(?P<lower>{N})\s*(?P<unit1>{U})?\s*{SEP}\s*(?P<upper>{N})\s*(?P<unit2>{U})?', text, re.I) | |
| if m: | |
| data = m.groupdict() | |
| if data['unit1'] and data['unit2'] and unit(data['unit1']) != unit(data['unit2']): | |
| return None | |
| return {'kind': 'range', 'lower': data['lower'], 'upper': data['upper'], | |
| 'unit': data['unit2'] or data['unit1']} | |
| m = re.fullmatch(rf'(?P<value>{N})\s*(?P<unit>{U})?', text, re.I) | |
| return {'kind': 'scalar', **m.groupdict()} if m else None | |
| def score(target, prediction): | |
| required = {'scalar': ('value',), 'range': ('lower', 'upper'), | |
| 'estimate_with_ci': ('value', 'lower', 'upper')}[target['kind']] | |
| if any(number(target.get(k)) is None for k in required) or unit(target.get('unit')) is None: | |
| raise ValueError('Malformed typed reference target') | |
| if 'lower' in required and number(target['lower']) > number(target['upper']): | |
| raise ValueError('Reference bounds are reversed') | |
| valid = isinstance(prediction, dict) | |
| p = prediction if valid else {} | |
| components = {k: number(p.get(k)) is not None and number(p[k]) == number(target[k]) for k in required} | |
| unit_match = valid and unit(p.get('unit')) == unit(target['unit']) | |
| conflicts = [] | |
| if p.get('confidence_level') is not None and target.get('confidence_level') is not None: | |
| if number(p['confidence_level']) != number(target['confidence_level']): | |
| conflicts.append('confidence_level') | |
| bounds_valid = not ('lower' in p or 'upper' in p) or ( | |
| number(p.get('lower')) is not None and number(p.get('upper')) is not None | |
| and number(p['lower']) <= number(p['upper'])) | |
| return {'format_parsed': valid, 'target_kind_matches': valid and p.get('kind') == target['kind'], | |
| 'numeric_component_matches': components, 'requested_numeric_component_recall': sum(components.values()) / len(required), | |
| 'unit_matches': unit_match, 'ordered_bounds_valid': bounds_valid, | |
| 'additional_component_conflicts': conflicts, | |
| 'fully_correct_on_numeric_contract': bool(valid and p.get('kind') == target['kind'] and | |
| all(components.values()) and unit_match and bounds_valid and not conflicts), | |
| 'whole_question_semantics_verified': False} | |