anagram-detectors / raw_offsets.py
Codex
Return a four-label partition of the original detector input
61556d6
Raw History Blame Contribute Delete
17.1 kB
"""Trace visible prose back to the input with half-open Unicode code-point offsets."""
import re
import unicodedata
from bisect import bisect_right
from html import unescape
from html.parser import HTMLParser
from markdown_it import MarkdownIt
from markdown_it.parser_inline import ParserInline
from markdown_it.rules_inline.state_inline import StateInline
import corpus_text as corpus
class View:
"""Sparse runs (display start/end, source start/end, linear). Insertions have no run."""
__slots__ = ("text", "runs")
def __init__(self, text, runs=()):
self.text, self.runs = text, runs
@classmethod
def original(cls, text):
return cls(text, [(0, len(text), 0, len(text), True)] if text else [])
def slice(self, a, b):
if a == 0 and b == len(self.text):
return self
runs = []
i = bisect_right(self.runs, a, key=lambda row: row[1])
while i < len(self.runs):
left, right, origin, end, linear = self.runs[i]
if left >= b:
break
start, stop = max(a, left), min(b, right)
if start < stop:
if linear:
origin, end = origin + start-left, origin + stop-left
runs.append((start-a, stop-a, origin, end, linear))
i += 1
return View(self.text[a:b], runs)
def as_glyph(self, text):
# An entity, grapheme or dash may produce several displayed characters.
if self.text == text:
return self
if len(self.runs) == 1:
a, b, s, e, _ = self.runs[0]
if a == 0 and b == len(self.text) and text:
return View(text, [(0, len(text), s, e, False)])
return View(text)
def strip(self):
return self.slice(len(self.text)-len(self.text.lstrip()), len(self.text.rstrip()))
def substitute(self, changes):
parts, end = [], 0
for a, b, replacement in changes:
parts.extend((self.slice(end, a), replacement))
end = b
return join([*parts, self.slice(end, len(self.text))]) if parts else self
def public_map(self):
result, pos = [], 0
for a, b, s, e, linear in self.runs:
if pos < a:
result.append(dict(start=pos, end=a, source_start=None, source_end=None, kind="unmapped"))
result.append(dict(start=a, end=b, source_start=s, source_end=e,
kind="copy" if linear else "replacement"))
pos = b
if pos < len(self.text):
result.append(dict(start=pos, end=len(self.text), source_start=None, source_end=None, kind="unmapped"))
return result
def join(parts):
strings, runs, pos = [], [], 0
for part in parts:
strings.append(part.text)
for a, b, s, e, linear in part.runs:
if runs and linear and runs[-1][4] and runs[-1][1] == pos+a and runs[-1][3] == s:
runs[-1] = (runs[-1][0], pos+b, runs[-1][2], e, True)
else:
runs.append((pos+a, pos+b, s, e, linear))
pos += len(part.text)
return View("".join(strings), runs)
def _canonical(body):
view = View.original(body)
if not unicodedata.is_normalized("NFC", body):
import regex
view = view.substitute((m.start(), m.end(), view.slice(*m.span()).as_glyph(unicodedata.normalize("NFC", m[0])))
for m in regex.finditer(r"\X", body) if not unicodedata.is_normalized("NFC", m[0]))
if "\r" in view.text:
view = view.substitute((m.start(), m.end(), view.slice(*m.span()).as_glyph("\n"))
for m in re.finditer(r"\r\n?", view.text))
if re.search(r"[\x00\ud800-\udfff]", view.text):
view = view.substitute((m.start(), m.end(), View("")) for m in re.finditer(r"[\x00\ud800-\udfff]+", view.text))
return view
class HTML(corpus._HTMLText):
def __init__(self, view):
HTMLParser.__init__(self, convert_charrefs=False)
self.view = view
self.lines = [0, *(m.end() for m in re.finditer("\n", view.text))]
self.pieces, self.skip = [], []
def source_offset(self):
line, column = self.getpos()
return self.lines[line-1] + column
def handle_data(self, data):
if not self.skip:
start = self.source_offset()
self.pieces.append(self.view.slice(start, start+len(data)))
def handle_entityref(self, name):
if self.skip:
return
a = self.source_offset()
b = a+1+len(name)
if self.view.text[b:b+1] == ";":
b += 1
part = self.view.slice(a, b)
try:
glyph = unescape(part.text)
except ValueError:
# Malformed numeric entities can exceed Python's integer conversion limit.
return
self.pieces.append(part.as_glyph(glyph))
def handle_charref(self, name):
self.handle_entityref("#"+name)
@classmethod
def render(cls, view, hidden=None):
parser = cls(view)
if hidden is not None:
parser.skip = hidden
parser.feed(view.text)
parser.close()
# The corpus parser emits paragraph separators for block/hidden tags.
return join(p if isinstance(p, View) else View(p) for p in parser.pieces)
# markdown-it-py and markdown-it source-position adapter attribution
#
# MIT License
#
# Copyright (c) 2020 ExecutableBookProject
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Copyright (c) 2014 Vitaly Puzrin, Alex Kocharin.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
class PositionedState(StateInline):
pending_start = None
def pushPending(self):
start = self.pending_start
content = self.pending
token = super().pushPending()
start = self.pos - len(content) if start is None else start
token.meta["source"] = (start, start + len(content))
self.pending_start = None
return token
class PositionedInline(ParserInline):
def parse(self, src, md, env, tokens):
state = PositionedState(src, md, env, tokens)
self.tokenize(state)
for rule in self.ruler2.getRules(""):
rule(state)
return state.tokens
def tokenize(self, state):
rules = self.ruler.getRules("")
end = state.posMax
while state.pos < end:
start, before = state.pos, len(state.tokens)
ok = False
if not state.pending:
state.pending_start = start
if state.level < state.md.options["maxNesting"]:
for rule in rules:
if rule(state, False):
ok = True
break
if not ok:
state.pending += state.src[state.pos]
state.pos += 1
marker_pos = start
for token in state.tokens[before:]:
if "source" in token.meta:
continue
if token.type == "text" and token.content in ("*", "_", "~", "~~"):
token.meta["source"] = (marker_pos, marker_pos + len(token.content))
marker_pos += len(token.content)
else:
token.meta["source"] = (start, state.pos)
# A rule can flush pending text and start a fresh pending suffix.
if state.pending and state.pending_start is None:
state.pending_start = state.pos - len(state.pending)
if state.pending:
state.pushPending()
def parser():
md = MarkdownIt("commonmark", {"html": True})
md.inline = PositionedInline()
md.inline.ruler2.disable("fragments_join")
md.core.ruler.disable("text_join")
md.enable(["table", "strikethrough"])
return md
_MARKDOWN = parser()
_HTML_START = re.compile(r"^\s*(?:<!doctype\s+html\b|<html\b|<(?:article|section|main|body|head|script|style|nav|header|footer|span|em|strong|a)\b)", re.I)
_HTML_TAG = re.compile(r"<(/?)([a-z][a-z0-9:-]*)\b[^<>]*>", re.I)
_HTML_NAMES = corpus._BLOCK | corpus._SKIP | {"html", "body", "main", "header", "span", "a", "b",
"strong", "em", "i", "code", "sup", "sub", "mark", "del", "small"}
def _contains_html(text):
opened = set()
for match in _HTML_TAG.finditer(text):
name = match[2].lower()
if name in {"br", "img"} or (match[1] and name in opened):
return True
if not match[1] and name in _HTML_NAMES:
opened.add(name)
return False
_MD_BLOCK = re.compile(r"(?m)^(?: {0,3}(?:={2,}|-{3,}|\*{3,}|_{3,})[ \t]*$| {0,3}\[[^\]\n]+\]:[ \t]+\S)")
# Like the corpus cleaner, ambiguous inline asterisks and underscores alone
# do not switch scientific or mathematical prose into Markdown mode.
_MD_EXTRA = re.compile(r"`[^`\n]+`|(?m:^ {0,3}~~~)")
def _inline_source(view, lines, part):
a, b = part.map
fragments = []
for i, content in enumerate(part.content.splitlines(keepends=True), a):
if i >= b:
return View(part.content)
lo, hi = lines[i], lines[i+1]
line = content.removesuffix("\n")
physical = view.text[lo:hi].removesuffix("\n")
at = physical.find(line)
if at < 0 or (line and physical.find(line, at+1) >= 0):
fragments.append(View(line))
else:
fragments.append(view.slice(lo+at, lo+at+len(line)))
if content.endswith("\n"):
fragments.append(view.slice(hi-1, hi) if view.text[hi-1:hi] == "\n" else View("\n"))
joined = join(fragments)
return joined if joined.text == part.content else View(part.content)
def _inline(view, tokens, tags):
out = []
for token in tokens:
kind = token.type
if kind == "html_inline":
tags.feed(token.content)
tags.pieces.clear()
if not tags.skip and re.fullmatch(r"<br\s*/?>", token.content, re.I):
out.append(View("\n"))
continue
if tags.skip or kind not in {"text", "text_special", "code_inline", "softbreak", "hardbreak"}:
continue
src = view.slice(*token.meta.get("source", (0, 0)))
value = "\n" if kind in {"softbreak", "hardbreak"} else token.content
if not value:
continue
if kind == "code_inline":
width = len(token.markup)
src = src.slice(width, len(src.text)-width)
src = src.substitute((m.start(), m.end(), src.slice(*m.span()).as_glyph(" "))
for m in re.finditer("\n", src.text))
if src.text.startswith(" ") and src.text.endswith(" ") and src.text.strip():
src = src.slice(1, len(src.text)-1)
if token.info == "entity":
out.append(src.as_glyph(value))
elif src.text == value:
out.append(src)
elif src.text.count(value) == 1:
at = src.text.index(value)
out.append(src.slice(at, at+len(value)))
else:
out.append(View(value))
return join(out)
def _markdown(view):
lines = [0, *(m.end() for m in re.finditer("\n", view.text)), len(view.text)]
parts, table, previous_end = [], False, None
tags = corpus._HTMLText()
for token in _MARKDOWN.parse(view.text):
if token.type in {"table_open", "table_close"}:
table = token.type == "table_open"
if table or token.type not in {"inline", "html_block"}:
continue
a, b = token.map
if token.type == "html_block":
body = view.slice(lines[a], lines[b])
# Container prefixes (e.g. blockquotes) may be stripped by the parser.
if body.text != token.content:
body = _inline_source(view, lines, token)
block = HTML.render(body, tags.skip)
else:
block = _inline(_inline_source(view, lines, token), token.children, tags)
separator = View("\n\n")
if previous_end is not None:
gap = view.slice(previous_end, lines[a])
if gap.text == "\n\n":
separator = gap
parts.extend((separator, block))
if token.type == "html_block":
parts.append(View("\n\n"))
previous_end = lines[b] - int(view.text[lines[b]-1:lines[b]] == "\n")
return join(parts)
def _finish(view):
if "://" in view.text or "www." in view.text.lower():
view = view.substitute((m.start(), m.end(), View("")) for m in corpus._URL.finditer(view.text))
if "\n" in view.text:
view = view.substitute((m.start(), m.end(), join((view.slice(m.start(), m.start()+1),
view.slice(m.end()-1, m.end()))))
for m in re.finditer(r"\n(?:[ \t]*\n)+", view.text) if m[0] != "\n\n")
return view.strip()
def _publisher(raw, source_id):
text = corpus.document_text(source_id, raw)
if not text:
return View("")
if text == raw.strip():
return View.original(raw).strip()
origins = corpus.source_origins(raw, text, source_id)
runs, i = [], 0
while i < len(origins):
origin = origins[i]
if origin is None:
i += 1
continue
s, e = origin
j = i+1
while j < len(origins) and origins[j] == origin:
j += 1
linear = j == i+1 and e == s+1
if linear:
while j < len(origins) and origins[j] == (e, e+1) and (
j+1 == len(origins) or origins[j+1] != origins[j]):
j += 1
e += 1
runs.append((i, j, s, e, linear))
i = j
return View(text, runs)
def visible(raw, source_id):
if source_id != "rendered_prose":
# Use the same publisher-specific rules as the corpus. HTML can carry
# precise character offsets through its parser, even for duplicate text.
if source_id in corpus._HTML | corpus._REVIEW_HTML and "<" in raw and (
corpus._HTML_WRAPPER.match(raw) or corpus._REVIEW_TAGS.search(raw) and source_id in corpus._REVIEW_HTML):
html = _finish(HTML.render(_canonical(raw)))
if html.text == corpus.document_text(source_id, raw):
return html
return _publisher(raw, source_id)
view = _canonical(raw)
markdown = corpus.content_hint(view.text) == "markdown"
if "<" in view.text and (corpus._HTML_WRAPPER.match(view.text) and corpus._HTML_END.search(view.text)
or _HTML_START.match(view.text) or (not markdown and ("<!--" in view.text or _contains_html(view.text)))):
return _finish(HTML.render(view))
if corpus._STRUCTURE.search(view.text):
view = view.substitute((a, b, View("\n\n")) for a, b, _ in corpus.structural_ranges(view.text))
if corpus.content_hint(view.text) == "markdown" or _MD_EXTRA.search(view.text) or _MD_BLOCK.search(view.text):
view = _markdown(view)
return _finish(view)