"""Render visible prose using the Anagram corpus rules.""" from html import unescape from html.parser import HTMLParser import re import unicodedata import xml.etree.ElementTree as ET import mwparserfromhell from markdown_it import MarkdownIt from mwparserfromhell import nodes def word_count(text): return len(re.findall(r"\b\w+(?:['’]\w+)*\b", text, re.UNICODE)) def content_hint(text): # Single asterisks/underscores alone are deliberately insufficient evidence. evidence = r"(?m)^ {0,3}(?:#{1,6}\s|`{3,}|~{3,}|>\s|[-+*]\s+\S|\d+[.)]\s+\S)|\[[^\]\n]+\]\([^\n]+\)|\*\*\S[^\n]*?\*\*|__\S[^\n]*?__" return "markdown" if re.search(evidence, text) else "plain_text" MIN_TABLE_ROWS = 3 MIN_TABLE_DELIMITERS = 2 def structural_ranges(text): """Locate display math, code fences and extracted table blocks in the input.""" lines = text.splitlines(keepends=True) starts, pos = [], 0 for line in lines: starts.append(pos) pos += len(line) starts.append(len(text)) ranges, i = [], 0 while i < len(lines): line = lines[i].strip() # Let CommonMark own fenced blocks, including their literal contents. fence = re.match(r"^(`{3,}|~{3,})(.*)$", line) if fence: marker = fence.group(1) j = i + 1 while j < len(lines) and not re.fullmatch( re.escape(marker[0]) + "{" + str(len(marker)) + r",}\s*", lines[j].strip(), ): j += 1 kind = ( "equation" if fence.group(2).strip().lower() in {"math", "latex", "tex"} else "code" ) ranges.append((starts[i], starts[min(j + 1, len(lines))], kind)) i = j + 1 continue closer = None if line.startswith("$$"): closer = "$$" elif line.startswith(r"\["): closer = r"\]" else: environment = re.match( r"^\\begin\{(equation\*?|align\*?|gather\*?|displaymath|eqnarray\*?)\}", line, ) if environment: closer = r"\end{" + environment.group(1) + "}" if closer: opening_len = 2 if line.startswith(("$$", r"\[")) else environment.end() j = i if closer not in line[opening_len:]: j += 1 while j < len(lines) and closer not in lines[j]: j += 1 ranges.append((starts[i], starts[min(j + 1, len(lines))], "equation")) i = j + 1 continue # Plain extracted tables: at least three adjacent delimiter/dot-leader rows. def table_row(s): return ( s.count("|") >= MIN_TABLE_DELIMITERS or s.count("\t") >= MIN_TABLE_DELIMITERS or bool(re.search(r"\.{4,}\s*\d", s)) ) if table_row(lines[i]): j = i + 1 while j < len(lines) and table_row(lines[j]): j += 1 if j - i >= MIN_TABLE_ROWS: ranges.append((starts[i], starts[j], "table")) i = j continue i += 1 return ranges _HTML = {"stack_exchange_answers", "se_202206", "stack_exchange_questions", "p_stackexchange"} _WIKI = {"wikibooks_english_2021", "wikibooks_20211201", "wikinews_english", "U02869", "creepypasta_wiki_2020", "creepypasta_2020"} _BLOCK = set("article aside blockquote br dd div dl dt h1 h2 h3 h4 h5 h6 hr li ol p section ul".split()) _SKIP = set("audio canvas figure footer form gallery head iframe map math nav noscript pre " "references script source style svg syntaxhighlight table template video".split()) _VOID = set("area base br col embed hr img input link meta param source track wbr".split()) _HTML_WRAPPER = re.compile(r"^\s*<(?:p|blockquote|pre|div|h[1-6]|ul|ol|table|hr|br)\b", re.I) _HTML_END = re.compile(r"\s*$", re.I) _KNOWN_QUOTES = {"cquote", "quote", "quotation", "blockquote", "quote box"} _BACK_MATTER = {"sources", "references", "external links", "related news", "see also", "further reading", "bibliography", "footnotes", "notes and references"} # Attached files, categories and interlanguage links render outside the prose. # A leading colon explicitly turns these back into ordinary visible links. _NON_ARTICLE_LINK = re.compile(r"^(?:file|image|media|category|special|[a-z]{2,3}(?:-[a-z]+)?):", re.I) _MAGIC = re.compile(r"__(?:NO(?:TOC|EDITSECTION|INDEX)|FORCETOC|TOC|INDEX)__", re.I) _URL = re.compile(r"(?i)\b(?:https?://|ftp://|www\.)[^\s<>\[\]{}]+") _STRUCTURE = re.compile(r"```|~~~|\$\$|\\(?:\[|begin\{)|\||\t|\.{4}") _MD = MarkdownIt("commonmark", {"html": True}).enable(["table", "strikethrough"]) _OPENSTAX = {"openstax_textbooks_2022", "openstax_2022"} _SCP = {"scp_wiki_tales", "scp_tales_wayback"} _WEATHER = {"nws_area_forecast_discussions", "U03275-archive"} _MEDQUAD = {"medquad_answers", "c_medquad_answers"} _REVIEW_HTML = {"amazon_reviews_2018", "amazon_reviews_2023", "food_com_reviews", "food_com", "ifdb_reviews", "ifdb_original"} _REDDIT = {"scruples_2019", "reddit_writingprompts_comments", "writingprompts_raw"} _MDN = {"mdn_web_docs_2022", "mdn_learn_2022"} _HANDBOOK = {"gitlab_handbook_2021", "c_gitlab_handbook_2021"} _MARKDOWN_SITES = _MDN | _HANDBOOK | {"kubernetes_blog", "U01143-blog"} _FRONT = re.compile(r"\A\ufeff?---[ \t]*\n(?=.*?^[\w-]+:[ \t])[^\x00]*?^---[ \t]*(?:\n|$)", re.M | re.S) _REVIEW_TAGS = re.compile(r"<(?:br\s*/?>|/?(?:p|a|b|i|strong|em|div|span|ul|ol|li)\b[^>]*>)", re.I) _CNXML_SKIP = {"metadata", "media", "figure", "table", "code", "preformat", "math", "equation", "label"} _CNXML_BLOCK = {"document", "title", "para", "section", "item", "note", "example", "definition", "problem", "solution", "meaning"} _NWS_DATE = re.compile(r"^\s*(?:issued at\s+)?[0-9:]{1,5}\s*(?:[AP]M|UTC|[A-Z]{2,4}T)\b", re.I) class _HTMLText(HTMLParser): """Stream fragments without limiting document size or constructing a DOM.""" def __init__(self): super().__init__(convert_charrefs=True) self.pieces = [] self.skip = [] def handle_starttag(self, tag, attrs): if self.skip: if tag == self.skip[-1]: self.skip.append(tag) return attrs = dict(attrs) if tag in _SKIP or "hidden" in attrs or attrs.get("aria-hidden") == "true": self.pieces.append("\n\n") if tag not in _VOID: self.skip.append(tag) elif tag in _BLOCK: self.pieces.append("\n\n") def handle_endtag(self, tag): if self.skip: if tag == self.skip[-1]: self.skip.pop() elif tag in _BLOCK: self.pieces.append("\n\n") def handle_data(self, data): if not self.skip: self.pieces.append(data) def _html_text(body): parser = _HTMLText() parser.feed(body) parser.close() return "".join(parser.pieces) def _openstax_text(body): """The released body is the complete CNXML module, including administrative XML.""" try: root = ET.fromstring(body) except ET.ParseError: return "" pieces = [] def visit(node): tag = node.tag.rsplit("}", 1)[-1] if tag in _CNXML_SKIP: return boundary = "\n\n" if tag in _CNXML_BLOCK else "" pieces.extend((boundary, node.text or "")) for child in node: visit(child) pieces.append(child.tail or "") pieces.append(boundary) visit(root) return re.sub(r"(?m)^[ \t]+|[ \t]+$", "", "".join(pieces)) def _wikidot_text(body): # Remove voting, CSS, credits and layout. The words between text-bearing # span, tab and collapsible directives belong to the story. body = re.sub(r"\[!--.*?(?:--\]|$)", "", body, flags=re.S) body = re.sub(r"\[\[include\b[^\]]*?component:license-box(?:[\s<\]]|$).*?\[\[include\b[^\]]*?component:license-box-end[^\]]*\]\]", "", body, flags=re.I | re.S) body = re.sub(r"\[\[(module\s+CSS|code)(?:\s[^\]]*)?\]\].*?\[\[/(?:module|code)\]\]", "", body, flags=re.I | re.S) body = re.sub(r"\[\[html\]\](.*?)\[\[/html\]\]", lambda m: _html_text(m[1]), body, flags=re.I | re.S) body = re.sub(r"(?m)^[ \t=]*(?:\[\[size[^\]\n]*\]\]\s*)?(?:\*\*)?<<[^\n]*?>>" r"(?:\*\*)?(?:\[\[/size\]\])?[ \t]*$", "", body) body = re.sub(r"\[\[\[([^\[\]]*?)\]\]\]", lambda m: m[1].split("|",1)[-1].strip(), body) body = re.sub(r"\[\[[^\[\]]*\]\]+", "", body) body = re.sub(r"(?m)^[ \t]*(?:@@[ \t]*@@|\])+[ \t]*$", "", body) # Some Wikidot source exports store external URLs inside actual anchor tags. if re.search(r"<(?:a\s|/?div\b|br\b)", body, flags=re.I): body = _html_text(body) body = re.sub(r"\[(?:\*?https?://[^\s\]]+)(?:\s+([^\]]+))?\]", lambda m: m[1] or "", body) body = re.sub(r"(?im)^[ \t]*(?:\++[ \t]+|>+[ \t]?|[-=]{3,}[ \t]*$)", "", body) body = re.sub(r"(?\- ]+(?:[A-Z]{2,4} [\d/<>\- ]+)*", s)): continue out.append(line.rstrip()) return "\n".join(out) def _site_markdown(source_id, body): if body.lstrip("\ufeff").startswith("---"): body = _FRONT.sub("", body, count=1) if source_id in _MDN: def macro(m): name = m[1].lower() args = re.findall(r'''["']([^"']+)["']''', m[2] or "") if args and (name.endswith("xref") or name in {"glossary", "htmlelement", "svgelement"}): return args[1] if name == "glossary" and len(args) > 1 else args[0] return "" body = re.sub(r"\{\{\s*([\w-]+)\s*(\([^{}]*\))?\s*\}\}", macro, body) elif source_id in _HANDBOOK: body = re.sub(r"(?im)^#{1,6} +On this page[ \t]*\n(?:\{:[^}\n]+\}[ \t]*\n)?\s*" r"[-*] +TOC[ \t]*\n\{:toc[^}\n]*\}", "", body) body = re.sub(r"<%.*?%>|(?m:^\s*\{:[^}\n]*\}[ \t]*$)", "", body, flags=re.S) if re.search(r"(?m)^\s*(?:= partial |[-=] (?:pages|data|[\w.]+\.each)\b|%(?:div|p|li|ul)\b)", body): # Unrendered Haml mixes Ruby expressions and declarations with text. # The publisher did not ship the evaluated page in the corpus. return "" else: body = re.sub(r"\{\{[<%].*?[%>]\}\}", "", body, flags=re.S) # A few historical posts wrap the URL of an inline image across lines. body = re.sub(r"!\[([^\]\n]*)\]\(([^()\s]+)\n[ \t]*([^()\s]+)\)", r"![\1](\2\3)", body) return body def _wiki_text(code): pieces = [] skipped_level = None for node in code.nodes: if isinstance(node, nodes.Heading): if skipped_level is not None and node.level > skipped_level: continue title = _wiki_text(node.title).strip() skipped_level = node.level if title.casefold() in _BACK_MATTER else None if skipped_level is None: pieces.extend(("\n\n", title, "\n\n")) elif skipped_level is not None: continue elif isinstance(node, nodes.Text): pieces.append(str(node)) elif isinstance(node, nodes.HTMLEntity): pieces.append(node.normalize()) elif isinstance(node, nodes.Wikilink): title = str(node.title).strip() if not _NON_ARTICLE_LINK.match(title): pieces.append(_wiki_text(node.text) if node.text is not None else title.lstrip(":").replace("_", " ")) elif isinstance(node, nodes.ExternalLink): if node.title: pieces.append(_wiki_text(node.title)) elif isinstance(node, nodes.Template): name = str(node.name).strip().casefold() # The Wikinews {{w|Wikipedia page|visible label}} link is frequent # inside sentences. Its first argument is displayed if unlabeled. if name == "w": params = ("2", "1") elif name in _KNOWN_QUOTES: params = ("text", "quote", "quotetext", "1") else: continue for param in params: if node.has(param, ignore_empty=True): pieces.append(_wiki_text(node.get(param).value)) break elif isinstance(node, nodes.Tag): tag = str(node.tag).strip().casefold() if tag in _SKIP or tag in {"ref", "timeline", "score", "imagemap"}: pieces.append("\n\n" if tag != "ref" else "") else: boundary = "\n\n" if tag in _BLOCK else "" pieces.extend((boundary, _wiki_text(node.contents) if node.contents else "", boundary)) return "".join(pieces) def _markdown_text(body): pieces = [] in_table = False for token in _MD.parse(body): if token.type in {"table_open", "table_close"}: in_table = token.type == "table_open" elif token.type == "html_block" and not in_table: pieces.extend(("\n\n", _html_text(token.content), "\n\n")) elif token.type == "inline" and not in_table: pieces.append("\n\n") for inline in token.children: if inline.type in {"text", "code_inline"}: pieces.append(inline.content) elif inline.type in {"softbreak", "hardbreak"}: pieces.append("\n") elif inline.type == "html_inline" and re.fullmatch(r"", inline.content, re.I): pieces.append("\n") return "".join(pieces) def document_text(source_id: str, body: str | None) -> str: """Render document prose, preserving section order and inline link labels.""" if not body: return "" text = unicodedata.normalize("NFC", body) if "\r" in text: text = text.replace("\r\n", "\n").replace("\r", "\n") if source_id == "google_local_2021" and text.lstrip().lower().startswith("(translated by google)"): # Only the original can contribute human-authored words. An absent # original leaves no recoverable human review. parts = re.split(r"(?:^|\n)\s*\(original\)\s*", text, maxsplit=1, flags=re.I) text = parts[1] if len(parts) == 2 else "" if source_id in _OPENSTAX: text = _openstax_text(text) elif source_id in _SCP: text = _wikidot_text(text) elif source_id in _WEATHER: text = _weather_text(text) elif source_id in _MEDQUAD: text = "\n".join(line.strip() for line in text.splitlines()) text = re.sub(r" {3,}-[ \t]+", "\n- ", text) elif source_id in _WIKI: if re.match(r"\s*#redirect\b", text, re.I): return "" text = _MAGIC.sub("", _wiki_text(mwparserfromhell.parse(text))) elif (("<" in text and source_id in _REVIEW_HTML and _REVIEW_TAGS.search(text)) or (_HTML_WRAPPER.match(text) and (source_id in _HTML or _HTML_END.search(text)))): text = _html_text(text) else: if source_id in _MARKDOWN_SITES: text = _site_markdown(source_id, text) if (source_id in _REVIEW_HTML or source_id in _REDDIT) and "&" in text: text = unescape(text) # Most released reviews are a short plain paragraph. Avoid multiple # regex scans of the billion-row review sources in that case. if (source_id in _REVIEW_HTML or source_id == "google_local_2021") and not any( marker in text for marker in ("\n", "\t", "|", "`", "~", "$", "\\", "....", "[", "**", "__", "://", "www.", "WWW.") ) and not text.lstrip().startswith(("#", ">", "- ", "* ", "+ ")): return text.strip() if _STRUCTURE.search(text): parts, end = [], 0 for start, stop, _ in structural_ranges(text): parts.extend((text[end:start], "\n\n")) end = stop if parts: text = "".join(parts) + text[end:] if source_id in _MARKDOWN_SITES or source_id == "lib_reviews" or content_hint(text) == "markdown": text = _markdown_text(text) elif source_id in _HTML and "&" in text: text = unescape(text) if "://" in text or "www." in text.lower(): text = _URL.sub("", text) if "\n" in text: text = re.sub(r"\n(?:[ \t]*\n)+", "\n\n", text) return text.strip() def source_origins(raw, rendered, source_id): """Map retained prose to raw Unicode offsets. Unverified positions are None.""" import regex # NFC and CRLF normalization are the first two corpus operations. if unicodedata.is_normalized("NFC", raw) and "\r" not in raw: text = raw origins = [(i, i + 1) for i in range(len(raw))] else: parts, origins = [], [] for m in regex.finditer(r"\X", raw): part = unicodedata.normalize("NFC", m[0]).replace("\r\n", "\n").replace("\r", "\n") parts.append(part) if part == m[0]: origins.extend((i, i + 1) for i in range(*m.span())) else: origins.extend([m.span()] * len(part)) text = "".join(parts) if rendered == text.strip(): left = len(text) - len(text.lstrip()) return origins[left:left + len(rendered)] mapped = [None] * len(rendered) if not rendered: return mapped # Replay the actual parser with unique word-end markers. Only surviving # markers can identify a source word. Repeated text in hidden markup is # therefore distinct from the identical words that the parser displayed. delimiter = "\ue000" while delimiter in text or delimiter in rendered: delimiter += "\ue000" marker = re.compile(re.escape(delimiter) + r"([0-9]+)" + re.escape(delimiter)) candidates = re.compile(r"<[^<>\n]*>|&(?:#\w+|\w+);|(?P[^\W_]+)") visible_words = set(re.findall(r"[^\W_]+", rendered)) words, pieces, cursor = [], [], 0 for match in candidates.finditer(text): if match.lastgroup != "word" or match[0] not in visible_words: continue pieces.extend((text[cursor:match.end()], f"{delimiter}{len(words)}{delimiter}")) words.append(match) cursor = match.end() pieces.append(text[cursor:]) marked = document_text(source_id, "".join(pieces)) if marker.sub("", marked) != rendered: return mapped anchors, removed = [], 0 for match in marker.finditer(marked): word = words[int(match[1])] end = match.start() - removed start = end - len(word[0]) removed += len(match[0]) if start >= 0 and rendered[start:end] == word[0]: mapped[start:end] = origins[word.start():word.end()] anchors.append((start, end, word.start(), word.end())) # Gaps project only when the source slice is literal or consists of # exactly the visible text plus HTML entity substitutions. prev_end = prev_raw = 0 for start, end, left, right in [*anchors, (len(rendered), len(rendered), len(text), len(text))]: if prev_end < start and prev_raw <= left: gap = text[prev_raw:left] if gap == rendered[prev_end:start]: mapped[prev_end:start] = origins[prev_raw:left] elif "&" in gap and unescape(gap) == rendered[prev_end:start]: values, spans, pos = [], [], prev_raw for entity in re.finditer(r"&(?:#[xX][\da-fA-F]+|#\d+|\w+);", gap): a, b = prev_raw + entity.start(), prev_raw + entity.end() values.extend((text[pos:a], unescape(entity[0]))) spans.extend(origins[pos:a]) spans.extend([(origins[a][0], origins[b - 1][1])] * len(unescape(entity[0]))) pos = b values.append(text[pos:left]) spans.extend(origins[pos:left]) if "".join(values) == rendered[prev_end:start]: mapped[prev_end:start] = spans prev_end, prev_raw = end, right return mapped