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:
3
volve_dia/__init__.py
Normal file
3
volve_dia/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
"""Volve-DIA: drilling-intelligence benchmark on the public Volve daily drilling reports."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
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
|
||||
42
volve_dia/names.py
Normal file
42
volve_dia/names.py
Normal file
@@ -0,0 +1,42 @@
|
||||
"""Wellbore names. Volve spells one wellbore in up to five ways:
|
||||
|
||||
DDR XML nameWellbore NO 15/9-F-15 A
|
||||
DDR file stem 15_9_F_15_A (15_9_F_15_A_2009_05_01.xml)
|
||||
NPD code (wellboreAlias) 15/9-F-15 A
|
||||
WITSML folder Norway-StatoilHydro-15_$47$_9-F-15A
|
||||
WITSML MetaFileInfo.txt 15/9-F-15A, NO 15/9-F-1 B
|
||||
|
||||
`canonical` maps every form to the NPD code with one space before the sidetrack suffix ("15/9-F-15 A"),
|
||||
`stem` maps a canonical name back to the file-stem form.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
_FOLDER_PREFIX = re.compile(r"^[A-Za-z]+-[A-Za-z]+-(?=(?:NO\s+)?\d)") # Norway-Statoil-, NA-NA-
|
||||
_STEM = re.compile(r"(\d+)_(\d+)_(?:(F)_)?(\d+)(?:_([A-Z]+\d*))?")
|
||||
_NPD = re.compile(r"(\d+/\d+-(?:F-)?\d+)\s*([A-Z]+\d*)?")
|
||||
|
||||
|
||||
def canonical(name: str) -> str:
|
||||
s = re.sub(r"\s+", " ", name.strip()).replace("_$47$_", "/").replace("$47$", "/")
|
||||
s = _FOLDER_PREFIX.sub("", s)
|
||||
s = re.sub(r"^NO\s+", "", s)
|
||||
m = _STEM.fullmatch(s)
|
||||
if m:
|
||||
a, b, f, n, suffix = m.groups()
|
||||
s = f"{a}/{b}-{'F-' if f else ''}{n}" + (f" {suffix}" if suffix else "")
|
||||
m = _NPD.fullmatch(s)
|
||||
if not m:
|
||||
raise ValueError(f"not a Volve wellbore name: {name!r}")
|
||||
return m.group(1) + (f" {m.group(2)}" if m.group(2) else "")
|
||||
|
||||
|
||||
def stem(name: str) -> str:
|
||||
return re.sub(r"[/\- ]", "_", canonical(name))
|
||||
|
||||
|
||||
def well_of(name: str) -> str:
|
||||
"""The well (slot) a wellbore belongs to: '15/9-F-15 A' -> '15/9-F-15'."""
|
||||
return canonical(name).split(" ")[0]
|
||||
426
volve_dia/ocr.py
Normal file
426
volve_dia/ocr.py
Normal file
@@ -0,0 +1,426 @@
|
||||
"""chandra OCR of PDF pages, read the way vopec-chatbot reads a page with no text layer (app/docs/ocr.py, the vllm
|
||||
route, commit 25076e6): one 200-DPI PNG per chat completion with the same prompt, temperature 0, the same token cap,
|
||||
the same loop cut and the same block parsing (`LABEL_MAP`, `html_blocks`, `text_of`, `bbox`).
|
||||
|
||||
Differences, all additive:
|
||||
* every page answer is cached on disk (`outputs/ocr/pages/<doc sha256[:16]>/pNNNN.json`) together with what produced
|
||||
it: model, prompt hash, DPI, token cap, temperature. A cached answer is reused only when all of them match;
|
||||
* the stream asks for token usage, and the finish reason is kept (`length` = the token cap was hit);
|
||||
* transport errors and 5xx answers are retried (`retries`), a failure is recorded, and a later run retries it;
|
||||
* the service is checked once before any page is rendered (`check_service`), and a run stops sending pages after
|
||||
`stop_after_failed` pages in a row failed (the service went down), leaving the rest for the next run;
|
||||
* a block keeps chandra's own label (`raw_label`) and its inner HTML for every label, not only for tables.
|
||||
|
||||
The service URL comes from VOLVE_DIA_OCR_URL (`.env`) and is never written to a log or a cache file.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, timezone
|
||||
from html import unescape
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable
|
||||
|
||||
import httpx
|
||||
import yaml
|
||||
|
||||
from .paths import REPO_ROOT, load_env, outputs_dir
|
||||
|
||||
MEGABYTE = 1024 * 1024
|
||||
CONFIG = REPO_ROOT / "configs" / "ocr.yaml"
|
||||
|
||||
#: chandra label -> block label, verbatim from vopec-chatbot.
|
||||
LABEL_MAP = {
|
||||
"title": "title", "section-header": "section_header", "section_header": "section_header",
|
||||
"sectionheader": "section_header", "heading": "section_header", "text": "paragraph", "paragraph": "paragraph",
|
||||
"plain-text": "paragraph", "list-item": "list_item", "list_item": "list_item", "list": "list_item",
|
||||
"table": "table", "caption": "caption", "footnote": "footnote", "formula": "formula", "equation": "formula",
|
||||
"page-header": "page_header", "page_header": "page_header", "page-footer": "page_footer",
|
||||
"page_footer": "page_footer", "picture": "picture", "figure": "picture", "image": "picture",
|
||||
"section header": "section_header", "header": "paragraph", "footer": "page_footer",
|
||||
}
|
||||
_DIV = re.compile(r'<div\s+data-bbox="([^"]*)"\s+data-label="([^"]*)"\s*>')
|
||||
#: What a cached page answer must match to be reused.
|
||||
KEY_FIELDS = ("model", "prompt_sha256", "dpi", "max_tokens", "temperature")
|
||||
|
||||
|
||||
class OCRError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Config:
|
||||
model: str
|
||||
prompt: str
|
||||
prompt_sha256: str
|
||||
dpi: int
|
||||
max_tokens: int
|
||||
temperature: float
|
||||
workers: int
|
||||
timeout_s: float
|
||||
retries: int
|
||||
loop_chars: int
|
||||
loop_max_unit: int
|
||||
loop_check_every: int
|
||||
max_page_image_mb: float
|
||||
stop_after_failed: int
|
||||
|
||||
def key(self) -> dict:
|
||||
return {k: getattr(self, k) for k in KEY_FIELDS}
|
||||
|
||||
|
||||
def load_config(path: Path = CONFIG) -> Config:
|
||||
raw = yaml.safe_load(path.read_text(encoding="utf-8"))
|
||||
prompt_file = REPO_ROOT / raw.pop("prompt_file")
|
||||
data = prompt_file.read_bytes()
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
if digest != raw["prompt_sha256"]:
|
||||
raise OCRError(f"{prompt_file.name}: sha256 {digest} != prompt_sha256 in {path.name}; "
|
||||
"the prompt changed, so every cached page answer is stale")
|
||||
return Config(prompt=data.decode("utf-8").strip(), **raw)
|
||||
|
||||
|
||||
def service_url() -> str:
|
||||
load_env()
|
||||
url = os.environ.get("VOLVE_DIA_OCR_URL", "").strip().rstrip("/")
|
||||
if not url:
|
||||
raise OCRError("VOLVE_DIA_OCR_URL is not set (put it in .env)")
|
||||
return url
|
||||
|
||||
|
||||
def check_service(client: httpx.Client, cfg: Config) -> None:
|
||||
"""Raise OCRError unless the service answers /v1/models and serves `cfg.model`. The message never holds the URL."""
|
||||
try:
|
||||
resp = client.get("/v1/models", timeout=30)
|
||||
except httpx.TransportError as exc:
|
||||
raise OCRError(f"OCR service not reachable: {type(exc).__name__}") from None
|
||||
if resp.status_code != 200:
|
||||
raise OCRError(f"OCR service not available: HTTP {resp.status_code}")
|
||||
try:
|
||||
served = [m.get("id") for m in resp.json().get("data", [])]
|
||||
except ValueError:
|
||||
raise OCRError("OCR service: /v1/models did not answer JSON") from None
|
||||
if cfg.model not in served:
|
||||
raise OCRError(f"OCR service does not serve {cfg.model!r} (it serves {served})")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- page answers -> blocks (vopec)
|
||||
|
||||
@dataclass
|
||||
class Block:
|
||||
page: int
|
||||
label: str # vopec label (LABEL_MAP)
|
||||
raw_label: str # chandra's own label
|
||||
text: str
|
||||
bbox: list[float]
|
||||
reading_order: int
|
||||
html: str # inner HTML of the block
|
||||
|
||||
|
||||
def html_blocks(content: str, number: int) -> list[Block]:
|
||||
blocks: list[Block] = []
|
||||
parts = _DIV.split(content)
|
||||
for raw_bbox, raw_label, body in zip(parts[1::3], parts[2::3], parts[3::3]):
|
||||
inner = re.sub(r"</div>\s*$", "", body.strip())
|
||||
text = text_of(inner)
|
||||
if not text:
|
||||
continue
|
||||
blocks.append(Block(page=number, label=LABEL_MAP.get(raw_label.strip().lower(), "paragraph"),
|
||||
raw_label=raw_label.strip(), text=text, bbox=bbox(raw_bbox.split()),
|
||||
reading_order=len(blocks), html=inner))
|
||||
return blocks
|
||||
|
||||
|
||||
def text_of(html: str) -> str:
|
||||
text = re.sub(r"</t[dh]>", " | ", html)
|
||||
text = re.sub(r"</tr>|<br\s*/?>|</p>", "\n", text)
|
||||
text = unescape(re.sub(r"<[^>]+>", "", text))
|
||||
lines = [re.sub(r"\s+", " ", line).strip(" |") for line in text.splitlines()]
|
||||
return "\n".join(line for line in lines if line)
|
||||
|
||||
|
||||
def bbox(raw: Any) -> list[float]:
|
||||
"""``xyxy_normalized_1000`` as four floats, or empty when unusable."""
|
||||
if isinstance(raw, dict):
|
||||
raw = raw.get("xyxy_normalized_1000") or raw.get("xyxy") or raw.get("bbox") or raw.get("coordinates")
|
||||
if not isinstance(raw, (list, tuple)) or len(raw) != 4:
|
||||
return []
|
||||
try:
|
||||
return [round(float(v), 1) for v in raw]
|
||||
except (TypeError, ValueError):
|
||||
return []
|
||||
|
||||
|
||||
def loop_start(text: str, cfg: Config) -> int | None:
|
||||
"""Where a repetition loop starts: the last `loop_chars` are one unit of at most `loop_max_unit` characters
|
||||
repeated (vopec: seen on a scanned empty table grid, blank rows up to the token cap). The cut is moved back to
|
||||
the start of the repetition and out of an open tag."""
|
||||
if len(text) < cfg.loop_chars:
|
||||
return None
|
||||
tail = text[-cfg.loop_chars:]
|
||||
for unit in range(1, cfg.loop_max_unit + 1):
|
||||
if tail[unit:] == tail[:-unit]:
|
||||
start = len(text) - cfg.loop_chars
|
||||
while start > 0 and text[start - 1] == text[start - 1 + unit]:
|
||||
start -= 1
|
||||
if text.rfind("<", 0, start) > text.rfind(">", 0, start):
|
||||
start = text.find(">", start) + 1
|
||||
return start
|
||||
return None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- one page
|
||||
|
||||
def payload(png: bytes, cfg: Config) -> dict:
|
||||
return {"model": cfg.model, "temperature": cfg.temperature, "max_tokens": cfg.max_tokens,
|
||||
"messages": [{"role": "user", "content": [
|
||||
{"type": "image_url", "image_url": {"url": "data:image/png;base64," + base64.b64encode(png).decode()}},
|
||||
{"type": "text", "text": cfg.prompt}]}]}
|
||||
|
||||
|
||||
def complete(client: httpx.Client, body: dict, cfg: Config) -> dict:
|
||||
"""One streamed chat completion: content (cut at a loop), looped, finish_reason, usage."""
|
||||
parts: list[str] = []
|
||||
size = checked = 0
|
||||
finish, usage = None, None
|
||||
req = {**body, "stream": True, "stream_options": {"include_usage": True}}
|
||||
with client.stream("POST", "/v1/chat/completions", json=req) as resp:
|
||||
if resp.status_code >= 400:
|
||||
resp.read()
|
||||
raise httpx.HTTPStatusError(f"{resp.status_code} {resp.text[:200]}", request=resp.request, response=resp)
|
||||
for line in resp.iter_lines():
|
||||
if not line.startswith("data: ") or line.strip() == "data: [DONE]":
|
||||
continue
|
||||
chunk = json.loads(line[6:])
|
||||
usage = chunk.get("usage") or usage
|
||||
choices = chunk.get("choices") or []
|
||||
if not choices:
|
||||
continue
|
||||
finish = choices[0].get("finish_reason") or finish
|
||||
delta = (choices[0].get("delta") or {}).get("content") or ""
|
||||
parts.append(delta)
|
||||
size += len(delta)
|
||||
if size - checked >= cfg.loop_check_every:
|
||||
checked = size
|
||||
text = "".join(parts)
|
||||
cut = loop_start(text, cfg)
|
||||
if cut is not None:
|
||||
return {"content": text[:cut], "looped": True, "finish_reason": "loop", "usage": usage}
|
||||
return {"content": "".join(parts), "looped": False, "finish_reason": finish, "usage": usage}
|
||||
|
||||
|
||||
def _retryable(exc: Exception) -> bool:
|
||||
if isinstance(exc, httpx.HTTPStatusError):
|
||||
return exc.response.status_code >= 500 or exc.response.status_code == 429
|
||||
return isinstance(exc, (httpx.TransportError, json.JSONDecodeError))
|
||||
|
||||
|
||||
def read_page(client: httpx.Client, png: bytes, cfg: Config) -> dict:
|
||||
"""OCR one page image, retrying transport errors, 429 and 5xx. Never raises: a failure is a record."""
|
||||
started = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
t0 = time.monotonic()
|
||||
error = None
|
||||
for attempt in range(1, cfg.retries + 2):
|
||||
try:
|
||||
answer = complete(client, payload(png, cfg), cfg)
|
||||
return {"status": "ok", **answer, "seconds": round(time.monotonic() - t0, 2), "started_utc": started,
|
||||
"attempts": attempt, "error": None}
|
||||
except Exception as exc: # noqa: BLE001 - recorded, retried on a later run
|
||||
error = f"{type(exc).__name__}: {str(exc)[:300]}"
|
||||
if not _retryable(exc) or attempt > cfg.retries:
|
||||
break
|
||||
time.sleep(10 * attempt)
|
||||
return {"status": "failed", "content": "", "looped": False, "finish_reason": None, "usage": None,
|
||||
"seconds": round(time.monotonic() - t0, 2), "started_utc": started, "attempts": attempt, "error": error}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- documents and the page cache
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with open(path, "rb") as f:
|
||||
for chunk in iter(lambda: f.read(1 << 22), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def cache_dir() -> Path:
|
||||
return outputs_dir() / "ocr" / "pages"
|
||||
|
||||
|
||||
def page_file(doc_sha256: str, page: int) -> Path:
|
||||
return cache_dir() / doc_sha256[:16] / f"p{page:04d}.json"
|
||||
|
||||
|
||||
def cached(doc_sha256: str, page: int, cfg: Config) -> dict | None:
|
||||
"""The cached answer for a page if it was produced with the current settings (failed answers included)."""
|
||||
f = page_file(doc_sha256, page)
|
||||
if not f.is_file():
|
||||
return None
|
||||
rec = json.loads(f.read_text(encoding="utf-8"))
|
||||
if rec.get("doc_sha256") != doc_sha256 or any(rec.get(k) != v for k, v in cfg.key().items()):
|
||||
return None
|
||||
return rec
|
||||
|
||||
|
||||
def _write(rec: dict) -> None:
|
||||
f = page_file(rec["doc_sha256"], rec["page"])
|
||||
f.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = f.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(rec, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
tmp.replace(f)
|
||||
|
||||
|
||||
def image_bytes(doc, page) -> int:
|
||||
"""Bytes of the images embedded in a page (vopec parse._image_bytes): a page above `max_page_image_mb` is a
|
||||
log plot rendered as one big image and is skipped."""
|
||||
try:
|
||||
return sum(len(doc.extract_image(img[0]).get("image") or b"") for img in page.get_images(full=True))
|
||||
except Exception: # noqa: BLE001 - a size hint only
|
||||
return 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class Task:
|
||||
file: str # path relative to the Volve root, for the record
|
||||
path: Path
|
||||
doc_sha256: str
|
||||
page: int # 1-based
|
||||
n_pages: int
|
||||
|
||||
|
||||
def tasks_for(pdfs: Iterable[Path], root: Path) -> list[Task]:
|
||||
import pymupdf
|
||||
|
||||
out = []
|
||||
for p in pdfs:
|
||||
sha = sha256_file(p)
|
||||
with pymupdf.open(p) as doc:
|
||||
n = doc.page_count
|
||||
out += [Task(str(p.relative_to(root)), p, sha, i, n) for i in range(1, n + 1)]
|
||||
return out
|
||||
|
||||
|
||||
def run(tasks: list[Task], cfg: Config, *, retry_failed: bool = True, progress_every: int = 25,
|
||||
limit: int | None = None) -> dict:
|
||||
"""OCR every task page not cached yet with the current settings. Pages are rendered in this thread (PyMuPDF
|
||||
is not thread-safe) and at most 2 x workers requests are in flight. Returns counts by outcome."""
|
||||
import pymupdf
|
||||
|
||||
todo = []
|
||||
counts = {"cached": 0, "ok": 0, "failed": 0, "skipped": 0}
|
||||
for t in tasks:
|
||||
rec = cached(t.doc_sha256, t.page, cfg)
|
||||
if rec is not None and (rec["status"] != "failed" or not retry_failed):
|
||||
counts["cached"] += 1
|
||||
else:
|
||||
todo.append(t)
|
||||
if limit is not None:
|
||||
todo = todo[:limit]
|
||||
print(f"[ocr] {len(tasks)} pages: {counts['cached']} cached, {len(todo)} to read with {cfg.workers} workers",
|
||||
flush=True)
|
||||
if not todo:
|
||||
return counts
|
||||
|
||||
url = service_url()
|
||||
t0 = time.monotonic()
|
||||
done = streak = 0
|
||||
pending: dict[Future, tuple[Task, dict]] = {}
|
||||
|
||||
def finish(fut: Future) -> None:
|
||||
nonlocal done, streak
|
||||
task, base = pending.pop(fut)
|
||||
rec = {**base, **fut.result()}
|
||||
_write(rec)
|
||||
counts[rec["status"]] += 1
|
||||
done += 1
|
||||
streak = streak + 1 if rec["status"] == "failed" else 0
|
||||
if rec["status"] == "failed":
|
||||
print(f"[ocr] FAILED {task.file} p{task.page}: {rec['error']}", flush=True)
|
||||
if done % progress_every == 0 or done == len(todo):
|
||||
rate = (time.monotonic() - t0) / done
|
||||
eta = rate * (len(todo) - done) / 60
|
||||
print(f"[ocr] {done}/{len(todo)} pages, {rate:.1f} s/page wall, eta {eta:.0f} min,"
|
||||
f" ok {counts['ok']} failed {counts['failed']} skipped {counts['skipped']}", flush=True)
|
||||
|
||||
with httpx.Client(base_url=url, timeout=cfg.timeout_s) as client, ThreadPoolExecutor(cfg.workers) as pool:
|
||||
check_service(client, cfg)
|
||||
open_doc = None
|
||||
for t in todo:
|
||||
if streak >= cfg.stop_after_failed:
|
||||
print(f"[ocr] stopped: {streak} pages in a row failed; the other pages are left for the next run",
|
||||
flush=True)
|
||||
break
|
||||
if open_doc is None or open_doc[0] != t.path:
|
||||
if open_doc is not None:
|
||||
open_doc[1].close()
|
||||
open_doc = (t.path, pymupdf.open(t.path))
|
||||
doc = open_doc[1]
|
||||
page = doc[t.page - 1]
|
||||
png = page.get_pixmap(dpi=cfg.dpi).tobytes("png")
|
||||
base = {"doc_sha256": t.doc_sha256, "file": t.file, "page": t.page, "n_pages": t.n_pages,
|
||||
**cfg.key(), "png_sha256": hashlib.sha256(png).hexdigest(), "png_bytes": len(png),
|
||||
"image_bytes": image_bytes(doc, page)}
|
||||
if base["image_bytes"] > cfg.max_page_image_mb * MEGABYTE:
|
||||
rec = {**base, "status": "skipped", "content": "", "looped": False, "finish_reason": None,
|
||||
"usage": None, "seconds": 0.0, "started_utc": None, "attempts": 0,
|
||||
"error": f"embedded images {base['image_bytes'] / MEGABYTE:.1f} MB > {cfg.max_page_image_mb}"}
|
||||
_write(rec)
|
||||
counts["skipped"] += 1
|
||||
done += 1
|
||||
continue
|
||||
while len(pending) >= 2 * cfg.workers:
|
||||
finished, _ = wait(pending, return_when=FIRST_COMPLETED)
|
||||
for fut in finished:
|
||||
finish(fut)
|
||||
pending[pool.submit(read_page, client, png, cfg)] = (t, base)
|
||||
if open_doc is not None:
|
||||
open_doc[1].close()
|
||||
while pending:
|
||||
finished, _ = wait(pending, return_when=FIRST_COMPLETED)
|
||||
for fut in finished:
|
||||
finish(fut)
|
||||
return counts
|
||||
|
||||
|
||||
def load_blocks(doc_sha256: str, n_pages: int, cfg: Config) -> tuple[list[Block], list[dict]]:
|
||||
"""Blocks of a document from the cache, in page and reading order, and the page records (without content).
|
||||
A page that is missing, failed or skipped contributes no blocks; its record says why."""
|
||||
blocks: list[Block] = []
|
||||
records = []
|
||||
for page in range(1, n_pages + 1):
|
||||
rec = cached(doc_sha256, page, cfg)
|
||||
if rec is None:
|
||||
records.append({"page": page, "status": "missing"})
|
||||
continue
|
||||
records.append({k: v for k, v in rec.items() if k != "content"})
|
||||
if rec["status"] == "ok":
|
||||
blocks += html_blocks(rec["content"], page)
|
||||
return blocks, records
|
||||
|
||||
|
||||
def block_dicts(blocks: list[Block]) -> list[dict]:
|
||||
return [asdict(b) for b in blocks]
|
||||
|
||||
|
||||
if __name__ == "__main__": # smoke test: python -m volve_dia.ocr some.pdf [page]
|
||||
cfg = load_config()
|
||||
pdf = Path(sys.argv[1]).resolve()
|
||||
import pymupdf
|
||||
|
||||
with pymupdf.open(pdf) as d:
|
||||
png = d[int(sys.argv[2]) - 1 if len(sys.argv) > 2 else 0].get_pixmap(dpi=cfg.dpi).tobytes("png")
|
||||
with httpx.Client(base_url=service_url(), timeout=cfg.timeout_s) as c:
|
||||
rec = read_page(c, png, cfg)
|
||||
print(json.dumps({k: v for k, v in rec.items() if k != "content"}, indent=1))
|
||||
for b in html_blocks(rec["content"], 1):
|
||||
print(f"[{b.raw_label} -> {b.label}] {b.text[:100]!r}")
|
||||
57
volve_dia/paths.py
Normal file
57
volve_dia/paths.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""Project paths. No absolute paths: everything is resolved from the repository root or from the
|
||||
environment variables VOLVE_DIA_VOLVE_ROOT / VOLVE_DIA_OUTPUTS, which may also be set in `.env`."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def load_env(path: Path | None = None) -> None:
|
||||
"""Read KEY=VALUE lines of `.env` into os.environ. Variables already set in the environment win."""
|
||||
path = path or REPO_ROOT / ".env"
|
||||
if not path.is_file():
|
||||
return
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
os.environ.setdefault(key.strip(), value.strip().strip("'\""))
|
||||
|
||||
|
||||
def volve_root() -> Path:
|
||||
"""Volve directory downloaded from the Data Village (Well_technical_data/, WITSML Realtime drilling data/, ...)."""
|
||||
env = os.environ.get("VOLVE_DIA_VOLVE_ROOT")
|
||||
return Path(env) if env else REPO_ROOT / "data" / "Volve"
|
||||
|
||||
|
||||
def well_technical_dir() -> Path:
|
||||
return volve_root() / "Well_technical_data"
|
||||
|
||||
|
||||
def ddr_xml_dir() -> Path:
|
||||
"""1,759 WITSML 1.4 drillReport files: the ground truth of every label."""
|
||||
return well_technical_dir() / "Daily Drilling Report - XML Version"
|
||||
|
||||
|
||||
def ddr_html_dir() -> Path:
|
||||
"""The same reports rendered to HTML by the publisher (what the PDF version prints)."""
|
||||
return well_technical_dir() / "Daily Drilling Report - HTML Version"
|
||||
|
||||
|
||||
def ddr_pdf_dir() -> Path:
|
||||
return well_technical_dir() / "Daily Drilling report - PDF Version"
|
||||
|
||||
|
||||
def witsml_dir() -> Path:
|
||||
return volve_root() / "WITSML Realtime drilling data"
|
||||
|
||||
|
||||
def outputs_dir() -> Path:
|
||||
env = os.environ.get("VOLVE_DIA_OUTPUTS")
|
||||
p = Path(env) if env else REPO_ROOT / "outputs"
|
||||
p.mkdir(parents=True, exist_ok=True)
|
||||
return p
|
||||
401
volve_dia/runlog.py
Normal file
401
volve_dia/runlog.py
Normal file
@@ -0,0 +1,401 @@
|
||||
"""Log and runtime recording for every run.
|
||||
|
||||
python -m volve_dia.runlog [-n NAME] [--note "..."] [--] <command> [args...]
|
||||
python -m volve_dia.runlog ls [-k 30] # most recent runs + runs in progress
|
||||
python -m volve_dia.runlog reindex # rebuild logs/index.csv from the meta.json files
|
||||
|
||||
Each run creates `logs/runs/<YYYYmmdd-HHMMSS>_<name>/` (root overridable via VOLVE_DIA_LOGS):
|
||||
log.txt merged stdout + stderr, including child workers (ProcessPool); each line carries the elapsed time [h:mm:ss]
|
||||
meta.json command, cwd, git commit + dirty state + source hash, thread/GPU variables, device, start/end,
|
||||
wall/CPU time, peak RSS, peak VRAM of the process tree, exit code; written at start with status=running
|
||||
and appends one row to `logs/index.csv`. A `.py` file at the head of the command is run with the current python.
|
||||
For nested calls (RUNLOG_DIR already set, e.g. the individual steps of scripts/run_p0.sh), the child step is placed
|
||||
inside the parent run's directory, and the `parent` column of the index points to the parent run.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import shlex
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
import fcntl
|
||||
import resource
|
||||
except ImportError: # Native Windows: neither module exists.
|
||||
fcntl = resource = None
|
||||
|
||||
from .paths import REPO_ROOT
|
||||
|
||||
FIELDS = ["run_id", "parent", "name", "status", "exit_code", "start", "end", "wall_s", "wall",
|
||||
"device", "git", "dirty", "code_sha", "source", "cmd"]
|
||||
ENV_KEYS = ["CUDA_VISIBLE_DEVICES", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS",
|
||||
"PYTHONHASHSEED", "DEVICE", "WORKERS", "VOLVE_DIA_OUTPUTS", "VOLVE_DIA_VOLVE_ROOT"]
|
||||
CODE_DIRS = ["volve_dia", "scripts", "configs", "tests"]
|
||||
GPU_POLL_S = 15.0
|
||||
|
||||
|
||||
def logs_dir() -> Path:
|
||||
env = os.environ.get("VOLVE_DIA_LOGS")
|
||||
return Path(env) if env else REPO_ROOT / "logs"
|
||||
|
||||
|
||||
def now() -> dt.datetime:
|
||||
return dt.datetime.now().astimezone()
|
||||
|
||||
|
||||
def fmt_wall(s: float | None) -> str:
|
||||
if s is None:
|
||||
return ""
|
||||
h, r = divmod(int(round(s)), 3600)
|
||||
return f"{h}:{r // 60:02d}:{r % 60:02d}"
|
||||
|
||||
|
||||
def _out(cmd: list[str]) -> str:
|
||||
try:
|
||||
return subprocess.run(cmd, capture_output=True, text=True, timeout=20, cwd=REPO_ROOT).stdout.strip()
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return ""
|
||||
|
||||
|
||||
def git_state() -> dict:
|
||||
"""Commit + working-tree state. Since uncommitted code may also be run, a content hash of the files in
|
||||
CODE_DIRS (tracked + untracked, excluding ignored files) is recorded to identify the exact code version run."""
|
||||
st = _out(["git", "status", "--porcelain"]).splitlines()
|
||||
files = sorted(_out(["git", "ls-files", "-co", "--exclude-standard", *CODE_DIRS]).splitlines())
|
||||
h = hashlib.sha256()
|
||||
for f in files:
|
||||
p = REPO_ROOT / f
|
||||
if p.is_file():
|
||||
h.update(f.encode() + b"\0" + p.read_bytes() + b"\0")
|
||||
return {"commit": _out(["git", "rev-parse", "--short=12", "HEAD"]), "branch": _out(["git", "branch", "--show-current"]),
|
||||
"dirty": any(not s.startswith("??") for s in st), "n_modified": sum(not s.startswith("??") for s in st),
|
||||
"n_untracked": sum(s.startswith("??") for s in st), "code_sha256": h.hexdigest()[:16] if files else ""}
|
||||
|
||||
|
||||
def gpu_state() -> list[dict]:
|
||||
rows = _out(["nvidia-smi", "--query-gpu=index,memory.used,memory.total,utilization.gpu",
|
||||
"--format=csv,noheader,nounits"])
|
||||
out = []
|
||||
for r in rows.splitlines():
|
||||
try:
|
||||
i, used, tot, util = (int(x) for x in r.split(","))
|
||||
except ValueError:
|
||||
continue
|
||||
out.append({"index": i, "mem_used_mib": used, "mem_total_mib": tot, "util_pct": util})
|
||||
return out
|
||||
|
||||
|
||||
def _group_pids(pgid: int) -> set[int]:
|
||||
if os.name == 'nt':
|
||||
import psutil
|
||||
try:
|
||||
parent = psutil.Process(pgid)
|
||||
return {pgid, *(p.pid for p in parent.children(recursive=True))}
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
||||
return set()
|
||||
pids = set()
|
||||
for d in Path("/proc").iterdir():
|
||||
if d.name.isdigit():
|
||||
try:
|
||||
if os.getpgid(int(d.name)) == pgid:
|
||||
pids.add(int(d.name))
|
||||
except OSError:
|
||||
pass
|
||||
return pids
|
||||
|
||||
|
||||
class GpuSampler(threading.Thread):
|
||||
"""Sample the VRAM of the process tree (same process group as the child process) every GPU_POLL_S seconds."""
|
||||
|
||||
def __init__(self, pgid: int):
|
||||
super().__init__(daemon=True)
|
||||
self.pgid, self.peak, self.stop = pgid, None, threading.Event()
|
||||
|
||||
def run(self) -> None:
|
||||
wait = 2.0 # early first sample so that short jobs still get a reading
|
||||
while not self.stop.wait(wait):
|
||||
wait = GPU_POLL_S
|
||||
rows = _out(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"])
|
||||
if not rows:
|
||||
continue
|
||||
pids = _group_pids(self.pgid)
|
||||
tot = 0
|
||||
measured = False
|
||||
for r in rows.splitlines():
|
||||
try:
|
||||
pid, mem = (int(x) for x in r.split(","))
|
||||
except ValueError:
|
||||
continue
|
||||
measured = True
|
||||
tot += mem if pid in pids else 0
|
||||
if measured:
|
||||
self.peak = max(self.peak or 0, tot)
|
||||
|
||||
|
||||
def default_name(cmd: list[str]) -> str:
|
||||
for a in cmd:
|
||||
m = re.search(r"(\d\d_\w+)\.py$", a) or re.search(r"(run_p\d+)\.sh$", a)
|
||||
if m:
|
||||
return m.group(1)
|
||||
if "pytest" in cmd:
|
||||
return "pytest"
|
||||
return re.sub(r"\W+", "_", Path(cmd[0]).stem) or "run"
|
||||
|
||||
|
||||
def device_of(cmd: list[str]) -> str:
|
||||
for i, a in enumerate(cmd):
|
||||
if a == "--device" and i + 1 < len(cmd):
|
||||
return cmd[i + 1]
|
||||
if a.startswith("--device="):
|
||||
return a.split("=", 1)[1]
|
||||
return os.environ.get("DEVICE", "")
|
||||
|
||||
|
||||
def write_json(path: Path, obj: dict) -> None:
|
||||
tmp = path.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(obj, indent=1, ensure_ascii=False, default=str), encoding='utf-8')
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
def append_index(row: dict, root: Path | None = None) -> None:
|
||||
root = root or logs_dir()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
with open(root / "index.csv", "a+", newline="", encoding='utf-8') as f:
|
||||
lock = None
|
||||
if fcntl is not None:
|
||||
fcntl.flock(f, fcntl.LOCK_EX)
|
||||
else:
|
||||
import msvcrt
|
||||
lock = open(root / '.index.lock', 'a+b')
|
||||
lock.seek(0, 2)
|
||||
if lock.tell() == 0:
|
||||
lock.write(b'0')
|
||||
lock.flush()
|
||||
lock.seek(0)
|
||||
msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)
|
||||
try:
|
||||
f.seek(0)
|
||||
new = not f.read(1)
|
||||
w = csv.DictWriter(f, FIELDS, extrasaction="ignore", lineterminator='\n')
|
||||
if new:
|
||||
w.writeheader()
|
||||
w.writerow(row)
|
||||
f.flush()
|
||||
finally:
|
||||
if fcntl is not None:
|
||||
fcntl.flock(f, fcntl.LOCK_UN)
|
||||
elif lock is not None:
|
||||
lock.seek(0)
|
||||
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
|
||||
lock.close()
|
||||
|
||||
|
||||
def index_row(meta: dict) -> dict:
|
||||
g = meta.get("git", {})
|
||||
return {"run_id": meta["run_id"], "parent": meta.get("parent") or "", "name": meta["name"], "status": meta["status"],
|
||||
"exit_code": "" if meta.get("exit_code") is None else meta["exit_code"], "start": meta.get("start") or "",
|
||||
"end": meta.get("end") or "", "wall_s": "" if meta.get("wall_s") is None else round(meta["wall_s"], 1),
|
||||
"wall": fmt_wall(meta.get("wall_s")), "device": meta.get("device", ""), "git": g.get("commit", ""),
|
||||
"dirty": g.get("dirty", ""), "code_sha": g.get("code_sha256", ""), "source": meta.get("source", "runlog"),
|
||||
"cmd": " ⏎ ".join(meta["cmd"].splitlines())}
|
||||
|
||||
|
||||
def new_run_dir(name: str, start: dt.datetime) -> tuple[Path, str, str | None]:
|
||||
parent = os.environ.get("RUNLOG_DIR")
|
||||
if parent and Path(parent).is_dir():
|
||||
k = sum(1 for p in Path(parent).iterdir() if p.is_dir()) + 1
|
||||
while any(Path(parent).glob(f"{k:02d}_*")):
|
||||
k += 1
|
||||
d = Path(parent) / f"{k:02d}_{name}"
|
||||
return d, f"{Path(parent).name}/{d.name}", os.environ.get("RUNLOG_ID")
|
||||
base = logs_dir() / "runs" / f"{start:%Y%m%d-%H%M%S}_{name}"
|
||||
d, k = base, 1
|
||||
while d.exists(): # two runs started in the same second
|
||||
k += 1
|
||||
d = base.with_name(f"{base.name}-{k}")
|
||||
return d, d.name, None
|
||||
|
||||
|
||||
class Tee:
|
||||
"""Write the child process bytes to the terminal (verbatim) and to log.txt (prefixing each line with [h:mm:ss])."""
|
||||
|
||||
def __init__(self, path: Path, t0: float, stamp: bool):
|
||||
self.f, self.t0, self.stamp, self.bol, self.echo = open(path, "ab"), t0, stamp, True, True
|
||||
|
||||
def write(self, b: bytes) -> None:
|
||||
if self.echo:
|
||||
try:
|
||||
sys.stdout.buffer.write(b)
|
||||
sys.stdout.buffer.flush()
|
||||
except (BrokenPipeError, ValueError): # terminal/pipe closed: keep writing to log.txt
|
||||
self.echo = False
|
||||
if self.stamp:
|
||||
parts = b.split(b"\n")
|
||||
out = []
|
||||
for i, p in enumerate(parts):
|
||||
if self.bol and (p or i < len(parts) - 1):
|
||||
out.append(f"[{fmt_wall(time.time() - self.t0)}] ".encode())
|
||||
self.bol = False
|
||||
out.append(p)
|
||||
if i < len(parts) - 1:
|
||||
out.append(b"\n")
|
||||
self.bol = True
|
||||
b = b"".join(out)
|
||||
self.f.write(b)
|
||||
self.f.flush()
|
||||
|
||||
def note(self, s: str) -> None:
|
||||
self.f.write(f"# {s}\n".encode())
|
||||
self.f.flush()
|
||||
|
||||
|
||||
def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int:
|
||||
if cmd and cmd[0].endswith(".py"):
|
||||
cmd = [sys.executable, *cmd]
|
||||
name = re.sub(r"[^\w.-]+", "_", name or default_name(cmd))
|
||||
start = now()
|
||||
rdir, run_id, parent = new_run_dir(name, start)
|
||||
rdir.mkdir(parents=True)
|
||||
t0 = time.time()
|
||||
meta = {"run_id": run_id, "parent": parent, "name": name, "note": note, "status": "running", "exit_code": None,
|
||||
"cmd": shlex.join(cmd), "argv": cmd, "cwd": os.getcwd(), "start": start.isoformat(timespec="seconds"),
|
||||
"end": None, "wall_s": None, "device": device_of(cmd), "host": socket.gethostname(),
|
||||
"user": os.environ.get("USER", ""), "launcher_pid": os.getpid(), "python": platform.python_version(),
|
||||
"env": {k: os.environ[k] for k in ENV_KEYS if k in os.environ}, "git": git_state(),
|
||||
"gpu_start": gpu_state(), "source": "runlog"}
|
||||
write_json(rdir / "meta.json", meta)
|
||||
tee = Tee(rdir / "log.txt", t0, stamp)
|
||||
tee.note(f"{run_id} {meta['start']} {meta['cmd']}")
|
||||
|
||||
env = os.environ | {"RUNLOG_DIR": str(rdir), "RUNLOG_ID": run_id, "PYTHONUNBUFFERED": "1", "PYTHONUTF8": "1"}
|
||||
try:
|
||||
group = {'creationflags': subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == 'nt' else {'process_group': 0}
|
||||
child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, **group)
|
||||
except OSError as e:
|
||||
tee.note(f"failed to launch: {e}")
|
||||
child = None
|
||||
got = []
|
||||
|
||||
def forward(sig, _frame): # Ctrl-C / kill: forward to the whole child process group and record it
|
||||
got.append(signal.Signals(sig).name)
|
||||
if child is not None:
|
||||
try:
|
||||
if os.name == 'nt':
|
||||
child.send_signal(signal.CTRL_BREAK_EVENT) if sig in (signal.SIGINT, signal.SIGBREAK) else child.terminate()
|
||||
else:
|
||||
os.killpg(child.pid, sig)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
signals = [signal.SIGINT, signal.SIGTERM]
|
||||
signals += [getattr(signal, name) for name in ('SIGHUP', 'SIGBREAK') if hasattr(signal, name)]
|
||||
for s in signals:
|
||||
signal.signal(s, forward)
|
||||
sampler = None
|
||||
if child is not None:
|
||||
sampler = GpuSampler(child.pid)
|
||||
sampler.start()
|
||||
fd = child.stdout.fileno()
|
||||
while True:
|
||||
try:
|
||||
b = os.read(fd, 65536)
|
||||
except InterruptedError:
|
||||
continue
|
||||
if not b:
|
||||
break
|
||||
tee.write(b)
|
||||
code = child.wait()
|
||||
sampler.stop.set()
|
||||
else:
|
||||
code = 127
|
||||
ru = resource.getrusage(resource.RUSAGE_CHILDREN) if resource is not None else None
|
||||
wall = time.time() - t0
|
||||
status = "ok" if code == 0 else ("interrupted" if got or code < 0 else "failed")
|
||||
meta |= {"status": status, "exit_code": code, "signals": got, "end": now().isoformat(timespec="seconds"),
|
||||
"wall_s": round(wall, 2), "wall": fmt_wall(wall), "cpu_user_s": round(ru.ru_utime, 1) if ru else None,
|
||||
"cpu_sys_s": round(ru.ru_stime, 1) if ru else None, "max_rss_mib": round(ru.ru_maxrss / 1024) if ru else None,
|
||||
"gpu_peak_mib": sampler.peak if sampler else None, "gpu_end": gpu_state()}
|
||||
write_json(rdir / "meta.json", meta)
|
||||
tee.note(f"{status} exit {code} wall {fmt_wall(wall)} ({wall:.1f} s)")
|
||||
append_index(index_row(meta))
|
||||
print(f"[runlog] {status} exit {code} wall {fmt_wall(wall)} -> {rdir}", file=sys.stderr, flush=True)
|
||||
return code if code >= 0 else 128 - code
|
||||
|
||||
|
||||
def all_metas(root: Path) -> list[dict]:
|
||||
metas = [json.loads(m.read_text(encoding='utf-8')) for m in [*(root / "runs").glob("*/meta.json"), *(root / "runs").glob("*/*/meta.json")]]
|
||||
return sorted(metas, key=lambda m: (m.get("start") or m.get("end") or "", m["run_id"]))
|
||||
|
||||
|
||||
def reindex() -> None:
|
||||
root = logs_dir()
|
||||
metas = [m for m in all_metas(root) if m.get("status") != "running"]
|
||||
(root / "index.csv").unlink(missing_ok=True)
|
||||
for m in metas:
|
||||
append_index(index_row(m), root)
|
||||
print(f"{len(metas)} rows -> {root / 'index.csv'}")
|
||||
|
||||
|
||||
def ls(k: int) -> None:
|
||||
root = logs_dir()
|
||||
rows = list(csv.DictReader(open(root / "index.csv", encoding='utf-8'))) if (root / "index.csv").exists() else []
|
||||
done = {r["run_id"] for r in rows}
|
||||
for meta in all_metas(root):
|
||||
if meta["run_id"] in done or meta.get("status") != "running":
|
||||
continue
|
||||
if os.name == 'nt':
|
||||
import psutil
|
||||
alive = psutil.pid_exists(meta.get('launcher_pid', -1))
|
||||
else:
|
||||
alive = Path(f"/proc/{meta.get('launcher_pid')}").exists()
|
||||
meta["status"] = "running" if alive else "lost" # launcher killed with -9 / machine rebooted
|
||||
start = dt.datetime.fromisoformat(meta["start"])
|
||||
meta["wall_s"] = (now() - start).total_seconds() if alive else None
|
||||
rows.append(index_row(meta))
|
||||
rows = rows[-k:]
|
||||
cols = ["run_id", "status", "exit_code", "start", "wall", "device", "cmd"]
|
||||
w = {c: min(60, max([len(c)] + [len(str(r[c])) for r in rows])) for c in cols}
|
||||
print(" ".join(c.ljust(w[c]) for c in cols))
|
||||
for r in rows:
|
||||
print(" ".join(str(r[c])[:w[c]].ljust(w[c]) for c in cols))
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
argv = sys.argv[1:] if argv is None else argv
|
||||
if argv[:1] == ["ls"]:
|
||||
ap = argparse.ArgumentParser(prog="python -m volve_dia.runlog ls")
|
||||
ap.add_argument("-k", type=int, default=30)
|
||||
ls(ap.parse_args(argv[1:]).k)
|
||||
return 0
|
||||
if argv == ["reindex"]:
|
||||
reindex()
|
||||
return 0
|
||||
ap = argparse.ArgumentParser(prog="python -m volve_dia.runlog", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("-n", "--name", help="run name (default: script name, e.g. 02_parse_ddr)")
|
||||
ap.add_argument("--note", default="", help="free-text note stored in meta.json")
|
||||
ap.add_argument("--no-stamp", action="store_true", help="do not prefix log.txt lines with [h:mm:ss]")
|
||||
ap.add_argument("cmd", nargs=argparse.REMAINDER)
|
||||
a = ap.parse_args(argv)
|
||||
cmd = a.cmd[1:] if a.cmd[:1] == ["--"] else a.cmd
|
||||
if not cmd:
|
||||
ap.error("missing command to run")
|
||||
return run(cmd, a.name, a.note, not a.no_stamp)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user