graph-knowledge-doc-parser 0.2.7__tar.gz → 0.2.10__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.7 → graph_knowledge_doc_parser-0.2.10}/PKG-INFO +4 -4
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/README.md +2 -2
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/models.py +19 -13
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/ocr.py +17 -12
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/pdf2png.py +2 -1
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/semantic_document_splitting_layerwise_edits.py +49 -12
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/utils/file_loaders.py +2 -1
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/__init__.py +2 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/adapters.py +125 -29
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/cache.py +17 -7
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/clients.py +23 -9
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/demo_harness.py +1 -2
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/handlers.py +15 -13
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/layered_contracts.py +18 -16
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/layerwise_llm.py +146 -50
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/models.py +206 -44
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/ocr_pipeline.py +26 -9
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/page_index.py +59 -45
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/parser_core.py +128 -31
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/probe.py +5 -6
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/runners.py +3 -1
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/semantics.py +83 -27
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/pyproject.toml +2 -2
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/__init__.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/cast_hinting.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/document_ingest_log_config.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/document_ingester_logger.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/llm_structured_output.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/text_processing_utils.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/utils/__init__.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/utils/bounded_threadpool_executor.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/utils/langchain.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/utils/log.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/utils/version_chaining.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/_kogwistar.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/cli.py +1 -1
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/design.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/parsing.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/providers.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/serialization.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/service.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/smoke_assets.py +0 -0
- {graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/workflow_ingest/strategy.py +1 -1
|
@@ -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.10
|
|
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"
|
|
@@ -86,8 +86,8 @@ to normal strategy selection. See the
|
|
|
86
86
|
The deterministic and text-only Bonsai fixture evaluation is recorded in the
|
|
87
87
|
[`PageIndex adversarial fixture report`](doc/page_index_adversarial_fixture_report.md).
|
|
88
88
|
The current patch release is documented in the
|
|
89
|
-
[`0.2.
|
|
90
|
-
[`0.2.
|
|
89
|
+
[`0.2.10` release note](doc/release_0.2.10.md); the prior
|
|
90
|
+
[`0.2.7` release note](doc/release_0.2.7.md) remains available for history.
|
|
91
91
|
|
|
92
92
|
For an adoption path that starts with parser-grounded source units and later
|
|
93
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.10` release note](doc/release_0.2.10.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.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/models.py
RENAMED
|
@@ -118,15 +118,17 @@ class OCRClusterResponse(ModeSlicingMixin, BaseModel):
|
|
|
118
118
|
|
|
119
119
|
@model_validator(mode='after')
|
|
120
120
|
def check_cluster_meaningful_ordering_agreement(self) -> Self:
|
|
121
|
-
|
|
122
|
-
|
|
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})
|
|
123
128
|
if overlap_id:
|
|
124
129
|
raise ValueError(f"cluster number from non_text_objects block and ocr text blocks must be ALL distinct. Overlapped ids: {list(overlap_id)}")
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
raise ValueError("meaningful_order must cover each text cluster at most once")
|
|
128
|
-
except Exception as e:
|
|
129
|
-
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")
|
|
130
132
|
return self
|
|
131
133
|
|
|
132
134
|
|
|
@@ -189,8 +191,9 @@ class SplitPage(OCRClusterResponseBc):
|
|
|
189
191
|
non_ocr_cluster = target.non_text_objects
|
|
190
192
|
if target.contains_table:
|
|
191
193
|
id_sorted_text_cluster = []
|
|
192
|
-
cluster_numbers =
|
|
193
|
-
|
|
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")
|
|
194
197
|
cluster_lookup_by_number = {i.cluster_number : i for i in (ocr_cluster + non_ocr_cluster#+ target.signature_blocks
|
|
195
198
|
)}
|
|
196
199
|
for i in target.meaningful_ordering:
|
|
@@ -200,7 +203,7 @@ class SplitPage(OCRClusterResponseBc):
|
|
|
200
203
|
cluster_dump: JsonObject = c_p.model_dump()
|
|
201
204
|
cluster_dump.pop("cluster_number")
|
|
202
205
|
id_sorted_text_cluster.append(cluster_dump)
|
|
203
|
-
others =
|
|
206
|
+
others = cluster_numbers - set(target.meaningful_ordering)
|
|
204
207
|
for i in others:
|
|
205
208
|
cluster_dump: JsonObject
|
|
206
209
|
cluster_dump = cluster_lookup_by_number[i].model_dump()
|
|
@@ -224,7 +227,8 @@ class SplitPage(OCRClusterResponseBc):
|
|
|
224
227
|
# expected_next = min(ocr_clus_nums + sig_clus_nums)
|
|
225
228
|
if ocr_clus_nums:
|
|
226
229
|
start_num = min(ocr_clus_nums + non_clus_nums)
|
|
227
|
-
|
|
230
|
+
if start_num not in [0, 1]:
|
|
231
|
+
raise ValueError("only allow 0-indexed based or 1-indexed based cluster numbers")
|
|
228
232
|
expected_next = start_num
|
|
229
233
|
while expected_next < start_num + (len(ocr_clus_nums) + len(non_clus_nums)):
|
|
230
234
|
if (i_ocr <len(ocr_cluster)) and expected_next == ocr_cluster[i_ocr].cluster_number:
|
|
@@ -239,7 +243,8 @@ class SplitPage(OCRClusterResponseBc):
|
|
|
239
243
|
|
|
240
244
|
|
|
241
245
|
id_sorted_text_cluster = sorted(ocr_cluster, key=lambda x : x.cluster_number )
|
|
242
|
-
|
|
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")
|
|
243
248
|
is_normal = True
|
|
244
249
|
shift = 0 # try zero indexing sanity
|
|
245
250
|
c : TextCluster #| TextCluster_yolo_bb
|
|
@@ -257,7 +262,8 @@ class SplitPage(OCRClusterResponseBc):
|
|
|
257
262
|
is_normal = False
|
|
258
263
|
break
|
|
259
264
|
# sig_num = set([i.cluster_number for i in self.signature_blocks])
|
|
260
|
-
|
|
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")
|
|
261
267
|
if is_normal:
|
|
262
268
|
# is sorted list where index is order + shift
|
|
263
269
|
texts = '\n'.join(id_sorted_text_cluster[i+shift].text for i in self.meaningful_ordering)
|
|
@@ -150,15 +150,17 @@ class RawOCRResponse(BaseModel):
|
|
|
150
150
|
|
|
151
151
|
@model_validator(mode='after')
|
|
152
152
|
def check_cluster_meaningful_ordering_agreement(self) -> Self:
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
raise
|
|
153
|
+
if bool(self.is_empty_page) == (len(self.boxes_2d) > 0):
|
|
154
|
+
raise ValueError(
|
|
155
|
+
f"is_empty_page value {self.is_empty_page} disagree with boxes_2d "
|
|
156
|
+
f"len={len(self.boxes_2d)}"
|
|
157
|
+
)
|
|
158
|
+
text_ids = {item.id for item in self.boxes_2d}
|
|
159
|
+
all_ids = [item.id for item in self.non_text_objects] + [item.id for item in self.boxes_2d]
|
|
160
|
+
if len(all_ids) != len(set(all_ids)):
|
|
161
|
+
raise ValueError(f"cluster number from non_text_objects block and boxes_2d must be ALL distinct. overlap ids {set(all_ids)}")
|
|
162
|
+
if len(self.meaningful_ordering) != len(text_ids) or set(self.meaningful_ordering) != text_ids:
|
|
163
|
+
raise ValueError("meaningful_ordering must cover each text cluster exactly once")
|
|
162
164
|
return self
|
|
163
165
|
|
|
164
166
|
|
|
@@ -567,7 +569,8 @@ def ocr_single_image(
|
|
|
567
569
|
else:
|
|
568
570
|
raise( PermissionError(f"output file {outfile_name} exists"))
|
|
569
571
|
|
|
570
|
-
|
|
572
|
+
if not gemini_key.startswith("AIza"):
|
|
573
|
+
raise ValueError("gemini_key must be a Google AI API key")
|
|
571
574
|
model_names = model_retry_priority_list or [# "gemini-2.0-flash", "gemini-2.0-flash-lite",
|
|
572
575
|
"gemini-3-flash-preview",
|
|
573
576
|
"gemini-2.5-flash",
|
|
@@ -614,7 +617,8 @@ def ocr_single_image(
|
|
|
614
617
|
final_resort(draft_responses, messages, page_file_name, model_name, image_file_path, cb)
|
|
615
618
|
finally:
|
|
616
619
|
time.sleep(5)
|
|
617
|
-
|
|
620
|
+
if not response_dict:
|
|
621
|
+
raise RuntimeError("OCR response was not produced")
|
|
618
622
|
|
|
619
623
|
response_dict['usage_metadata'] = cb.model_dump() # or usage_metadata
|
|
620
624
|
with open(outfile_name, 'w') as f:
|
|
@@ -679,7 +683,8 @@ def refine_table_ocr(
|
|
|
679
683
|
is_preserved = [fuzz.partial_ratio(text_after, i) >= get_threshold(i) for i in text_before]
|
|
680
684
|
lost_text = [i for i, preserved in zip(sp.OCR_text_clusters, is_preserved) if not preserved]
|
|
681
685
|
ok = all(tf or (tc.text.strip() == "") for tf, tc in zip(is_preserved, sp.OCR_text_clusters))
|
|
682
|
-
|
|
686
|
+
if not ok:
|
|
687
|
+
raise ValueError(f"Some text or punctuations are lost through OCR text grouping, lost text = {lost_text}")
|
|
683
688
|
response_dict['refined_version'] = oc_refined_result.model_dump()
|
|
684
689
|
break
|
|
685
690
|
except Exception as e:
|
{graph_knowledge_doc_parser-0.2.7 → graph_knowledge_doc_parser-0.2.10}/kg_doc_parser/pdf2png.py
RENAMED
|
@@ -27,7 +27,8 @@ def batch_split_pdf(
|
|
|
27
27
|
file_loader: RawFileLoader | None = None,
|
|
28
28
|
) -> None:
|
|
29
29
|
cnt = 0
|
|
30
|
-
|
|
30
|
+
if document_folder is None and file_loader is None:
|
|
31
|
+
raise ValueError("document_folder or file_loader is required")
|
|
31
32
|
class old_walker_inplace(RawFileLoader):
|
|
32
33
|
def __init__(
|
|
33
34
|
self,
|
|
@@ -234,11 +234,8 @@ class HydratedTextPointer(ModeSlicingMixin, BaseModel):
|
|
|
234
234
|
validation_method: Annotated[str, BackendField(), LLMField(), ExcludeMode("llm")] | None = Field(None, description="The exact text of this fragment. This MUST match the text at the specified pointer location.")
|
|
235
235
|
# backend and llm used, default to dump include, but ExcludeMode("llm") specified must be excluded when dumping to llm mode
|
|
236
236
|
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
if self.end_char == -1 and self.verbatim_text:
|
|
240
|
-
self.end_char += len(self.verbatim_text)
|
|
241
|
-
return self
|
|
237
|
+
# Keep -1 as a reversible "to the end" sentinel. Resolving it by adding
|
|
238
|
+
# len(verbatim_text) is wrong whenever start_char is non-zero.
|
|
242
239
|
# --------------------------
|
|
243
240
|
# pointer -> ref dict
|
|
244
241
|
# --------------------------
|
|
@@ -1192,7 +1189,8 @@ def retried_level_node_llm_parsing(
|
|
|
1192
1189
|
if response.get('parsing_error'):
|
|
1193
1190
|
raise response['parsing_error']
|
|
1194
1191
|
parsed: LLMLevelResponse[llm] = response['parsed']
|
|
1195
|
-
|
|
1192
|
+
if not all(i.parent_node_id in parent_node_id_set for i in parsed.children):
|
|
1193
|
+
raise ValueError("llm generated non-existent parent id")
|
|
1196
1194
|
return cast(LLMLevelResponse, response["parsed"]).model_dump()
|
|
1197
1195
|
except Exception as e:
|
|
1198
1196
|
err_msg = str(e)
|
|
@@ -1956,19 +1954,58 @@ def correct_and_validate_pointer(
|
|
|
1956
1954
|
print(f"🚨 Delimiter Resolution Error: {e}")
|
|
1957
1955
|
return None # Or propagate error? Returning None causes it to be added to "unresolved" which triggers LLM retry.
|
|
1958
1956
|
|
|
1957
|
+
# Offset pointers must remain in their declared source cluster. The older
|
|
1958
|
+
# fallback below could silently move evidence across clusters or accept
|
|
1959
|
+
# fuzzy text; make the authoritative decision before that compatibility
|
|
1960
|
+
# code is reached.
|
|
1961
|
+
source_cluster = source_map.get(proposed_pointer.source_cluster_id)
|
|
1962
|
+
if not source_cluster or not proposed_pointer.verbatim_text:
|
|
1963
|
+
return None
|
|
1964
|
+
source_text = _source_map_entry_text(source_cluster)
|
|
1965
|
+
end_exclusive = (
|
|
1966
|
+
len(source_text)
|
|
1967
|
+
if proposed_pointer.end_char == -1
|
|
1968
|
+
else proposed_pointer.end_char + 1
|
|
1969
|
+
)
|
|
1970
|
+
valid_bounds = (
|
|
1971
|
+
type(proposed_pointer.start_char) is int
|
|
1972
|
+
and type(proposed_pointer.end_char) is int
|
|
1973
|
+
and 0 <= proposed_pointer.start_char < end_exclusive <= len(source_text)
|
|
1974
|
+
)
|
|
1975
|
+
if valid_bounds:
|
|
1976
|
+
actual = source_text[proposed_pointer.start_char:end_exclusive]
|
|
1977
|
+
return proposed_pointer.model_copy(
|
|
1978
|
+
update={
|
|
1979
|
+
"end_char": end_exclusive - 1,
|
|
1980
|
+
"verbatim_text": actual,
|
|
1981
|
+
}
|
|
1982
|
+
)
|
|
1983
|
+
|
|
1984
|
+
first = source_text.find(proposed_pointer.verbatim_text)
|
|
1985
|
+
if first >= 0 and source_text.find(
|
|
1986
|
+
proposed_pointer.verbatim_text, first + len(proposed_pointer.verbatim_text)
|
|
1987
|
+
) < 0:
|
|
1988
|
+
return proposed_pointer.model_copy(
|
|
1989
|
+
update={
|
|
1990
|
+
"start_char": first,
|
|
1991
|
+
"end_char": first + len(proposed_pointer.verbatim_text) - 1,
|
|
1992
|
+
"verbatim_text": source_text[
|
|
1993
|
+
first : first + len(proposed_pointer.verbatim_text)
|
|
1994
|
+
],
|
|
1995
|
+
"start_delimiter": None,
|
|
1996
|
+
"end_delimiter": None,
|
|
1997
|
+
"validation_method": "exact_unique_relocation",
|
|
1998
|
+
}
|
|
1999
|
+
)
|
|
2000
|
+
|
|
1959
2001
|
# Ensure verbatim_text is present for legacy logic
|
|
1960
2002
|
if not proposed_pointer.verbatim_text:
|
|
1961
2003
|
# If no delimiters and no verbatim text, we can't do anything
|
|
1962
2004
|
print("🚨 REJECTED: Pointer missing both delimiters and verbatim_text.")
|
|
1963
2005
|
return None
|
|
1964
2006
|
|
|
1965
|
-
ids = list(source_map.keys())
|
|
1966
|
-
ids_same_page, id_dif_page = partition(ids, predicate = lambda x: x.split("_")[0] == proposed_pointer.source_cluster_id.split('_')[0])
|
|
1967
|
-
_, ids_same_page_dif_cluster = partition(ids_same_page, predicate = lambda x: x == proposed_pointer.source_cluster_id)
|
|
1968
|
-
# Try some heuristic possible hallucinated cluster ids
|
|
1969
2007
|
verification_method = None
|
|
1970
|
-
for
|
|
1971
|
-
[source_map.get(i) for i in ids_same_page_dif_cluster + id_dif_page]):
|
|
2008
|
+
for source_cluster in [source_map.get(proposed_pointer.source_cluster_id)]:
|
|
1972
2009
|
validation_method = None
|
|
1973
2010
|
if not source_cluster:
|
|
1974
2011
|
# print(
|
|
@@ -174,7 +174,8 @@ class RawFileLoader():
|
|
|
174
174
|
filtering_callbacks: that apply to each path, when True, it allows continue, when False, it continue to next file
|
|
175
175
|
"""
|
|
176
176
|
|
|
177
|
-
|
|
177
|
+
if bucket_blob_connection_str is not None and env_flist_path is not None:
|
|
178
|
+
raise ValueError("bucket_blob_connection_str and env_flist_path are mutually exclusive")
|
|
178
179
|
self.allow_startwith_relative_paths = allow_startwith_relative_paths
|
|
179
180
|
self.pattern = pattern
|
|
180
181
|
self.include = include or []
|
|
@@ -72,6 +72,7 @@ from .parser_core import (
|
|
|
72
72
|
prepare_layer_frontier,
|
|
73
73
|
propose_layer_breakdown,
|
|
74
74
|
review_layer,
|
|
75
|
+
source_map_fingerprint,
|
|
75
76
|
)
|
|
76
77
|
from .parsing import (
|
|
77
78
|
OCRParseRequest,
|
|
@@ -221,6 +222,7 @@ __all__ = [
|
|
|
221
222
|
"propose_layer_breakdown",
|
|
222
223
|
"provider_call_metrics_snapshot",
|
|
223
224
|
"review_layer",
|
|
225
|
+
"source_map_fingerprint",
|
|
224
226
|
"run_demo_harness",
|
|
225
227
|
"run_demo_harness_workflow",
|
|
226
228
|
"run_ingest_workflow",
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
from __future__ import annotations
|
|
2
2
|
|
|
3
|
+
import math
|
|
4
|
+
from collections.abc import Mapping
|
|
3
5
|
from typing import NotRequired, TypedDict
|
|
4
6
|
|
|
5
7
|
from .models import (
|
|
@@ -41,6 +43,59 @@ class OCRPageJSON(TypedDict):
|
|
|
41
43
|
text: NotRequired[str]
|
|
42
44
|
|
|
43
45
|
|
|
46
|
+
def _ocr_page_number(value: object) -> int:
|
|
47
|
+
"""Return a positive page number without permissive bool/float coercion."""
|
|
48
|
+
if type(value) is int:
|
|
49
|
+
page_number = value
|
|
50
|
+
elif isinstance(value, str) and value.strip().isdigit():
|
|
51
|
+
page_number = int(value.strip())
|
|
52
|
+
else:
|
|
53
|
+
raise ValueError("OCR pdf_page_num must be a positive integer")
|
|
54
|
+
if page_number < 1:
|
|
55
|
+
raise ValueError("OCR pdf_page_num must be a positive integer")
|
|
56
|
+
return page_number
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _ocr_cluster_number(value: object) -> int | None:
|
|
60
|
+
if value is None:
|
|
61
|
+
return None
|
|
62
|
+
if type(value) is int:
|
|
63
|
+
cluster_number = value
|
|
64
|
+
elif isinstance(value, str) and value.strip().isdigit():
|
|
65
|
+
cluster_number = int(value.strip())
|
|
66
|
+
else:
|
|
67
|
+
raise ValueError("OCR cluster_number must be a non-negative integer")
|
|
68
|
+
if cluster_number < 0:
|
|
69
|
+
raise ValueError("OCR cluster_number must be a non-negative integer")
|
|
70
|
+
return cluster_number
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _ocr_coordinate(value: object, *, default: float = 0.0) -> float:
|
|
74
|
+
if value is None:
|
|
75
|
+
return default
|
|
76
|
+
if isinstance(value, bool):
|
|
77
|
+
raise TypeError("OCR bounding-box coordinates must be finite numbers")
|
|
78
|
+
if not isinstance(value, (int, float, str)):
|
|
79
|
+
raise TypeError("OCR bounding-box coordinates must be finite numbers")
|
|
80
|
+
try:
|
|
81
|
+
coordinate = float(value)
|
|
82
|
+
except ValueError:
|
|
83
|
+
raise ValueError("OCR bounding-box coordinates must be finite numbers") from None
|
|
84
|
+
if not math.isfinite(coordinate):
|
|
85
|
+
raise ValueError("OCR bounding-box coordinates must be finite numbers")
|
|
86
|
+
return coordinate
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _ocr_bbox(raw: Mapping[str, object]) -> BoundingBox:
|
|
90
|
+
y_min = _ocr_coordinate(raw.get("bb_y_min"))
|
|
91
|
+
x_min = _ocr_coordinate(raw.get("bb_x_min"))
|
|
92
|
+
y_max = _ocr_coordinate(raw.get("bb_y_max"))
|
|
93
|
+
x_max = _ocr_coordinate(raw.get("bb_x_max"))
|
|
94
|
+
if y_min > y_max or x_min > x_max:
|
|
95
|
+
raise ValueError("OCR bounding-box minimums must not exceed maximums")
|
|
96
|
+
return BoundingBox(y_min=y_min, x_min=x_min, y_max=y_max, x_max=x_max)
|
|
97
|
+
|
|
98
|
+
|
|
44
99
|
def normalize_ocr_pages(
|
|
45
100
|
*,
|
|
46
101
|
document_id: str,
|
|
@@ -53,41 +108,58 @@ def normalize_ocr_pages(
|
|
|
53
108
|
cluster metadata. `embedding_space="image"` is an intent label here; it
|
|
54
109
|
does not imply a separate image embedder is already wired at runtime.
|
|
55
110
|
"""
|
|
111
|
+
if not isinstance(pages, list):
|
|
112
|
+
raise TypeError("OCR pages must be a list")
|
|
56
113
|
normalized_pages: list[NormalizedPage] = []
|
|
114
|
+
seen_page_numbers: set[int] = set()
|
|
57
115
|
for raw_page in pages:
|
|
58
|
-
|
|
116
|
+
if not isinstance(raw_page, dict):
|
|
117
|
+
raise TypeError("each OCR page must be an object")
|
|
118
|
+
if "pdf_page_num" not in raw_page:
|
|
119
|
+
raise ValueError("each OCR page requires pdf_page_num")
|
|
120
|
+
page_number = _ocr_page_number(raw_page["pdf_page_num"])
|
|
121
|
+
if page_number in seen_page_numbers:
|
|
122
|
+
raise ValueError(f"duplicate OCR pdf_page_num: {page_number}")
|
|
123
|
+
seen_page_numbers.add(page_number)
|
|
124
|
+
seen_clusters: dict[str, set[int]] = {"text": set(), "image": set()}
|
|
59
125
|
units: list[SourceUnit] = []
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
126
|
+
text_clusters = raw_page.get("OCR_text_clusters", [])
|
|
127
|
+
non_text_objects = raw_page.get("non_text_objects", [])
|
|
128
|
+
if not isinstance(text_clusters, list) or not isinstance(non_text_objects, list):
|
|
129
|
+
raise TypeError("OCR cluster collections must be lists")
|
|
130
|
+
for cluster in text_clusters:
|
|
131
|
+
if not isinstance(cluster, dict):
|
|
132
|
+
raise TypeError("each OCR text cluster must be an object")
|
|
133
|
+
cluster_number = _ocr_cluster_number(cluster.get("cluster_number"))
|
|
134
|
+
if cluster_number is not None and cluster_number in seen_clusters["text"]:
|
|
135
|
+
raise ValueError(f"duplicate OCR text cluster_number: {cluster_number}")
|
|
136
|
+
if cluster_number is not None:
|
|
137
|
+
seen_clusters["text"].add(cluster_number)
|
|
67
138
|
units.append(
|
|
68
139
|
SourceUnit(
|
|
69
140
|
modality="ocr_text",
|
|
70
141
|
page_number=page_number,
|
|
71
|
-
cluster_number=
|
|
142
|
+
cluster_number=cluster_number,
|
|
72
143
|
text=cluster.get("text"),
|
|
73
|
-
bbox=
|
|
144
|
+
bbox=_ocr_bbox(cluster),
|
|
74
145
|
metadata={},
|
|
75
146
|
)
|
|
76
147
|
)
|
|
77
|
-
for obj in
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
148
|
+
for obj in non_text_objects:
|
|
149
|
+
if not isinstance(obj, dict):
|
|
150
|
+
raise TypeError("each OCR non-text object must be an object")
|
|
151
|
+
cluster_number = _ocr_cluster_number(obj.get("cluster_number"))
|
|
152
|
+
if cluster_number is not None and cluster_number in seen_clusters["image"]:
|
|
153
|
+
raise ValueError(f"duplicate OCR image cluster_number: {cluster_number}")
|
|
154
|
+
if cluster_number is not None:
|
|
155
|
+
seen_clusters["image"].add(cluster_number)
|
|
84
156
|
units.append(
|
|
85
157
|
SourceUnit(
|
|
86
158
|
modality="image_region",
|
|
87
159
|
page_number=page_number,
|
|
88
|
-
cluster_number=
|
|
160
|
+
cluster_number=cluster_number,
|
|
89
161
|
description=obj.get("description"),
|
|
90
|
-
bbox=
|
|
162
|
+
bbox=_ocr_bbox(obj),
|
|
91
163
|
# Keep the "image" space label for future routing; the
|
|
92
164
|
# current engine still embeds through a single function.
|
|
93
165
|
embedding_space="image",
|
|
@@ -125,26 +197,50 @@ def normalize_ocr_pages(
|
|
|
125
197
|
)
|
|
126
198
|
|
|
127
199
|
|
|
200
|
+
def _allocated_cluster_numbers(units: list[SourceUnit]) -> list[int]:
|
|
201
|
+
"""Allocate missing cluster numbers exactly as the source-map builder does."""
|
|
202
|
+
reserved: dict[str, set[int]] = {"t": set(), "i": set()}
|
|
203
|
+
for unit in units:
|
|
204
|
+
prefix = "t" if unit.modality in {"text", "ocr_text"} else "i"
|
|
205
|
+
if unit.cluster_number is not None:
|
|
206
|
+
reserved[prefix].add(unit.cluster_number)
|
|
207
|
+
|
|
208
|
+
next_ordinal: dict[str, int] = {"t": 0, "i": 0}
|
|
209
|
+
used: dict[str, set[int]] = {"t": set(), "i": set()}
|
|
210
|
+
allocated: list[int] = []
|
|
211
|
+
for unit in units:
|
|
212
|
+
prefix = "t" if unit.modality in {"text", "ocr_text"} else "i"
|
|
213
|
+
cluster_number = unit.cluster_number
|
|
214
|
+
if cluster_number is not None and cluster_number in used[prefix]:
|
|
215
|
+
raise ValueError(f"duplicate cluster number {cluster_number} in page")
|
|
216
|
+
if cluster_number is None:
|
|
217
|
+
cluster_number = next_ordinal[prefix]
|
|
218
|
+
while cluster_number in reserved[prefix] or cluster_number in used[prefix]:
|
|
219
|
+
cluster_number += 1
|
|
220
|
+
used[prefix].add(cluster_number)
|
|
221
|
+
next_ordinal[prefix] = cluster_number + 1
|
|
222
|
+
allocated.append(cluster_number)
|
|
223
|
+
return allocated
|
|
224
|
+
|
|
225
|
+
|
|
128
226
|
def build_authoritative_source_map(
|
|
129
227
|
inp: WorkflowIngestInput,
|
|
130
228
|
) -> dict[str, GroundedSourceRecord]:
|
|
131
229
|
source_map: dict[str, GroundedSourceRecord] = {}
|
|
132
230
|
for collection in inp.collections:
|
|
133
231
|
for page in collection.pages:
|
|
134
|
-
|
|
135
|
-
for unit in page.units:
|
|
232
|
+
allocated_clusters = _allocated_cluster_numbers(page.units)
|
|
233
|
+
for unit, allocated_cluster in zip(page.units, allocated_clusters, strict=True):
|
|
136
234
|
modality_prefix = "t" if unit.modality in {"text", "ocr_text"} else "i"
|
|
137
|
-
|
|
138
|
-
if original_cluster is None:
|
|
139
|
-
original_cluster = ordinal_by_modality.get(modality_prefix, 0)
|
|
140
|
-
ordinal_by_modality[modality_prefix] = ordinal_by_modality.get(modality_prefix, 0) + 1
|
|
141
|
-
unit_id = unit.unit_id or f"{collection.collection_id}|p{page.page_number}_{modality_prefix}{original_cluster}"
|
|
235
|
+
unit_id = unit.unit_id or f"{collection.collection_id}|p{page.page_number}_{modality_prefix}{allocated_cluster}"
|
|
142
236
|
record = GroundedSourceRecord(
|
|
143
237
|
unit_id=unit_id,
|
|
144
238
|
collection_id=collection.collection_id,
|
|
145
239
|
modality=unit.modality,
|
|
146
240
|
page_number=page.page_number,
|
|
147
|
-
|
|
241
|
+
# Persist the allocated identity so the record agrees with
|
|
242
|
+
# its source-map key when the input omitted a cluster number.
|
|
243
|
+
cluster_number=allocated_cluster,
|
|
148
244
|
text=unit.text or unit.description or "",
|
|
149
245
|
parser_text=unit.parser_text,
|
|
150
246
|
source_uri=unit.source_uri,
|
|
@@ -173,9 +269,9 @@ def build_parser_input_dict(
|
|
|
173
269
|
for page in collection.pages:
|
|
174
270
|
text_clusters = []
|
|
175
271
|
non_text_objects = []
|
|
176
|
-
|
|
272
|
+
allocated_clusters = _allocated_cluster_numbers(page.units)
|
|
273
|
+
for unit, cluster_number in zip(page.units, allocated_clusters, strict=True):
|
|
177
274
|
bbox = unit.bbox
|
|
178
|
-
cluster_number = unit.cluster_number if unit.cluster_number is not None else next_cluster
|
|
179
275
|
if unit.modality in {"text", "ocr_text"}:
|
|
180
276
|
text_clusters.append(
|
|
181
277
|
{
|
|
@@ -47,13 +47,23 @@ class WorkflowLLMCallCache:
|
|
|
47
47
|
) -> T:
|
|
48
48
|
path = self._cache_path(operation, fingerprint)
|
|
49
49
|
if path.exists():
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
50
|
+
try:
|
|
51
|
+
cached = json.loads(path.read_text(encoding="utf-8"))
|
|
52
|
+
except (OSError, json.JSONDecodeError):
|
|
53
|
+
# A cache entry is an optimization, not parser state. A
|
|
54
|
+
# truncated or unreadable entry must not abort ingestion.
|
|
55
|
+
try:
|
|
56
|
+
path.unlink(missing_ok=True)
|
|
57
|
+
except OSError:
|
|
58
|
+
pass
|
|
59
|
+
else:
|
|
60
|
+
emit_probe_event(
|
|
61
|
+
self.probe,
|
|
62
|
+
"workflow.llm_cache_hit",
|
|
63
|
+
operation=operation,
|
|
64
|
+
cache_path=str(path),
|
|
65
|
+
)
|
|
66
|
+
return cast(T, cached)
|
|
57
67
|
result = fn()
|
|
58
68
|
payload = _jsonable(result)
|
|
59
69
|
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
@@ -21,7 +21,6 @@ from uuid import uuid4
|
|
|
21
21
|
|
|
22
22
|
from kogwistar.engine_core import GraphKnowledgeEngine
|
|
23
23
|
from kogwistar.engine_core.models import Edge, Node
|
|
24
|
-
from .serialization import JsonValue
|
|
25
24
|
from kogwistar.runtime.models import StepRunResult
|
|
26
25
|
|
|
27
26
|
from .design import (
|
|
@@ -37,6 +36,7 @@ from .models import (
|
|
|
37
36
|
WorkflowIngestInput,
|
|
38
37
|
)
|
|
39
38
|
from .probe import WorkflowProbe, emit_probe_event
|
|
39
|
+
from .serialization import JsonValue
|
|
40
40
|
|
|
41
41
|
|
|
42
42
|
class UnsupportedClientOperation(RuntimeError):
|
|
@@ -146,23 +146,33 @@ def _string_list(value: object, *, field_name: str) -> list[str]:
|
|
|
146
146
|
return []
|
|
147
147
|
if not isinstance(value, (list, tuple)):
|
|
148
148
|
raise TypeError(f"graph payload field {field_name!r} must be a list")
|
|
149
|
-
|
|
149
|
+
if any(not isinstance(item, str) for item in value):
|
|
150
|
+
raise TypeError(f"graph payload field {field_name!r} items must be strings")
|
|
151
|
+
return list(value)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _optional_record_id(record: Mapping[str, object], *, field_name: str) -> str:
|
|
155
|
+
value = record.get("id")
|
|
156
|
+
if value is None:
|
|
157
|
+
return ""
|
|
158
|
+
if not isinstance(value, str):
|
|
159
|
+
raise TypeError(f"graph payload {field_name!r} record id must be a string")
|
|
160
|
+
return value
|
|
150
161
|
|
|
151
162
|
|
|
152
163
|
def _json_int(value: object, default: int = 0) -> int:
|
|
153
164
|
"""Read an integer counter from an untrusted JSON response."""
|
|
154
165
|
|
|
155
166
|
if isinstance(value, bool):
|
|
156
|
-
return
|
|
167
|
+
return default
|
|
157
168
|
if isinstance(value, int):
|
|
158
|
-
return value
|
|
159
|
-
if isinstance(value, float):
|
|
160
|
-
return int(value)
|
|
169
|
+
return value if value >= 0 else default
|
|
161
170
|
if isinstance(value, str):
|
|
162
171
|
try:
|
|
163
|
-
|
|
172
|
+
parsed = int(value)
|
|
164
173
|
except ValueError:
|
|
165
174
|
return default
|
|
175
|
+
return parsed if parsed >= 0 else default
|
|
166
176
|
return default
|
|
167
177
|
|
|
168
178
|
|
|
@@ -174,17 +184,21 @@ def _to_temp_id_graph_payload(graph_payload: Mapping[str, object]) -> JsonObject
|
|
|
174
184
|
|
|
175
185
|
node_id_map: dict[str, str] = {}
|
|
176
186
|
for idx, node in enumerate(nodes, start=1):
|
|
177
|
-
original_id =
|
|
187
|
+
original_id = _optional_record_id(node, field_name="nodes")
|
|
178
188
|
temp_id = f"nn:{idx}"
|
|
179
189
|
if original_id:
|
|
190
|
+
if original_id in node_id_map:
|
|
191
|
+
raise ValueError(f"duplicate graph payload node id: {original_id!r}")
|
|
180
192
|
node_id_map[original_id] = temp_id
|
|
181
193
|
node["id"] = temp_id
|
|
182
194
|
|
|
183
195
|
edge_id_map: dict[str, str] = {}
|
|
184
196
|
for idx, edge in enumerate(edges, start=1):
|
|
185
|
-
original_id =
|
|
197
|
+
original_id = _optional_record_id(edge, field_name="edges")
|
|
186
198
|
temp_id = f"ne:{idx}"
|
|
187
199
|
if original_id:
|
|
200
|
+
if original_id in edge_id_map:
|
|
201
|
+
raise ValueError(f"duplicate graph payload edge id: {original_id!r}")
|
|
188
202
|
edge_id_map[original_id] = temp_id
|
|
189
203
|
edge["id"] = temp_id
|
|
190
204
|
|
|
@@ -28,8 +28,6 @@ from pathlib import Path
|
|
|
28
28
|
from types import TracebackType
|
|
29
29
|
from typing import Literal, Protocol
|
|
30
30
|
|
|
31
|
-
from .serialization import JsonValue
|
|
32
|
-
|
|
33
31
|
from .cache import WorkflowLLMCallCache
|
|
34
32
|
from .clients import (
|
|
35
33
|
DocumentTreeApiPersistenceClient,
|
|
@@ -47,6 +45,7 @@ from .models import (
|
|
|
47
45
|
from .probe import WorkflowProbe, emit_probe_event
|
|
48
46
|
from .providers import WorkflowProviderSettings
|
|
49
47
|
from .semantics import HydratedTextPointer
|
|
48
|
+
from .serialization import JsonValue
|
|
50
49
|
from .service import StorageBackendFactory, build_default_engines
|
|
51
50
|
|
|
52
51
|
_DEMO_JWT_SECRET = "kg-doc-parser-demo-test-secret"
|