graph-knowledge-doc-parser 0.2.6__tar.gz → 0.2.9__tar.gz
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.
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/PKG-INFO +5 -4
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/README.md +2 -2
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/__init__.py +4 -3
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/cast_hinting.py +4 -1
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/document_ingester_logger.py +101 -57
- graph_knowledge_doc_parser-0.2.9/kg_doc_parser/llm_structured_output.py +73 -0
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/models.py +40 -39
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/ocr.py +120 -62
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/pdf2png.py +9 -4
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/semantic_document_splitting_layerwise_edits.py +362 -237
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/text_processing_utils.py +11 -4
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/utils/file_loaders.py +55 -34
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/utils/langchain.py +108 -33
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/utils/log.py +8 -6
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/utils/version_chaining.py +136 -67
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/__init__.py +6 -0
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/adapters.py +125 -29
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/cache.py +22 -10
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/cli.py +3 -2
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/clients.py +175 -56
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/demo_harness.py +49 -13
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/design.py +27 -1
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/handlers.py +173 -51
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/layered_contracts.py +33 -14
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/layerwise_llm.py +353 -203
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/models.py +251 -88
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/ocr_pipeline.py +56 -22
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/page_index.py +172 -118
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/parser_core.py +181 -32
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/parsing.py +94 -12
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/probe.py +20 -18
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/providers.py +99 -41
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/runners.py +44 -26
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/semantics.py +131 -53
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/serialization.py +36 -8
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/service.py +56 -19
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/strategy.py +33 -14
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/pyproject.toml +8 -2
- graph_knowledge_doc_parser-0.2.6/kg_doc_parser/llm_structured_output.py +0 -46
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/document_ingest_log_config.py +0 -0
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/utils/__init__.py +0 -0
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/utils/bounded_threadpool_executor.py +0 -0
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/_kogwistar.py +0 -0
- {graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/workflow_ingest/smoke_assets.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: graph-knowledge-doc-parser
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.9
|
|
4
4
|
Summary: doc parser using llm driven engine with graph knowledge awareness
|
|
5
5
|
Author: humblemat810
|
|
6
6
|
Author-email: 67593116+humblemat810@users.noreply.github.com
|
|
@@ -21,7 +21,7 @@ Provides-Extra: openai
|
|
|
21
21
|
Provides-Extra: vertex
|
|
22
22
|
Requires-Dist: diskcache (>=5.6,<6.0) ; platform_python_implementation == "PyPy"
|
|
23
23
|
Requires-Dist: joblib (>=1.5.3,<2.0.0) ; platform_python_implementation == "CPython"
|
|
24
|
-
Requires-Dist: kogwistar (==0.6.
|
|
24
|
+
Requires-Dist: kogwistar (==0.6.7)
|
|
25
25
|
Requires-Dist: langchain-core (>=1.2.5,<2.0.0)
|
|
26
26
|
Requires-Dist: langchain-google-genai (>=4.1.2,<5.0.0) ; extra == "gemini" or extra == "cloud"
|
|
27
27
|
Requires-Dist: langchain-google-vertexai (>=3.2.4,<4.0.0) ; extra == "vertex" or extra == "cloud"
|
|
@@ -34,6 +34,7 @@ Requires-Dist: pydantic (>=2.12.5,<3.0.0)
|
|
|
34
34
|
Requires-Dist: pydantic-extension (>=0.0.7,<0.0.8)
|
|
35
35
|
Requires-Dist: pypdf (>=6.5.0,<7.0.0)
|
|
36
36
|
Requires-Dist: rapidfuzz (>=3.14.3,<4.0.0)
|
|
37
|
+
Requires-Dist: typing-extensions (>=4.8.0,<5.0.0)
|
|
37
38
|
Project-URL: Homepage, https://github.com/humblemat810/kg_doc_parser
|
|
38
39
|
Project-URL: Repository, https://github.com/humblemat810/kg_doc_parser
|
|
39
40
|
Description-Content-Type: text/markdown
|
|
@@ -85,8 +86,8 @@ to normal strategy selection. See the
|
|
|
85
86
|
The deterministic and text-only Bonsai fixture evaluation is recorded in the
|
|
86
87
|
[`PageIndex adversarial fixture report`](doc/page_index_adversarial_fixture_report.md).
|
|
87
88
|
The current patch release is documented in the
|
|
88
|
-
[`0.2.
|
|
89
|
-
[`0.2.
|
|
89
|
+
[`0.2.9` release note](doc/release_0.2.9.md); the prior
|
|
90
|
+
[`0.2.7` release note](doc/release_0.2.7.md) remains available for history.
|
|
90
91
|
|
|
91
92
|
For an adoption path that starts with parser-grounded source units and later
|
|
92
93
|
adds LLM-Wiki cross-document maintenance, see
|
|
@@ -45,8 +45,8 @@ to normal strategy selection. See the
|
|
|
45
45
|
The deterministic and text-only Bonsai fixture evaluation is recorded in the
|
|
46
46
|
[`PageIndex adversarial fixture report`](doc/page_index_adversarial_fixture_report.md).
|
|
47
47
|
The current patch release is documented in the
|
|
48
|
-
[`0.2.
|
|
49
|
-
[`0.2.
|
|
48
|
+
[`0.2.9` release note](doc/release_0.2.9.md); the prior
|
|
49
|
+
[`0.2.7` release note](doc/release_0.2.7.md) remains available for history.
|
|
50
50
|
|
|
51
51
|
For an adoption path that starts with parser-grounded source units and later
|
|
52
52
|
adds LLM-Wiki cross-document maintenance, see
|
{graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/__init__.py
RENAMED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
1
|
"""Public import surface for the document parser package."""
|
|
4
2
|
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
5
|
from . import workflow_ingest
|
|
6
6
|
from .workflow_ingest import * # noqa: F401,F403
|
|
7
7
|
from .workflow_ingest import __all__ as _workflow_ingest_all
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
# The parser package intentionally mirrors the workflow package's public API.
|
|
10
|
+
__all__ = ["workflow_ingest", *_workflow_ingest_all] # pyright: ignore[reportUnsupportedDunderAll]
|
|
@@ -88,25 +88,65 @@ import sqlite3
|
|
|
88
88
|
import threading
|
|
89
89
|
import time
|
|
90
90
|
import traceback
|
|
91
|
+
from collections.abc import Mapping
|
|
91
92
|
from contextlib import closing
|
|
92
93
|
from dataclasses import dataclass
|
|
93
94
|
from datetime import datetime, timezone
|
|
94
|
-
from typing import Any, Dict, Optional, Tuple, Callable
|
|
95
95
|
from threading import Lock
|
|
96
|
+
from typing import Protocol
|
|
97
|
+
from uuid import UUID
|
|
98
|
+
|
|
96
99
|
from langchain_core.callbacks.base import BaseCallbackHandler
|
|
100
|
+
from langchain_core.messages import BaseMessage
|
|
97
101
|
from langchain_core.outputs.chat_generation import ChatGeneration
|
|
98
102
|
from langchain_core.outputs.llm_result import LLMResult
|
|
99
|
-
from langchain_core.messages import BaseMessage
|
|
100
|
-
from uuid import UUID
|
|
101
103
|
|
|
102
104
|
from kg_doc_parser.workflow_ingest.serialization import safe_json_dumps
|
|
103
105
|
|
|
106
|
+
|
|
107
|
+
class TextRedactor(Protocol):
|
|
108
|
+
"""Redact one text value before it is written to ingestion telemetry."""
|
|
109
|
+
|
|
110
|
+
def __call__(self, text: str, /) -> str: ...
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _metadata_float(value: object, default: float = 0.0) -> float:
|
|
114
|
+
if isinstance(value, bool):
|
|
115
|
+
return float(value)
|
|
116
|
+
if isinstance(value, (int, float)):
|
|
117
|
+
return float(value)
|
|
118
|
+
if isinstance(value, str):
|
|
119
|
+
try:
|
|
120
|
+
return float(value)
|
|
121
|
+
except ValueError:
|
|
122
|
+
return default
|
|
123
|
+
return default
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _metadata_int_or_none(value: object) -> int | None:
|
|
127
|
+
if isinstance(value, bool):
|
|
128
|
+
return int(value)
|
|
129
|
+
if isinstance(value, int):
|
|
130
|
+
return value
|
|
131
|
+
if isinstance(value, float) and value.is_integer():
|
|
132
|
+
return int(value)
|
|
133
|
+
if isinstance(value, str):
|
|
134
|
+
try:
|
|
135
|
+
return int(value)
|
|
136
|
+
except ValueError:
|
|
137
|
+
return None
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _metadata_text(value: object) -> str | None:
|
|
142
|
+
return value if isinstance(value, str) else None
|
|
143
|
+
|
|
104
144
|
# ---------------------------
|
|
105
145
|
# Pricing / cost calculation
|
|
106
146
|
# ---------------------------
|
|
107
147
|
|
|
108
148
|
# per-1K token pricing in USD (example values; keep yours here)
|
|
109
|
-
_COST_TABLE:
|
|
149
|
+
_COST_TABLE: dict[str, dict[str, float]] = {
|
|
110
150
|
"gemini-3-flash-preview": {"input": 0.0005, "output": 0.003, "cache": 0.0},
|
|
111
151
|
"gemini-3.0-pro": {"input": 0.002000, "output": 0.0120, "cache": 0.00031},
|
|
112
152
|
"gemini-2.0-flash": {"input": 0.0001, "output": 0.0004, "cache": 0.0},
|
|
@@ -174,13 +214,13 @@ class _IngestEvent:
|
|
|
174
214
|
Internal event embedding queued from callback thread(s) to writer thread.
|
|
175
215
|
"""
|
|
176
216
|
ts_iso: str
|
|
177
|
-
document_id:
|
|
178
|
-
run_id:
|
|
179
|
-
parent_run_id:
|
|
217
|
+
document_id: str | None
|
|
218
|
+
run_id: str | None
|
|
219
|
+
parent_run_id: str | None
|
|
180
220
|
event_name: str
|
|
181
|
-
model_name:
|
|
182
|
-
filename:
|
|
183
|
-
line_number:
|
|
221
|
+
model_name: str | None
|
|
222
|
+
filename: str | None
|
|
223
|
+
line_number: int | None
|
|
184
224
|
token_count: int
|
|
185
225
|
cost_usd: float
|
|
186
226
|
n_try: float
|
|
@@ -226,7 +266,7 @@ class SQLiteIngestEventWriter:
|
|
|
226
266
|
|
|
227
267
|
os.makedirs(os.path.dirname(db_path) or ".", exist_ok=True)
|
|
228
268
|
|
|
229
|
-
self._q:
|
|
269
|
+
self._q: queue.Queue[_IngestEvent] = queue.Queue()
|
|
230
270
|
self._stop = threading.Event()
|
|
231
271
|
self._thread = threading.Thread(target=self._run, name="sqlite_ingest_writer", daemon=True)
|
|
232
272
|
|
|
@@ -370,7 +410,7 @@ class SQLiteIngestEventWriter:
|
|
|
370
410
|
# Helper: error frame info
|
|
371
411
|
# ---------------------------
|
|
372
412
|
|
|
373
|
-
def _best_effort_error_location(exc: BaseException) ->
|
|
413
|
+
def _best_effort_error_location(exc: BaseException) -> tuple[str | None, int | None]:
|
|
374
414
|
"""
|
|
375
415
|
Extract (filename, line_number) from the deepest traceback frame.
|
|
376
416
|
|
|
@@ -400,8 +440,12 @@ def _utc_now_iso() -> str:
|
|
|
400
440
|
# ---------------------------
|
|
401
441
|
# The LangChain callback
|
|
402
442
|
# ---------------------------
|
|
403
|
-
def
|
|
404
|
-
|
|
443
|
+
def _as_mapping(value: object) -> Mapping[str, object]:
|
|
444
|
+
return value if isinstance(value, Mapping) else {}
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _invoked_model_name(kwargs: Mapping[str, object]) -> str | None:
|
|
448
|
+
inv_params = _as_mapping(kwargs.get("invocation_params"))
|
|
405
449
|
m = inv_params.get("model")
|
|
406
450
|
return str(m) if m else None
|
|
407
451
|
class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
@@ -441,7 +485,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
441
485
|
log_errors: bool = True,
|
|
442
486
|
include_traceback: bool = True,
|
|
443
487
|
max_text_chars: int = 40_000,
|
|
444
|
-
redact:
|
|
488
|
+
redact: TextRedactor | None = None,
|
|
445
489
|
) -> None:
|
|
446
490
|
super().__init__()
|
|
447
491
|
self._writer = SQLiteIngestEventWriter(db_path=db_path)
|
|
@@ -453,15 +497,15 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
453
497
|
self.include_traceback = include_traceback
|
|
454
498
|
self.max_text_chars = int(max_text_chars)
|
|
455
499
|
self.redact = redact or (lambda s: s)
|
|
456
|
-
self._run_meta: dict[str, dict[str,
|
|
500
|
+
self._run_meta: dict[str, dict[str, object]] = {}
|
|
457
501
|
self._run_meta_lock = Lock()
|
|
458
|
-
def _remember(self, run_id: UUID, metadata: dict[str,
|
|
502
|
+
def _remember(self, run_id: UUID, metadata: dict[str, object] | None, tags: list[str] | None) -> None:
|
|
459
503
|
md = dict(metadata or {})
|
|
460
504
|
md["_tags"] = list(tags or [])
|
|
461
505
|
with self._run_meta_lock:
|
|
462
506
|
self._run_meta[str(run_id)] = md
|
|
463
507
|
|
|
464
|
-
def _recall(self, run_id: UUID, metadata: dict[str,
|
|
508
|
+
def _recall(self, run_id: UUID, metadata: dict[str, object] | None, tags: list[str] | None) -> dict[str, object]:
|
|
465
509
|
# prefer real-time metadata if present; else fallback to remembered
|
|
466
510
|
if metadata:
|
|
467
511
|
return dict(metadata)
|
|
@@ -485,22 +529,22 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
485
529
|
|
|
486
530
|
def on_chat_model_start(
|
|
487
531
|
self,
|
|
488
|
-
serialized:
|
|
532
|
+
serialized: dict[str, object],
|
|
489
533
|
messages: list[list[BaseMessage]],
|
|
490
534
|
*,
|
|
491
|
-
run_id:
|
|
492
|
-
parent_run_id:
|
|
493
|
-
tags:
|
|
494
|
-
metadata:
|
|
495
|
-
**kwargs:
|
|
535
|
+
run_id: UUID,
|
|
536
|
+
parent_run_id: UUID | None = None,
|
|
537
|
+
tags: list[str] | None = None,
|
|
538
|
+
metadata: dict[str, object] | None = None,
|
|
539
|
+
**kwargs: object,
|
|
496
540
|
) -> None:
|
|
497
541
|
self._remember(run_id, metadata, tags)
|
|
498
542
|
md = metadata or {}
|
|
499
543
|
document_id = md.get("document_id")
|
|
500
544
|
filename = md.get("source_filename")
|
|
501
|
-
n_try =
|
|
545
|
+
n_try = _metadata_float(md.get("n_try", 0))
|
|
502
546
|
|
|
503
|
-
payload:
|
|
547
|
+
payload: dict[str, object] = {
|
|
504
548
|
"serialized": serialized,
|
|
505
549
|
"tags": tags or [],
|
|
506
550
|
"metadata": md,
|
|
@@ -534,7 +578,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
534
578
|
event_name="chat_model_start",
|
|
535
579
|
model_name=_invoked_model_name(kwargs) or None,
|
|
536
580
|
filename=str(filename) if filename is not None else None,
|
|
537
|
-
line_number=md.get("line_number"),
|
|
581
|
+
line_number=_metadata_int_or_none(md.get("line_number")),
|
|
538
582
|
token_count=0,
|
|
539
583
|
cost_usd=0.0,
|
|
540
584
|
n_try=n_try,
|
|
@@ -543,14 +587,14 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
543
587
|
)
|
|
544
588
|
def on_llm_start(
|
|
545
589
|
self,
|
|
546
|
-
serialized:
|
|
590
|
+
serialized: dict[str, object],
|
|
547
591
|
prompts: list[str],
|
|
548
592
|
*,
|
|
549
593
|
run_id: UUID,
|
|
550
|
-
parent_run_id:
|
|
551
|
-
tags:
|
|
552
|
-
metadata:
|
|
553
|
-
**kwargs:
|
|
594
|
+
parent_run_id: UUID | None = None,
|
|
595
|
+
tags: list[str] | None = None,
|
|
596
|
+
metadata: dict[str, object] | None = None,
|
|
597
|
+
**kwargs: object,
|
|
554
598
|
) -> None:
|
|
555
599
|
|
|
556
600
|
self._remember(run_id, metadata, tags)
|
|
@@ -566,9 +610,9 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
566
610
|
document_id = md.get("document_id")
|
|
567
611
|
filename = md.get("source_filename")
|
|
568
612
|
if model_name is None:
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
613
|
+
inv_params = kwargs.get("invocation_params")
|
|
614
|
+
if isinstance(inv_params, Mapping) and inv_params.get("model"):
|
|
615
|
+
model_name = str(inv_params["model"])
|
|
572
616
|
payload = {
|
|
573
617
|
"serialized": serialized,
|
|
574
618
|
"tags": tags or [],
|
|
@@ -579,7 +623,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
579
623
|
if self.log_prompts:
|
|
580
624
|
payload["prompts"] = [self._clip(p) for p in prompts]
|
|
581
625
|
if model_name is None:
|
|
582
|
-
mdn
|
|
626
|
+
mdn = _metadata_text(md.get("model_name"))
|
|
583
627
|
if mdn is not None:
|
|
584
628
|
model_name = mdn
|
|
585
629
|
self._writer.enqueue(
|
|
@@ -591,7 +635,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
591
635
|
event_name="llm_start",
|
|
592
636
|
model_name=model_name,
|
|
593
637
|
filename=str(filename) if filename is not None else None,
|
|
594
|
-
line_number=md.get("line_number"),
|
|
638
|
+
line_number=_metadata_int_or_none(md.get("line_number")),
|
|
595
639
|
token_count=0,
|
|
596
640
|
cost_usd=0.0,
|
|
597
641
|
n_try = payload.get('n_try', 0),
|
|
@@ -604,10 +648,10 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
604
648
|
response: LLMResult,
|
|
605
649
|
*,
|
|
606
650
|
run_id: UUID,
|
|
607
|
-
parent_run_id:
|
|
608
|
-
tags:
|
|
609
|
-
metadata:
|
|
610
|
-
**kwargs:
|
|
651
|
+
parent_run_id: UUID | None = None,
|
|
652
|
+
tags: list[str] | None = None,
|
|
653
|
+
metadata: dict[str, object] | None = None,
|
|
654
|
+
**kwargs: object,
|
|
611
655
|
) -> None:
|
|
612
656
|
"""
|
|
613
657
|
Called after the LLM returns.
|
|
@@ -623,7 +667,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
623
667
|
|
|
624
668
|
# Defaults if we can't find usage
|
|
625
669
|
input_tokens = output_tokens = cached_tokens = reasoning_tokens = 0
|
|
626
|
-
model_name:
|
|
670
|
+
model_name: str | None = None
|
|
627
671
|
|
|
628
672
|
# LangChain response.generations: List[List[Generation]]
|
|
629
673
|
for gen_list in response.generations:
|
|
@@ -648,9 +692,9 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
648
692
|
gi = getattr(gen, "generation_info", None) or {}
|
|
649
693
|
model_name = gi.get("model_name") or model_name
|
|
650
694
|
if model_name is None:
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
695
|
+
inv_params = kwargs.get("invocation_params")
|
|
696
|
+
if isinstance(inv_params, Mapping) and inv_params.get("model"):
|
|
697
|
+
model_name = str(inv_params["model"])
|
|
654
698
|
token_count = int(input_tokens + output_tokens)
|
|
655
699
|
cost_usd = 0.0
|
|
656
700
|
if model_name and (input_tokens or output_tokens or cached_tokens):
|
|
@@ -670,10 +714,10 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
670
714
|
"response_llm_output": getattr(response, "llm_output", None),
|
|
671
715
|
}
|
|
672
716
|
if self.log_responses:
|
|
673
|
-
outs: list[dict[str,
|
|
717
|
+
outs: list[dict[str, object]] = []
|
|
674
718
|
for gen_list in response.generations:
|
|
675
719
|
for gen in gen_list:
|
|
676
|
-
item: dict[str,
|
|
720
|
+
item: dict[str, object] = {"type": type(gen).__name__}
|
|
677
721
|
|
|
678
722
|
# Text-y
|
|
679
723
|
if hasattr(gen, "text") and gen.text:
|
|
@@ -695,7 +739,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
695
739
|
payload["outputs"] = outs
|
|
696
740
|
|
|
697
741
|
if model_name is None:
|
|
698
|
-
mdn
|
|
742
|
+
mdn = _metadata_text(md.get("model_name"))
|
|
699
743
|
if mdn is not None:
|
|
700
744
|
model_name = mdn
|
|
701
745
|
self._writer.enqueue(
|
|
@@ -707,7 +751,7 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
707
751
|
event_name="llm_end",
|
|
708
752
|
model_name=str(model_name) if model_name is not None else None,
|
|
709
753
|
filename=str(filename) if filename is not None else None,
|
|
710
|
-
line_number=md.get("line_number"),
|
|
754
|
+
line_number=_metadata_int_or_none(md.get("line_number")),
|
|
711
755
|
token_count=token_count,
|
|
712
756
|
cost_usd=float(cost_usd),
|
|
713
757
|
n_try=float(payload.get('n_try', 0)),
|
|
@@ -720,10 +764,10 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
720
764
|
error: BaseException,
|
|
721
765
|
*,
|
|
722
766
|
run_id: UUID,
|
|
723
|
-
parent_run_id:
|
|
724
|
-
tags:
|
|
725
|
-
metadata:
|
|
726
|
-
**kwargs:
|
|
767
|
+
parent_run_id: UUID | None = None,
|
|
768
|
+
tags: list[str] | None = None,
|
|
769
|
+
metadata: dict[str, object] | None = None,
|
|
770
|
+
**kwargs: object,
|
|
727
771
|
) -> None:
|
|
728
772
|
"""
|
|
729
773
|
Called when the LLM call errors.
|
|
@@ -758,11 +802,11 @@ class DocumentIngestSQLiteCallback(BaseCallbackHandler):
|
|
|
758
802
|
else:
|
|
759
803
|
payload["error_type"] = type(error).__name__
|
|
760
804
|
if model_name is None:
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
805
|
+
inv_params = kwargs.get("invocation_params")
|
|
806
|
+
if isinstance(inv_params, Mapping) and inv_params.get("model"):
|
|
807
|
+
model_name = str(inv_params["model"])
|
|
764
808
|
if model_name is None:
|
|
765
|
-
mdn
|
|
809
|
+
mdn = _metadata_text(md.get("model_name"))
|
|
766
810
|
if mdn is not None:
|
|
767
811
|
model_name = mdn
|
|
768
812
|
self._writer.enqueue(
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Literal, Protocol, Self, TypeAlias, TypedDict, cast
|
|
4
|
+
|
|
5
|
+
from kogwistar.llm_tasks.providers import (
|
|
6
|
+
SupportsStructuredOutput,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from kogwistar.llm_tasks.providers import StructuredModelLike
|
|
11
|
+
else:
|
|
12
|
+
class StructuredModelLike(Protocol):
|
|
13
|
+
"""Compatibility fallback for released Core versions."""
|
|
14
|
+
|
|
15
|
+
@classmethod
|
|
16
|
+
def model_validate(cls, payload: object, /) -> Self: ...
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def model_json_schema(cls) -> dict[str, object]: ...
|
|
20
|
+
|
|
21
|
+
# Keep the historical parser names as aliases, but use the core contracts as
|
|
22
|
+
# the single source of truth for provider/schema compatibility.
|
|
23
|
+
StructuredSchema: TypeAlias = StructuredModelLike
|
|
24
|
+
StructuredOutputModel: TypeAlias = SupportsStructuredOutput
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class _StructuredOutputOptions(TypedDict, total=False):
|
|
28
|
+
include_raw: bool
|
|
29
|
+
method: Literal["function_calling", "json_mode", "json_schema"]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class StructuredOutputRunnable(Protocol):
|
|
33
|
+
"""Runnable returned by a structured-output model adapter."""
|
|
34
|
+
|
|
35
|
+
steps: list[object]
|
|
36
|
+
|
|
37
|
+
def invoke(
|
|
38
|
+
self,
|
|
39
|
+
messages: object,
|
|
40
|
+
config: object | None = None,
|
|
41
|
+
**kwargs: object,
|
|
42
|
+
) -> dict[str, object]: ...
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def build_structured_output_runnable(
|
|
46
|
+
model: StructuredOutputModel,
|
|
47
|
+
schema: type[StructuredSchema],
|
|
48
|
+
*,
|
|
49
|
+
include_raw: bool = True,
|
|
50
|
+
prefer_json_schema: bool = True,
|
|
51
|
+
) -> StructuredOutputRunnable:
|
|
52
|
+
"""Build a structured-output runnable with strict-schema-first fallback."""
|
|
53
|
+
attempts: list[_StructuredOutputOptions] = []
|
|
54
|
+
if prefer_json_schema:
|
|
55
|
+
attempts.append({"include_raw": include_raw, "method": "json_schema"})
|
|
56
|
+
attempts.append({"include_raw": include_raw, "method": "function_calling"})
|
|
57
|
+
attempts.append({"include_raw": include_raw})
|
|
58
|
+
|
|
59
|
+
last_error: Exception | None = None
|
|
60
|
+
for kwargs in attempts:
|
|
61
|
+
try:
|
|
62
|
+
# LangChain returns a runnable with ``steps``; the dependency-light
|
|
63
|
+
# core protocol intentionally does not require that implementation
|
|
64
|
+
# detail. Keep the cast at this parser-only compatibility boundary.
|
|
65
|
+
return cast(
|
|
66
|
+
StructuredOutputRunnable,
|
|
67
|
+
model.with_structured_output(schema, **kwargs),
|
|
68
|
+
)
|
|
69
|
+
except (TypeError, ValueError) as exc:
|
|
70
|
+
last_error = exc
|
|
71
|
+
if last_error is not None:
|
|
72
|
+
raise last_error
|
|
73
|
+
raise TypeError("with_structured_output is unavailable on this model")
|
{graph_knowledge_doc_parser-0.2.6 → graph_knowledge_doc_parser-0.2.9}/kg_doc_parser/models.py
RENAMED
|
@@ -47,25 +47,20 @@ Edges (Relationships):
|
|
|
47
47
|
"""
|
|
48
48
|
if True:
|
|
49
49
|
import logging
|
|
50
|
-
import os
|
|
51
50
|
logger = logging.getLogger(__name__)
|
|
52
51
|
logger.addHandler(logging.NullHandler())
|
|
53
52
|
logger.debug("loading models")
|
|
54
|
-
from typing import
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
53
|
+
from typing import Literal, Self, TypeAlias
|
|
54
|
+
from pydantic import BaseModel, Field, ValidationInfo, field_validator, model_validator
|
|
55
|
+
from pydantic_extension.model_slicing import (
|
|
56
|
+
DtoType,
|
|
57
|
+
ModeSlicingMixin,
|
|
58
|
+
)
|
|
59
|
+
from pydantic_extension.model_slicing.mixin import DtoField
|
|
60
60
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
FrontendType,
|
|
65
|
-
LLMType,
|
|
66
|
-
use_mode)
|
|
67
|
-
from pydantic_extension.model_slicing.mixin import ExcludeMode, DtoField
|
|
68
|
-
JsonPrimitive = Union[str, int, float, bool, None]
|
|
61
|
+
JsonPrimitive = str | int | float | bool | None
|
|
62
|
+
JsonValue: TypeAlias = JsonPrimitive | list["JsonValue"] | dict[str, "JsonValue"]
|
|
63
|
+
JsonObject: TypeAlias = dict[str, JsonValue]
|
|
69
64
|
#========================= OCR DOC
|
|
70
65
|
|
|
71
66
|
# pre-validation model
|
|
@@ -102,8 +97,8 @@ class OCRClusterResponse(ModeSlicingMixin, BaseModel):
|
|
|
102
97
|
the first image box id (cluster numebr) will be '2', the next signature will be '3' """
|
|
103
98
|
OCR_text_clusters: DtoType[list[TextCluster]] = Field(description="the OCR text results. Share cluster number uniqueness with non-OCR objects. Include emoji or unicode text")
|
|
104
99
|
non_text_objects: DtoType[list[NonTextCluster]] = Field(description="the non-OCR object results. Share cluster number uniqueness with OCR texts. ")
|
|
105
|
-
is_empty_page: DtoType[
|
|
106
|
-
printed_page_number: DtoType[
|
|
100
|
+
is_empty_page: DtoType[bool | None] = Field(default = False, description="true if the whole page is empty without recognisable text.")
|
|
101
|
+
printed_page_number: DtoType[str | None] = Field(description='the page number identified from OCR texts, can be in form of roman numerals such as "i", "ii", "iii", "iv"...; '
|
|
107
102
|
'Arabic numeral such as 1, 2, 3... or letter such as "a", "b", "c"...\n'
|
|
108
103
|
'Sometimes the are surrounded by symbols such as "- 1 -", "- 2 -"'
|
|
109
104
|
r"Can be null/none if there is no page order assigned and printed and found in the scanned texts. Do not assign page number. Only use page number found.")
|
|
@@ -123,15 +118,17 @@ class OCRClusterResponse(ModeSlicingMixin, BaseModel):
|
|
|
123
118
|
|
|
124
119
|
@model_validator(mode='after')
|
|
125
120
|
def check_cluster_meaningful_ordering_agreement(self) -> Self:
|
|
126
|
-
|
|
127
|
-
|
|
121
|
+
if bool(self.is_empty_page) == (len(self.OCR_text_clusters) > 0):
|
|
122
|
+
raise ValueError(
|
|
123
|
+
f"is_empty_page value {self.is_empty_page} disagree with OCR_text_clusters "
|
|
124
|
+
f"len={len(self.OCR_text_clusters)}"
|
|
125
|
+
)
|
|
126
|
+
text_ids = {item.cluster_number for item in self.OCR_text_clusters}
|
|
127
|
+
overlap_id = text_ids.intersection({item.cluster_number for item in self.non_text_objects})
|
|
128
128
|
if overlap_id:
|
|
129
129
|
raise ValueError(f"cluster number from non_text_objects block and ocr text blocks must be ALL distinct. Overlapped ids: {list(overlap_id)}")
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
raise ValueError("meaningful_order must cover each text cluster at most once")
|
|
133
|
-
except Exception as e:
|
|
134
|
-
raise e
|
|
130
|
+
if len(self.meaningful_ordering) != len(text_ids) or set(self.meaningful_ordering) != text_ids:
|
|
131
|
+
raise ValueError("meaningful_ordering must cover each text cluster exactly once")
|
|
135
132
|
return self
|
|
136
133
|
|
|
137
134
|
|
|
@@ -154,12 +151,12 @@ class SplitPage(OCRClusterResponseBc):
|
|
|
154
151
|
# model not for LLM response
|
|
155
152
|
pdf_page_num: int
|
|
156
153
|
metadata: SplitPageMeta
|
|
157
|
-
refined_version:
|
|
158
|
-
def model_dump(self, *arg:
|
|
154
|
+
refined_version: OCRClusterResponse[DtoField] | None = Field(default = None, description = "refined processed/ grouped/ merged version of ocr text clusters. ")
|
|
155
|
+
def model_dump(self, *arg: object, **kwarg: object) -> JsonObject:
|
|
159
156
|
return self.to_doc()
|
|
160
|
-
def dump_raw(self, *arg:
|
|
157
|
+
def dump_raw(self, *arg: object, **kwarg: object) -> JsonObject:
|
|
161
158
|
return super(SplitPage, self).model_dump(exclude = ["refined_version"], *arg, **kwarg)
|
|
162
|
-
def dump_supercede_parse(self, *arg:
|
|
159
|
+
def dump_supercede_parse(self, *arg: object, **kwarg: object) -> JsonObject:
|
|
163
160
|
return super(SplitPage, self).model_dump(exclude = ["refined_version", "metadata"], *arg, **kwarg)
|
|
164
161
|
@model_validator(mode="after")
|
|
165
162
|
def roundtrip_invariant(self, info: ValidationInfo) -> "SplitPage":
|
|
@@ -185,7 +182,7 @@ class SplitPage(OCRClusterResponseBc):
|
|
|
185
182
|
raise ValueError("Roundtrip invariant failed: dump->validate changed the model")
|
|
186
183
|
|
|
187
184
|
return self
|
|
188
|
-
def to_doc(self) ->
|
|
185
|
+
def to_doc(self) -> JsonObject:
|
|
189
186
|
"""Model to llm one-way serializer with manual slicing logic, can refactor using sliced view
|
|
190
187
|
with some token saving logic.
|
|
191
188
|
"""
|
|
@@ -194,24 +191,25 @@ class SplitPage(OCRClusterResponseBc):
|
|
|
194
191
|
non_ocr_cluster = target.non_text_objects
|
|
195
192
|
if target.contains_table:
|
|
196
193
|
id_sorted_text_cluster = []
|
|
197
|
-
cluster_numbers =
|
|
198
|
-
|
|
194
|
+
cluster_numbers = {i.cluster_number for i in ocr_cluster}
|
|
195
|
+
if len(cluster_numbers) != len(ocr_cluster):
|
|
196
|
+
raise ValueError("OCR cluster numbers must be unique")
|
|
199
197
|
cluster_lookup_by_number = {i.cluster_number : i for i in (ocr_cluster + non_ocr_cluster#+ target.signature_blocks
|
|
200
198
|
)}
|
|
201
199
|
for i in target.meaningful_ordering:
|
|
202
200
|
c_p = cluster_lookup_by_number.get(i)
|
|
203
201
|
if c_p is None:
|
|
204
202
|
raise KeyError(f"{i} does not exist")
|
|
205
|
-
cluster_dump:
|
|
203
|
+
cluster_dump: JsonObject = c_p.model_dump()
|
|
206
204
|
cluster_dump.pop("cluster_number")
|
|
207
205
|
id_sorted_text_cluster.append(cluster_dump)
|
|
208
|
-
others =
|
|
206
|
+
others = cluster_numbers - set(target.meaningful_ordering)
|
|
209
207
|
for i in others:
|
|
210
|
-
cluster_dump:
|
|
208
|
+
cluster_dump: JsonObject
|
|
211
209
|
cluster_dump = cluster_lookup_by_number[i].model_dump()
|
|
212
210
|
cluster_dump.pop("cluster_number")
|
|
213
211
|
id_sorted_text_cluster.append(cluster_dump)
|
|
214
|
-
c_return = {}
|
|
212
|
+
c_return: JsonObject = {}
|
|
215
213
|
c_return['pdf_page_num'] = self.pdf_page_num
|
|
216
214
|
c_return['printed_page_number'] = self.printed_page_number
|
|
217
215
|
c_return['OCR_text_clusters'] = id_sorted_text_cluster
|
|
@@ -229,7 +227,8 @@ class SplitPage(OCRClusterResponseBc):
|
|
|
229
227
|
# expected_next = min(ocr_clus_nums + sig_clus_nums)
|
|
230
228
|
if ocr_clus_nums:
|
|
231
229
|
start_num = min(ocr_clus_nums + non_clus_nums)
|
|
232
|
-
|
|
230
|
+
if start_num not in [0, 1]:
|
|
231
|
+
raise ValueError("only allow 0-indexed based or 1-indexed based cluster numbers")
|
|
233
232
|
expected_next = start_num
|
|
234
233
|
while expected_next < start_num + (len(ocr_clus_nums) + len(non_clus_nums)):
|
|
235
234
|
if (i_ocr <len(ocr_cluster)) and expected_next == ocr_cluster[i_ocr].cluster_number:
|
|
@@ -244,7 +243,8 @@ class SplitPage(OCRClusterResponseBc):
|
|
|
244
243
|
|
|
245
244
|
|
|
246
245
|
id_sorted_text_cluster = sorted(ocr_cluster, key=lambda x : x.cluster_number )
|
|
247
|
-
|
|
246
|
+
if len(id_sorted_text_cluster) != len({i.cluster_number for i in id_sorted_text_cluster}):
|
|
247
|
+
raise ValueError("OCR cluster numbers must be unique")
|
|
248
248
|
is_normal = True
|
|
249
249
|
shift = 0 # try zero indexing sanity
|
|
250
250
|
c : TextCluster #| TextCluster_yolo_bb
|
|
@@ -262,7 +262,8 @@ class SplitPage(OCRClusterResponseBc):
|
|
|
262
262
|
is_normal = False
|
|
263
263
|
break
|
|
264
264
|
# sig_num = set([i.cluster_number for i in self.signature_blocks])
|
|
265
|
-
|
|
265
|
+
if not set(self.meaningful_ordering) <= {i.cluster_number for i in self.OCR_text_clusters}:
|
|
266
|
+
raise ValueError("meaningful_ordering references an unknown OCR cluster")
|
|
266
267
|
if is_normal:
|
|
267
268
|
# is sorted list where index is order + shift
|
|
268
269
|
texts = '\n'.join(id_sorted_text_cluster[i+shift].text for i in self.meaningful_ordering)
|
|
@@ -270,7 +271,7 @@ class SplitPage(OCRClusterResponseBc):
|
|
|
270
271
|
# general case
|
|
271
272
|
tcd = {x.cluster_number:x for x in id_sorted_text_cluster}
|
|
272
273
|
texts = '\n'.join(tcd[i].text for i in self.meaningful_ordering)
|
|
273
|
-
c_return = {}
|
|
274
|
+
c_return: JsonObject = {}
|
|
274
275
|
c_return['pdf_page_num'] = self.pdf_page_num
|
|
275
276
|
c_return['printed_page_number'] = self.printed_page_number
|
|
276
277
|
c_return['text'] = texts
|