Skip to content

Fast, accurate OCR with correctness assessment.

2.3 KB
Raw Blame
import json
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable, List, Optional, Tuple


ENGINE_FAILURE_RE = re.compile(
    r"^\s*<!--\s*(?P<msg>.*?)\s*-->\s*$",
    re.DOTALL,
)


_ENGINE_FAILURE_MARKERS = (
    "failed",
    "cuda out of memory",
    "outofmemoryerror",
    "enginecore",
    "traceback",
)


def classify_engine_text(raw_text: str) -> Tuple[str, Optional[str]]:
    'Split engine output into (text, error).'
    text = raw_text or ""
    match = ENGINE_FAILURE_RE.match(text)
    if not match:
        return text, None
    msg = match.group("msg").strip()
    lowered = msg.lower()
    if any(marker in lowered for marker in _ENGINE_FAILURE_MARKERS):
        return "", msg
    return text, None


def now_iso() -> str:
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def ensure_dir(path: Path) -> None:
    path.mkdir(parents=True, exist_ok=True)


def read_json(path: Path, default: Any = None) -> Any:
    if not path.exists():
        return default
    with path.open("r", encoding="utf-8") as f:
        return json.load(f)


def write_json(path: Path, payload: Any, indent: int = 2) -> None:
    ensure_dir(path.parent)
    with path.open("w", encoding="utf-8") as f:
        json.dump(payload, f, ensure_ascii=False, indent=indent)
        f.write("\n")


def append_jsonl(path: Path, payload: Any) -> None:
    ensure_dir(path.parent)
    with path.open("a", encoding="utf-8") as f:
        f.write(json.dumps(payload, ensure_ascii=False) + "\n")


def read_jsonl(path: Path) -> List[Any]:
    if not path.exists():
        return []
    rows: List[Any] = []
    with path.open("r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            rows.append(json.loads(line))
    return rows


def mean(values: Iterable[float]) -> float:
    vals = list(values)
    if not vals:
        return 0.0
    return sum(vals) / len(vals)


def percentile(values: Iterable[float], pct: float) -> float:
    vals = sorted(values)
    if not vals:
        return 0.0
    if len(vals) == 1:
        return vals[0]
    idx = (len(vals) - 1) * pct
    lo = int(idx)
    hi = min(lo + 1, len(vals) - 1)
    frac = idx - lo
    return vals[lo] * (1 - frac) + vals[hi] * frac