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.
- qaechi/parser/__init__.py +23 -0
- qaechi/parser/__main__.py +5 -0
- qaechi/parser/api.py +119 -0
- qaechi/parser/cli.py +87 -0
- qaechi/parser/config.py +150 -0
- qaechi/parser/llm.py +53 -0
- qaechi/parser/parsers/__init__.py +3 -0
- qaechi/parser/parsers/ledger.py +115 -0
- qaechi/parser/pipeline/__init__.py +65 -0
- qaechi/parser/pipeline/chunk.py +110 -0
- qaechi/parser/pipeline/extract.py +116 -0
- qaechi/parser/pipeline/grade.py +55 -0
- qaechi/parser/pipeline/graph.py +128 -0
- qaechi/parser/pipeline/index.py +64 -0
- qaechi/parser/pipeline/load.py +267 -0
- qaechi/parser/pipeline/nodes.py +185 -0
- qaechi/parser/pipeline/prompts.py +37 -0
- qaechi/parser/pipeline/retrieve.py +53 -0
- qaechi/parser/pipeline/state.py +35 -0
- qaechi/parser/pipeline/verbatim.py +67 -0
- qaechi/parser/registry.py +131 -0
- qaechi/parser/schemas.py +132 -0
- qaechi/parser/sources.py +103 -0
- qaechi/parser/store.py +103 -0
- qaechi_parser-2.0.0.dist-info/METADATA +381 -0
- qaechi_parser-2.0.0.dist-info/RECORD +31 -0
- qaechi_parser-2.0.0.dist-info/WHEEL +5 -0
- qaechi_parser-2.0.0.dist-info/entry_points.txt +2 -0
- qaechi_parser-2.0.0.dist-info/licenses/LICENSE +202 -0
- qaechi_parser-2.0.0.dist-info/licenses/NOTICE +5 -0
- qaechi_parser-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""qaechi-parser: evidence-first document extraction engine."""
|
|
2
|
+
|
|
3
|
+
from .schemas import Extraction, FieldSpec, FieldValue, JobRequest, LineItem, Provenance
|
|
4
|
+
|
|
5
|
+
__version__ = "2.0.0" # x-release-please-version
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"Extraction",
|
|
9
|
+
"FieldSpec",
|
|
10
|
+
"FieldValue",
|
|
11
|
+
"JobRequest",
|
|
12
|
+
"LineItem",
|
|
13
|
+
"Provenance",
|
|
14
|
+
"__version__",
|
|
15
|
+
"parse",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def parse(path: str, doc_type: str, **kwargs: object) -> Extraction:
|
|
20
|
+
"""Parse a local file without running the server. See `pipeline.parse_file`."""
|
|
21
|
+
from .pipeline import parse_file
|
|
22
|
+
|
|
23
|
+
return parse_file(path, doc_type, **kwargs) # type: ignore[arg-type]
|
qaechi/parser/api.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""HTTP API.
|
|
2
|
+
|
|
3
|
+
qaechi-parser does not know users. The caller authorizes them and calls this service
|
|
4
|
+
with a shared token. Two layers of defense:
|
|
5
|
+
1. bind to 127.0.0.1 so browsers cannot reach it (the main one)
|
|
6
|
+
2. X-Internal-Token, in case another process on the host tries
|
|
7
|
+
Do not rely on the token alone and bind to 0.0.0.0.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hmac
|
|
13
|
+
import importlib.util
|
|
14
|
+
import logging
|
|
15
|
+
import uuid
|
|
16
|
+
|
|
17
|
+
from fastapi import APIRouter, BackgroundTasks, Depends, FastAPI, Header, HTTPException, Query
|
|
18
|
+
|
|
19
|
+
from . import __version__, config, registry, sources, store
|
|
20
|
+
from .pipeline import graph, run_job
|
|
21
|
+
from .schemas import Extraction, ExtractionList, ExtractionSummary, Job, JobRequest, ParserInfo
|
|
22
|
+
|
|
23
|
+
log = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
OPTIONAL_MODULES = ("httpx", "pymupdf", "pymupdf4llm", "openpyxl", "pptx", "langchain_openai",
|
|
26
|
+
"langgraph")
|
|
27
|
+
MAX_LIMIT = 200
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def verify_token(x_internal_token: str | None = Header(default=None)) -> None:
|
|
31
|
+
try:
|
|
32
|
+
expected = config.internal_token()
|
|
33
|
+
except config.MissingConfig as exc:
|
|
34
|
+
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
|
35
|
+
# Constant-time compare so response timing does not leak the token.
|
|
36
|
+
if x_internal_token is None or not hmac.compare_digest(x_internal_token.encode(),
|
|
37
|
+
expected.encode()):
|
|
38
|
+
raise HTTPException(status_code=401, detail="unauthorized")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
router = APIRouter()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@router.post("/jobs", status_code=202, response_model=Job)
|
|
45
|
+
def create_job(req: JobRequest, background: BackgroundTasks) -> Job:
|
|
46
|
+
# Return right away. Parsing takes minutes and callers should not hold a connection.
|
|
47
|
+
job_id = str(uuid.uuid4())
|
|
48
|
+
job = store.get_store().insert_job(job_id, req)
|
|
49
|
+
background.add_task(run_job, job_id, req)
|
|
50
|
+
return job
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@router.get("/jobs/{job_id}", response_model=Job)
|
|
54
|
+
def get_job(job_id: str) -> Job:
|
|
55
|
+
job = store.get_store().get_job(job_id)
|
|
56
|
+
if job is None:
|
|
57
|
+
raise HTTPException(status_code=404, detail="job not found")
|
|
58
|
+
return job
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@router.get("/results", response_model=ExtractionList)
|
|
62
|
+
def list_results(document_id: str | None = Query(default=None, alias="documentId"),
|
|
63
|
+
limit: int = Query(default=50, ge=1, le=MAX_LIMIT),
|
|
64
|
+
offset: int = Query(default=0, ge=0)) -> ExtractionList:
|
|
65
|
+
items, total = store.get_store().list_results(document_id=document_id, limit=limit,
|
|
66
|
+
offset=offset)
|
|
67
|
+
return ExtractionList(
|
|
68
|
+
items=[ExtractionSummary.model_validate(r.model_dump()) for r in items],
|
|
69
|
+
total=total, limit=limit, offset=offset)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@router.get("/results/{result_id}", response_model=Extraction)
|
|
73
|
+
def get_result(result_id: str) -> Extraction:
|
|
74
|
+
result = store.get_store().get_result(result_id)
|
|
75
|
+
if result is None:
|
|
76
|
+
raise HTTPException(status_code=404, detail="result not found")
|
|
77
|
+
return result
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@router.get("/parsers", response_model=list[ParserInfo])
|
|
81
|
+
def list_parsers() -> list[ParserInfo]:
|
|
82
|
+
return [p.info() for p in registry.parsers()]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def health() -> dict[str, object]:
|
|
86
|
+
return {
|
|
87
|
+
"status": "ok",
|
|
88
|
+
"version": __version__,
|
|
89
|
+
"stub_mode": sources.backend() is None,
|
|
90
|
+
"source": sources.backend() or "none",
|
|
91
|
+
"llm": config.llm_available(),
|
|
92
|
+
"store": store.backend_name(),
|
|
93
|
+
"pipeline_engine": graph.engine(),
|
|
94
|
+
"retrieve": config.retrieve_enabled(),
|
|
95
|
+
"rewrite": config.rewrite_enabled(),
|
|
96
|
+
"embedding_dim": config.embedding_dim(),
|
|
97
|
+
"parsers": [p.name for p in registry.parsers()],
|
|
98
|
+
"optional_modules": {m: importlib.util.find_spec(m) is not None
|
|
99
|
+
for m in OPTIONAL_MODULES},
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def create_app() -> FastAPI:
|
|
104
|
+
docs = config.api_docs_enabled()
|
|
105
|
+
app = FastAPI(
|
|
106
|
+
title="qaechi-parser",
|
|
107
|
+
version=__version__,
|
|
108
|
+
# Off by default: the schema lists every route without needing a token.
|
|
109
|
+
docs_url="/docs" if docs else None,
|
|
110
|
+
redoc_url=None,
|
|
111
|
+
openapi_url="/openapi.json" if docs else None,
|
|
112
|
+
)
|
|
113
|
+
app.add_api_route("/health", health, methods=["GET"])
|
|
114
|
+
app.include_router(router, dependencies=[Depends(verify_token)])
|
|
115
|
+
registry.load_plugins()
|
|
116
|
+
return app
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
app = create_app()
|
qaechi/parser/cli.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Command line.
|
|
2
|
+
|
|
3
|
+
qaechi-parser serve run the HTTP service on 127.0.0.1:3100
|
|
4
|
+
qaechi-parser parse FILE --doc-type T parse one file and print JSON
|
|
5
|
+
qaechi-parser parsers list registered parsers
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _field(text: str) -> dict[str, str]:
|
|
19
|
+
# name[:kind[:description]]
|
|
20
|
+
name, _, rest = text.partition(":")
|
|
21
|
+
kind, _, description = rest.partition(":")
|
|
22
|
+
return {"name": name, "kind": kind or "text", "description": description}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _serve(args: argparse.Namespace) -> int:
|
|
26
|
+
try:
|
|
27
|
+
import fastapi # noqa: F401
|
|
28
|
+
import uvicorn
|
|
29
|
+
except ImportError:
|
|
30
|
+
print("The HTTP service needs the server extra: pip install 'qaechi-parser[server]'",
|
|
31
|
+
file=sys.stderr)
|
|
32
|
+
return 2
|
|
33
|
+
|
|
34
|
+
uvicorn.run("qaechi.parser.api:app", host=args.host, port=args.port, reload=args.reload)
|
|
35
|
+
return 0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _parse(args: argparse.Namespace) -> int:
|
|
39
|
+
from .pipeline import parse_file
|
|
40
|
+
|
|
41
|
+
result = parse_file(args.file, args.doc_type, fields=[_field(f) for f in args.field],
|
|
42
|
+
lines=args.lines, period=args.period, source_kind=args.source_kind)
|
|
43
|
+
print(json.dumps(result.model_dump(mode="json", by_alias=True), ensure_ascii=False, indent=2))
|
|
44
|
+
return 0
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _parsers(_args: argparse.Namespace) -> int:
|
|
48
|
+
from . import registry
|
|
49
|
+
|
|
50
|
+
for spec in registry.parsers():
|
|
51
|
+
print(f"{spec.name}\t{spec.version}\t{','.join(sorted(spec.doc_types))}\t"
|
|
52
|
+
f"{','.join(spec.extensions)}")
|
|
53
|
+
return 0
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def main(argv: list[str] | None = None) -> int:
|
|
57
|
+
parser = argparse.ArgumentParser(prog="qaechi-parser", description="Evidence-first extraction.")
|
|
58
|
+
parser.add_argument("--version", action="version", version=f"qaechi-parser {__version__}")
|
|
59
|
+
parser.add_argument("-v", "--verbose", action="store_true")
|
|
60
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
61
|
+
|
|
62
|
+
serve = sub.add_parser("serve", help="run the HTTP service")
|
|
63
|
+
serve.add_argument("--host", default="127.0.0.1")
|
|
64
|
+
serve.add_argument("--port", type=int, default=3100)
|
|
65
|
+
serve.add_argument("--reload", action="store_true")
|
|
66
|
+
serve.set_defaults(func=_serve)
|
|
67
|
+
|
|
68
|
+
parse = sub.add_parser("parse", help="parse one local file")
|
|
69
|
+
parse.add_argument("file")
|
|
70
|
+
parse.add_argument("--doc-type", required=True)
|
|
71
|
+
parse.add_argument("--field", action="append", default=[],
|
|
72
|
+
help="name[:kind[:description]], repeatable")
|
|
73
|
+
parse.add_argument("--lines", action="store_true", help="also extract line items and total")
|
|
74
|
+
parse.add_argument("--period")
|
|
75
|
+
parse.add_argument("--source-kind")
|
|
76
|
+
parse.set_defaults(func=_parse)
|
|
77
|
+
|
|
78
|
+
sub.add_parser("parsers", help="list registered parsers").set_defaults(func=_parsers)
|
|
79
|
+
|
|
80
|
+
args = parser.parse_args(argv)
|
|
81
|
+
logging.basicConfig(level=logging.INFO if args.verbose else logging.WARNING,
|
|
82
|
+
format="%(asctime)s %(levelname)s %(name)s %(message)s")
|
|
83
|
+
return args.func(args)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
if __name__ == "__main__":
|
|
87
|
+
sys.exit(main())
|
qaechi/parser/config.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Settings from environment variables.
|
|
2
|
+
|
|
3
|
+
Only QAECHI_INTERNAL_TOKEN is required, and only for protected routes. Anything else
|
|
4
|
+
that is missing turns its feature off, so the service always starts and /health
|
|
5
|
+
can tell you what is missing.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import importlib.util
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
try:
|
|
15
|
+
from dotenv import load_dotenv
|
|
16
|
+
except ImportError:
|
|
17
|
+
load_dotenv = None
|
|
18
|
+
|
|
19
|
+
if load_dotenv is not None:
|
|
20
|
+
load_dotenv(Path.cwd() / ".env")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MissingConfig(RuntimeError):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _get(name: str) -> str | None:
|
|
28
|
+
value = os.getenv(name)
|
|
29
|
+
return value.strip() if value and value.strip() else None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _flag(name: str) -> bool:
|
|
33
|
+
return (_get(name) or "").lower() in ("1", "true", "on", "yes")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _int(name: str, default: int, minimum: int = 1) -> int:
|
|
37
|
+
# A typo in an env var falls back to the default instead of crashing the process.
|
|
38
|
+
try:
|
|
39
|
+
value = int(_get(name) or default)
|
|
40
|
+
except ValueError:
|
|
41
|
+
return default
|
|
42
|
+
return value if value >= minimum else default
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _float(name: str, default: float, low: float, high: float) -> float:
|
|
46
|
+
try:
|
|
47
|
+
value = float(_get(name) or default)
|
|
48
|
+
except ValueError:
|
|
49
|
+
return default
|
|
50
|
+
return value if low <= value <= high else default
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def internal_token() -> str:
|
|
54
|
+
token = _get("QAECHI_INTERNAL_TOKEN")
|
|
55
|
+
if not token:
|
|
56
|
+
raise MissingConfig("QAECHI_INTERNAL_TOKEN is not set. Copy .env.example to .env first.")
|
|
57
|
+
return token
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# Sources
|
|
61
|
+
def source_dir() -> str | None:
|
|
62
|
+
return _get("QAECHI_SOURCE_DIR")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def source_url() -> str | None:
|
|
66
|
+
return _get("QAECHI_SOURCE_URL")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def source_token() -> str | None:
|
|
70
|
+
return _get("QAECHI_SOURCE_TOKEN")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def source_max_bytes() -> int:
|
|
74
|
+
return _int("QAECHI_SOURCE_MAX_MB", 100) * 1024 * 1024
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def pdf_password() -> str | None:
|
|
78
|
+
return _get("QAECHI_PDF_PASSWORD")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# LLM
|
|
82
|
+
def openai_api_key() -> str | None:
|
|
83
|
+
return _get("OPENAI_API_KEY")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def llm_model() -> str:
|
|
87
|
+
return _get("QAECHI_LLM_MODEL") or "gpt-4o-mini"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def embedding_model() -> str:
|
|
91
|
+
return _get("QAECHI_EMBEDDING_MODEL") or "text-embedding-3-small"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def embedding_dim() -> int:
|
|
95
|
+
# Changing this means re-indexing everything, so it is pinned by config.
|
|
96
|
+
return _int("QAECHI_EMBEDDING_DIM", 768)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def llm_timeout_seconds() -> int:
|
|
100
|
+
return _int("QAECHI_LLM_TIMEOUT_SECONDS", 120)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def llm_max_retries() -> int:
|
|
104
|
+
return _int("QAECHI_LLM_MAX_RETRIES", 2, minimum=0)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def llm_max_input_chars() -> int:
|
|
108
|
+
return _int("QAECHI_LLM_MAX_INPUT_CHARS", 200_000)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def embed_max_chunks() -> int:
|
|
112
|
+
return _int("QAECHI_EMBED_MAX_CHUNKS", 3_000)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def llm_available() -> bool:
|
|
116
|
+
return openai_api_key() is not None and importlib.util.find_spec("langchain_openai") is not None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
# Pipeline
|
|
120
|
+
def job_timeout_seconds() -> int:
|
|
121
|
+
return _int("QAECHI_JOB_TIMEOUT_SECONDS", 1_800)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def retrieve_enabled() -> bool:
|
|
125
|
+
return _flag("QAECHI_RETRIEVE")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def rewrite_enabled() -> bool:
|
|
129
|
+
return _flag("QAECHI_REWRITE")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def retrieve_min_chars() -> int:
|
|
133
|
+
return _int("QAECHI_RETRIEVE_MIN_CHARS", 12_000)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def search_min_score() -> float:
|
|
137
|
+
return _float("QAECHI_SEARCH_MIN_SCORE", 0.30, 0.0, 1.0)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# Service
|
|
141
|
+
def plugins() -> list[str]:
|
|
142
|
+
return [p.strip() for p in (_get("QAECHI_PLUGINS") or "").split(",") if p.strip()]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def api_docs_enabled() -> bool:
|
|
146
|
+
return _flag("QAECHI_API_DOCS")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def memory_max_results() -> int:
|
|
150
|
+
return _int("QAECHI_MEMORY_MAX_RESULTS", 1_000)
|
qaechi/parser/llm.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""LLM and embedding clients, with timeouts and input limits on every call.
|
|
2
|
+
|
|
3
|
+
Inputs over the limit fail instead of being cut. A truncated document silently
|
|
4
|
+
loses its last items, which looks like a normal result.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from . import config
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class InputTooLarge(RuntimeError):
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def check_input_chars(text: str, what: str) -> None:
|
|
19
|
+
limit = config.llm_max_input_chars()
|
|
20
|
+
if len(text) > limit:
|
|
21
|
+
raise InputTooLarge(
|
|
22
|
+
f"{what} input is {len(text):,} chars, over the {limit:,} limit "
|
|
23
|
+
"(QAECHI_LLM_MAX_INPUT_CHARS). Split the document or raise the limit.")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def check_embed_count(count: int) -> None:
|
|
27
|
+
limit = config.embed_max_chunks()
|
|
28
|
+
if count > limit:
|
|
29
|
+
raise InputTooLarge(
|
|
30
|
+
f"{count:,} chunks to embed, over the {limit:,} limit (QAECHI_EMBED_MAX_CHUNKS).")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def chat_model() -> Any:
|
|
34
|
+
from langchain_openai import ChatOpenAI
|
|
35
|
+
|
|
36
|
+
return ChatOpenAI(
|
|
37
|
+
model=config.llm_model(),
|
|
38
|
+
temperature=0,
|
|
39
|
+
timeout=config.llm_timeout_seconds(),
|
|
40
|
+
max_retries=config.llm_max_retries(),
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def embeddings_model() -> Any:
|
|
45
|
+
# Indexing and querying must share one model and dimension.
|
|
46
|
+
from langchain_openai import OpenAIEmbeddings
|
|
47
|
+
|
|
48
|
+
return OpenAIEmbeddings(
|
|
49
|
+
model=config.embedding_model(),
|
|
50
|
+
dimensions=config.embedding_dim(),
|
|
51
|
+
timeout=config.llm_timeout_seconds(),
|
|
52
|
+
max_retries=config.llm_max_retries(),
|
|
53
|
+
)
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Ledger parser: a table of labels and amounts (CSV, XLSX, XLSM).
|
|
2
|
+
|
|
3
|
+
doc_type `ledger`. In each sheet it looks for a header row with a label column and
|
|
4
|
+
an amount column, then reads every row below it as a line item. A row labelled
|
|
5
|
+
"total" becomes the total.
|
|
6
|
+
|
|
7
|
+
Values are read as written. If the lines do not add up to the total, both are
|
|
8
|
+
returned unchanged; a mismatch is a signal for the caller, not something to fix.
|
|
9
|
+
Rows that cannot be read are counted in `skippedRows`, never dropped silently.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
from decimal import Decimal, InvalidOperation
|
|
16
|
+
|
|
17
|
+
from ..pipeline.load import SheetRows, load_csv_rows, load_xlsx_sheets, row_text
|
|
18
|
+
from ..registry import LayoutError, ParseInput, ParseOutput, register
|
|
19
|
+
from ..schemas import FieldValue, LineItem, Provenance
|
|
20
|
+
|
|
21
|
+
LABEL_WORDS = re.compile(r"^(item|description|label|name|account|항목|내역|품목|적요|계정)", re.I)
|
|
22
|
+
AMOUNT_WORDS = re.compile(r"(amount|total|price|sum|value|금액|합계|청구액|지급액)", re.I)
|
|
23
|
+
TOTAL_LABEL = re.compile(r"^\s*(grand\s+)?(total|합계|총계|총액)\s*$", re.I)
|
|
24
|
+
HEADER_DEPTH = 20
|
|
25
|
+
_CURRENCY = re.compile(r"[,\s₩$€£¥원]")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _cell(value: object) -> str:
|
|
29
|
+
return "" if value is None else str(value).strip()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def find_header(rows: list[list[object]]) -> tuple[int, int, int] | None:
|
|
33
|
+
"""Return (row index, label column, amount column) or None."""
|
|
34
|
+
for r, row in enumerate(rows[:HEADER_DEPTH]):
|
|
35
|
+
cells = [_cell(c) for c in row]
|
|
36
|
+
label = next((i for i, c in enumerate(cells) if LABEL_WORDS.search(c)), None)
|
|
37
|
+
amount = next((i for i, c in enumerate(cells)
|
|
38
|
+
if i != label and AMOUNT_WORDS.search(c)), None)
|
|
39
|
+
if label is not None and amount is not None:
|
|
40
|
+
return r, label, amount
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def to_number(value: object) -> int | float | None:
|
|
45
|
+
if isinstance(value, bool) or value is None:
|
|
46
|
+
return None
|
|
47
|
+
if isinstance(value, int):
|
|
48
|
+
return value
|
|
49
|
+
if isinstance(value, float):
|
|
50
|
+
return int(value) if value.is_integer() else value
|
|
51
|
+
text = _CURRENCY.sub("", str(value))
|
|
52
|
+
negative = text.startswith("(") and text.endswith(")")
|
|
53
|
+
text = text.strip("()")
|
|
54
|
+
if not text:
|
|
55
|
+
return None
|
|
56
|
+
try:
|
|
57
|
+
number = Decimal(text)
|
|
58
|
+
except InvalidOperation:
|
|
59
|
+
return None
|
|
60
|
+
number = -number if negative else number
|
|
61
|
+
return int(number) if number == number.to_integral_value() else float(number)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _sheet(doc: ParseInput, sheet: SheetRows, out: ParseOutput) -> dict[str, object] | None:
|
|
65
|
+
found = find_header(sheet.rows)
|
|
66
|
+
if found is None:
|
|
67
|
+
return None
|
|
68
|
+
header, label_col, amount_col = found
|
|
69
|
+
skipped = 0
|
|
70
|
+
lines = 0
|
|
71
|
+
for r in range(header + 1, len(sheet.rows)):
|
|
72
|
+
row = sheet.rows[r]
|
|
73
|
+
label = _cell(row[label_col]) if label_col < len(row) else ""
|
|
74
|
+
raw = row[amount_col] if amount_col < len(row) else None
|
|
75
|
+
if not label and _cell(raw) == "":
|
|
76
|
+
continue
|
|
77
|
+
amount = to_number(raw)
|
|
78
|
+
if not label or amount is None:
|
|
79
|
+
skipped += 1
|
|
80
|
+
continue
|
|
81
|
+
value = FieldValue(value=amount, confidence=1.0, provenance=Provenance(
|
|
82
|
+
document_id=doc.document_id, page=sheet.index, quote=row_text(row)))
|
|
83
|
+
if TOTAL_LABEL.match(label):
|
|
84
|
+
if out.total is not None:
|
|
85
|
+
out.notes.append(f"more than one total row; kept the first ({sheet.name})")
|
|
86
|
+
continue
|
|
87
|
+
out.total = value
|
|
88
|
+
else:
|
|
89
|
+
out.lines.append(LineItem(label=label, amount=value))
|
|
90
|
+
lines += 1
|
|
91
|
+
return {"name": sheet.name, "headerRow": header + 1, "lines": lines,
|
|
92
|
+
"skippedRows": skipped, "truncated": sheet.truncated}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@register("ledger", doc_types={"ledger"}, extensions=(".csv", ".xlsx", ".xlsm"), version="1")
|
|
96
|
+
def parse_ledger(doc: ParseInput) -> ParseOutput:
|
|
97
|
+
sheets = ([load_csv_rows(doc.path)] if doc.path.lower().endswith(".csv")
|
|
98
|
+
else load_xlsx_sheets(doc.path))
|
|
99
|
+
out = ParseOutput()
|
|
100
|
+
read: list[dict[str, object]] = []
|
|
101
|
+
skipped_sheets: list[str] = []
|
|
102
|
+
for sheet in sheets:
|
|
103
|
+
info = _sheet(doc, sheet, out)
|
|
104
|
+
if info is None:
|
|
105
|
+
skipped_sheets.append(sheet.name)
|
|
106
|
+
continue
|
|
107
|
+
read.append(info)
|
|
108
|
+
if sheet.truncated:
|
|
109
|
+
out.notes.append(f"sheet '{sheet.name}' was truncated")
|
|
110
|
+
if not read:
|
|
111
|
+
raise LayoutError("no sheet has a label column and an amount column")
|
|
112
|
+
if skipped_sheets:
|
|
113
|
+
out.notes.append(f"skipped {len(skipped_sheets)} sheet(s) without a ledger header")
|
|
114
|
+
out.payload = {"sheets": read, "skippedSheets": skipped_sheets}
|
|
115
|
+
return out
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Run one job end to end: fetch, extract, grade, save.
|
|
2
|
+
|
|
3
|
+
Every failure ends as job status 'failed' with a short message. Stopping loudly beats
|
|
4
|
+
being quietly wrong. Results are proposals; nothing is final here.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import time
|
|
12
|
+
import uuid
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from ..schemas import Extraction, FieldSpec, JobRequest
|
|
16
|
+
from ..store import get_store
|
|
17
|
+
from . import graph
|
|
18
|
+
|
|
19
|
+
log = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
__all__ = ["parse_file", "run_job"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _cleanup(run: dict[str, Any]) -> None:
|
|
25
|
+
# Source documents can hold personal data. Do not leave copies behind.
|
|
26
|
+
path = run.get("temp_path")
|
|
27
|
+
if path and os.path.exists(path):
|
|
28
|
+
try:
|
|
29
|
+
os.unlink(path)
|
|
30
|
+
except OSError:
|
|
31
|
+
log.warning("could not delete temp file %s", path)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def run_job(job_id: str, req: JobRequest) -> Extraction | None:
|
|
35
|
+
started = time.monotonic()
|
|
36
|
+
store = get_store()
|
|
37
|
+
store.update_job(job_id, "running")
|
|
38
|
+
run: dict[str, Any] = {}
|
|
39
|
+
log.info("job %s started doc=%s type=%s", job_id, req.document_id, req.doc_type)
|
|
40
|
+
try:
|
|
41
|
+
final = graph.run({"job_id": job_id, "req": req, "started": started,
|
|
42
|
+
"run": run, "attempts": 0})
|
|
43
|
+
log.info("job %s finished in %.1fs", job_id, time.monotonic() - started)
|
|
44
|
+
return final.get("result")
|
|
45
|
+
except Exception as exc: # noqa: BLE001 - every failure becomes a job status
|
|
46
|
+
log.exception("job %s failed", job_id)
|
|
47
|
+
store.update_job(job_id, "failed", error=f"{type(exc).__name__}: {exc}"[:500])
|
|
48
|
+
return None
|
|
49
|
+
finally:
|
|
50
|
+
_cleanup(run)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def parse_file(path: str, doc_type: str, *, fields: list[FieldSpec | dict[str, Any]] | None = None,
|
|
54
|
+
lines: bool = False, period: str | None = None, source_kind: str | None = None,
|
|
55
|
+
document_id: str | None = None) -> Extraction:
|
|
56
|
+
"""Parse a local file in-process. Raises instead of recording a failed job."""
|
|
57
|
+
specs = [f if isinstance(f, FieldSpec) else FieldSpec.model_validate(f) for f in fields or []]
|
|
58
|
+
req = JobRequest(document_id=document_id or str(uuid.uuid4()), source=os.path.basename(path),
|
|
59
|
+
doc_type=doc_type, fields=specs, lines=lines, period=period,
|
|
60
|
+
source_kind=source_kind)
|
|
61
|
+
if not os.path.isfile(path):
|
|
62
|
+
raise FileNotFoundError(path)
|
|
63
|
+
final = graph.run({"job_id": None, "req": req, "local_path": os.path.abspath(path),
|
|
64
|
+
"started": time.monotonic(), "run": {}, "attempts": 0})
|
|
65
|
+
return final["result"]
|