"""A rendered DDR, the publisher's HTML or chandra's OCR of the PDF, reduced to one comparable structure. Both renderings are read as a sequence of events: header lines, section titles, text paragraphs, tables and (OCR only) page breaks. `assemble` turns the events into a `Rendered` report: * header: the "Wellbore:" and "Period:" lines, and as "other" any header text besides them and "Summary report"; * fields: the key/value tables printed before the first section title (wellboreInfoTable_1/2/3), keyed by `norm_key` of the printed label; * texts: section title -> paragraph text; * tables: section title -> `Table` (column header, if the table has one, and rows of cell strings). What the page layout does to the OCR is undone here, not in the comparison: a table that follows another table of the same section with no title in between continues it (a header row repeated by the PDF on a new page is dropped); a single cell that starts with a bold "Key:" holds a key/value pair; header lines that chandra reads as table rows are header lines; a row that only continues the cells of the row above (a cell printed on several lines, read as rows) is merged into it; page headers and footers are skipped. Each repair is recorded in `Rendered.notes`. """ from __future__ import annotations import re from dataclasses import asdict, dataclass, field from html.parser import HTMLParser #:

classes of the publisher HTML -> event kind. P_CLASSES = {"DDR-ReportHeader": "header", "DDR-SubReportHeader": "header", "TextHeader": "title", "TextData": "text"} #: chandra labels (lower-cased) that carry no report content. SKIP_LABELS = {"page-header", "page_header", "page-footer", "page_footer", "picture", "figure", "image"} _HEADER_LINE = re.compile(r"^(Summary report|Wellbore:|Period:)", re.M) _WELLBORE = re.compile(r"Wellbore:\s*(.*?)\s*(?=Period:|$)", re.M) _PERIOD = re.compile(r"Period:\s*(.*?)\s*$", re.M) def clean(s: str) -> str: return re.sub(r"\s+", " ", s).strip() def norm_key(s: str) -> str: """Field label or section title as a lookup key: whitespace collapsed, trailing colon dropped, case folded.""" return clean(s).rstrip(":").strip().casefold() @dataclass class Cell: text: str head: bool = False # , a ColHead* class, or (OCR) text that is bold throughout bold: str = "" # the bold part of the text colspan: int = 1 @dataclass class Event: kind: str # header | title | text | table | page text: str = "" rows: list[list[Cell]] = field(default_factory=list) page: int = 1 @dataclass class Table: header: list[str] | None rows: list[list[str]] @property def n_cols(self) -> int: return len(self.header) if self.header else max((len(r) for r in self.rows), default=0) @dataclass class Rendered: header: dict[str, str] = field(default_factory=dict) fields: dict[str, str] = field(default_factory=dict) texts: dict[str, str] = field(default_factory=dict) tables: dict[str, Table] = field(default_factory=dict) notes: list[str] = field(default_factory=list) # what `assemble` had to repair, for the QC report def to_dict(self) -> dict: return asdict(self) @classmethod def from_dict(cls, d: dict) -> Rendered: return cls(header=d["header"], fields=d["fields"], texts=d["texts"], tables={k: Table(**t) for k, t in d["tables"].items()}, notes=d.get("notes", [])) class _Parser(HTMLParser): """Paragraphs and tables of an HTML fragment as events. Nested tables are flattened into their own events.""" def __init__(self, p_kind=None): super().__init__(convert_charrefs=True) self.p_kind = p_kind or (lambda attrs: P_CLASSES.get(attrs.get("class") or "")) self.events: list[Event] = [] self._tables: list[list[list[Cell]]] = [] self._cell: dict | None = None self._p: tuple[str, list[str]] | None = None self._bold = 0 def _text(self, s: str) -> None: if self._cell is not None: self._cell["parts"].append(s) if self._bold: self._cell["bold"].append(s) elif s.strip(): self._cell["plain"] = True elif self._p is not None: self._p[1].append(s) def handle_starttag(self, tag, attrs): a = dict(attrs) if tag == "table": self._close_cell() self._tables.append([]) elif tag == "tr" and self._tables: self._close_cell() self._tables[-1].append([]) elif tag in ("td", "th") and self._tables: self._close_cell() if not self._tables[-1]: self._tables[-1].append([]) span = a.get("colspan") or "1" self._cell = {"parts": [], "bold": [], "plain": False, "colspan": int(span) if span.isdigit() else 1, "head": tag == "th" or (a.get("class") or "").startswith("ColHead")} elif tag == "p" and self._cell is None: kind = self.p_kind(a) self._p = (kind, []) if kind else None elif tag == "br": self._text("\n") elif tag in ("b", "strong"): self._bold += 1 def handle_endtag(self, tag): if tag in ("b", "strong"): self._bold = max(0, self._bold - 1) elif tag in ("td", "th"): self._close_cell() elif tag == "table" and self._tables: self._close_cell() rows = self._tables.pop() self.events.append(Event("table", rows=[r for r in rows if r])) elif tag == "p" and self._p is not None: kind, parts = self._p self._p = None text = "\n".join(clean(line) for line in "".join(parts).splitlines() if clean(line)) if text: self.events.append(Event(kind, text=text)) elif tag in ("p", "div", "li") and self._cell is not None: self._text("\n") def handle_data(self, data): self._text(data) def _close_cell(self) -> None: if self._cell is None or not self._tables: self._cell = None return c, self._cell = self._cell, None text, bold = clean("".join(c["parts"])), clean("".join(c["bold"])) head = c["head"] or (bool(text) and not c["plain"]) self._tables[-1][-1].append(Cell(text, head, bold, c["colspan"])) def html_events(html: str) -> list[Event]: """Events of a publisher HTML report (p.DDR-ReportHeader / DDR-SubReportHeader / TextHeader / TextData, tables).""" p = _Parser() p.feed(html) p.close() return p.events def table_rows(fragment: str) -> list[list[Cell]]: """Rows of the tables in an HTML fragment, e.g. the body of a chandra Table block.""" p = _Parser(p_kind=lambda attrs: None) p.feed(fragment) p.close() return [r for e in p.events if e.kind == "table" for r in e.rows] def _all_bold(fragment: str) -> bool: rest = re.sub(r"(?s)<(b|strong)\b[^>]*>.*?", "", fragment) return bool(re.search(r"<(b|strong)\b", fragment)) and not re.sub(r"<[^>]+>| |\s", "", rest) def ocr_events(blocks) -> list[Event]: """Events of chandra blocks (`volve_dia.ocr.Block`, in page and reading order). Classification by content first, label second: before the first title, a block with a "Summary report", "Wellbore:" or "Period:" line is the header (chandra calls it Header, Page-Header or Text, or reads it as rows of a table); a text block that is bold throughout is a section title whatever its label.""" events: list[Event] = [] page, titled = None, False for b in blocks: if b.page != page: if page is not None: events.append(Event("page", page=b.page)) page = b.page label = (b.raw_label or b.label).strip().lower() if b.label == "table" or label == "table": rows = table_rows(b.html or "") head = [] if titled else [r for r in rows if _HEADER_LINE.match(_line(r))] if head: events.append(Event("header", text="\n".join(_line(r) for r in head), page=b.page)) rows = [r for r in rows if not any(r is h for h in head)] if rows: events.append(Event("table", rows=rows, page=b.page)) continue if not titled and _HEADER_LINE.search(b.text): events.append(Event("header", text=b.text, page=b.page)) continue if label in SKIP_LABELS: continue if b.label in ("title", "section_header") or _all_bold(b.html or ""): titled = True events.append(Event("title", text=clean(b.text), page=b.page)) else: events.append(Event("text", text=b.text, page=b.page)) return events def _line(row: list[Cell]) -> str: return clean(" ".join(c.text for c in row)) def _field(row: list[Cell]) -> tuple[str, str] | None: cells = [c for c in row if c.text or c.head] if not cells: return None if len(cells) >= 2: return cells[0].text, clean(" ".join(c.text for c in cells[1:])) c = cells[0] if c.bold and c.text.startswith(c.bold) and c.bold != c.text: # "Depth mMD: 1353" return c.bold, c.text[len(c.bold):].strip() return c.text, "" def _table(rows: list[list[Cell]]) -> Table: rows = [r for r in rows if any(c.text for c in r)] header = None if rows and len(rows[0]) > 1 and all(c.head for c in rows[0]): # row-oriented tables start head, value header = [c.text for c in rows[0]] rows = rows[1:] return Table(header, [[c.text for c in r] for r in rows]) def _put(d: dict, key: str, value) -> str: k, n = key, 1 while k in d: n += 1 k = f"{key} #{n}" d[k] = value return k def assemble(events: list[Event]) -> Rendered: out = Rendered() header_lines: list[str] = [] title: str | None = None last: Event | None = None # previous content event (page breaks skipped) last_key: str | None = None # key in out.texts / out.tables of what `last` produced broke = False # a page break since `last` for e in events: if e.kind == "page": broke = True continue if e.kind == "header": header_lines.extend(e.text.splitlines()) elif e.kind == "title": title = e.text elif e.kind == "text": if title is None: header_lines.extend(e.text.splitlines()) out.notes.append("text before the first title read as header") elif last is not None and last.kind == "text": # the paragraph goes on in a new block or page out.texts[last_key] += "\n" + e.text else: last_key = _put(out.texts, title, e.text) elif e.kind == "table": if title is None: for row in e.rows: kv = _field(row) if kv and norm_key(kv[0]): _put(out.fields, norm_key(kv[0]), kv[1]) else: t = _table(e.rows) prev = out.tables.get(last_key) if last is not None and last.kind == "table" else None if prev is not None and (t.header == prev.header or (t.header is None and t.n_cols == prev.n_cols)): prev.rows.extend(t.rows) out.notes.append(f"table continued: {last_key}") elif prev is not None and t.header is None and broke: # a column merged or split on one page prev.rows.extend(t.rows) out.notes.append(f"table continued, columns differ: {last_key}") elif prev is not None and t.header is not None and prev.header is None and t.n_cols == prev.n_cols: prev.rows.extend([t.header] + t.rows) # a data row read as a header out.notes.append(f"table continued (header row kept as data): {last_key}") else: last_key = _put(out.tables, title, t) last, broke = e, False text = "\n".join(header_lines) for key, rx in (("wellbore", _WELLBORE), ("period", _PERIOD)): m = rx.search(text) if m: out.header[key] = m.group(1) text = text[:m.start()] + text[m.end():] other = clean(text.replace("Summary report", "", 1)) if other: out.header["other"] = other return out def _unwrap(t: Table) -> int: """Merge into the row above every row whose first cell is empty and at most half of whose cells are filled: chandra reads a cell printed on several lines (a long remark) as several rows. Returns the rows merged.""" rows: list[list[str]] = [] for r in t.rows: if rows and r and not r[0] and 2 * sum(bool(c) for c in r) <= len(r): above = rows[-1] above.extend([""] * (len(r) - len(above))) for j, c in enumerate(r): if c: above[j] = f"{above[j]}\n{c}" if above[j] else c else: rows.append(list(r)) n, t.rows = len(t.rows) - len(rows), rows return n def parse_html(html: str) -> Rendered: return assemble(html_events(html)) def parse_ocr(blocks) -> Rendered: out = assemble(ocr_events(blocks)) for title, t in out.tables.items(): n = _unwrap(t) if n: out.notes.append(f"rows merged into the row above: {title} ({n})") return out