Add P0 infrastructure for the Volve-DIA benchmark
Set up the data, parsing and quality-control layer for a public benchmark on the Volve daily drilling reports (DDR) and WITSML real-time data. - Data manifest with SHA-256 hashes of the three Volve subtrees in use. - DDR XML parser into DuckDB (1,759 reports, 26 wellbores, 23,447 activities, 17 tables) with locked expected counts. - Render QC of the publisher HTML against the XML (272,544 items). - OCR client for the shared chandra vLLM service, with a page cache keyed on model, prompt hash, dpi, max_tokens and temperature, and OCR QC against the HTML on a 26-report pilot. - Run logging (scripts/runlog.sh, logs/index.csv), the P0 runner and 40 tests. - Research plan, technical overview and progress page (in Vietnamese). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1
volve_dia/ddr/__init__.py
Normal file
1
volve_dia/ddr/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Daily drilling reports: the WITSML XML version (ground truth) and the rendered HTML/PDF versions."""
|
||||
267
volve_dia/ddr/qc.py
Normal file
267
volve_dia/ddr/qc.py
Normal file
@@ -0,0 +1,267 @@
|
||||
"""Fidelity of one rendering of a DDR against another, item by item.
|
||||
|
||||
`compare(ref, hyp)` lines up two `Rendered` reports and returns one item per thing printed in `ref`: the two header
|
||||
lines, every header field, every section text, every column header and every table cell, plus one `*_label` item
|
||||
per field label, section title and table title (was the label itself read right?). An item holds both strings,
|
||||
whether they are equal, and the character and word edit distances, so every rate in a report is a group-by over
|
||||
items and every error can be shown. A label that `hyp` misreads is paired by its place in the printed order, so
|
||||
its value is still compared. Table rows are aligned by a monotone alignment of row similarity; columns by position
|
||||
or, when `hyp` has a different number of columns (one merged or split), by aligning the column headers. A `ref`
|
||||
row or column with no partner yields its cells with `hyp` = None; a `hyp` row or column with no partner yields one
|
||||
`row_extra` / `col_extra` item, and a header line, field, text or table of `hyp` that no `ref` label matched one
|
||||
`*_extra` item.
|
||||
|
||||
Two uses:
|
||||
* OCR fidelity: ref = the publisher HTML, hyp = chandra's OCR of the PDF, `equal=exact`;
|
||||
* render fidelity: ref = `from_xml` (what the HTML should print, built from the WITSML source), hyp = the HTML,
|
||||
`equal=same_value` (numbers compared as numbers; a printed sentinel or "None" is missing).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from rapidfuzz import fuzz, process
|
||||
from rapidfuzz.distance import Levenshtein
|
||||
|
||||
from ..names import canonical
|
||||
from .rendered import Rendered, Table, clean, norm_key
|
||||
from .xml import SENTINELS
|
||||
|
||||
#: Header field label (`norm_key`, unit suffix removed) -> drillReport column it prints. Found by matching every
|
||||
#: label against every column on all 1,759 reports (agreement 1.0 for each pair below). Labels with no column
|
||||
#: ("wellbore type", "dia last casing", "depth at kick off mtvd") are always printed empty.
|
||||
FIELD_COLUMNS = {
|
||||
"status": "versionKind", "report creation time": "createDate", "report number": "reportNo",
|
||||
"days ahead/behind": "daysAhead", "operator": "operator", "rig name": "rigAlias_NPD_Name",
|
||||
"drilling contractor": "drillContractor", "spud date": "dTimSpud", "wellbore type": None,
|
||||
"elevation rkb-msl": "elevKelly", "water depth msl": "waterDepth", "tight well": "tightWell", "hpht": "hpht",
|
||||
"temperature": "avgTempBH", "pressure": "avgPresBH", "date well complete": "dateDrillComplete",
|
||||
"dist drilled": "distDrill", "penetration rate": "ropCurrent", "hole dia": "diaHole",
|
||||
"pressure test type": "presTestType", "formation strength": "strengthForm", "dia last casing": None,
|
||||
"depth at kick off mmd": "mdKickoff", "depth at kick off mtvd": None, "depth mmd": "md", "depth mtvd": "tvd",
|
||||
"plug back depth mmd": "mdPlugTop", "depth at formation strength mmd": "mdStrengthForm",
|
||||
"depth at formation strength mtvd": "tvdStrengthForm", "depth at last casing mmd": "mdCsgLast",
|
||||
"depth at last casing mtvd": "tvdCsgLast",
|
||||
}
|
||||
#: 0/1 flags: the expected print is N/Y.
|
||||
FLAGS = {"tightWell", "hpht"}
|
||||
TEXT_COLUMNS = {"Summary of activities (24 Hours)": "sum24Hr",
|
||||
"Summary of planned activities (24 Hours)": "forecast24Hr"}
|
||||
OPERATIONS = ("Operations", ["Start time", "End time", "End Depth mMD", "Main - Sub Activity", "State", "Remark"])
|
||||
_UNIT = re.compile(r"\s*\([^)]*\)$")
|
||||
_ISO = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}")
|
||||
|
||||
|
||||
def field_name(label_key: str) -> str:
|
||||
"""'hole dia (in)' and 'hole dia ()' -> 'hole dia': the publisher prints the unit only when there is a value."""
|
||||
return _UNIT.sub("", label_key)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- equality
|
||||
|
||||
def exact(ref: str, hyp: str | None) -> bool:
|
||||
return hyp is not None and clean(ref) == clean(hyp)
|
||||
|
||||
|
||||
def _same_label(ref: str, hyp: str | None) -> bool:
|
||||
return hyp is not None and norm_key(ref) == norm_key(hyp)
|
||||
|
||||
|
||||
def _missing(s: str) -> bool:
|
||||
s = clean(s)
|
||||
if s in ("", "None"):
|
||||
return True
|
||||
try:
|
||||
return float(s) in SENTINELS
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def same_value(ref: str, hyp: str | None) -> bool:
|
||||
"""Equal as printed values: whitespace collapsed, numbers as numbers, '', 'None' and sentinels as missing."""
|
||||
if hyp is None:
|
||||
return False
|
||||
if _missing(ref) or _missing(hyp):
|
||||
return _missing(ref) and _missing(hyp)
|
||||
a, b = clean(ref), clean(hyp)
|
||||
if a == b:
|
||||
return True
|
||||
try:
|
||||
return math.isclose(float(a), float(b), rel_tol=0, abs_tol=1e-9)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- items
|
||||
|
||||
def _item(part: str, table: str, key: str, row: int, ref: str, hyp: str | None, equal) -> dict:
|
||||
r, h = clean(ref), clean(hyp or "")
|
||||
return {"part": part, "table": table, "key": key, "row": row, "ref": r, "hyp": None if hyp is None else h,
|
||||
"exact": bool(equal(ref, hyp)), "edits": Levenshtein.distance(r, h), "chars": len(r),
|
||||
"w_edits": Levenshtein.distance(r.split(), h.split()), "words": len(r.split())}
|
||||
|
||||
|
||||
def align(a: list[list[str]], b: list[list[str]], min_sim: float = 0.5) -> list[tuple[int, int]]:
|
||||
"""Monotone row alignment maximising the summed gain `similarity - min_sim` of the pairs. A pair must be worth
|
||||
more than leaving both rows unpaired, so two mediocre pairs never outweigh one good one (a dropped row next to
|
||||
an invented one), and rows no more similar than `min_sim` never pair."""
|
||||
if not a or not b:
|
||||
return []
|
||||
gain = process.cdist([" | ".join(r) for r in a], [" | ".join(r) for r in b], scorer=fuzz.ratio) / 100.0 - min_sim
|
||||
n, m = gain.shape
|
||||
best = np.zeros((n + 1, m + 1))
|
||||
for i in range(n - 1, -1, -1):
|
||||
for j in range(m - 1, -1, -1):
|
||||
v = max(best[i + 1, j], best[i, j + 1])
|
||||
if gain[i, j] > 0:
|
||||
v = max(v, gain[i, j] + best[i + 1, j + 1])
|
||||
best[i, j] = v
|
||||
pairs, i, j = [], 0, 0
|
||||
while i < n and j < m:
|
||||
if gain[i, j] > 0 and math.isclose(best[i, j], gain[i, j] + best[i + 1, j + 1]):
|
||||
pairs.append((i, j))
|
||||
i, j = i + 1, j + 1
|
||||
elif best[i + 1, j] >= best[i, j + 1]:
|
||||
i += 1
|
||||
else:
|
||||
j += 1
|
||||
return pairs
|
||||
|
||||
|
||||
def _extra(part: str, table: str, key: str, row: int, content: str) -> dict:
|
||||
return {**_item(part, table, key, row, "", content, exact), "exact": False}
|
||||
|
||||
|
||||
def _table_items(title: str, ref: Table, hyp: Table | None, equal) -> list[dict]:
|
||||
items = []
|
||||
hyp = hyp or Table(None, [])
|
||||
h_header, h_rows = hyp.header, hyp.rows
|
||||
if ref.header and not h_header and h_rows and fuzz.ratio(" | ".join(ref.header), " | ".join(h_rows[0])) >= 80:
|
||||
h_header, h_rows = h_rows[0], h_rows[1:] # header printed but not recognised as one
|
||||
cols = ref.header or [f"c{j}" for j in range(ref.n_cols)]
|
||||
if ref.header and h_header and len(h_header) != len(ref.header):
|
||||
col = dict(align([[c] for c in ref.header], [[c] for c in h_header]))
|
||||
else:
|
||||
col = {j: j for j in range(ref.n_cols)}
|
||||
if ref.header:
|
||||
for j, name in enumerate(ref.header):
|
||||
hj = col.get(j)
|
||||
items.append(_item("colhead", title, name, -1, name,
|
||||
h_header[hj] if h_header and hj is not None and hj < len(h_header) else None, equal))
|
||||
pairs = dict(align(ref.rows, h_rows))
|
||||
for i, row in enumerate(ref.rows):
|
||||
other = h_rows[pairs[i]] if i in pairs else None
|
||||
for j, cell in enumerate(row):
|
||||
name, hj = (cols[j] if j < len(cols) else f"c{j}"), col.get(j)
|
||||
h = None if other is None or hj is None else (other[hj] if hj < len(other) else "")
|
||||
items.append(_item("cell", title, name, i, cell, h, equal))
|
||||
for j in sorted(set(range(len(h_rows))) - set(pairs.values())):
|
||||
items.append(_extra("row_extra", title, "", j, " | ".join(h_rows[j])))
|
||||
paired = [h_rows[j] for j in sorted(pairs.values())]
|
||||
width = max([len(h_header or [])] + [len(r) for r in paired])
|
||||
for hj in sorted(set(range(width)) - set(col.values())):
|
||||
head = h_header[hj] if h_header and hj < len(h_header) else ""
|
||||
content = " | ".join(c for c in [head] + [r[hj] for r in paired if hj < len(r)] if c)
|
||||
if content:
|
||||
items.append(_extra("col_extra", title, head, -1, content))
|
||||
return items
|
||||
|
||||
|
||||
def _matcher(ref_keys, hyp_keys):
|
||||
"""ref key -> hyp key: the hyp key with the same `norm_key`; else, labels being printed in a fixed order, the
|
||||
hyp key that `align` pairs with it among the keys left over on both sides (more than half similar: "hptt" for
|
||||
"hpht"). A misread label still finds its value, and the label error is an item of its own."""
|
||||
norm = {norm_key(k): k for k in hyp_keys}
|
||||
pairs = {k: norm[norm_key(k)] for k in ref_keys if norm_key(k) in norm}
|
||||
taken = set(pairs.values())
|
||||
ref_rest = [k for k in ref_keys if k not in pairs]
|
||||
hyp_rest = [k for k in hyp_keys if k not in taken]
|
||||
for i, j in align([[norm_key(k)] for k in ref_rest], [[norm_key(k)] for k in hyp_rest]):
|
||||
pairs[ref_rest[i]] = hyp_rest[j]
|
||||
return pairs.get
|
||||
|
||||
|
||||
def _flat(v: str | Table) -> str:
|
||||
if isinstance(v, str):
|
||||
return v
|
||||
return " | ".join(" | ".join(r) for r in ([v.header] if v.header else []) + v.rows)
|
||||
|
||||
|
||||
def compare(ref: Rendered, hyp: Rendered, equal=exact, extras: bool = True) -> list[dict]:
|
||||
"""Items of `ref` against `hyp`. With `extras`, every header line, field, text or table of `hyp` that no `ref`
|
||||
key matched is one `*_extra` item (ref "", hyp = its label and content), so text that `hyp` invents counts as
|
||||
insertions."""
|
||||
items = [_item("header", "", k, -1, v, hyp.header.get(k), equal) for k, v in ref.header.items()]
|
||||
if extras:
|
||||
items += [_extra("header_extra", "", k, -1, v) for k, v in hyp.header.items() if k not in ref.header]
|
||||
for part, ref_d, hyp_d in (("field", ref.fields, hyp.fields), ("text", ref.texts, hyp.texts),
|
||||
("table", ref.tables, hyp.tables)):
|
||||
match = _matcher(ref_d, hyp_d)
|
||||
used = set()
|
||||
for k, v in ref_d.items():
|
||||
hk = match(k)
|
||||
used.add(hk)
|
||||
items.append(_item(f"{part}_label", "", k, -1, k, hk, _same_label))
|
||||
if part == "field":
|
||||
items.append(_item("field", "", k, -1, v, None if hk is None else hyp_d[hk], equal))
|
||||
elif part == "text":
|
||||
items.append(_item("text", k, k, -1, v, None if hk is None else hyp_d[hk], equal))
|
||||
else:
|
||||
items += _table_items(k, v, None if hk is None else hyp_d[hk], equal)
|
||||
if extras:
|
||||
for hk in hyp_d:
|
||||
if hk not in used:
|
||||
items.append(_extra(f"{part}_extra", "", hk, -1, f"{hk}: {_flat(hyp_d[hk])}".rstrip(": ")))
|
||||
return items
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- what the HTML should print
|
||||
|
||||
def _printed(v) -> str:
|
||||
if v is None or pd.isna(v):
|
||||
return ""
|
||||
if isinstance(v, str) and _ISO.match(v):
|
||||
return v[:16].replace("T", " ")
|
||||
if isinstance(v, float) and v.is_integer():
|
||||
return str(int(v))
|
||||
return str(v)
|
||||
|
||||
|
||||
def from_xml(report: dict, activities: list[dict]) -> Rendered:
|
||||
"""The parts of a report the publisher HTML should print, built from the drillReport: header, the header fields
|
||||
in `FIELD_COLUMNS`, the two summaries and the Operations table. Keys are field names (unit suffix removed),
|
||||
so compare with `html_for_xml` of the HTML side."""
|
||||
out = Rendered()
|
||||
out.header = {"wellbore": report["wellbore"],
|
||||
"period": f"{_printed(report.get('dTimStart'))} - {_printed(report.get('dTimEnd'))}"}
|
||||
for name, col in FIELD_COLUMNS.items():
|
||||
v = report.get(col) if col else None
|
||||
if col in FLAGS and v is not None and not pd.isna(v):
|
||||
v = "Y" if int(v) == 1 else "N"
|
||||
out.fields[name] = _printed(v)
|
||||
for title, col in TEXT_COLUMNS.items():
|
||||
out.texts[title] = _printed(report.get(col))
|
||||
if activities:
|
||||
title, header = OPERATIONS
|
||||
out.tables[title] = Table(header, [[_printed(a.get("dTimStart"))[11:16], _printed(a.get("dTimEnd"))[11:16],
|
||||
_printed(a.get("md")), _printed(a.get("proprietaryCode")),
|
||||
_printed(a.get("state")), _printed(a.get("comments"))]
|
||||
for a in sorted(activities, key=lambda a: a["seq"])])
|
||||
return out
|
||||
|
||||
|
||||
def html_for_xml(r: Rendered) -> Rendered:
|
||||
"""An HTML rendering keyed like `from_xml`: field keys without the unit suffix, wellbore canonical."""
|
||||
out = Rendered(header=dict(r.header), texts=r.texts, tables=r.tables, notes=r.notes)
|
||||
if "wellbore" in out.header:
|
||||
try:
|
||||
out.header["wellbore"] = canonical(out.header["wellbore"])
|
||||
except ValueError:
|
||||
pass
|
||||
for k, v in r.fields.items():
|
||||
out.fields.setdefault(field_name(k), v)
|
||||
return out
|
||||
336
volve_dia/ddr/rendered.py
Normal file
336
volve_dia/ddr/rendered.py
Normal file
@@ -0,0 +1,336 @@
|
||||
"""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
|
||||
|
||||
#: <p> 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 # <th>, 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[^>]*>.*?</\1>", "", 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: # "<b>Depth mMD:</b> 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
|
||||
203
volve_dia/ddr/xml.py
Normal file
203
volve_dia/ddr/xml.py
Normal file
@@ -0,0 +1,203 @@
|
||||
"""WITSML 1.4.0.0 drillReport files (the XML version of the Volve DDRs) as flat tables.
|
||||
|
||||
One file holds one report. The report-level elements (names, aliases, wellboreInfo, statusInfo) become one row of
|
||||
`reports`; every repeated section becomes a table of its own (`SECTIONS`). Column names are the WITSML element names,
|
||||
so every value can be traced back to the schema. Two normalisations, both counted rather than silent:
|
||||
|
||||
* the sentinels -999.99, -999.25 and -9999 become missing (counted per column in the `sentinels` table);
|
||||
* a measure (an element with a `uom` attribute) becomes a float. Its unit goes to the `units` table, and
|
||||
`parse_dir` refuses a column that is published in more than one unit.
|
||||
|
||||
Times stay ISO strings with their UTC offset, as published; `parse_dir` adds UTC timestamps for the report period
|
||||
and the activities.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import collections
|
||||
import re
|
||||
import xml.etree.ElementTree as ET
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ..names import canonical, stem
|
||||
|
||||
NS = "{http://www.witsml.org/schemas/1series}"
|
||||
SENTINELS = {-999.99, -999.25, -9999.0}
|
||||
|
||||
#: drillReport child element -> table. Everything else in a drillReport is report-level.
|
||||
SECTIONS = {
|
||||
"activity": "activities",
|
||||
"fluid": "fluids",
|
||||
"surveyStation": "surveys",
|
||||
"porePressure": "pore_pressure",
|
||||
"equipFailureInfo": "equip_failures",
|
||||
"gasReadingInfo": "gas_readings",
|
||||
"lithShowInfo": "lith_shows",
|
||||
"stratInfo": "strat",
|
||||
"casing_liner_tubing": "casings",
|
||||
"bitRecord": "bits",
|
||||
"logInfo": "log_info",
|
||||
"perfInfo": "perforations",
|
||||
"coreInfo": "cores",
|
||||
"wellTestInfo": "well_tests",
|
||||
}
|
||||
#: Report-level elements that are flattened into `reports` (their leaves become columns).
|
||||
REPORT_GROUPS = ("wellboreInfo", "statusInfo")
|
||||
#: Numbers published without a unit.
|
||||
INTS = {"reportNo", "tightWell", "hpht"}
|
||||
FLOATS = {"daysAhead", "daysBehind"}
|
||||
_FILE = re.compile(r"(.+)_(\d{4})_(\d{2})_(\d{2})")
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParsedReport:
|
||||
report: dict
|
||||
sections: dict[str, list[dict]] = field(default_factory=lambda: collections.defaultdict(list))
|
||||
units: dict[tuple[str, str], tuple[str, str]] = field(default_factory=dict) # (table, column) -> (uom, datum)
|
||||
sentinels: collections.Counter = field(default_factory=collections.Counter) # (table, column) -> count
|
||||
|
||||
|
||||
def _tag(e: ET.Element) -> str:
|
||||
return e.tag.replace(NS, "")
|
||||
|
||||
|
||||
def _slug(s: str) -> str:
|
||||
return re.sub(r"\W+", "_", s.strip()).strip("_")
|
||||
|
||||
|
||||
class _Flattener:
|
||||
def __init__(self, parsed: ParsedReport, table: str):
|
||||
self.parsed, self.table = parsed, table
|
||||
|
||||
def value(self, e: ET.Element, column: str):
|
||||
text = (e.text or "").strip()
|
||||
if "uom" in e.attrib:
|
||||
self.parsed.units[(self.table, column)] = (e.attrib["uom"], e.attrib.get("datum", ""))
|
||||
if not text:
|
||||
return None
|
||||
v = float(text)
|
||||
if v in SENTINELS:
|
||||
self.parsed.sentinels[(self.table, column)] += 1
|
||||
return None
|
||||
return v
|
||||
if not text:
|
||||
return None
|
||||
if _tag(e) in INTS:
|
||||
return int(text)
|
||||
if _tag(e) in FLOATS:
|
||||
return float(text)
|
||||
return text
|
||||
|
||||
def leaves(self, elem: ET.Element, row: dict, prefix: str = "") -> dict:
|
||||
"""Leaves of `elem` into `row`. A nested alias (name + namingSystem) becomes `<tag>_<namingSystem>`;
|
||||
other nested elements prefix their leaves with their tag, numbered from the second occurrence on."""
|
||||
seen = collections.Counter()
|
||||
for child in elem:
|
||||
tag = _tag(child)
|
||||
if len(child) == 0:
|
||||
self._put(row, prefix + tag, self.value(child, prefix + tag))
|
||||
continue
|
||||
names = {_tag(g): (g.text or "").strip() for g in child}
|
||||
if set(names) == {"name", "namingSystem"}:
|
||||
self._put(row, f"{prefix}{tag}_{_slug(names['namingSystem'])}", names["name"] or None)
|
||||
continue
|
||||
seen[tag] += 1
|
||||
self.leaves(child, row, f"{prefix}{tag}{seen[tag] if seen[tag] > 1 else ''}_")
|
||||
return row
|
||||
|
||||
@staticmethod
|
||||
def _put(row: dict, key: str, value) -> None:
|
||||
k, n = key, 1
|
||||
while k in row: # repeated leaf: keep both, never overwrite
|
||||
n += 1
|
||||
k = f"{key}_{n}"
|
||||
row[k] = value
|
||||
|
||||
|
||||
def parse_file(path: Path) -> ParsedReport:
|
||||
root = ET.parse(path).getroot()
|
||||
reports = root.findall(NS + "drillReport")
|
||||
if len(reports) != 1:
|
||||
raise ValueError(f"{path.name}: {len(reports)} drillReport elements, expected 1")
|
||||
(dr,) = reports
|
||||
m = _FILE.fullmatch(path.stem)
|
||||
if not m:
|
||||
raise ValueError(f"unexpected DDR file name: {path.name}")
|
||||
report_id = path.stem
|
||||
parsed = ParsedReport(report={})
|
||||
head = _Flattener(parsed, "reports")
|
||||
rep = {"report_id": report_id, "file_wellbore": canonical(m.group(1)),
|
||||
"file_date": f"{m.group(2)}-{m.group(3)}-{m.group(4)}"}
|
||||
for child in dr:
|
||||
tag = _tag(child)
|
||||
if tag in SECTIONS:
|
||||
continue
|
||||
if len(child) == 0:
|
||||
head._put(rep, tag, head.value(child, tag))
|
||||
elif tag in REPORT_GROUPS:
|
||||
head.leaves(child, rep)
|
||||
else: # wellAlias / wellboreAlias: name + namingSystem
|
||||
names = {_tag(g): (g.text or "").strip() for g in child}
|
||||
head._put(rep, f"{tag}_{_slug(names.get('namingSystem', 'name'))}", names.get("name") or None)
|
||||
rep["wellbore"] = canonical(rep["nameWellbore"])
|
||||
parsed.report = rep
|
||||
for child in dr:
|
||||
tag = _tag(child)
|
||||
if tag not in SECTIONS:
|
||||
continue
|
||||
table = SECTIONS[tag]
|
||||
rows = parsed.sections[table]
|
||||
row = {"report_id": report_id, "wellbore": rep["wellbore"], "seq": len(rows)}
|
||||
_Flattener(parsed, table).leaves(child, row)
|
||||
if table == "activities":
|
||||
row["act_id"] = f"{report_id}:{row['seq']:03d}"
|
||||
code = row.get("proprietaryCode") or ""
|
||||
main, _, sub = code.partition(" -- ")
|
||||
row["code_main"], row["code_sub"] = main or None, sub or None
|
||||
rows.append(row)
|
||||
return parsed
|
||||
|
||||
|
||||
def _utc(s: pd.Series) -> pd.Series:
|
||||
return pd.to_datetime(s, utc=True, format="ISO8601")
|
||||
|
||||
|
||||
def parse_dir(directory: Path) -> dict[str, pd.DataFrame]:
|
||||
"""All drillReport files of `directory` as DataFrames: `reports`, one table per section, `units`, `sentinels`."""
|
||||
files = sorted(directory.glob("*.xml"))
|
||||
if not files:
|
||||
raise FileNotFoundError(f"no XML files in {directory}")
|
||||
reports: list[dict] = []
|
||||
sections: dict[str, list[dict]] = collections.defaultdict(list)
|
||||
units: dict[tuple[str, str], set] = collections.defaultdict(set)
|
||||
unit_files: collections.Counter = collections.Counter()
|
||||
sentinels: collections.Counter = collections.Counter()
|
||||
for f in files:
|
||||
p = parse_file(f)
|
||||
reports.append(p.report)
|
||||
for table, rows in p.sections.items():
|
||||
sections[table].extend(rows)
|
||||
for key, u in p.units.items():
|
||||
units[key].add(u)
|
||||
unit_files[key] += 1
|
||||
sentinels.update(p.sentinels)
|
||||
mixed = {k: v for k, v in units.items() if len(v) > 1}
|
||||
if mixed:
|
||||
raise ValueError(f"columns published in more than one unit: {mixed}")
|
||||
|
||||
out = {"reports": pd.DataFrame(reports)}
|
||||
for table in SECTIONS.values():
|
||||
out[table] = pd.DataFrame(sections.get(table, []))
|
||||
r = out["reports"]
|
||||
r["start_utc"], r["end_utc"] = _utc(r["dTimStart"]), _utc(r["dTimEnd"])
|
||||
r["stem_ok"] = [stem(w) == stem(fw) for w, fw in zip(r["wellbore"], r["file_wellbore"])]
|
||||
a = out["activities"]
|
||||
a["start_utc"], a["end_utc"] = _utc(a["dTimStart"]), _utc(a["dTimEnd"])
|
||||
a["duration_h"] = (a["end_utc"] - a["start_utc"]).dt.total_seconds() / 3600
|
||||
out["units"] = pd.DataFrame([{"table": t, "column": c, "uom": u, "datum": d, "n_files": unit_files[(t, c)]}
|
||||
for (t, c), ((u, d),) in sorted(units.items())])
|
||||
out["sentinels"] = pd.DataFrame([{"table": t, "column": c, "n": n} for (t, c), n in sorted(sentinels.items())])
|
||||
return out
|
||||
Reference in New Issue
Block a user