"""Auditable English research preprocessing with original-character mapping.""" import re,unicodedata INVISIBLE=set('\u200b\u200c\u200d\u2060\ufeff\u00ad') def prepare(text, scope='all'): # Remove invisibles before grouping combining marks: otherwise an inserted # zero-width character can prevent canonical composition of accented letters. filtered=[(c,i,i+1) for i,c in enumerate(text) if c not in INVISIBLE] chars=[];mapping=[];i=0;changes=len(text)-len(filtered) while ibegin and out[end-1].isspace():end-=1 out=out[begin:end];orig=orig[begin:end] normalized=''.join(out) excluded=[] if scope=='body': hit=re.search(r'(?im)^\s*(?:#+\s*|[IVX\d]+[.)]?\s*)?(?:references|bibliography)\s*$',normalized) if hit:excluded.append({'start':hit.start(),'end':len(normalized),'reason':'reference_section'}) if scope not in ('all','body'):raise ValueError('scope must be all or body') end=excluded[0]['start'] if excluded else len(normalized) analysis=normalized[:end] sentences=[] for m in re.finditer(r'\S[\s\S]*?(?:[.!?](?=\s|$)|$)',analysis): if not m.group().strip():continue a,b=m.span() sentences.append({'start':a,'end':b,'original_start':orig[a][0],'original_end':orig[b-1][1],'text':m.group().strip()}) warnings=[] if len(analysis.split())<300:warnings.append('Under 300 words: limited context; treat interpretations as uncertain.') if re.search('[\u0370-\u03ff\u0400-\u04ff]',analysis):warnings.append('Greek/Cyrillic characters retained; no blanket homoglyph folding was applied.') return {'text':analysis,'sentences':sentences,'excluded':excluded,'scope':scope, 'original_characters':len(text),'normalized_characters':len(normalized),'analyzed_characters':len(analysis), 'words':len(analysis.split()),'normalization_changes':changes,'warnings':warnings, 'normalization':'NFKC per base/combining cluster, remove selected invisibles, collapse horizontal whitespace; retain paragraph breaks.'}