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,131 @@
1
+ """Parser plugins.
2
+
3
+ A parser reads a fixed-layout document directly and returns values with evidence.
4
+ It never calls an LLM. Register one with the decorator:
5
+
6
+ @register("acme_invoice", doc_types={"invoice"}, extensions=(".xlsx",))
7
+ def parse(doc: ParseInput) -> ParseOutput: ...
8
+
9
+ Plugins load from three places: built-ins, modules in QAECHI_PLUGINS, and the
10
+ `qaechi.parsers` entry point group. The most recently registered match wins,
11
+ so a plugin can override a built-in.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import importlib
17
+ import logging
18
+ import os
19
+ import sys
20
+ from collections.abc import Callable
21
+ from dataclasses import dataclass, field
22
+ from importlib.metadata import entry_points
23
+ from typing import Any
24
+
25
+ from . import config
26
+ from .schemas import FieldSpec, FieldValue, LineItem, ParserInfo
27
+
28
+ log = logging.getLogger(__name__)
29
+
30
+
31
+ class LayoutError(ValueError):
32
+ """The document does not look like what the parser expects. Stop rather than misread."""
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class ParseInput:
37
+ path: str
38
+ document_id: str
39
+ doc_type: str
40
+ period: str | None = None
41
+ source_kind: str | None = None
42
+ fields: tuple[FieldSpec, ...] = ()
43
+
44
+
45
+ @dataclass
46
+ class ParseOutput:
47
+ fields: dict[str, FieldValue] = field(default_factory=dict)
48
+ lines: list[LineItem] = field(default_factory=list)
49
+ total: FieldValue | None = None
50
+ notes: list[str] = field(default_factory=list)
51
+ payload: dict[str, Any] = field(default_factory=dict)
52
+
53
+
54
+ ParserFn = Callable[[ParseInput], ParseOutput]
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class ParserSpec:
59
+ name: str
60
+ fn: ParserFn
61
+ doc_types: frozenset[str]
62
+ extensions: tuple[str, ...]
63
+ version: str = "1"
64
+ # Empty means any source_kind.
65
+ source_kinds: frozenset[str] = frozenset()
66
+
67
+ def matches(self, doc_type: str, path: str, source_kind: str | None) -> bool:
68
+ if doc_type not in self.doc_types:
69
+ return False
70
+ if not path.lower().endswith(self.extensions):
71
+ return False
72
+ return not self.source_kinds or source_kind in self.source_kinds
73
+
74
+ def info(self) -> ParserInfo:
75
+ return ParserInfo(name=self.name, version=self.version, doc_types=sorted(self.doc_types),
76
+ extensions=list(self.extensions), source_kinds=sorted(self.source_kinds))
77
+
78
+
79
+ _registry: dict[str, ParserSpec] = {}
80
+ _loaded = False
81
+
82
+
83
+ def register(name: str, *, doc_types: set[str] | frozenset[str], extensions: tuple[str, ...],
84
+ version: str = "1",
85
+ source_kinds: set[str] | frozenset[str] = frozenset()) -> Callable[[ParserFn], ParserFn]:
86
+ def wrap(fn: ParserFn) -> ParserFn:
87
+ # Re-registering moves the parser to the end, so it takes priority.
88
+ _registry.pop(name, None)
89
+ _registry[name] = ParserSpec(
90
+ name=name, fn=fn, doc_types=frozenset(doc_types),
91
+ extensions=tuple(e.lower() for e in extensions), version=version,
92
+ source_kinds=frozenset(source_kinds))
93
+ return fn
94
+
95
+ return wrap
96
+
97
+
98
+ def unregister(name: str) -> None:
99
+ _registry.pop(name, None)
100
+
101
+
102
+ def load_plugins() -> None:
103
+ global _loaded
104
+ if _loaded:
105
+ return
106
+ _loaded = True
107
+ importlib.import_module("qaechi.parser.parsers")
108
+ modules = config.plugins()
109
+ # Console scripts do not put the working directory on sys.path; `python -m` does.
110
+ if modules and os.getcwd() not in sys.path:
111
+ sys.path.insert(0, os.getcwd())
112
+ for module in modules:
113
+ importlib.import_module(module)
114
+ log.info("loaded parser plugin module %s", module)
115
+ for ep in entry_points(group="qaechi.parsers"):
116
+ ep.load()
117
+ log.info("loaded parser plugin %s", ep.name)
118
+
119
+
120
+ def parsers() -> list[ParserSpec]:
121
+ load_plugins()
122
+ return list(_registry.values())
123
+
124
+
125
+ def find(doc_type: str, path: str | None, source_kind: str | None = None) -> ParserSpec | None:
126
+ if not path:
127
+ return None
128
+ for spec in reversed(parsers()):
129
+ if spec.matches(doc_type, path, source_kind):
130
+ return spec
131
+ return None
@@ -0,0 +1,132 @@
1
+ """Wire contract. JSON is camelCase, Python stays snake_case."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from typing import Any, Literal
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field
9
+
10
+
11
+ def to_camel(name: str) -> str:
12
+ head, *rest = name.split("_")
13
+ return head + "".join(word.capitalize() for word in rest)
14
+
15
+
16
+ class Base(BaseModel):
17
+ model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
18
+
19
+
20
+ FieldKind = Literal["text", "integer", "number", "date"]
21
+ Groundedness = Literal["yes", "no", "unknown"]
22
+ JobStatus = Literal["queued", "running", "succeeded", "failed"]
23
+ Route = Literal["parser", "llm", "stub"]
24
+ Value = str | int | float | None
25
+
26
+
27
+ class Provenance(Base):
28
+ """Where a value came from. `quote` must be cut from the source as-is."""
29
+
30
+ document_id: str
31
+ chunk_id: int | None = None
32
+ page: int | None = None
33
+ quote: str
34
+
35
+
36
+ class FieldValue(Base):
37
+ value: Value = None
38
+ confidence: float = Field(default=0.0, ge=0, le=1)
39
+ provenance: Provenance | None = None
40
+
41
+
42
+ class LineItem(Base):
43
+ label: str
44
+ amount: FieldValue
45
+
46
+
47
+ class FieldSpec(Base):
48
+ """A field the caller wants. Used by the LLM route; parsers may ignore it."""
49
+
50
+ name: str = Field(pattern=r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
51
+ kind: FieldKind = "text"
52
+ description: str = Field(default="", max_length=500)
53
+
54
+
55
+ class QuoteCheck(Base):
56
+ checked: int = 0
57
+ not_in_source: list[str] = Field(default_factory=list)
58
+
59
+
60
+ class Extraction(Base):
61
+ """A proposal. Callers decide whether to accept it."""
62
+
63
+ id: str
64
+ job_id: str | None = None
65
+ document_id: str
66
+ doc_type: str
67
+ route: Route
68
+ parser: str | None = None
69
+ parser_version: str | None = None
70
+ fields: dict[str, FieldValue] = Field(default_factory=dict)
71
+ lines: list[LineItem] = Field(default_factory=list)
72
+ total: FieldValue | None = None
73
+ groundedness: Groundedness = "unknown"
74
+ quote_check: QuoteCheck = Field(default_factory=QuoteCheck)
75
+ # True when nothing was read. Never treat stub values as real.
76
+ stub: bool = False
77
+ notes: list[str] = Field(default_factory=list)
78
+ payload: dict[str, Any] = Field(default_factory=dict)
79
+ created_at: datetime
80
+
81
+
82
+ class ExtractionSummary(Base):
83
+ id: str
84
+ job_id: str | None = None
85
+ document_id: str
86
+ doc_type: str
87
+ route: Route
88
+ parser: str | None = None
89
+ groundedness: Groundedness
90
+ stub: bool
91
+ created_at: datetime
92
+
93
+
94
+ class ExtractionList(Base):
95
+ items: list[ExtractionSummary]
96
+ total: int
97
+ limit: int
98
+ offset: int
99
+
100
+
101
+ class JobRequest(Base):
102
+ document_id: str = Field(min_length=1, max_length=200)
103
+ # Path relative to the configured source (local dir or HTTP base).
104
+ source: str = Field(min_length=1, max_length=1000)
105
+ doc_type: str = Field(min_length=1, max_length=64)
106
+ fields: list[FieldSpec] = Field(default_factory=list, max_length=50)
107
+ # Ask the LLM route for line items and a total as well.
108
+ lines: bool = False
109
+ period: str | None = Field(default=None, max_length=32)
110
+ # Lets one doc_type pick between parsers, e.g. two vendors' invoices.
111
+ source_kind: str | None = Field(default=None, max_length=64)
112
+ # Audit only. qaechi-parser does not authorize users.
113
+ requested_by: str | None = Field(default=None, max_length=200)
114
+
115
+
116
+ class Job(Base):
117
+ job_id: str
118
+ status: JobStatus
119
+ document_id: str
120
+ doc_type: str
121
+ created_at: datetime
122
+ finished_at: datetime | None = None
123
+ error: str | None = None
124
+ result_id: str | None = None
125
+
126
+
127
+ class ParserInfo(Base):
128
+ name: str
129
+ version: str
130
+ doc_types: list[str]
131
+ extensions: list[str]
132
+ source_kinds: list[str]
@@ -0,0 +1,103 @@
1
+ """Fetch the original document.
2
+
3
+ Two backends:
4
+ local QAECHI_SOURCE_DIR files under one directory
5
+ http QAECHI_SOURCE_URL GET {base}/{source}, optional bearer QAECHI_SOURCE_TOKEN
6
+ (works with S3-style object stores such as Supabase Storage)
7
+ With neither set, jobs run in stub mode.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import os
14
+ import tempfile
15
+ from dataclasses import dataclass
16
+ from pathlib import Path, PurePosixPath
17
+ from urllib.parse import quote
18
+
19
+ from . import config
20
+
21
+ log = logging.getLogger(__name__)
22
+
23
+
24
+ class SourceError(RuntimeError):
25
+ pass
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Fetched:
30
+ path: str
31
+ # Temporary copies are deleted when the job ends. Local files are never deleted.
32
+ temporary: bool
33
+
34
+
35
+ def backend() -> str | None:
36
+ if config.source_url():
37
+ return "http"
38
+ if config.source_dir():
39
+ return "local"
40
+ return None
41
+
42
+
43
+ def _clean(source: str) -> str:
44
+ parts = PurePosixPath(source.replace("\\", "/").lstrip("/")).parts
45
+ if not parts or any(p in ("..", "") for p in parts):
46
+ raise SourceError(f"invalid source path: {source}")
47
+ return "/".join(parts)
48
+
49
+
50
+ def _local(source: str) -> Fetched:
51
+ root = Path(config.source_dir() or ".").resolve()
52
+ path = (root / _clean(source)).resolve()
53
+ # Resolve first, then check, so symlinks cannot escape the root.
54
+ if not path.is_relative_to(root):
55
+ raise SourceError(f"source is outside QAECHI_SOURCE_DIR: {source}")
56
+ if not path.is_file():
57
+ raise SourceError(f"source not found: {source}")
58
+ return Fetched(str(path), temporary=False)
59
+
60
+
61
+ def _http(source: str) -> Fetched:
62
+ try:
63
+ import httpx
64
+ except ModuleNotFoundError as exc:
65
+ raise SourceError("httpx is required for QAECHI_SOURCE_URL: pip install 'qaechi-parser[parse]'") \
66
+ from exc
67
+
68
+ base = (config.source_url() or "").rstrip("/")
69
+ url = f"{base}/{quote(_clean(source))}"
70
+ headers = {}
71
+ token = config.source_token()
72
+ if token:
73
+ headers["Authorization"] = f"Bearer {token}"
74
+
75
+ limit = config.source_max_bytes()
76
+ suffix = os.path.splitext(source)[1] or ".bin"
77
+ fd, tmp = tempfile.mkstemp(suffix=suffix, prefix="qaechi-")
78
+ size = 0
79
+ try:
80
+ with os.fdopen(fd, "wb") as out, httpx.Client(timeout=120.0) as client:
81
+ with client.stream("GET", url, headers=headers) as resp:
82
+ if resp.status_code == 404:
83
+ raise SourceError(f"source not found: {source}")
84
+ resp.raise_for_status()
85
+ for block in resp.iter_bytes():
86
+ size += len(block)
87
+ if size > limit:
88
+ raise SourceError(f"source is larger than {limit // 1024 // 1024} MB")
89
+ out.write(block)
90
+ except BaseException:
91
+ os.unlink(tmp)
92
+ raise
93
+ log.info("fetched %s (%.1f MB)", source, size / 1024 / 1024)
94
+ return Fetched(tmp, temporary=True)
95
+
96
+
97
+ def fetch(source: str) -> Fetched | None:
98
+ kind = backend()
99
+ if kind == "http":
100
+ return _http(source)
101
+ if kind == "local":
102
+ return _local(source)
103
+ return None
qaechi/parser/store.py ADDED
@@ -0,0 +1,103 @@
1
+ """Job and result storage.
2
+
3
+ The default store keeps everything in memory, which is enough for one process.
4
+ Plug in your own backend with `set_store()`; it only has to match `Store`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import threading
10
+ from collections import OrderedDict
11
+ from datetime import datetime, timezone
12
+ from typing import Protocol
13
+
14
+ from . import config
15
+ from .schemas import Extraction, Job, JobRequest, JobStatus
16
+
17
+
18
+ def now() -> datetime:
19
+ return datetime.now(timezone.utc)
20
+
21
+
22
+ class Store(Protocol):
23
+ def insert_job(self, job_id: str, req: JobRequest) -> Job: ...
24
+
25
+ def get_job(self, job_id: str) -> Job | None: ...
26
+
27
+ def update_job(self, job_id: str, status: JobStatus, *, error: str | None = None,
28
+ result_id: str | None = None) -> None: ...
29
+
30
+ def save_result(self, result: Extraction) -> str: ...
31
+
32
+ def get_result(self, result_id: str) -> Extraction | None: ...
33
+
34
+ def list_results(self, *, document_id: str | None, limit: int,
35
+ offset: int) -> tuple[list[Extraction], int]: ...
36
+
37
+
38
+ class MemoryStore:
39
+ def __init__(self, max_results: int | None = None) -> None:
40
+ self._lock = threading.Lock()
41
+ self._jobs: dict[str, Job] = {}
42
+ self._results: OrderedDict[str, Extraction] = OrderedDict()
43
+ self._max_results = max_results or config.memory_max_results()
44
+
45
+ def insert_job(self, job_id: str, req: JobRequest) -> Job:
46
+ job = Job(job_id=job_id, status="queued", document_id=req.document_id,
47
+ doc_type=req.doc_type, created_at=now())
48
+ with self._lock:
49
+ self._jobs[job_id] = job
50
+ return job
51
+
52
+ def get_job(self, job_id: str) -> Job | None:
53
+ with self._lock:
54
+ return self._jobs.get(job_id)
55
+
56
+ def update_job(self, job_id: str, status: JobStatus, *, error: str | None = None,
57
+ result_id: str | None = None) -> None:
58
+ with self._lock:
59
+ job = self._jobs.get(job_id)
60
+ if job is None:
61
+ return
62
+ done = status in ("succeeded", "failed")
63
+ self._jobs[job_id] = job.model_copy(update={
64
+ "status": status,
65
+ "error": error,
66
+ "result_id": result_id or job.result_id,
67
+ "finished_at": now() if done else None,
68
+ })
69
+
70
+ def save_result(self, result: Extraction) -> str:
71
+ with self._lock:
72
+ self._results[result.id] = result
73
+ # Drop the oldest results so memory stays bounded.
74
+ while len(self._results) > self._max_results:
75
+ self._results.popitem(last=False)
76
+ return result.id
77
+
78
+ def get_result(self, result_id: str) -> Extraction | None:
79
+ with self._lock:
80
+ return self._results.get(result_id)
81
+
82
+ def list_results(self, *, document_id: str | None, limit: int,
83
+ offset: int) -> tuple[list[Extraction], int]:
84
+ with self._lock:
85
+ items = [r for r in reversed(self._results.values())
86
+ if document_id is None or r.document_id == document_id]
87
+ return items[offset:offset + limit], len(items)
88
+
89
+
90
+ _store: Store = MemoryStore()
91
+
92
+
93
+ def get_store() -> Store:
94
+ return _store
95
+
96
+
97
+ def set_store(store: Store) -> None:
98
+ global _store
99
+ _store = store
100
+
101
+
102
+ def backend_name() -> str:
103
+ return "memory" if isinstance(_store, MemoryStore) else type(_store).__name__