SailorEval / evaluation /quality.py
QingchengChang's picture
Update
ef00b98 verified
Raw History Blame Contribute Delete
5.51 kB
"""Checks for source-grounded generation inputs, without preparation dependencies."""
import re
from decimal import Decimal
from datetime import datetime
COORDINATE_PAIR=r'(\d{2}-\d{2}(?:\.\d+)?(?:-\d{2}(?:\.\d+)?)?[NS]?)\s+(\d{3}-\d{2}(?:\.\d+)?(?:-\d{2}(?:\.\d+)?)?[EW]?)'
def degree_option_value(text):
"""Compare standalone decimal degrees, including marine 033°.75 notation.
Do not strip units from other quantities or discard direction/side suffixes.
"""
match=re.fullmatch(r'\s*([+-]?\d+(?:\.\d+)?)\s*°(?:\s*\.(\d+))?\s*',str(text))
if not match:return None
number,fraction=match.groups()
if fraction:
if '.' in number:return None
number+='.'+fraction
return Decimal(number)
def missing_case_material_errors(row):
"""High-confidence missing observations; chart theory needs no instance map."""
if row.get('context') or row.get('media',{}).get('image'):return []
question=row.get('question','')
chart=re.search(r'\b(?:weather|surface|synoptic|wave|typhoon)\s+charts?\b',question,re.I)
if chart and re.search(r'\bat that time\b',question,re.I):
return ['case-specific weather chart is not supplied']
return []
HEADING_FIELDS = {
'COASTAL WARNING {district} {notice}': {'district', 'notice'},
'NORWEGIAN NAV. WARNING {notice}': {'notice'},
'UKRAINE COASTAL WARNING {notice} {office}-NAVTEX': {'office', 'notice'},
'UKRAINE COASTAL WARNING {office}-NAVTEX': {'office'},
'MSI {notice}': {'notice'},
'FORECAST FOR HIGH SEAS {south} - TO THE {north}': {'south', 'north'},
}
MONTHS = 'JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC'.split()
def navtex_header_errors(context, fixed):
"""Reconstruct the expected fixed fields from the dispatch or legacy input."""
if set(fixed) != {'message_id', 'datetime', 'category_line'}:
return ['invalid NAVTEX fixed fields']
try:
if 'dispatch' in context:
if set(context) != {'dispatch', 'semantic_facts'}:
return ['unexpected NAVTEX dispatch input']
order = context['dispatch']
station, subject = order['station_letter'], order['subject_letter']
sequence = order['sequence']
if not (re.fullmatch('[A-Z]', station) and re.fullmatch('[A-Z]', subject)
and type(sequence) is int and 0 <= sequence <= 99):
return ['invalid NAVTEX transmission identifier components']
message_id = f'{station}{subject}{sequence:02d}'
pattern, entries = order['heading_format'], order['heading_entries']
if (set(entries) != HEADING_FIELDS[pattern]
or not all(isinstance(v, str) and v.strip() for v in entries.values())):
return ['invalid NAVTEX heading entries']
heading = pattern.format_map(entries).upper()
issued = order['issued_utc']
else:
message_id = context['message_id']
heading = context['category_line']
issued = context['datetime_utc']
stamp = datetime.strptime(issued, '%Y-%m-%dT%H:%MZ')
expected_time = f'{stamp.day:02d}{stamp.hour:02d}{stamp.minute:02d} UTC {MONTHS[stamp.month-1]} {stamp.year % 100:02d}'
except (KeyError, TypeError, ValueError, AttributeError):
return ['invalid NAVTEX dispatch fields']
expected = {'message_id': message_id, 'datetime': expected_time, 'category_line': heading}
# The fixed-field scorer collapses whitespace in the transmitted text.
if all(isinstance(fixed[k], str) and ' '.join(fixed[k].split()) == v for k, v in expected.items()):
return []
return ['NAVTEX input/reference fields differ']
def navtex_input_errors(row):
context=row.get('context',{});body=row.get('answer',{}).get('open_content','')
errors=navtex_header_errors(context,row.get('answer',{}).get('fixed_fields',{}))
if 'body_points' in context:errors.append('verbatim target-body input is not a semantic brief')
facts=context.get('semantic_facts')
if not isinstance(facts,dict) or not facts:
return errors+['missing NAVTEX semantic facts']
normalized=lambda value:' '.join(str(value).casefold().split())
def strings(value):
if isinstance(value,str):yield value
elif isinstance(value,dict):
for child in value.values():yield from strings(child)
elif isinstance(value,list):
for child in value:yield from strings(child)
input_text='\n'.join([row.get('question',''), *strings(context)])
if body and normalized(body) in normalized(input_text):
errors.append('complete reference body appears in model input')
try:
positions=[(p['first_coordinate'],p['second_coordinate']) for p in facts.get('reported_positions',[])]
if positions!=re.findall(COORDINATE_PAIR,body):errors.append('semantic positions differ from source reference')
cancellation=facts.get('cancellation',{})
ids=cancellation.get('prior_warning_ids',[])
if any(not isinstance(v,str) or not re.search(r'(?<!\d)'+re.escape(v)+r'(?!\d)',body) for v in ids):
errors.append('cancellation identifier absent from source reference')
if 'in_force_warning_ids' in facts and facts['in_force_warning_ids']!=re.findall(r'\b\d+/\d{2}\b',body):
errors.append('in-force warning list differs from source reference')
except (KeyError,TypeError):errors.append('malformed NAVTEX semantic facts')
return errors