"""Conservative high-precision removal, strict document selection. Never generate replacement prose.""" import re,collections,hashlib import trial_clean_rules as base VERSION='books_strict_clean_v1_20261205' HELD_SOURCES={'common-pile/doab_filtered','common-pile/library_of_congress_filtered','common-pile/pre_1929_books_filtered'} 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|Primary Navigation|Toggle navigation|Page ID|Table of contents)\s*$',re.I) ATTR=re.compile(r'(?im)^[ \t]*(?:#{1,6}[ \t]*)?(?:Contributors and Attributions|Media Attributions|Licenses and Attributions|Image Attributions|Contributors|Attributions)[ \t]*$') TRANS_HEAD=re.compile(r"(?im)^[ \t|+#*_\[\]-]*(?:TRANSCRIBER[’']?S?)[ \t]+(?:NOTES?|CORRECTIONS)(?:[ \t:]|\n|$)") PG_HEAD=re.compile(r'(?is)^\s*(?:The Project Gutenberg (?:eBook|Etext) of|This eBook is for the use of anyone anywhere|This etext was|E-text prepared by)') CREDIT=re.compile(r'(?is)^\s*(?:(?:This eBook was |E-text )?(?:[Pp]roduced|[Pp]repared) by[: ]|[^\n]{0,120}\bOnline Distributed Proofreading Team[^\n]*$)') ADS=re.compile(r"(?im)^[ \t]*(?:[A-Z][A-Z '&\u2019.-]{2,75}(?:BOOKS|STORIES|SERIES)|.*(?:GROSSET\s*&\s*DUNLAP|GROSSET AND DUNLAP)|.*Great Books at Little Prices|Send [Ff]or [Oo]ur [Ff]ree [Ii]llustrated [Cc]atalog[^\n]*|[^\n]{0,80}By Mail, from the Publishers, on Receipt of Price[^\n]*)$") SUSP_AD=re.compile(r'(?i)send for (?:our|a|free).{0,50}catalog|may be had wherever books are sold|on receipt of (?:the )?price|all booksellers|price[,: ]+\$[0-9]|postpaid[, .]|Grosset\s*&\s*Dunlap|cheap(?:est)? publishing|great books at little prices') CAT_TITLE=re.compile(r'(?i)^Index of the Project Gutenberg Works|^(?:Index|Table of Contents) (?:of|to)\b|\b(?:type[- ]?book|type specimens?|professional development catalog)\b') FRAG=re.compile(r'(?i)The person charging this material|The Institute has attempted to obtain|selected template will load here|This action is not available') FORMULA_PATTERNS=[ re.compile(r'\\\([\s\S]*?\\\)'),re.compile(r'\\\[[\s\S]*?\\\]'),re.compile(r'\$\$[\s\S]*?\$\$'), re.compile(r'\[latex\][\s\S]*?\[/latex\]',re.I),re.compile(r'<(?:sup|sub)\b[^>]*>[\s\S]*?',re.I)] def sha(s):return hashlib.sha256(s.encode()).hexdigest() def clean(text,repo,title): """All offsets in ORIGINAL input Markdown; only deletions, with immutable removed text.""" _,initial=base.clean(text,repo,title) spans=[(x['start'],x['end'],r) for x in initial for r in x['reasons']] # Separate explicit fences/inline maths; indentation alone isn't enough to protect printer boilerplate. protected=[] for a,b in base.protected_spans(text): segment=text[a:b] if segment.lstrip().startswith(('```','~~~','\\(','\\[','$$','[latex]','x for x,y in protected):return spans.append((a,b,reason)) ps=base.paragraphs(text) # Exact web toolbar/empty layout list markers, not exercise numbering or legitimate code. offset=0 for line in text.splitlines(keepends=True): if UI.fullmatch(line.rstrip('\n')):add(offset,offset+len(line),'web_toolbar') if line.strip() in ('-','*') and 'gutenberg' not in repo:add(offset,offset+len(line),'empty_list_marker') offset+=len(line) # Source title duplicated in added H1 wrapper; retain metadata and wrapper title. first=re.match(r'\s*([^\n]+)\n',text) if first and first[1].strip()==str(title).strip(): add(0,first.end(),'duplicate_source_title_line') if 'gutenberg' in repo: for i,(a,b,p) in enumerate(ps): st=p.strip() if a<12000: if PG_HEAD.search(p) and len(p)<5000:add(a,b,'gutenberg_distribution_notice',True) if CREDIT.search(p) and len(p)<2200:add(a,b,'production_attribution_to_sidecar',True) if re.match(r'(?i)^(?:Release Date:|Language:|Character set encoding:|\[Most recently updated:)',st) and len(p)<700: add(a,b,'ebook_release_metadata',True) if a<15000 and base.TRANS.search(p[:220]) and len(p)<6000 and base.TRANS_LINE.search(p): add(a,b,'front_transcriber_note',True) # End-of-file editorial transcription notes, strict heading anchored and positioned. for match in TRANS_HEAD.finditer(text): start=match.start() if start>len(text)*.80 and len(text)-start<25000: tail=text[start:] if base.TRANS_LINE.search(tail) and not re.search(r'(?im)^\s*(?:#{1,6}\s+)?CHAPTER\s+[IVX0-9]+',tail): add(start,len(text),'end_transcriber_note',True) elif start<10000: # Notes split across paragraphs; consume only note-like blocks, bounded. blockidx=next((i for i,(a,b,p) in enumerate(ps) if a<=start6000 or len(p)>2200 or not base.TRANS_LINE.search(p):break if re.search(r'(?im)^\s*(?:#{1,6}\s+)?(?:CHAPTER|PREFACE|CONTENTS)\b',p):break end=b add(start,end,'front_transcriber_note',True) # Book-ending advertising blocks with concrete ad markers; if not removable with confidence, assess quarantines. for match in ADS.finditer(text): a=match.start() if a>len(text)*.75 and len(text)-a<60000 and SUSP_AD.search(text[a:]): # Start at this isolated paragraph, never backtrack into narrative. pa=next((x for x,y,p in ps if x<=a=len(text)*.55: add(m.start(),len(text),'attribution_and_media_tail_to_sidecar',True);break # Generic site-wide call-to-action, whole exact lines only. for m in re.finditer(r'(?im)^.*Want to create or adapt books like this\?.*(?:\n|$)',text): if len(m[0])<600:add(m.start(),m.end(),'pressbooks_site_promotion') # Clearly labelled absent graphical resources have captions retained except empty interactive buttons. for m in re.finditer(r'(?im)^[ \t]*(?:Multiple Choice|Drag and Drop|Fill in the Blank|Link to Learning)[ \t]*\n',text): if len(text)-m.end()<2500:add(m.start(),m.end(),'empty_interactive_heading') spans.sort();merged=[] for a,b,r in spans: if merged and a<=merged[-1]['end']: merged[-1]['end']=max(b,merged[-1]['end']);merged[-1]['reasons'].add(r) else:merged.append({'start':a,'end':b,'reasons':{r}}) parts=[];rem=[];p=0 for x in merged: parts.append(text[p:x['start']]);s=text[x['start']:x['end']] rem.append({'start':x['start'],'end':x['end'],'reasons':sorted(x['reasons']),'text':s,'sha256':sha(s)}) p=x['end'] parts.append(text[p:]);out=''.join(parts) # Preserve nonremoved exact text; reversibility checked in processor. return out,rem def assess(text,title,repo,removed,meta): reasons,flags,metrics=base.assess(text,title,repo) if repo in HELD_SOURCES:reasons.append('source_extraction_quality_hold') if CAT_TITLE.search(title):reasons.append('index_catalogue_or_type_specimen_not_body') if len(text.strip())<600 or len(re.findall(r'[A-Za-z]{2,}',text))<100:reasons.append('short_or_low_standalone_body') # Narrow ASCII corruption flags; rare proper nouns alone are NOT a reject rule. if metrics.get('common_ocr_confusion_count',0)>=2:reasons.append('ocr_word_corruption') if FRAG.search(text):reasons.append('residual_template_or_scan_notice') if SUSP_AD.search(text):reasons.append('residual_publisher_promotion') if TRANS_HEAD.search(text):reasons.append('residual_transcriber_note') if re.search(r'(?i)(?:End of Project Gutenberg|Project Gutenberg License|www\.pgdp\.net|gutenberg\.org/(?:files|ebooks))',text): reasons.append('residual_ebook_wrapper') if repo.endswith('project_gutenberg_filtered'): if re.search(r'(?im)^\s*(?:Produced by|E-text prepared by|This eBook was produced)',text[:12000]): reasons.append('residual_production_wrapper') # Conservatively isolate substantial PDF-style repeated or incomplete paragraphs. if not base.POETRY.search(title) and metrics['nonadjacent_long_repeated_chars']>=400: reasons.append('long_repeated_prose_not_source_verified') else: # Reject technical extraction cases with escaped subscripts in maths, known corrupted encoding, or absent matrix/example. if re.search(r'\b(?:CaCO|H[23]PO|Na[23]CO)[234]',text):reasons.append('damaged_chemical_notation') if re.search(r'(?i)(?:we (?:write|obtain|get|have)|the following).{0,60}(?:matrix|equation).{0,50}(?:as follows|below|following)[:.]\s*\n(?!\s*(?:\\|\[latex|\$|\|))',text): reasons.append('possible_missing_equation_or_matrix') if re.search(r'\\_[{A-Za-z0-9]|¼|þ',text):reasons.append('uncertain_formula_markup') if re.search(r'\b(?:Incomplete|Not available)\b',text[:300],re.I):reasons.append('incomplete_source') if re.search(r'(?:\b(?:is|that|the|a|an|of|to|and|for|with|following|where|by)|[,:;])\s*\Z',text): reasons.append('abrupt_incomplete_ending') if re.search(r'(?i)all rights reserved|CC.BY.NC|Attribution.Non.Commercial|this translation is by',text): reasons.append('embedded_rights_scope_unresolved') if metrics['nonadjacent_long_repeated_chars']>=300:reasons.append('repeated_prose_requires_primary_source') if re.search(r'(?i)FOR PEER REVIEW||selected template|This action is not available',text):reasons.append('extraction_or_boilerplate_residue') if not base.POETRY.search(title) and metrics.get('short_lowercase_fragments',0)>2:reasons.append('unresolved_fragmented_layout') # Fresh quality decision is selection, not guessed OCR rewrite. return sorted(set(reasons)),flags,metrics