datax-open / docs /books-strict-processing /trial_clean_rules.py
xytpai's picture
Replace books with strict-cleaned quality-first subset; quarantine hard-to-repair source text
00b8e9c verified
Raw History Blame Contribute Delete
12.6 kB
"""Removal-only cleanup with reversible offsets. Quarantine is a review disposition, not proof of low quality."""
import re,collections,hashlib,unicodedata,functools
from wordfreq import zipf_frequency
VERSION='books_clean10pct_v2_20261205'
FENCE=re.compile(r'^ {0,3}(`{3,}|~{3,})([^\n]*)')
UI=re.compile(r'^\s*(?:[-*]\s*)?(?:selected template will load here|This action is not available\.|Last updated|Save as PDF|Expand/collapse global location|Back to top|Skip to main content)\s*$',re.I)
PG_START=re.compile(r'(?im)^ {0,3}\*{3}[ \t]*START OF (?:THE|THIS) PROJECT GUTENBERG[^\n]*\*{3}[ \t]*\n?')
PG_END=re.compile(r"(?im)^ {0,3}(?:\*{3}[ \t]*END OF (?:THE|THIS) PROJECT GUTENBERG[^\n]*|End of Project Gutenberg[’']s [^\n]*)")
PRODUCER=re.compile(r'(?is)^\s*(?:This eBook was )?(?:Produced|prepared) by\b')
TRANS=re.compile(r"(?i)transcriber[’']?s?\s+(?:note|notes|corrections)")
TRANS_LINE=re.compile(r"(?i)(?:transcriber|typos?|typograph|hyphenation|spelling|italic|bolded|proofread|original document|obvious printer|page\s+\d+|changed to|corrected|underscores|brackets|retained|e-?text|woodcut|illustration|end quotation|end quote|inconsistent|punctuation)")
LOAN=re.compile(r'(?is)^\s*The person charging this material is responsible for (?:its )?(?:return|renewal)')
FILM=re.compile(r'(?is)^\s*The Institute has attempted to obtain the best original copy available for filming')
POETRY=re.compile(r'\b(?:poems?|poetry|verses?|hymns?|songs?|plays?|dramas?|epics?|sonnets?|bible|psalms?|shakespeare|chaucer)\b',re.I)
TYPEBOOK=re.compile(r'\btype[- ]?book\b|\btype specimens?\b|\bspecimens? of (?:printing )?type\b',re.I)
MATH=re.compile(r'\\[A-Za-z]+|\\[\[(]|\$\$|\[latex\]|<su[bp]\b|[=∑∫√±≤≥∞]',re.I)
AD=re.compile(r"(?im)^[ \t]*(?:A FEW OF[ \t]*\n)?[ \t]*(?:GROSSET\s*&\s*DUNLAP[’']?S|GROSSET AND DUNLAP[’']?S|GREAT BOOKS AT LITTLE PRICES)[^\n]*")
def sha(s):return hashlib.sha256(s.encode('utf-8')).hexdigest()
def paragraphs(text):
spans=[];pos=0
for m in re.finditer(r'\n[ \t]*\n+',text):
if text[pos:m.start()].strip():spans.append((pos,m.start(),text[pos:m.start()]))
pos=m.end()
if text[pos:].strip():spans.append((pos,len(text),text[pos:]))
return spans
def protected_spans(text):
out=[];offset=0;state=None;start=0
for line in text.splitlines(keepends=True):
f=FENCE.match(line)
if state:
if f and f[1][0]==state[0] and len(f[1])>=state[1] and not f[2].strip():
out.append((start,offset+len(line)));state=None
elif f:
state=(f[1][0],len(f[1]));start=offset
elif line.startswith((' ','\t')):
# A boxed transcriber note is not executable code; still protected unless explicitly reviewed.
out.append((offset,offset+len(line)))
offset+=len(line)
if state:out.append((start,len(text)))
for pat in [r'\\\([\s\S]*?\\\)',r'\\\[[\s\S]*?\\\]',r'\$\$[\s\S]*?\$\$',r'\[latex\][\s\S]*?\[/latex\]',
r'(?i)<pre\b[^>]*>[\s\S]*?</pre>',r'(?i)<table\b[^>]*>[\s\S]*?</table>',r'`[^`\n]+`']:
out.extend((m.start(),m.end()) for m in re.finditer(pat,text))
return sorted(out)
def clean(text,repo,title):
protected=protected_spans(text);candidates=[];ps=paragraphs(text)
def add(a,b,reason,allow_protected=False):
if b<=a:return
if not allow_protected and any(a<y and b>x for x,y in protected):return
candidates.append((a,b,reason))
# Only exact UI strings, outside source code/math.
offset=0
for l in text.splitlines(keepends=True):
if UI.fullmatch(l.rstrip('\n')):add(offset,offset+len(l),'web_ui_template')
offset+=len(l)
if 'gutenberg' in repo:
m=PG_START.search(text[:min(len(text),40000)])
if m and m.end()<len(text)*.25:add(0,m.end(),'gutenberg_standard_header',True)
ms=list(PG_END.finditer(text))
if ms and ms[-1].start()>len(text)*.8:add(ms[-1].start(),len(text),'gutenberg_footer_or_license_to_sidecar',True)
for i,(a,b,p) in enumerate(ps):
if a<6000 and len(p)<1800 and PRODUCER.search(p) and re.search(r'Gutenberg|[Pp]roofread|pgdp|[Dd]istributed|eBook',p):
add(a,b,'production_credit_to_sidecar')
if 'gutenberg' in repo and a<6000 and len(p)<2500 and (
p.strip().lower().startswith('the project gutenberg ebook of ') or
p.strip().lower().startswith('this ebook is for the use of anyone anywhere') or
(p.strip().startswith(('Release Date:','[Most recently updated:','Language:')) and len(p)<600)):
add(a,b,'gutenberg_explicit_distribution_metadata',True)
if a<12000 and len(p)<2400 and LOAN.search(p):
add(a,b,'library_loan_notice')
if a<8000 and len(p)<2400 and FILM.search(p):
add(a,b,'microfilm_scanning_notice')
if ('gutenberg' in repo and (a<8000 or a>len(text)*.85) and TRANS.search(p[:200]) and len(p)<5000
and len(TRANS_LINE.findall(p))>=2):
add(a,b,'transcriber_note_to_sidecar',True)
# Standalone transcriber heading: remove only clearly matched subsequent note paragraphs, never following narrative.
if 'gutenberg' in repo and a>len(text)*.8 and re.fullmatch(r"[\s#*_\[\]:-]*transcriber[’']?s?\s+notes?[\s#*_\[\]:-]*",p,re.I):
end=b
for x,y,body in ps[i+1:i+7]:
if y-a>6000 or len(body)>2000 or not TRANS_LINE.search(body):break
if re.search(r'(?m)^#{1,6}\s+|\bCHAPTER\b',body):break
end=y
if end>b:add(a,end,'trailing_transcriber_notes_to_sidecar',True)
# Conservative publishers' advertisements at very end; never remove a catalogue as if it were fiction.
if not re.search(r'catalog|advertis|publishing|publisher|bibliograph',title,re.I):
for m in AD.finditer(text):
if m.start()<len(text)*.8 or len(text)-m.start()>25000:continue
tail=text[m.start():]
if re.search(r'(?i)price|\$\d|[0-9]\s*s[.]|booksellers|sent.*(?:mail|receipt)|may be had wherever books are sold',tail):
add(m.start(),len(text),'explicit_publisher_advertisement_tail',True);break
# Only long immediately adjacent exact prose repeats. Never poetry, equations, lists, quotes or repetitions at a distance.
if not POETRY.search(title) and not TYPEBOOK.search(title):
for (a,b,p),(x,y,q) in zip(ps,ps[1:]):
if p.strip()!=q.strip() or len(q.strip())<300:continue
if MATH.search(q) or re.search(r'(?m)^\s*(?:>|[-*+]\s|\d+[.)]\s)',q):continue
if q.lstrip().startswith(('"','“','‘',"'")) or q.count('\n')>len(q)/35:continue
add(x,y,'adjacent_exact_long_prose_duplicate')
# Merge spans. Removed text remains in a non-training sidecar with char coordinates.
candidates.sort()
merged=[]
for a,b,reason in candidates:
if merged and a<=merged[-1]['end']:
merged[-1]['end']=max(b,merged[-1]['end']);merged[-1]['reasons'].add(reason)
else:merged.append({'start':a,'end':b,'reasons':{reason}})
out=[];last=0;rem=[]
for x in merged:
out.append(text[last:x['start']]);raw=text[x['start']:x['end']]
rem.append({'start':x['start'],'end':x['end'],'reasons':sorted(x['reasons']),'text':raw,'sha256':sha(raw)})
last=x['end']
out.append(text[last:]);result=''.join(out)
# Reconstruction invariant (all retained characters and their order unchanged).
rebuilt=[];inpos=0;outpos=0
for x in rem:
keep=x['start']-inpos;rebuilt.append(result[outpos:outpos+keep]);rebuilt.append(x['text'])
outpos+=keep;inpos=x['end']
rebuilt.append(result[outpos:])
assert ''.join(rebuilt)==text
return result,rem
@functools.lru_cache(maxsize=200000)
def freq(word):return zipf_frequency(word,'en')
def assess(text,title,repo):
reasons=[];flags=[];metrics={'replacement_chars':text.count('\ufffd')}
if metrics['replacement_chars']>0:reasons.append('upstream_replacement_character')
# Inspect paragraphs for clearly broken formula encoding or character mapping, not non-Latin prose alone.
ps=paragraphs(text)
max_unusual=0;formula_bad=0
for a,b,p in ps:
if len(p)<120:continue
if p.count('¼')>=3 and p.count('þ')+p.count('ð')>=2 and MATH.search(p):formula_bad+=1
ext=sum('\u0180'<=c<='\u024f' or '\u0700'<=c<='\u074f' for c in p)
if ext>=35 and ext/len(p)>.035 and re.search(r'\b(?:the|and|of|in|to)\b',p,re.I):max_unusual=max(max_unusual,ext)
if formula_bad:reasons.append('suspected_formula_encoding_corruption')
if max_unusual:reasons.append('suspected_font_mapping_corruption')
metrics.update(formula_corrupt_blocks=formula_bad,font_corrupt_marker_max=max_unusual)
# Scientific superscript/subscript ambiguity: isolate for review; do not guess fix.
if re.search(r'\b(?:CaCO|H[23]PO|Na[23]CO)<sup>[234]</sup>',text):
reasons.append('suspected_chemical_subscript_as_superscript')
# Non-adjacent long literal repeated paragraphs aren't auto-deleted.
count=collections.Counter(p.strip() for _,_,p in ps if len(p.strip())>=300 and not MATH.search(p)
and not p.lstrip().startswith(('>','"','“',"'",'‘')))
dup=sum((n-1)*len(p) for p,n in count.items() if n>1)
metrics['nonadjacent_long_repeated_chars']=dup
if dup>=800 and dup/max(1,len(text))>=.03 and not POETRY.search(title) and not TYPEBOOK.search(title):
reasons.append('substantial_long_paragraph_repetition_requires_review')
elif dup:flags.append('long_paragraph_repetition_possible_legitimate_quote')
# Limited OCR risk screening for English prose only. Proper nouns/technical vocabulary => review, not definitive failure.
windows=[];unknowns=[];ratios=[]
if not POETRY.search(title):
for pos in sorted(set([0,max(0,len(text)//2-1800),max(0,len(text)-3600)])):
w=text[pos:pos+3600]
if MATH.search(w) or '|' in w or len(re.findall(r'\b\d+\b',w))>40:continue
words=re.findall(r'\b[A-Za-z]{3,}\b',w)
# Lowercase prose, ignore likely names and acronyms.
eligible=[v for v in words if v.islower()]
if len(eligible)<160:continue
bad=[v for v in eligible if freq(v)<1.0]
ratios.append(len(bad)/len(eligible));unknowns.extend(bad[:12])
metrics['prose_ocr_unknown_word_ratios']=ratios
metrics['ocr_example_low_frequency_words']=unknowns[:20]
if sum(x>.24 for x in ratios)>=2 or any(x>.40 for x in ratios):
reasons.append('suspected_dense_prose_ocr_dictionary_risk')
# Strong repeated OCR-confusion symptoms in old scans; do not auto-correct words.
ocr_words=re.findall(r'\b(?:tlie|tiie|wiien|wiiere|wbicli|througli|throngli|tliat|wliich|ujjon|liim|liis)\b',text,re.I)
metrics['distinct_common_ocr_confusions']=len(set(x.lower() for x in ocr_words))
metrics['common_ocr_confusion_count']=len(ocr_words)
if len(ocr_words)>=6 and metrics['distinct_common_ocr_confusions']>=3:
reasons.append('recurrent_common_word_ocr_confusions')
elif ocr_words:flags.append('occasional_ocr_word_confusions')
# Broken OCR numeric tables: isolate, never infer cell meanings. Math/rosters/alphabets aren't enough alone.
numeric_bad=0
for a,b,p in ps:
if not 150<=len(p)<=5000 or MATH.search(p) or re.search(r'(?i)alphabet|survivors|regiment|references',p):continue
if re.search(r'[A-Za-z0-9\]}][_^]\{[^}\n]+\}',p):
continue # Explicit TeX-style chemical/mathematical table, not gibberish.
words=re.findall(r'[A-Za-z]+',p)
if len(words)<30:continue
tiny=sum(len(x)<=2 for x in words)/len(words)
odd=sum(c in '^~■«»' for c in p)
digits=sum(c.isdigit() for c in p)
if tiny>.62 and odd>=4 and (digits>10 or sum(c.isupper() for c in p)>50):
numeric_bad+=1
metrics['broken_numeric_layout_blocks']=numeric_bad
if numeric_bad:reasons.append('suspected_unreadable_ocr_numeric_table')
# Symptoms of interleaved PDF extraction. Conservative flags unless several chopped fragments coexist.
fragments=[p.strip() for _,_,p in ps if 4<=len(p.strip())<=90 and p.strip()[0].islower()
and not MATH.search(p) and len(p.split())>=3 and not re.search(r'^\s*(?:[a-z]\)|https?://)',p)]
metrics['short_lowercase_fragments']=len(fragments)
if 'doab' in repo and len(fragments)>=5 and len(fragments)>len(ps)*.15 and len(text)<100000:
reasons.append('possible_pdf_reading_order_fragments')
elif len(fragments)>=3:
if dup>=300 and 'doab' in repo:reasons.append('combined_repetition_and_fragment_layout')
else:flags.append('fragment_layout_requires_spotcheck')
if re.search(r'(?i)selected template will load here|This action is not available',text):flags.append('remaining_ui_in_protected_context')
if re.search(r'(?i)\[illustration[^\]\n]*\]',text):flags.append('image_caption_or_placeholder_retained')
if re.search(r'(?i)Creative Commons Attribution Non.Commercial|CC.BY.NC',text):flags.append('embedded_nc_reference_not_automatic_license_conflict')
if len(text.strip())<200:reasons.append('too_little_standalone_text_after_cleanup')
elif len(re.findall(r'[A-Za-z]{2,}',text))<35 and not POETRY.search(title) and not MATH.search(text):reasons.append('low_standalone_text_content_review')
return sorted(set(reasons)),sorted(set(flags)),metrics