-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdocument_ingester.py
More file actions
557 lines (447 loc) · 18.9 KB
/
document_ingester.py
File metadata and controls
557 lines (447 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
"""Generic document → graph ingester (Phase C).
Replaces domain-specific ingest scripts with a domain-agnostic pipeline
driven by a ``DomainProfile``. Per-corpus configuration (stopwords,
metadata patterns, category → NodeKind mapping) lives in a TOML profile
next to the corpus data, not in code.
Given:
- A :class:`CorpusSource` that yields :class:`DocumentRecord` objects
- A ``StorageBackend`` to write to
- A ``DomainProfile`` for ontology / NodeKind mapping
Builds a graph with:
- **Category nodes** (``NodeKind.CONCEPT``) — one per distinct category
- **Document nodes** — ``kind`` taken from ``profile.ontology_hints`` for
the document's category (defaults to ``NodeKind.ENTITY``)
- **Chunk nodes** (``NodeKind.CHUNK``) — one per ``ChunkRecord``
- **Edges**:
- ``PART_OF``: doc → category
- ``CONTAINS``: doc → chunk
- ``NEXT_CHUNK``: chunk → next chunk (sequential)
All ids are deterministic so re-ingesting the same corpus is idempotent
under the ``skip`` merge strategy.
Example::
from synaptic.extensions.domain_profile import DomainProfile
from synaptic.extensions.document_ingester import (
DocumentIngester,
JsonlDocumentSource,
)
profile = DomainProfile.load("profiles/my_corpus.toml")
source = JsonlDocumentSource(
"data/documents.jsonl",
"data/chunks.jsonl",
)
ingester = DocumentIngester(profile=profile, backend=backend)
stats = await ingester.ingest(source)
print(stats.documents_ingested, stats.chunks_created)
"""
from __future__ import annotations
import hashlib
import json
import time
import unicodedata
from collections import defaultdict
from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Literal, Protocol
from synaptic.models import (
ConsolidationLevel,
Edge,
EdgeKind,
Node,
NodeKind,
)
if TYPE_CHECKING:
from synaptic.extensions.domain_profile import DomainProfile
from synaptic.protocols import StorageBackend
def _nfc(s: str) -> str:
return unicodedata.normalize("NFC", s) if s else s
# --- Record types ---
@dataclass(slots=True)
class ChunkRecord:
"""A single chunk of a document."""
chunk_id: str
doc_id: str
text: str
index: int = 0
page_number: int | None = None
properties: dict[str, str] = field(default_factory=dict)
@dataclass(slots=True)
class DocumentRecord:
"""A single document ready for ingestion.
``content`` is optional — if ``chunks`` is populated, the document
node itself stores the title (for FTS matching on queries that
reference the document by name) while the full body text lives in
the chunks.
"""
doc_id: str
title: str
content: str = ""
source: str = ""
category: str = ""
year: int | None = None
properties: dict[str, str] = field(default_factory=dict)
chunks: list[ChunkRecord] = field(default_factory=list)
# --- Sources ---
class CorpusSource(Protocol):
"""Iterator-based source of documents for ingestion.
Implementations yield ``DocumentRecord`` instances one at a time.
The ingester does not assume any ordering — categories are deduped
on the fly and chunks within a document are sorted by ``index``.
"""
def documents(self) -> Iterator[DocumentRecord]: ...
class JsonlDocumentSource:
"""Corpus source that reads from JSONL files.
Supports two file layouts:
1. **Docs-only** — a single JSONL file where each line is a full
document (including inline ``chunks`` array).
2. **Docs + separate chunks** — one JSONL with documents and a
second JSONL with chunks referencing ``doc_id``. This matches
the output of a two-stage parser that emits docs and chunks
into different files.
Expected doc JSON keys (all optional except ``doc_id``):
``doc_id``, ``title``, ``content``, ``source_path``,
``category``, ``year``, ``properties``, ``chunks``.
Expected chunk JSON keys:
``chunk_id``, ``doc_id``, ``text``, ``index``, ``page_number``.
Unknown keys are ignored. Files are NOT loaded fully into memory —
documents stream one line at a time. Chunks, if supplied as a
separate file, are loaded once into an in-memory dict keyed by
``doc_id`` because they must be joined back to their parent.
"""
__slots__ = ("_chunks_path", "_docs_path")
def __init__(
self,
docs_path: Path | str,
chunks_path: Path | str | None = None,
) -> None:
self._docs_path = Path(docs_path)
self._chunks_path = Path(chunks_path) if chunks_path else None
def documents(self) -> Iterator[DocumentRecord]:
chunks_by_doc: dict[str, list[ChunkRecord]] = defaultdict(list)
if self._chunks_path is not None and self._chunks_path.exists():
with self._chunks_path.open(encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
c = json.loads(line)
doc_id = str(c.get("doc_id", ""))
if not doc_id:
continue
chunks_by_doc[doc_id].append(
ChunkRecord(
chunk_id=str(c.get("chunk_id", "")),
doc_id=doc_id,
text=str(c.get("text", "")),
index=int(c.get("index", 0) or 0),
page_number=c.get("page_number"),
)
)
with self._docs_path.open(encoding="utf-8") as f:
for line in f:
if not line.strip():
continue
d = json.loads(line)
doc_id = str(d.get("doc_id", ""))
if not doc_id:
continue
# Inline chunks override the separate file
inline_chunks_raw = d.get("chunks")
if isinstance(inline_chunks_raw, list):
inline_chunks = [
ChunkRecord(
chunk_id=str(c.get("chunk_id", "")),
doc_id=doc_id,
text=str(c.get("text", "")),
index=int(c.get("index", 0) or 0),
page_number=c.get("page_number"),
)
for c in inline_chunks_raw
if isinstance(c, dict)
]
else:
inline_chunks = chunks_by_doc.get(doc_id, [])
props_raw = d.get("properties", {})
props = (
{k: str(v) for k, v in props_raw.items()} if isinstance(props_raw, dict) else {}
)
year_raw = d.get("year")
year = int(year_raw) if isinstance(year_raw, (int, float)) else None
yield DocumentRecord(
doc_id=doc_id,
title=str(d.get("title", "")),
content=str(d.get("content", "")),
source=str(d.get("source_path", d.get("source", ""))),
category=str(d.get("category", "")),
year=year,
properties=props,
chunks=inline_chunks,
)
class InMemoryDocumentSource:
"""Convenience source that wraps a pre-built list of records.
Useful for tests and for callers that build documents programmatically.
"""
__slots__ = ("_docs",)
def __init__(self, docs: list[DocumentRecord]) -> None:
self._docs = list(docs)
def documents(self) -> Iterator[DocumentRecord]:
yield from self._docs
# --- Stats ---
@dataclass(slots=True)
class IngestStats:
"""Summary of one ``DocumentIngester.ingest`` run."""
documents_ingested: int = 0
documents_skipped: int = 0
chunks_created: int = 0
categories_created: int = 0
edges_created: int = 0
elapsed_seconds: float = 0.0
# --- Ingester ---
MergeStrategy = Literal["skip", "replace"]
class DocumentIngester:
"""Generic corpus → graph ingester driven by a ``DomainProfile``.
Args:
profile: Domain profile. Only ``profile.ontology_hints`` is
consulted — stopwords, metadata patterns, etc. belong to
the extractor / entity linker, not the ingester.
backend: Graph backend to write to.
merge_strategy: What to do when a document with the same
``doc_id`` already exists:
- ``"skip"`` (default) — leave existing doc alone, increment
``documents_skipped``. Idempotent for repeated runs.
- ``"replace"`` — delete existing doc + connected chunks +
outgoing/incoming edges, then re-ingest. Use when you
re-parsed a corpus and want fresh content.
Notes:
- Ids are deterministic so ``skip`` is genuinely idempotent on
repeated runs against the same data.
- The ingester does **not** run phrase extraction or entity
linking. Use :class:`EntityLinker` as a separate post-processing
pass — that separation keeps extraction reruns cheap.
"""
__slots__ = ("_backend", "_merge_strategy", "_profile")
def __init__(
self,
*,
profile: DomainProfile,
backend: StorageBackend,
merge_strategy: MergeStrategy = "skip",
) -> None:
if merge_strategy not in ("skip", "replace"):
msg = f"Unknown merge_strategy: {merge_strategy}"
raise ValueError(msg)
self._profile = profile
self._backend = backend
self._merge_strategy = merge_strategy
async def ingest(self, source: CorpusSource) -> IngestStats:
"""Walk the corpus and materialize category / document / chunk nodes."""
stats = IngestStats()
t0 = time.time()
category_ids: dict[str, str] = {}
for doc in source.documents():
doc_node_id = _doc_node_id(doc.doc_id)
doc_category = _nfc(doc.category)
doc_title = _nfc(doc.title)
existing = await self._backend.get_node(doc_node_id)
if existing is not None:
if self._merge_strategy == "skip":
stats.documents_skipped += 1
continue
# replace
await self._delete_document_cascade(doc_node_id)
# Ensure category node
category_id = await self._ensure_category(doc_category, category_ids, stats)
doc_kind = self._profile.ontology_hints.get(doc_category, NodeKind.ENTITY)
doc_props = dict(doc.properties)
doc_props["doc_id"] = doc.doc_id
if doc.year is not None:
doc_props["year"] = str(doc.year)
# ``year`` is also the temporal anchor — we surface it
# under ``valid_from`` so the agent tools (and future
# temporal filters) have a single, kind-agnostic field.
doc_props.setdefault("valid_from", str(doc.year))
if doc_category:
doc_props["category"] = doc_category
# Authority tag from the profile. Only set when the profile
# has an explicit mapping — we never guess a default
# authority, because wrong authority values propagate into
# conflict resolution and silently change agent behaviour.
authority = self._profile.authority_by_kind.get(doc_kind)
if authority is not None:
doc_props["authority"] = str(authority)
# Document content. Historical default was title-only, which
# meant Document nodes didn't participate meaningfully in FTS
# — the agent had to traverse CONTAINS to reach searchable
# text. When ``profile.enrich_document_content`` is True
# (default) we glue the title together with the opening
# chunks so each Document node carries its own semantic
# signal. The limit caps the worst case at ~600 chars so
# Document rows stay compact even on very long corpora.
if doc.content:
doc_content = doc.content
elif self._profile.enrich_document_content and doc.chunks:
doc_content = _build_document_preview(
title=doc_title,
chunks=sorted(doc.chunks, key=lambda c: c.index),
limit=self._profile.document_preview_chars,
)
else:
doc_content = doc_title
await self._backend.save_node(
Node(
id=doc_node_id,
kind=doc_kind,
title=doc_title,
content=doc_content,
tags=["document"],
source=doc.source,
properties=doc_props,
level=ConsolidationLevel.L0_RAW,
)
)
stats.documents_ingested += 1
if category_id is not None:
await self._backend.save_edge(
Edge(
id=_edge_id("part_of", doc_node_id, category_id),
source_id=doc_node_id,
target_id=category_id,
kind=EdgeKind.PART_OF,
weight=1.0,
)
)
stats.edges_created += 1
# Chunks
prev_chunk_node_id: str | None = None
for chunk in sorted(doc.chunks, key=lambda c: c.index):
chunk_node_id = _chunk_node_id(chunk.chunk_id)
chunk_props = dict(chunk.properties)
chunk_props["doc_id"] = doc.doc_id
chunk_props["chunk_index"] = str(chunk.index)
if chunk.page_number is not None:
chunk_props["page_number"] = str(chunk.page_number)
await self._backend.save_node(
Node(
id=chunk_node_id,
kind=NodeKind.CHUNK,
title=f"{doc_title} #{chunk.index}",
content=chunk.text,
tags=["chunk"],
source=doc.source,
properties=chunk_props,
level=ConsolidationLevel.L0_RAW,
)
)
stats.chunks_created += 1
await self._backend.save_edge(
Edge(
id=_edge_id("contains", doc_node_id, chunk_node_id),
source_id=doc_node_id,
target_id=chunk_node_id,
kind=EdgeKind.CONTAINS,
weight=1.0,
)
)
stats.edges_created += 1
if prev_chunk_node_id is not None:
await self._backend.save_edge(
Edge(
id=_edge_id("next", prev_chunk_node_id, chunk_node_id),
source_id=prev_chunk_node_id,
target_id=chunk_node_id,
kind=EdgeKind.NEXT_CHUNK,
weight=0.9,
)
)
stats.edges_created += 1
prev_chunk_node_id = chunk_node_id
stats.elapsed_seconds = time.time() - t0
return stats
async def _ensure_category(
self,
category_name: str,
cache: dict[str, str],
stats: IngestStats,
) -> str | None:
if not category_name:
return None
cached = cache.get(category_name)
if cached is not None:
return cached
cat_id = _category_node_id(category_name)
existing = await self._backend.get_node(cat_id)
if existing is None:
await self._backend.save_node(
Node(
id=cat_id,
kind=NodeKind.CONCEPT,
title=category_name,
content=category_name,
tags=["category"],
level=ConsolidationLevel.L0_RAW,
)
)
stats.categories_created += 1
cache[category_name] = cat_id
return cat_id
async def _delete_document_cascade(self, doc_node_id: str) -> None:
"""Delete a doc + its outgoing CONTAINS chunks + all touching edges.
Called in ``replace`` mode. Walks outgoing CONTAINS edges to find
chunks, deletes them, then deletes the doc itself. Any stray
incoming edges to the doc are cleaned up by ``delete_node`` on
backends that implement cascade; otherwise they'll dangle but
not corrupt queries since the target id is gone.
"""
outgoing = await self._backend.get_edges(doc_node_id, direction="outgoing")
for edge in outgoing:
if edge.kind == EdgeKind.CONTAINS:
await self._backend.delete_node(edge.target_id)
await self._backend.delete_node(doc_node_id)
# --- Content enrichment ---
def _build_document_preview(
*,
title: str,
chunks: list[ChunkRecord],
limit: int,
) -> str:
"""Build a searchable preview for a Document node.
Joins the title with the opening chunks' text, stopping as soon as
we hit ``limit`` characters. The title is always included so a
title-only FTS match still works; the chunk text is only there to
raise recall on queries that would otherwise miss the document.
The preview is NOT a summary — it's a prefix. For proper
summarisation use ``ConsolidationCascade`` on the chunks once the
graph is built. The goal here is purely retrieval: give FTS
something of substance to match against.
"""
title = (title or "").strip()
parts: list[str] = []
remaining = limit
if title:
parts.append(title)
remaining -= len(title) + 1 # +1 for the newline separator
if remaining <= 0:
return title
for chunk in chunks:
text = (chunk.text or "").strip()
if not text:
continue
if len(text) > remaining:
parts.append(text[: max(0, remaining)])
remaining = 0
break
parts.append(text)
remaining -= len(text) + 1
if remaining <= 0:
break
return "\n".join(parts).strip()
# --- Deterministic id helpers ---
def _doc_node_id(doc_id: str) -> str:
return f"doc_{_hash16(doc_id)}"
def _chunk_node_id(chunk_id: str) -> str:
return f"chunk_{_hash16(chunk_id)}"
def _category_node_id(category: str) -> str:
return f"cat_{_hash16(category)}"
def _edge_id(prefix: str, source_id: str, target_id: str) -> str:
return f"{prefix}_{_hash16(f'{source_id}->{target_id}')}"
def _hash16(text: str) -> str:
return hashlib.md5(text.encode("utf-8")).hexdigest()[:16]