"""Draft/preview engine for Step 2 of authoring. Drop a sample → extract once → auto-classify each column (constant across the file's rows ⇒ per-document; varies ⇒ per-row; never found ⇒ absent) → let the user refine (rename / remove / reorder / re-toggle classification / add a column) and see the result update WITHOUT re-running the LLM unless what is actually extracted changed. How "cheap" is achieved: extraction is cached per (folder, file). A column's extraction identity is its stable id + (description, examples) — NOT its display name — so renaming, removing, reordering and re-classifying are pure-Python re-assembly (no LLM). Adding a column, editing a column's description/examples, or changing the row grain (anchor) re-extracts. Assembly/enrich/gate are NOT duplicated here — we compile the column-model to the generic engine definition and run the real engine with the cached extraction injected. """ import re from .blocks.extract import extract as extract_block from .compile import compile_to_engine from .engine import run_workflow from .parsing import parse_document # In-memory per (folder_id, filename) cache. Single-creator MVP; cleared on restart. _CACHE: dict[tuple, dict] = {} def _sig(col: dict) -> tuple: """A column's extraction identity — what would change the extracted value. Excludes the display name, so a pure rename does not invalidate the cache.""" return (col.get("description", ""), tuple(col.get("examples") or [])) def _norm(s: str) -> str: return re.sub(r"\s+", " ", (s or "").strip().lower()) def classify(by_id: dict, ids: list[str]) -> dict[str, str]: """Observe each column across the extracted rows.""" out: dict[str, str] = {} for cid in ids: grounded = [_norm(c.get("value", "")) for c in by_id.get(cid, []) if c.get("grounded") and c.get("value")] if not grounded: out[cid] = "absent" elif len(set(grounded)) == 1: out[cid] = "per_document" # one distinct value wherever present -> doc-level else: out[cid] = "per_row" return out def _broadcast(cells: list[dict]) -> dict: for c in cells: if c.get("grounded"): return c return cells[0] if cells else {"value": "", "grounded": False} def to_compile_model(m: dict) -> dict: """Translate the UI wire-model (columns identified by id; anchor + lookup join key given as ids) into the name-based model compile_to_engine consumes. Used by the SAVE path, where each column already carries its confirmed source (per_document/per_row).""" columns = m.get("columns", []) id2name = {c["id"]: c["name"] for c in columns} anchor = m.get("anchor", "") out = { "name": m.get("name", "Workflow"), "anchor": id2name.get(anchor, "") if anchor else "", "columns": [{"name": c["name"], "description": c.get("description", ""), "examples": c.get("examples") or [], "source": c.get("source")} for c in columns], } lk = m.get("lookup") if lk: out["lookup"] = {"reference": lk["reference"], "match_left": id2name.get(lk["match_left"], lk["match_left"]), "match_right": lk["match_right"], "pull": lk["pull"], "on_miss": lk.get("on_miss", "flag")} return out def draft_preview(*, folder_id, filename, content=None, columns, anchor="", lookup=None, references=None, aliases=None, model=None, name="Workflow"): """Run (or re-assemble) a preview. `columns` are the document columns: [{id, name, description?, examples?, source?}]. `anchor` is a column id ("" = one row per document). `lookup` (optional): {reference, match_left: , match_right, pull: [master col names], on_miss?}. Returns {result, classification, pages, extracted_fresh}.""" key = (folder_id, filename) cache = _CACHE.get(key) if content is not None: cache = {"doc": parse_document(filename, content), "anchor": None, "sigset": set(), "by_id": {}, "nrows": 0} _CACHE[key] = cache elif cache is None: raise ValueError("No cached document for this draft — resend the sample file.") doc = cache["doc"] id2name = {c["id"]: c["name"] for c in columns} if anchor and anchor not in id2name: anchor = "" # stale anchor id -> fall back to the benign document grain if lookup and lookup.get("match_left") not in id2name: raise ValueError("The client-master match column no longer exists — re-pick it.") needed = {(c["id"], _sig(c)) for c in columns} fresh = cache["anchor"] != anchor or not needed <= cache["sigset"] if fresh: card = "many" if anchor else "one" anchor_name = id2name.get(anchor, "item") fields = [{"name": c["name"], "description": c.get("description", ""), "examples": c.get("examples") or []} for c in columns] recs = extract_block(doc, fields, cardinality=card, item_label=anchor_name, model=model, purpose="draft") cache["by_id"] = {c["id"]: [r.get(c["name"], {"value": "", "grounded": False}) for r in recs] for c in columns} cache["nrows"] = len(recs) cache["anchor"] = anchor cache["sigset"] = needed by_id, nrows = cache["by_id"], cache["nrows"] auto = classify(by_id, [c["id"] for c in columns]) def source_of(c): if c.get("source") in ("per_document", "per_row"): return c["source"] # user-confirmed override return "per_document" if auto[c["id"]] == "per_document" else "per_row" final = {c["id"]: source_of(c) for c in columns} if anchor: final[anchor] = "per_row" # the grain is always per-row if lookup: final[lookup["match_left"]] = "per_document" # the join key is doc-level # Compile the column-model to the generic engine definition (display names). mcols = [{"name": c["name"], "description": c.get("description", ""), "examples": c.get("examples") or [], "source": final[c["id"]]} for c in columns] cmodel = {"name": name, "anchor": id2name.get(anchor, "") if anchor else "", "columns": mcols} if lookup: cmodel["lookup"] = {"reference": lookup["reference"], "match_left": id2name[lookup["match_left"]], "match_right": lookup["match_right"], "pull": lookup["pull"], "on_miss": lookup.get("on_miss", "flag")} defn = compile_to_engine(cmodel) # Build the injected extraction matching the compiled steps. per_doc = [c["id"] for c in columns if final[c["id"]] == "per_document"] per_row = [c["id"] for c in columns if final[c["id"]] == "per_row"] extracted: dict[str, list[dict]] = {} if anchor: extracted["items"] = [ {id2name[cid]: by_id[cid][ri] for cid in per_row} for ri in range(nrows) ] if per_doc: extracted["doc_facts"] = [{id2name[cid]: _broadcast(by_id[cid]) for cid in per_doc}] else: extracted["doc_facts"] = [{id2name[cid]: _broadcast(by_id[cid]) for cid in (per_doc + per_row)}] result = run_workflow(defn, doc, references or {}, extracted=extracted, aliases=aliases or {}) return { "result": result, "classification": {id2name[c["id"]]: auto[c["id"]] for c in columns}, "columns": [c["name"] for c in defn["output"]["columns"]], "pages": [{"number": p.number, "text": p.text} for p in doc.pages], "extracted_fresh": fresh, } def clear_draft(folder_id, filename=None) -> None: """Drop cached drafts for a folder (on save/abandon).""" for k in [k for k in _CACHE if k[0] == folder_id and (filename is None or k[1] == filename)]: _CACHE.pop(k, None)