docloc 0.1.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.
docloc/__init__.py ADDED
@@ -0,0 +1,175 @@
1
+ """Document parsing and structure-aware chunking with original source locators."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import BinaryIO, Literal
7
+
8
+ from docloc.chunking import Chunker, build_search_passages, count_tokens, verify_locator
9
+ from docloc.errors import ErrorCode, ParseError, ProvenanceError
10
+ from docloc.models import (
11
+ Chunk,
12
+ ChunkOptions,
13
+ Locator,
14
+ LocatorKind,
15
+ ParsedBlock,
16
+ ParsedDocument,
17
+ TableRow,
18
+ )
19
+ from docloc.parsers import (
20
+ DocxParser,
21
+ FormatParser,
22
+ OCRHook,
23
+ ParseOptions,
24
+ ParserCapability,
25
+ ParserRegistry,
26
+ PdfParser,
27
+ TextParser,
28
+ XlsxParser,
29
+ detect_kind,
30
+ )
31
+ from docloc.preview import (
32
+ ContextLine,
33
+ ContextWindow,
34
+ ProjectionMatch,
35
+ ReadingContext,
36
+ ReadingProjection,
37
+ build_reading_projection,
38
+ extract_context_window,
39
+ locate_chunk_in_projection,
40
+ normalize_text,
41
+ )
42
+
43
+ __version__ = "0.1.0"
44
+
45
+
46
+ def parse_file(
47
+ path: str | Path,
48
+ *,
49
+ kind: str | None = None,
50
+ options: ParseOptions | None = None,
51
+ ocr_hook: OCRHook | None = None,
52
+ ) -> ParsedDocument:
53
+ """Parse a local file into located blocks."""
54
+ registry = ParserRegistry(ocr_hook=ocr_hook)
55
+ return registry.parse_file(path, kind=kind, options=options)
56
+
57
+
58
+ def parse_bytes(
59
+ data: bytes,
60
+ *,
61
+ kind: str,
62
+ source_name: str = "",
63
+ options: ParseOptions | None = None,
64
+ ocr_hook: OCRHook | None = None,
65
+ ) -> ParsedDocument:
66
+ """Parse raw bytes of a known format into located blocks."""
67
+ registry = ParserRegistry(ocr_hook=ocr_hook)
68
+ return registry.parse_bytes(data, kind=kind, source_name=source_name, options=options)
69
+
70
+
71
+ def parse_stream(
72
+ stream: BinaryIO,
73
+ *,
74
+ kind: str,
75
+ source_name: str = "",
76
+ options: ParseOptions | None = None,
77
+ ocr_hook: OCRHook | None = None,
78
+ ) -> ParsedDocument:
79
+ """Parse a binary stream of a known format into located blocks."""
80
+ registry = ParserRegistry(ocr_hook=ocr_hook)
81
+ return registry.parse_stream(stream, kind=kind, source_name=source_name, options=options)
82
+
83
+
84
+ def chunk_document(
85
+ document: ParsedDocument,
86
+ *,
87
+ options: ChunkOptions | None = None,
88
+ target_tokens: int | None = None,
89
+ overlap_tokens: int | None = None,
90
+ min_word_ratio: float | None = None,
91
+ table_mode: Literal["row", "budget"] | None = None,
92
+ document_id: str | None = None,
93
+ ) -> list[Chunk]:
94
+ """Split a parsed document into structure-aware, located chunks."""
95
+ if options is None:
96
+ base = ChunkOptions()
97
+ resolved = ChunkOptions(
98
+ target_tokens=base.target_tokens if target_tokens is None else target_tokens,
99
+ overlap_tokens=base.overlap_tokens if overlap_tokens is None else overlap_tokens,
100
+ min_word_ratio=base.min_word_ratio if min_word_ratio is None else min_word_ratio,
101
+ table_mode=base.table_mode if table_mode is None else table_mode,
102
+ )
103
+ else:
104
+ resolved = options
105
+ return Chunker().split(document, resolved, document_id=document_id)
106
+
107
+
108
+ def parse_and_chunk(
109
+ path: str | Path,
110
+ *,
111
+ kind: str | None = None,
112
+ parse_options: ParseOptions | None = None,
113
+ chunk_options: ChunkOptions | None = None,
114
+ target_tokens: int | None = None,
115
+ overlap_tokens: int | None = None,
116
+ min_word_ratio: float | None = None,
117
+ table_mode: Literal["row", "budget"] | None = None,
118
+ document_id: str | None = None,
119
+ ocr_hook: OCRHook | None = None,
120
+ ) -> tuple[ParsedDocument, list[Chunk]]:
121
+ """Parse a file and immediately split it into located chunks."""
122
+ doc = parse_file(path, kind=kind, options=parse_options, ocr_hook=ocr_hook)
123
+ chunks = chunk_document(
124
+ doc,
125
+ options=chunk_options,
126
+ target_tokens=target_tokens,
127
+ overlap_tokens=overlap_tokens,
128
+ min_word_ratio=min_word_ratio,
129
+ table_mode=table_mode,
130
+ document_id=document_id,
131
+ )
132
+ return doc, chunks
133
+
134
+
135
+ __all__ = [
136
+ "Chunk",
137
+ "ChunkOptions",
138
+ "Chunker",
139
+ "ContextLine",
140
+ "ContextWindow",
141
+ "DocxParser",
142
+ "ErrorCode",
143
+ "FormatParser",
144
+ "Locator",
145
+ "LocatorKind",
146
+ "OCRHook",
147
+ "ParseError",
148
+ "ParseOptions",
149
+ "ParsedBlock",
150
+ "ParsedDocument",
151
+ "ParserCapability",
152
+ "ParserRegistry",
153
+ "PdfParser",
154
+ "ProjectionMatch",
155
+ "ProvenanceError",
156
+ "ReadingContext",
157
+ "ReadingProjection",
158
+ "TableRow",
159
+ "TextParser",
160
+ "XlsxParser",
161
+ "__version__",
162
+ "build_reading_projection",
163
+ "build_search_passages",
164
+ "chunk_document",
165
+ "count_tokens",
166
+ "detect_kind",
167
+ "extract_context_window",
168
+ "locate_chunk_in_projection",
169
+ "normalize_text",
170
+ "parse_and_chunk",
171
+ "parse_bytes",
172
+ "parse_file",
173
+ "parse_stream",
174
+ "verify_locator",
175
+ ]
docloc/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Module entry point for ``python -m docloc``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from docloc.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ raise SystemExit(main())
docloc/chunking.py ADDED
@@ -0,0 +1,379 @@
1
+ """Structure-aware, deterministic chunking with verifiable source locators."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ import unicodedata
8
+ from collections.abc import Iterator
9
+ from dataclasses import replace
10
+
11
+ from docloc.errors import ProvenanceError
12
+ from docloc.models import (
13
+ Chunk,
14
+ ChunkOptions,
15
+ Locator,
16
+ LocatorKind,
17
+ ParsedBlock,
18
+ ParsedDocument,
19
+ TableRow,
20
+ )
21
+ from docloc.parsers.xlsx import col_letter, format_row_ranges
22
+
23
+ _HAN = re.compile(r"[\u3400-\u9fff]")
24
+ _ASCII_TOKENS = re.compile(r"[A-Za-z0-9_]+(?:[-./][A-Za-z0-9_]+)*|[^\w\s]")
25
+ _ATX_HEADING = re.compile(r"^#{1,6}[ \t]+(.+?)(?:[ \t]+#+[ \t]*)?$")
26
+ _MAX_HEADING_CHARS = 256
27
+ _LINE_KINDS = frozenset({LocatorKind.TEXT_LINES, LocatorKind.MARKDOWN_LINES})
28
+ _TABLE_KINDS = frozenset({LocatorKind.WORD_TABLE, LocatorKind.EXCEL_RANGE})
29
+
30
+
31
+ def _is_word_character(char: str) -> bool:
32
+ return (char.isalnum() or char == "_") and _HAN.fullmatch(char) is None
33
+
34
+
35
+ def _token_spans(text: str) -> Iterator[tuple[int, int]]:
36
+ if text.isascii():
37
+ yield from (match.span() for match in _ASCII_TOKENS.finditer(text))
38
+ return
39
+
40
+ # Keep Unicode words and their combining marks together. Han characters
41
+ # stay separate, and separators inside technical identifiers stay attached.
42
+ position = 0
43
+ while position < len(text):
44
+ start = position
45
+ char = text[position]
46
+ position += 1
47
+ if char.isspace():
48
+ continue
49
+ if _is_word_character(char):
50
+ while position < len(text):
51
+ next_char = text[position]
52
+ if _is_word_character(next_char) or unicodedata.category(next_char).startswith("M"):
53
+ position += 1
54
+ elif (
55
+ next_char in "-./"
56
+ and position + 1 < len(text)
57
+ and _is_word_character(text[position + 1])
58
+ ):
59
+ position += 2
60
+ else:
61
+ break
62
+ elif _HAN.fullmatch(char):
63
+ while position < len(text) and unicodedata.category(text[position]).startswith("M"):
64
+ position += 1
65
+ yield start, position
66
+
67
+
68
+ def count_tokens(text: str) -> int:
69
+ """Count Unicode text tokens for the chunk budget."""
70
+ return sum(1 for _ in _token_spans(text))
71
+
72
+
73
+ def _indexable(piece: str, min_word_ratio: float) -> bool:
74
+ if not piece:
75
+ return False
76
+ if min_word_ratio <= 0.0:
77
+ return True
78
+ alnum = sum(1 for char in piece if char.isalnum())
79
+ return alnum / len(piece) >= min_word_ratio
80
+
81
+
82
+ def _pieces(
83
+ text: str, options: ChunkOptions, spans: list[tuple[int, int]]
84
+ ) -> list[tuple[str, int, int]]:
85
+ step = options.target_tokens - options.overlap_tokens
86
+ pieces: list[tuple[str, int, int]] = []
87
+ for start in range(0, len(spans), step):
88
+ end = min(start + options.target_tokens, len(spans))
89
+ raw_start = spans[start][0]
90
+ raw_end = spans[end - 1][1]
91
+ raw = text[raw_start:raw_end]
92
+
93
+ left_trim = len(raw) - len(raw.lstrip())
94
+ trimmed = raw[left_trim:].rstrip()
95
+ char_start = raw_start + left_trim
96
+ char_end = char_start + len(trimmed)
97
+ piece = text[char_start:char_end]
98
+
99
+ if _indexable(piece, options.min_word_ratio):
100
+ pieces.append((piece, char_start, char_end))
101
+ if end == len(spans):
102
+ break
103
+ return pieces
104
+
105
+
106
+ def _table_rows(block: ParsedBlock) -> tuple[tuple[TableRow, ...], bool]:
107
+ if block.rows:
108
+ return block.rows, True
109
+ synthetic: list[TableRow] = []
110
+ for line in block.text.splitlines():
111
+ stripped = line.strip()
112
+ if not stripped:
113
+ continue
114
+ synthetic.append(TableRow(row_number=len(synthetic) + 1, cells=tuple(stripped.split("\t"))))
115
+ return tuple(synthetic), False
116
+
117
+
118
+ def _excel_cell_range(rows: tuple[TableRow, ...], data_rows: list[TableRow]) -> str:
119
+ width = max(1, max(len(row.cells) for row in rows))
120
+ return format_row_ranges([rows[0], *data_rows], col_letter(width - 1))
121
+
122
+
123
+ def _content_hash(text: str) -> str:
124
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
125
+
126
+
127
+ def _make_chunk(
128
+ text: str,
129
+ locator: Locator,
130
+ *,
131
+ block_index: int,
132
+ ordinal: int,
133
+ document_id: str | None,
134
+ ) -> Chunk:
135
+ digest = _content_hash(text)
136
+ identity = hashlib.sha256(f"{document_id or ''}\0{ordinal}\0{digest}".encode()).hexdigest()
137
+ return Chunk(
138
+ chunk_id=identity,
139
+ ordinal=ordinal,
140
+ text=text,
141
+ content_hash=digest,
142
+ locator=locator,
143
+ block_index=block_index,
144
+ document_id=document_id,
145
+ )
146
+
147
+
148
+ class Chunker:
149
+ """Split a :class:`ParsedDocument` into deterministic, located chunks."""
150
+
151
+ _token_spans = staticmethod(_token_spans)
152
+
153
+ def split(
154
+ self,
155
+ document: ParsedDocument,
156
+ options: ChunkOptions | None = None,
157
+ *,
158
+ document_id: str | None = None,
159
+ ) -> list[Chunk]:
160
+ resolved = options or ChunkOptions()
161
+ chunks: list[Chunk] = []
162
+
163
+ for block_index, block in enumerate(document.blocks):
164
+ if block.locator.kind in _TABLE_KINDS:
165
+ chunks.extend(
166
+ self.split_table(
167
+ block,
168
+ resolved,
169
+ block_index=block_index,
170
+ start_ordinal=len(chunks),
171
+ document_id=document_id,
172
+ )
173
+ )
174
+ continue
175
+
176
+ # Never cross source blocks: a chunk's locator must truthfully cover
177
+ # every character it contains.
178
+ base_line = block.locator.start_line or 1
179
+ spans = list(self._token_spans(block.text))
180
+ for piece, char_start, char_end in _pieces(block.text, resolved, spans):
181
+ locator = replace(block.locator, char_start=char_start, char_end=char_end)
182
+ if locator.kind in _LINE_KINDS:
183
+ start_line = base_line + block.text.count("\n", 0, char_start)
184
+ end_line = base_line + block.text.count("\n", 0, char_end)
185
+ locator = replace(locator, start_line=start_line, end_line=end_line)
186
+ chunks.append(
187
+ _make_chunk(
188
+ piece,
189
+ locator,
190
+ block_index=block_index,
191
+ ordinal=len(chunks),
192
+ document_id=document_id,
193
+ )
194
+ )
195
+ return chunks
196
+
197
+ def split_table(
198
+ self,
199
+ block: ParsedBlock,
200
+ options: ChunkOptions,
201
+ *,
202
+ block_index: int = 0,
203
+ start_ordinal: int = 0,
204
+ document_id: str | None = None,
205
+ ) -> list[Chunk]:
206
+ """Keep table rows together with their header; never invent coordinates."""
207
+ rows, has_real_rows = _table_rows(block)
208
+ if not rows:
209
+ return []
210
+
211
+ header = rows[0]
212
+ data_rows = list(rows[1:])
213
+ header_text = header.text
214
+ header_tokens = count_tokens(header_text)
215
+
216
+ groups: list[list[TableRow]]
217
+ if not data_rows:
218
+ groups = [[]]
219
+ elif options.table_mode == "row":
220
+ groups = [[row] for row in data_rows]
221
+ else:
222
+ groups = []
223
+ current: list[TableRow] = []
224
+ current_tokens = 0
225
+ for row in data_rows:
226
+ row_tokens = count_tokens(row.text)
227
+ if current and header_tokens + current_tokens + row_tokens > options.target_tokens:
228
+ groups.append(current)
229
+ current = []
230
+ current_tokens = 0
231
+ current.append(row)
232
+ current_tokens += row_tokens
233
+ if current:
234
+ groups.append(current)
235
+
236
+ use_excel_range = has_real_rows and block.locator.kind == LocatorKind.EXCEL_RANGE
237
+ chunks: list[Chunk] = []
238
+ for offset, group in enumerate(groups):
239
+ text = "\n".join([header_text, *(row.text for row in group)])
240
+ locator = replace(block.locator, char_start=None, char_end=None)
241
+ if use_excel_range:
242
+ locator = replace(locator, cell_range=_excel_cell_range(rows, group))
243
+ chunks.append(
244
+ _make_chunk(
245
+ text,
246
+ locator,
247
+ block_index=block_index,
248
+ ordinal=start_ordinal + offset,
249
+ document_id=document_id,
250
+ )
251
+ )
252
+ return chunks
253
+
254
+
255
+ def verify_locator(chunk: Chunk, document: ParsedDocument) -> Locator:
256
+ """Prove that ``chunk`` truthfully maps back to its source block in ``document``."""
257
+ if not 0 <= chunk.block_index < len(document.blocks):
258
+ raise ProvenanceError(f"chunk block_index {chunk.block_index} is out of range")
259
+ if _content_hash(chunk.text) != chunk.content_hash:
260
+ raise ProvenanceError("chunk content_hash does not match chunk text")
261
+
262
+ block = document.blocks[chunk.block_index]
263
+ if chunk.locator.kind != block.locator.kind:
264
+ raise ProvenanceError("chunk locator kind does not match its source block")
265
+
266
+ if block.locator.kind in _TABLE_KINDS:
267
+ _verify_table_chunk(chunk, block)
268
+ return chunk.locator
269
+
270
+ _verify_text_chunk(chunk, block)
271
+ return chunk.locator
272
+
273
+
274
+ def _verify_text_chunk(chunk: Chunk, block: ParsedBlock) -> None:
275
+ if (
276
+ chunk.locator.page != block.locator.page
277
+ or chunk.locator.paragraph != block.locator.paragraph
278
+ or chunk.locator.heading != block.locator.heading
279
+ ):
280
+ raise ProvenanceError("chunk locator metadata does not match its source block")
281
+
282
+ c_start = chunk.locator.char_start
283
+ c_end = chunk.locator.char_end
284
+ if c_start is not None or c_end is not None:
285
+ if c_start is None or c_end is None:
286
+ raise ProvenanceError("chunk has incomplete character offsets")
287
+ if c_end > len(block.text) or block.text[c_start:c_end] != chunk.text:
288
+ raise ProvenanceError("chunk text does not match source block character offsets")
289
+ spans = [(c_start, c_end)]
290
+ else:
291
+ spans = [(m.start(), m.end()) for m in re.finditer(re.escape(chunk.text), block.text)]
292
+ if not spans:
293
+ raise ProvenanceError("chunk text was not found in its source block")
294
+
295
+ if block.locator.kind not in _LINE_KINDS:
296
+ return
297
+
298
+ base_line = block.locator.start_line or 1
299
+ for span_start, span_end in spans:
300
+ expected_start = base_line + block.text.count("\n", 0, span_start)
301
+ expected_end = base_line + block.text.count("\n", 0, span_end)
302
+ if (chunk.locator.start_line, chunk.locator.end_line) == (expected_start, expected_end):
303
+ return
304
+ raise ProvenanceError("chunk line numbers do not match its source block")
305
+
306
+
307
+ def _verify_table_chunk(chunk: Chunk, block: ParsedBlock) -> None:
308
+ expected_locator = replace(block.locator, char_start=None, char_end=None)
309
+ if replace(chunk.locator, cell_range=expected_locator.cell_range) != expected_locator:
310
+ raise ProvenanceError("table chunk locator metadata does not match its source block")
311
+
312
+ rows, has_real_rows = _table_rows(block)
313
+ if not rows:
314
+ raise ProvenanceError("source table block contains no rows")
315
+
316
+ header_text = rows[0].text
317
+ chunk_lines = chunk.text.split("\n")
318
+ if not chunk_lines or chunk_lines[0] != header_text:
319
+ raise ProvenanceError("table chunk header does not match source table header")
320
+
321
+ chunk_data = chunk_lines[1:]
322
+ data_rows = list(rows[1:])
323
+ data_texts = [row.text for row in data_rows]
324
+ use_excel_range = has_real_rows and block.locator.kind == LocatorKind.EXCEL_RANGE
325
+
326
+ if not chunk_data and data_rows:
327
+ raise ProvenanceError("table chunk is missing data rows")
328
+
329
+ size = len(chunk_data)
330
+ if size > len(data_texts):
331
+ raise ProvenanceError("table chunk has more data rows than source table")
332
+
333
+ matched_starts = [
334
+ index
335
+ for index in range(0, len(data_texts) - size + 1)
336
+ if data_texts[index : index + size] == chunk_data
337
+ ]
338
+ if not matched_starts:
339
+ raise ProvenanceError("table chunk rows do not appear consecutively in source table")
340
+
341
+ if use_excel_range:
342
+ valid_ranges = {
343
+ _excel_cell_range(rows, data_rows[start : start + size]) for start in matched_starts
344
+ }
345
+ if chunk.locator.cell_range not in valid_ranges:
346
+ raise ProvenanceError("table chunk cell_range does not match source row coordinates")
347
+ elif chunk.locator.cell_range != block.locator.cell_range:
348
+ raise ProvenanceError("table chunk cell_range does not match source block")
349
+
350
+
351
+ def _heading_text(line: str) -> str | None:
352
+ match = _ATX_HEADING.fullmatch(line.strip())
353
+ return match.group(1).strip() if match else None
354
+
355
+
356
+ def build_search_passages(chunks: list[Chunk]) -> list[Chunk]:
357
+ """Omit standalone Markdown heading chunks whose next chunk carries that heading."""
358
+ by_key = {(chunk.document_id, chunk.ordinal): chunk for chunk in chunks}
359
+ passages: list[Chunk] = []
360
+ for chunk in chunks:
361
+ heading = (
362
+ _heading_text(chunk.text)
363
+ if chunk.locator.kind == LocatorKind.MARKDOWN_LINES
364
+ else None
365
+ )
366
+ if heading and heading == chunk.locator.heading and len(heading) <= _MAX_HEADING_CHARS:
367
+ following = by_key.get((chunk.document_id, chunk.ordinal + 1))
368
+ if (
369
+ following is not None
370
+ and following.locator.kind == LocatorKind.MARKDOWN_LINES
371
+ and following.locator.heading == heading
372
+ and _heading_text(following.text.split("\n", 1)[0]) is None
373
+ ):
374
+ continue
375
+ passages.append(chunk)
376
+ return passages
377
+
378
+
379
+ __all__ = ["Chunker", "build_search_passages", "count_tokens", "verify_locator"]