"""Bounded edit lattice: preserve all literal context, accept multiple local repairs. No word-count, readability or keyword reward. Unicode NFC and whitespace are normalised; capitalisation, punctuation, words and all facts remain significant. """ import re,unicodedata def tokens(text): if not isinstance(text,str):return None return tuple(re.findall(r'\w+|[^\w\s]',unicodedata.normalize('NFC',text),re.UNICODE)) def lattice(text,segments,allow_source=True): got=tokens(text) if got is None or len(got)>3000:return 0.0 # Position -> best number of corrected slots at that position. Dynamic programming # avoids regex backtracking and handles alternatives with overlapping prefixes. states={0:0};count=0 for segment in segments: if isinstance(segment,str):options=[(tokens(segment),0)] else: count+=1;options=[(tokens(v),1) for v in segment['good']] if allow_source and 'bad' in segment:options.append((tokens(segment['bad']),0)) nxt={} for pos,score in states.items(): for seq,credit in options: end=pos+len(seq) if got[pos:end]==seq:nxt[end]=max(nxt.get(end,-1),score+credit) states=nxt if not states:return 0.0 return states.get(len(got),0)/count if count else float(len(got) in states) def edit_quality(answer,args): try: if not isinstance(answer,dict) or set(answer)!={'documents'}:return 0.0 docs=answer['documents'] if not isinstance(docs,dict) or set(docs)!=set(args['ids']):return 0.0 if any(not isinstance(v,str) for v in docs.values()):return 0.0 return lattice(docs[args['id']],args['segments']) except (KeyError,TypeError,ValueError,AttributeError):return 0.0