datax-open / docs /books-markdown-processing /format_markdown.py
xytpai's picture
Expand books to full six-source corpus with programmatic Markdown, audited JSONL and preserved formulas
0b8a041 verified
Raw History Blame Contribute Delete
12.6 kB
"""Conservative deterministic formatting; never infer missing table cells or rewrite words."""
import re,html,collections,statistics
from lxml import html as LH
VERSION="conservative_markdown_v3_20261205"
FENCE=re.compile(r"^ {0,3}(`{3,}|~{3,})([^\n]*)")
STRUCTURE=re.compile(r"^(?:CHAPTER|PART|BOOK|SECTION|ACT|SCENE|APPENDIX)\s+(?:[IVXLCDM]{1,12}|\d{1,4}|[A-Z]|ONE|TWO|THREE|FOUR|FIVE|SIX|SEVEN|EIGHT|NINE|TEN)(?:[.:\-—]?(?:\s+.{0,100})?)$",re.I)
NAMED=re.compile(r"^(?:PREFACE|FOREWORD|INTRODUCTION|PROLOGUE|EPILOGUE|CONCLUSION|CONCLUSIONS|ACKNOWLEDGMENTS|ACKNOWLEDGEMENTS|BIBLIOGRAPHY|REFERENCES|GLOSSARY|INDEX|CONTENTS|TABLE OF CONTENTS|AFTERWORD|APPENDIX|APPENDICES)(?:[.:])?$",re.I)
POETRY=re.compile(r"\b(poem|poems|poetry|verse|verses|sonnets?|lyrics?|songs?|hymns?|plays?|dramas?|epics?|tragedy|comedy|shakespeare|psalms?)\b",re.I)
INLINE=re.compile(r"(`+)[^\n]*?\1|\\\([\s\S]*?\\\)|(?<!\\)\$[^$\n]+\$")
MATH_START=re.compile(r"^\s*(?:\$\$|\\\[|\\begin\{(?:equation\*?|align\*?|gather\*?|displaymath|verbatim|lstlisting|tikzpicture)\})")
def prose_unwrap(block,poetry,edits):
if poetry or any(c in block for c in ("\\","`","|","\t","<",">","$","=","{","}")):return block
if re.search(r"\b\d+:\d+\b",block):return block
lines=block.splitlines(keepends=True)
if len(lines)<4 or len(block)<450:return block
if any(l.startswith((" ","\t","#",">")) or l.rstrip("\n").endswith(" ") for l in lines):return block
if any(re.match(r"^(?:[-*+•●▪]\s|\d+[.)]\s|[A-Z]:\s)",l) for l in lines):return block
longlines=[l.rstrip("\n") for l in lines if 55<=len(l.rstrip("\n"))<=95]
if len(longlines)<len(lines)*.7:return block
if sum(c.isalpha() or c.isspace() or c in ".,;:!?\"'’“”‘()-—" for c in block)<len(block)*.97:return block
out=[]
for i,l in enumerate(lines):
stripped=l.rstrip("\n")
if i+1<len(lines) and l.endswith("\n"):
nxt=lines[i+1]
# Only a clear lowercase continuation; keep every other newline, including paragraph starts.
if (55<=len(stripped)<=95 and len(stripped.split())>=9 and
re.match(r"[a-z]",nxt) and len(nxt.rstrip("\n"))>=25 and
not stripped.endswith(("-","‐","‑","\u00ad")) and
not re.search(r"[.!?:][\"’”']?\s*$",stripped)):
out.append(stripped+" ");edits["prose_hardwraps_joined"]+=1;continue
out.append(l)
joined="".join(out)
assert joined.split()==block.split()
return joined
def heading_candidate(st):
if NAMED.fullmatch(st):return True
if not st[:1].isupper():return False
if len(re.findall(r"\b(?:CHAPTER|PART|BOOK|SECTION|ACT|SCENE|APPENDIX)\b",st,re.I))>1:return False
if any(c in st for c in ("\\","*","[","]","$","=")):return False
ident=r"(?:[IVXLCDM]{1,12}|\d{1,4}|[A-Z]|ONE|TWO|THREE|FOUR|FIVE|SIX|SEVEN|EIGHT|NINE|TEN)"
m=re.fullmatch(r"(?i)(CHAPTER|PART|BOOK|SECTION|ACT|SCENE|APPENDIX)\s+("+ident+r")(?=$|[.\s:—-])(.*)",st)
if not m:return False
tail=m.group(3).strip()
if m.group(1).lower()=="section" and tail not in ("", ".", ":"):return False
if not tail or tail in (".",":"):return True
if re.match(r"^[.:—-]\s*[A-Z]",tail) and len(tail)<=90:return True
if tail.isupper() and len(tail)<=90 and not tail[-1:].isdigit():return True
return False
def inline_html(text,edits):
# Protect inline code/math, and leave subscripts/superscripts as valid inline HTML.
saved=[]
def protect(m):
saved.append(m.group());return f"\x00KEEP{len(saved)-1}\x00"
text=INLINE.sub(protect,text)
for tags,mark in [(r"(?:strong|b)","**"),(r"(?:em|i)","*")]:
pattern=re.compile(rf"<{tags}\s*>([^<\n]+)</{tags}\s*>",re.I)
text,n=pattern.subn(lambda m:mark+m.group(1)+mark,text)
if n:edits["html_emphasis"]+=n
def link(m):
url=html.unescape(m.group(2));label=html.unescape(m.group(3))
if not re.match(r"https?://|mailto:|#",url):return m.group()
if any(c in label for c in "[]\n") or any(c in url for c in "\n<>"):return m.group()
edits["html_links"]+=1
return "["+label+"]("+url.replace(" ","%20").replace(")","%29")+")"
text=re.sub(r'<a\s+href=(["\'])(.*?)\1\s*>([^<]+)</a\s*>',link,text,flags=re.I)
for i,v in enumerate(saved):text=text.replace(f"\x00KEEP{i}\x00",v)
return text
def simple_table(m,edits):
raw=m.group()
try:
t=LH.fromstring(raw)
if t.tag.lower()!="table" or t.xpath(".//table|.//pre|.//code|.//math|.//script|.//style|.//img"):return raw
rows=t.xpath(".//tr")
if not 2<=len(rows)<=200:return raw
data=[]
for row in rows:
cells=row.xpath("./th|./td")
if not cells or any(c.get("rowspan","1")!="1" or c.get("colspan","1")!="1" for c in cells):return raw
vals=[]
for c in cells:
if len(c) or "\n" in (c.text or "").strip():return raw
text=(c.text or "").strip()
if any(x in text for x in ("\\","`","$")):return raw
vals.append(text.replace("|",r"\|"))
data.append(vals)
width=len(data[0])
if not 1<width<=16 or any(len(row)!=width for row in data):return raw
caption=t.xpath("./caption")
if caption and (len(caption)>1 or len(caption[0])):return raw
first_header=all(c.tag.lower()=="th" for c in rows[0].xpath("./th|./td"))
output=[]
if caption:output.append((caption[0].text or "").strip()+"\n")
if first_header:output.append("| "+" | ".join(data.pop(0))+" |")
else:output.append("| "+" | ".join([""]*width)+" |")
output.append("| "+" | ".join(["---"]*width)+" |")
output.extend("| "+" | ".join(row)+" |" for row in data)
edits["simple_html_tables"]+=1
return "\n\n"+"\n".join(output)+"\n\n"
except Exception:return raw
def html_blocks(text,edits):
if "<" not in text:return text
preserved=[];literal=[]
def keep_literal(m):
literal.append(m.group());return f"\x00LIT{len(literal)-1}\x00"
text=INLINE.sub(keep_literal,text)
def pre(m):
inside=m.group(1)
if re.search(r"<(?!/?code\b)[A-Za-z]",inside):return m.group()
inside=re.sub(r"^<code(?:\s+class=['\"]language-[\w+-]+['\"])?\s*>|</code\s*>$","",inside,flags=re.I)
inside=html.unescape(inside)
runs=re.findall(r"`+",inside);fence="`"*max(3,max((len(x)+1 for x in runs),default=3))
edits["html_pre_to_fenced_code"]+=1
preserved.append("\n\n"+fence+"\n"+inside+("\n" if not inside.endswith("\n") else "")+fence+"\n\n")
return f"\x00PRE{len(preserved)-1}\x00"
# Convert pre separately, then protect generated fences from all later formatting.
text=re.sub(r"<pre\s*>([\s\S]*?)</pre\s*>",pre,text,flags=re.I)
text=re.sub(r"<table\b[^>]*>[\s\S]*?</table\s*>",lambda m:simple_table(m,edits),text,flags=re.I)
def heading(m):
edits["html_headings"]+=1
return "\n\n"+"#"*max(2,int(m.group(1)))+" "+html.unescape(m.group(2).strip())+"\n\n"
text=re.sub(r"<h([1-6])\s*>([^<\n]+)</h\1\s*>",heading,text,flags=re.I)
def para(m):
edits["html_paragraphs"]+=1
return "\n\n"+m.group(1)+"\n\n"
# Only plain paragraph contents; no inline formulas/unknown nested tags.
text=re.sub(r"<p\s*>([^<>]+)</p\s*>",para,text,flags=re.I)
# Keep <br> as valid inline HTML: uppercase BR may denote breathing rate in inequalities.
# Preserving it also avoids altering literal poem/work titles.
def lists(m):
tag=m.group(1).lower();inside=m.group(2)
items=re.findall(r"<li\s*>([^<>]+)</li\s*>",inside,flags=re.I)
remain=re.sub(r"<li\s*>[^<>]+</li\s*>","",inside,flags=re.I).strip()
if not items or remain:return m.group()
edits["html_lists"]+=1
return "\n\n"+"\n".join((f"{i}. " if tag=="ol" else "- ")+html.unescape(v.strip()) for i,v in enumerate(items,1))+"\n\n"
text=re.sub(r"<(ul|ol)\s*>([\s\S]*?)</\1\s*>",lists,text,flags=re.I)
for i,value in enumerate(preserved):text=text.replace(f"\x00PRE{i}\x00",value)
for i,value in enumerate(literal):text=text.replace(f"\x00LIT{i}\x00",value)
return text
def plain(text,poetry,edits,allow_html=True):
if allow_html and "|" not in text:text=html_blocks(text,edits)
# Pass fences created from HTML pre through untouched.
out=[];chunk=[];state=None
def flush():
if not chunk:return
segment="".join(chunk);chunk.clear()
blocks=re.split(r"(\n[ \t]*\n+)",segment)
for i in range(0,len(blocks),2):
b=blocks[i]
st=b.strip()
if not st:continue
# Avoid page-number TOC entries and preserve meaningful indentation.
if "\n" not in st and len(st)<=120 and not b.startswith((" ","\t","#")) and not re.search(r"\.{2,}|\s\d{2,}$",st):
if heading_candidate(st):
lead=b[:len(b)-len(b.lstrip())]
trail=b[len(b.rstrip()):]
blocks[i]=lead+"## "+st+trail
edits["plain_headings"]+=1
continue
if "|" not in b and not any(x in b for x in ("\\","`","$")):
b,n=(re.subn(r"(?m)^([ ]{0,3})[•●▪][ \t]+(?=[A-Za-z])",r"\1- ",b)
if len(re.findall(r"(?m)^[ ]{0,3}[•●▪][ \t]+(?=[A-Za-z])",b))>=2 else (b,0))
if n:edits["unicode_bullets"]+=n
b,n=(re.subn(r"(?m)^([ ]{0,3})(\d{1,3})\)[ \t]+(?=[A-Za-z])",r"\1\2. ",b)
if len(re.findall(r"(?m)^[ ]{0,3}\d{1,3}\)[ \t]+(?=[A-Za-z])",b))>=2 else (b,0))
if n:edits["numbered_list_markers"]+=n
if allow_html and "|" not in b:b=inline_html(b,edits)
blocks[i]=prose_unwrap(b,poetry,edits)
out.append("".join(blocks))
for l in text.splitlines(keepends=True):
f=FENCE.match(l)
if f:
flush();out.append(l)
if state is None:state=(f.group(1)[0],len(f.group(1)))
elif f.group(1)[0]==state[0] and len(f.group(1))>=state[1] and not f.group(2).strip():state=None
elif state:out.append(l)
elif l.startswith((" ","\t")):
flush();out.append(l)
else:chunk.append(l)
flush()
return "".join(out)
def transform(text,title=""):
edits=collections.Counter();out=[];buffer=[];fence=None;math=None;prebuffer=None
poetry=bool(POETRY.search(title))
# Educational source code is content, not markup to render. Conservative whole-record opt-out.
allow_html=not (re.search(r"<(?:!doctype|html|head|body|script|style)\b",text,re.I) or
(re.search(r"<[A-Za-z][^>]*>",text) and re.search(
r"\b(?:HTML|CSS|JavaScript|markup|web design|web accessibility|web page|source code|tags?|Pressbooks|digital humanities)\b",
title+"\n"+text,re.I)))
def flush():
if buffer:out.append(plain("".join(buffer),poetry,edits,allow_html));buffer.clear()
for l in text.splitlines(keepends=True):
f=FENCE.match(l)
if prebuffer is not None:
prebuffer.append(l)
if re.search(r"</pre\s*>",l,re.I):
out.append(plain("".join(prebuffer),poetry,edits,allow_html));prebuffer=None
elif not fence and not math and re.match(r"^ {0,3}<pre\s*>",l,re.I):
flush()
if re.search(r"</pre\s*>",l,re.I):out.append(plain(l,poetry,edits,allow_html))
else:prebuffer=[l]
elif fence:
out.append(l)
if f and f.group(1)[0]==fence[0] and len(f.group(1))>=fence[1] and not f.group(2).strip():fence=None
elif math:
out.append(l)
if (math=='$$' and '$$' in l) or (math=='\\]' and '\\]' in l) or (math.startswith('\\end') and math in l):math=None
elif f:
flush();out.append(l);fence=(f.group(1)[0],len(f.group(1)))
elif l.startswith((" ","\t")):
flush();out.append(l)
elif MATH_START.match(l):
flush();out.append(l)
if '$$' in l:
if l.count('$$')<2:math='$$'
elif '\\[' in l:
if '\\]' not in l:math='\\]'
else:
env=re.search(r'\\begin\{([^}]+)\}',l)
if env and '\\end{'+env[1]+'}' not in l:math='\\end{'+env[1]+'}'
else:buffer.append(l)
flush()
if prebuffer is not None:out.append("".join(prebuffer))
result="".join(out)
assert "\x00KEEP" not in result
return result,dict(edits)