qaechi-parser 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,110 @@
1
+ """Chunking. Tables are never split.
2
+
3
+ Splitting a table separates rows from their header and the numbers lose meaning.
4
+
5
+ sheet pages -> one chunk per page (the whole page is a table)
6
+ other pages -> cut into blocks: runs of table lines, and prose in between
7
+ table block -> kept whole, never cut
8
+ prose block -> recursive splitter (or a plain window without langchain)
9
+ small neighbouring blocks are packed together up to CHUNK_SIZE, so a
10
+ table keeps the sentence that introduces it when they fit
11
+
12
+ A line is a table line when it has at least TABLE_LINE_PIPES pipes (`| a | b |`,
13
+ `a | b | c`). Chunk text is kept verbatim so quotes can be checked against it.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass
19
+
20
+ from .load import Page
21
+
22
+ CHUNK_SIZE = 1000
23
+ CHUNK_OVERLAP = 100
24
+ TABLE_LINE_PIPES = 2
25
+ # Kept for `looks_like_table`: a page with one wide row is treated as a table page.
26
+ _TABLE_PIPES = 4
27
+
28
+
29
+ @dataclass
30
+ class Chunk:
31
+ ord: int
32
+ page_no: int
33
+ content: str
34
+
35
+
36
+ def looks_like_table(text: str) -> bool:
37
+ # When unsure, call it a table. Splitting a table loses more than keeping prose whole.
38
+ return any(line.count("|") >= _TABLE_PIPES for line in text.splitlines())
39
+
40
+
41
+ def is_table_line(line: str) -> bool:
42
+ return line.count("|") >= TABLE_LINE_PIPES
43
+
44
+
45
+ def blocks(text: str) -> list[tuple[bool, str]]:
46
+ """Cut text into (is_table, block) runs. Joining the blocks with newlines gives the text."""
47
+ out: list[tuple[bool, list[str]]] = []
48
+ for line in text.splitlines():
49
+ table = is_table_line(line)
50
+ if out and out[-1][0] == table:
51
+ out[-1][1].append(line)
52
+ else:
53
+ out.append((table, [line]))
54
+ return [(table, "\n".join(lines)) for table, lines in out]
55
+
56
+
57
+ def context_header(doc_type: str, period: str | None, page_no: int) -> str:
58
+ parts = [f"doc: {doc_type}"]
59
+ if period:
60
+ parts.append(f"period: {period}")
61
+ parts.append(f"p.{page_no}")
62
+ return f"[{' | '.join(parts)}]\n"
63
+
64
+
65
+ def split_page(page: Page, size: int = CHUNK_SIZE) -> list[str]:
66
+ text = page.text.strip()
67
+ if not text:
68
+ return []
69
+ if page.kind == "sheet" or len(text) <= size:
70
+ return [text]
71
+ parts: list[str] = []
72
+ buf = ""
73
+ for table, block in blocks(text):
74
+ block = block.strip("\n")
75
+ if not block.strip():
76
+ continue
77
+ if buf and len(buf) + 1 + len(block) <= size:
78
+ buf += "\n" + block
79
+ continue
80
+ if buf:
81
+ parts.append(buf)
82
+ buf = ""
83
+ if table or len(block) <= size:
84
+ buf = block
85
+ continue
86
+ pieces = split_prose(block, size)
87
+ parts.extend(pieces[:-1])
88
+ buf = pieces[-1]
89
+ if buf:
90
+ parts.append(buf)
91
+ return parts
92
+
93
+
94
+ def chunk_pages(pages: list[Page], doc_type: str, period: str | None) -> list[Chunk]:
95
+ out: list[Chunk] = []
96
+ for page in pages:
97
+ header = context_header(doc_type, period, page.page_no)
98
+ for part in split_page(page):
99
+ out.append(Chunk(ord=len(out), page_no=page.page_no, content=header + part))
100
+ return out
101
+
102
+
103
+ def split_prose(text: str, size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:
104
+ try:
105
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
106
+ except ImportError:
107
+ step = max(size - overlap, 1)
108
+ return [text[i:i + size] for i in range(0, len(text), step)] or [text]
109
+ return RecursiveCharacterTextSplitter(
110
+ chunk_size=size, chunk_overlap=overlap, length_function=len).split_text(text)
@@ -0,0 +1,116 @@
1
+ """Extraction routes. All three produce the same `ParseOutput`.
2
+
3
+ parser a registered plugin reads the file directly. No tokens, confidence 1.0
4
+ llm structured output over the chunks, every value with a quote
5
+ stub nothing to read (no source or no LLM). Values stay null; nothing is invented
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from pydantic import BaseModel, Field, create_model
13
+
14
+ from .. import llm
15
+ from ..registry import ParseInput, ParseOutput, ParserSpec
16
+ from ..schemas import FieldKind, FieldSpec, FieldValue, LineItem, Provenance
17
+ from .chunk import Chunk
18
+ from .prompts import EXTRACT_SYSTEM_PROMPT, fence
19
+ from .verbatim import find_chunk
20
+
21
+ _TYPES: dict[FieldKind, type] = {"text": str, "integer": int, "number": float, "date": str}
22
+
23
+
24
+ class Cited(BaseModel):
25
+ quote: str | None = Field(default=None, description="exact text copied from the document")
26
+ page: int | None = Field(default=None, description="page number from the chunk header")
27
+ confidence: float = Field(default=0.0, ge=0, le=1)
28
+
29
+
30
+ class CitedLine(Cited):
31
+ label: str
32
+ amount: float | None = None
33
+
34
+
35
+ def _field_model(spec: FieldSpec) -> type[Cited]:
36
+ hint = "ISO date YYYY-MM-DD" if spec.kind == "date" else spec.kind
37
+ return create_model(
38
+ f"Field_{spec.name}",
39
+ __base__=Cited,
40
+ value=(_TYPES[spec.kind] | None, Field(default=None, description=hint)),
41
+ )
42
+
43
+
44
+ def output_model(fields: list[FieldSpec], lines: bool) -> type[BaseModel]:
45
+ """Build the structured-output schema from the requested fields."""
46
+ defs: dict[str, Any] = {
47
+ f.name: (_field_model(f) | None, Field(default=None, description=f.description or f.name))
48
+ for f in fields
49
+ }
50
+ if lines:
51
+ defs["lines"] = (list[CitedLine], Field(default_factory=list))
52
+ defs["total"] = (CitedLine | None, Field(default=None, description="document total"))
53
+ return create_model("Extracted", **defs)
54
+
55
+
56
+ def _number(value: float | None) -> int | float | None:
57
+ # Keep integers as integers so amounts do not come back as 1000.0.
58
+ if value is None:
59
+ return None
60
+ return int(value) if float(value).is_integer() else value
61
+
62
+
63
+ def cite(document_id: str, item: Cited | None, value: Any,
64
+ chunks: list[Chunk]) -> FieldValue:
65
+ if item is None:
66
+ return FieldValue(value=None, confidence=0.0)
67
+ prov = None
68
+ if item.quote:
69
+ chunk = find_chunk(item.quote, chunks)
70
+ prov = Provenance(document_id=document_id, quote=item.quote,
71
+ chunk_id=chunk.ord if chunk else None,
72
+ page=chunk.page_no if chunk else item.page)
73
+ return FieldValue(value=value, confidence=item.confidence, provenance=prov)
74
+
75
+
76
+ def run_llm(document_id: str, fields: list[FieldSpec], lines: bool,
77
+ chunks: list[Chunk]) -> ParseOutput:
78
+ if not fields and not lines:
79
+ raise ValueError("nothing to extract: pass `fields` or set `lines` to true")
80
+ context = "\n\n".join(c.content for c in chunks)
81
+ llm.check_input_chars(context, "extract")
82
+ model = output_model(fields, lines)
83
+ structured = llm.chat_model().with_structured_output(model, method="function_calling")
84
+ data = structured.invoke([
85
+ {"role": "system", "content": EXTRACT_SYSTEM_PROMPT},
86
+ {"role": "user", "content": fence(context)},
87
+ ])
88
+ return to_output(document_id, fields, lines, data, chunks)
89
+
90
+
91
+ def to_output(document_id: str, fields: list[FieldSpec], lines: bool, data: BaseModel,
92
+ chunks: list[Chunk]) -> ParseOutput:
93
+ out = ParseOutput()
94
+ for spec in fields:
95
+ item = getattr(data, spec.name, None)
96
+ raw = getattr(item, "value", None)
97
+ value = _number(raw) if spec.kind in ("integer", "number") else raw
98
+ out.fields[spec.name] = cite(document_id, item, value, chunks)
99
+ if lines:
100
+ for ln in getattr(data, "lines", []):
101
+ out.lines.append(LineItem(label=ln.label,
102
+ amount=cite(document_id, ln, _number(ln.amount), chunks)))
103
+ total = getattr(data, "total", None)
104
+ out.total = cite(document_id, total, _number(getattr(total, "amount", None)), chunks)
105
+ return out
106
+
107
+
108
+ def run_stub(fields: list[FieldSpec], reason: str) -> ParseOutput:
109
+ return ParseOutput(
110
+ fields={f.name: FieldValue() for f in fields},
111
+ notes=[f"stub: {reason}"],
112
+ )
113
+
114
+
115
+ def run_parser(spec: ParserSpec, doc: ParseInput) -> ParseOutput:
116
+ return spec.fn(doc)
@@ -0,0 +1,55 @@
1
+ """Groundedness grader. A secondary signal only.
2
+
3
+ The grader is also an LLM, so its errors correlate with the extractor's. Base hard
4
+ decisions on deterministic checks (quote_check, arithmetic) on the caller side.
5
+ No key means 'unknown', never an optimistic 'yes'.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+
12
+ from pydantic import BaseModel, Field
13
+
14
+ from .. import config, llm
15
+ from ..registry import ParseOutput
16
+ from ..schemas import FieldValue, Groundedness
17
+ from .chunk import Chunk
18
+ from .prompts import GRADE_SYSTEM_PROMPT, fence
19
+
20
+ log = logging.getLogger(__name__)
21
+
22
+
23
+ class Verdict(BaseModel):
24
+ binary_score: str = Field(description="'yes' if supported, otherwise 'no'")
25
+
26
+
27
+ def _claim(name: str, value: FieldValue) -> str:
28
+ quote = value.provenance.quote if value.provenance else ""
29
+ return f"- {name}: {value.value} (quote: {quote})"
30
+
31
+
32
+ def claims(out: ParseOutput) -> list[str]:
33
+ rows = [_claim(k, v) for k, v in out.fields.items() if v.value is not None]
34
+ rows += [_claim(ln.label, ln.amount) for ln in out.lines]
35
+ if out.total is not None and out.total.value is not None:
36
+ rows.append(_claim("total", out.total))
37
+ return rows
38
+
39
+
40
+ def grade(out: ParseOutput, chunks: list[Chunk]) -> Groundedness:
41
+ rows = claims(out)
42
+ if not rows or not chunks or not config.llm_available():
43
+ return "unknown"
44
+ context = "\n\n".join(c.content for c in chunks)
45
+ try:
46
+ llm.check_input_chars(context, "grade")
47
+ structured = llm.chat_model().with_structured_output(Verdict, method="function_calling")
48
+ verdict: Verdict = structured.invoke([
49
+ {"role": "system", "content": GRADE_SYSTEM_PROMPT},
50
+ {"role": "user", "content": f"Source:\n{fence(context)}\n\nValues:\n" + "\n".join(rows)},
51
+ ])
52
+ except Exception: # noqa: BLE001 - a failed grade must not fail the job
53
+ log.exception("grade failed, leaving it unknown")
54
+ return "unknown"
55
+ return "yes" if verdict.binary_score.strip().lower() == "yes" else "no"
@@ -0,0 +1,128 @@
1
+ """Pipeline graph.
2
+
3
+ fetch ─┬─ parse ──────────────────────────────────────────────── save
4
+ ├─ extract (stub) ─ grade ─────────────────────────────── save
5
+ └─ load ─ chunk ─ index ─ retrieve ─ extract ─ grade ─┬─ save
6
+ ▲ └─ rewrite (once)
7
+ └─────────────────────┘
8
+
9
+ With langgraph installed this compiles to a StateGraph. Without it, a small runner
10
+ walks the same nodes and edges, so a minimal install behaves the same way.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import functools
16
+ import logging
17
+ import time
18
+ from collections.abc import Callable
19
+ from typing import Any
20
+
21
+ from .. import config
22
+ from . import nodes
23
+ from .state import PipelineState
24
+
25
+ log = logging.getLogger(__name__)
26
+
27
+ END = "__end__"
28
+ NodeFn = Callable[[PipelineState], dict[str, Any]]
29
+
30
+
31
+ class JobTimeout(RuntimeError):
32
+ pass
33
+
34
+
35
+ NODES: dict[str, NodeFn] = {
36
+ "fetch": nodes.fetch,
37
+ "parse": nodes.parse,
38
+ "load": nodes.load_pages,
39
+ "chunk": nodes.chunk,
40
+ "index": nodes.index,
41
+ "retrieve": nodes.retrieve,
42
+ "extract": nodes.extract,
43
+ "grade": nodes.grade_node,
44
+ "rewrite": nodes.rewrite,
45
+ "save": nodes.save,
46
+ }
47
+ EDGES: dict[str, str] = {
48
+ "parse": "save",
49
+ "load": "chunk",
50
+ "chunk": "index",
51
+ "index": "retrieve",
52
+ "retrieve": "extract",
53
+ "extract": "grade",
54
+ "rewrite": "extract",
55
+ "save": END,
56
+ }
57
+ BRANCHES: dict[str, tuple[Callable[[PipelineState], str], tuple[str, ...]]] = {
58
+ "fetch": (nodes.after_fetch, ("parse", "load", "extract")),
59
+ "grade": (nodes.after_grade, ("rewrite", "save")),
60
+ }
61
+ ENTRY = "fetch"
62
+ # The longest path, with one rewrite, is 11 steps.
63
+ MAX_STEPS = 20
64
+
65
+
66
+ def guarded(name: str, fn: NodeFn) -> NodeFn:
67
+ """Check the job deadline before each step. A running step cannot be interrupted."""
68
+
69
+ @functools.wraps(fn)
70
+ def run(state: PipelineState) -> dict[str, Any]:
71
+ started = state.get("started")
72
+ limit = config.job_timeout_seconds()
73
+ # Never drop a finished result just because the deadline passed.
74
+ if name != "save" and started is not None and time.monotonic() - started > limit:
75
+ raise JobTimeout(f"job exceeded {limit}s before step '{name}'")
76
+ return fn(state)
77
+
78
+ return run
79
+
80
+
81
+ class SequentialGraph:
82
+ def invoke(self, state: PipelineState, config: dict[str, Any] | None = None) -> PipelineState:
83
+ limit = int((config or {}).get("recursion_limit", MAX_STEPS))
84
+ current = ENTRY
85
+ for _ in range(limit):
86
+ if current == END:
87
+ return state
88
+ state = {**state, **guarded(current, NODES[current])(state)} # type: ignore[typeddict-item]
89
+ current = BRANCHES[current][0](state) if current in BRANCHES else EDGES[current]
90
+ raise RuntimeError(f"pipeline ran more than {limit} steps; check the edges")
91
+
92
+
93
+ def _compile_langgraph() -> Any:
94
+ from langgraph.graph import END as LG_END
95
+ from langgraph.graph import START, StateGraph
96
+
97
+ builder = StateGraph(PipelineState)
98
+ for name, fn in NODES.items():
99
+ builder.add_node(name, guarded(name, fn))
100
+ builder.add_edge(START, ENTRY)
101
+ for source, target in EDGES.items():
102
+ builder.add_edge(source, LG_END if target == END else target)
103
+ for source, (router, targets) in BRANCHES.items():
104
+ builder.add_conditional_edges(source, router, {t: t for t in targets})
105
+ return builder.compile()
106
+
107
+
108
+ _compiled: Any = None
109
+
110
+
111
+ def engine() -> str:
112
+ try:
113
+ import langgraph # noqa: F401
114
+ except ImportError:
115
+ return "sequential"
116
+ return "langgraph"
117
+
118
+
119
+ def get_graph() -> Any:
120
+ global _compiled
121
+ if _compiled is None:
122
+ _compiled = _compile_langgraph() if engine() == "langgraph" else SequentialGraph()
123
+ log.info("pipeline engine: %s", engine())
124
+ return _compiled
125
+
126
+
127
+ def run(state: PipelineState) -> PipelineState:
128
+ return get_graph().invoke(state, {"recursion_limit": MAX_STEPS})
@@ -0,0 +1,64 @@
1
+ """In-memory vector index, used to narrow long documents before extraction.
2
+
3
+ Search is always filtered by document_id. Mixing in another document's text is not
4
+ a worse answer, it is a wrong one.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import threading
11
+ from dataclasses import dataclass
12
+
13
+ from .. import config, llm
14
+ from .chunk import Chunk
15
+
16
+
17
+ @dataclass
18
+ class Hit:
19
+ ord: int
20
+ score: float
21
+
22
+
23
+ class MemoryIndex:
24
+ def __init__(self) -> None:
25
+ self._lock = threading.Lock()
26
+ self._docs: dict[str, list[tuple[int, list[float]]]] = {}
27
+
28
+ def store(self, document_id: str, chunks: list[Chunk]) -> int:
29
+ if not chunks:
30
+ return 0
31
+ llm.check_embed_count(len(chunks))
32
+ vectors = llm.embeddings_model().embed_documents([c.content for c in chunks])
33
+ with self._lock:
34
+ # Re-indexing a document replaces its old chunks.
35
+ self._docs[document_id] = [(c.ord, v) for c, v in zip(chunks, vectors)]
36
+ return len(chunks)
37
+
38
+ def search(self, document_id: str, query: str, top_k: int) -> list[Hit]:
39
+ with self._lock:
40
+ rows = list(self._docs.get(document_id, []))
41
+ if not rows:
42
+ return []
43
+ q = llm.embeddings_model().embed_query(query)
44
+ floor = config.search_min_score()
45
+ hits = [Hit(ord, _cosine(q, v)) for ord, v in rows]
46
+ hits = [h for h in hits if h.score >= floor]
47
+ return sorted(hits, key=lambda h: h.score, reverse=True)[:top_k]
48
+
49
+ def has(self, document_id: str) -> bool:
50
+ with self._lock:
51
+ return bool(self._docs.get(document_id))
52
+
53
+
54
+ def _cosine(a: list[float], b: list[float]) -> float:
55
+ dot = sum(x * y for x, y in zip(a, b))
56
+ norm = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b))
57
+ return dot / norm if norm else 0.0
58
+
59
+
60
+ index = MemoryIndex()
61
+
62
+
63
+ def available() -> bool:
64
+ return config.llm_available()