docresolve 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.
- docresolve/__init__.py +80 -0
- docresolve/__main__.py +4 -0
- docresolve/chunker.py +125 -0
- docresolve/cli.py +85 -0
- docresolve/core.py +2307 -0
- docresolve/document_parser.py +79 -0
- docresolve/providers.py +379 -0
- docresolve-0.1.0.dist-info/METADATA +240 -0
- docresolve-0.1.0.dist-info/RECORD +13 -0
- docresolve-0.1.0.dist-info/WHEEL +5 -0
- docresolve-0.1.0.dist-info/entry_points.txt +2 -0
- docresolve-0.1.0.dist-info/licenses/LICENSE +21 -0
- docresolve-0.1.0.dist-info/top_level.txt +1 -0
docresolve/__init__.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""DocResolve: conflict-aware retrieval-augmented answering over documents that disagree.
|
|
2
|
+
|
|
3
|
+
This package is the system configuration reported in the paper:
|
|
4
|
+
|
|
5
|
+
* first-stage retrieval: BM25 + dense fusion (``retrieval="hybrid"``)
|
|
6
|
+
* governance-aware reranking and conflict diversification
|
|
7
|
+
* resolution policy: answer-and-flag, final prompt (``policy="answer_and_flag_final"``):
|
|
8
|
+
governance -> corroboration by distinct documents -> consistency; factual
|
|
9
|
+
disagreements are always resolved and the answer states the committed value only.
|
|
10
|
+
|
|
11
|
+
Ablations stay available as arguments: ``policy="answer_and_flag"`` (the first prompt,
|
|
12
|
+
"without commitment"), ``policy="strict"`` (refuse on conflict), ``retrieval="dense"``.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import List, Optional
|
|
20
|
+
|
|
21
|
+
from .core import Document, GovRAGGemini
|
|
22
|
+
from .document_parser import SUPPORTED_EXTENSIONS, parse_document_bytes
|
|
23
|
+
from .providers import LocalEmbedder, OpenAICompatGenerator
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"__version__",
|
|
27
|
+
"Document",
|
|
28
|
+
"GovRAGGemini",
|
|
29
|
+
"LocalEmbedder",
|
|
30
|
+
"OpenAICompatGenerator",
|
|
31
|
+
"DEFAULT_RETRIEVAL",
|
|
32
|
+
"DEFAULT_POLICY",
|
|
33
|
+
"load_folder",
|
|
34
|
+
"build_pipeline",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
__version__ = "0.1.0"
|
|
38
|
+
DEFAULT_RETRIEVAL = "hybrid"
|
|
39
|
+
DEFAULT_POLICY = "answer_and_flag_final"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def load_folder(folder: str) -> List[Document]:
|
|
43
|
+
"""Load every supported file (.md, .txt, .pdf, .docx) under ``folder``.
|
|
44
|
+
|
|
45
|
+
The document name is the path relative to ``folder`` so a folder tree keeps
|
|
46
|
+
its structure in citations.
|
|
47
|
+
"""
|
|
48
|
+
base = Path(folder)
|
|
49
|
+
if not base.is_dir():
|
|
50
|
+
raise FileNotFoundError(f"Not a directory: {folder}")
|
|
51
|
+
docs: List[Document] = []
|
|
52
|
+
for path in sorted(p for p in base.rglob("*") if p.is_file()):
|
|
53
|
+
ext = path.suffix.lower()
|
|
54
|
+
if ext not in SUPPORTED_EXTENSIONS:
|
|
55
|
+
continue
|
|
56
|
+
text = parse_document_bytes(path.read_bytes(), ext)
|
|
57
|
+
if text and text.strip():
|
|
58
|
+
docs.append(Document(filename=str(path.relative_to(base)), text=text))
|
|
59
|
+
if not docs:
|
|
60
|
+
raise ValueError(f"No supported documents ({', '.join(sorted(SUPPORTED_EXTENSIONS))}) found under {folder}")
|
|
61
|
+
return docs
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def build_pipeline(
|
|
65
|
+
documents: List[Document],
|
|
66
|
+
model: Optional[str] = None,
|
|
67
|
+
base_url: Optional[str] = None,
|
|
68
|
+
api_key: Optional[str] = None,
|
|
69
|
+
embed_model: Optional[str] = None,
|
|
70
|
+
use_llm: bool = True,
|
|
71
|
+
) -> GovRAGGemini:
|
|
72
|
+
"""Index ``documents`` and return a ready pipeline.
|
|
73
|
+
|
|
74
|
+
``model`` and ``base_url`` select any OpenAI-compatible chat endpoint
|
|
75
|
+
(defaults: ``NEMOTRON_MODEL`` / ``DOCRESOLVE_BASE_URL`` env vars, then the
|
|
76
|
+
NVIDIA hosted endpoint). The embedder runs locally.
|
|
77
|
+
"""
|
|
78
|
+
embedder = LocalEmbedder(model_name=embed_model) if embed_model else LocalEmbedder()
|
|
79
|
+
generator = OpenAICompatGenerator(model=model, base_url=base_url, api_key=api_key) if use_llm else None
|
|
80
|
+
return GovRAGGemini(None, embedder=embedder, generator=generator, use_llm=use_llm, documents=documents)
|
docresolve/__main__.py
ADDED
docresolve/chunker.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Split long documents into overlapping chunks for retrieval.
|
|
2
|
+
|
|
3
|
+
Short documents (the common case for ConflictBench-style single-page bulletins)
|
|
4
|
+
are returned as a single chunk, so existing whole-document behavior is
|
|
5
|
+
unchanged when a document already fits within the target size.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from typing import List, NamedTuple, Optional
|
|
12
|
+
|
|
13
|
+
# Word count is used as a cheap proxy for token count (~0.75 words/token is
|
|
14
|
+
# typical for English, so this comfortably targets the requested 800-1200
|
|
15
|
+
# token / 100-200 token overlap range without adding a tokenizer dependency).
|
|
16
|
+
TARGET_CHUNK_WORDS = 900
|
|
17
|
+
OVERLAP_WORDS = 150
|
|
18
|
+
MIN_CHUNK_WORDS = 50
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ChunkSegment(NamedTuple):
|
|
22
|
+
text: str
|
|
23
|
+
page_start: Optional[int] = None
|
|
24
|
+
page_end: Optional[int] = None
|
|
25
|
+
section: Optional[str] = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _split_paragraphs(text: str) -> List[str]:
|
|
29
|
+
paragraphs = re.split(r"\n\s*\n", text.strip())
|
|
30
|
+
return [p.strip() for p in paragraphs if p.strip()]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _split_sentences(text: str) -> List[str]:
|
|
34
|
+
return [s.strip() for s in re.split(r"(?<=[.!?])\s+|\n+", text) if s.strip()]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _word_count(text: str) -> int:
|
|
38
|
+
return len(text.split())
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def chunk_text(
|
|
42
|
+
text: str,
|
|
43
|
+
target_words: int = TARGET_CHUNK_WORDS,
|
|
44
|
+
overlap_words: int = OVERLAP_WORDS,
|
|
45
|
+
) -> List[str]:
|
|
46
|
+
"""Split text into overlapping chunks on paragraph/sentence boundaries."""
|
|
47
|
+
text = text.strip()
|
|
48
|
+
if not text:
|
|
49
|
+
return []
|
|
50
|
+
|
|
51
|
+
if _word_count(text) <= target_words:
|
|
52
|
+
return [text]
|
|
53
|
+
|
|
54
|
+
# Paragraphs are the preferred unit; any paragraph bigger than the target
|
|
55
|
+
# on its own is further split into sentences so nothing gets skipped.
|
|
56
|
+
units: List[str] = []
|
|
57
|
+
for para in _split_paragraphs(text):
|
|
58
|
+
if _word_count(para) <= target_words:
|
|
59
|
+
units.append(para)
|
|
60
|
+
else:
|
|
61
|
+
units.extend(_split_sentences(para))
|
|
62
|
+
|
|
63
|
+
chunks: List[str] = []
|
|
64
|
+
buffer_units: List[str] = []
|
|
65
|
+
buffer_words = 0
|
|
66
|
+
|
|
67
|
+
def flush() -> None:
|
|
68
|
+
nonlocal buffer_units, buffer_words
|
|
69
|
+
if buffer_units:
|
|
70
|
+
chunks.append(" ".join(buffer_units).strip())
|
|
71
|
+
buffer_units = []
|
|
72
|
+
buffer_words = 0
|
|
73
|
+
|
|
74
|
+
for unit in units:
|
|
75
|
+
unit_words = _word_count(unit)
|
|
76
|
+
|
|
77
|
+
if buffer_words + unit_words > target_words and buffer_units:
|
|
78
|
+
flush()
|
|
79
|
+
# Carry trailing overlap words forward from the chunk just finished.
|
|
80
|
+
if chunks:
|
|
81
|
+
tail_words = chunks[-1].split()[-overlap_words:]
|
|
82
|
+
if tail_words:
|
|
83
|
+
buffer_units = [" ".join(tail_words)]
|
|
84
|
+
buffer_words = len(tail_words)
|
|
85
|
+
|
|
86
|
+
buffer_units.append(unit)
|
|
87
|
+
buffer_words += unit_words
|
|
88
|
+
|
|
89
|
+
flush()
|
|
90
|
+
|
|
91
|
+
# Merge a too-small trailing chunk into the previous one.
|
|
92
|
+
if len(chunks) > 1 and _word_count(chunks[-1]) < MIN_CHUNK_WORDS:
|
|
93
|
+
chunks[-2] = chunks[-2] + " " + chunks[-1]
|
|
94
|
+
chunks.pop()
|
|
95
|
+
|
|
96
|
+
return chunks
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def chunk_text_with_locations(text: str) -> List[ChunkSegment]:
|
|
100
|
+
"""Chunk normalized text and attach only locations explicitly available."""
|
|
101
|
+
if "\f" in text:
|
|
102
|
+
segments = []
|
|
103
|
+
for page_number, page_text in enumerate(text.split("\f"), start=1):
|
|
104
|
+
page_chunks = chunk_text(page_text)
|
|
105
|
+
for page_chunk in page_chunks:
|
|
106
|
+
segments.append(ChunkSegment(
|
|
107
|
+
text=page_chunk,
|
|
108
|
+
page_start=page_number,
|
|
109
|
+
page_end=page_number,
|
|
110
|
+
section=_section_for_text(page_chunk),
|
|
111
|
+
))
|
|
112
|
+
return segments
|
|
113
|
+
|
|
114
|
+
return [
|
|
115
|
+
ChunkSegment(text=chunk, section=_section_for_text(chunk))
|
|
116
|
+
for chunk in chunk_text(text)
|
|
117
|
+
]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _section_for_text(text: str) -> Optional[str]:
|
|
121
|
+
for line in text.splitlines():
|
|
122
|
+
match = re.match(r"^\s{0,3}#{1,6}\s+(.+?)\s*#*\s*$", line)
|
|
123
|
+
if match:
|
|
124
|
+
return match.group(1).strip()
|
|
125
|
+
return None
|
docresolve/cli.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Command line entry point: ``python -m docresolve ask --docs DIR "question"``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import contextlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from . import DEFAULT_POLICY, DEFAULT_RETRIEVAL, build_pipeline, load_folder
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _load_env_file(path: Path) -> None:
|
|
16
|
+
"""Minimal KEY=VALUE loader; never prints values."""
|
|
17
|
+
if not path.is_file():
|
|
18
|
+
return
|
|
19
|
+
for line in path.read_text().splitlines():
|
|
20
|
+
line = line.strip()
|
|
21
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
22
|
+
continue
|
|
23
|
+
key, value = line.split("=", 1)
|
|
24
|
+
os.environ.setdefault(key.strip(), value.strip().strip('"').strip("'"))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _print_result(result: dict) -> None:
|
|
28
|
+
print("\n" + "=" * 72)
|
|
29
|
+
print(f"Decision : {result.get('decision')}"
|
|
30
|
+
+ (" (conflict flagged)" if result.get("conflict_detected") else ""))
|
|
31
|
+
print(f"Answer : {result.get('answer')}")
|
|
32
|
+
shorts = result.get("short_answers") or []
|
|
33
|
+
if shorts:
|
|
34
|
+
print(f"Short : {', '.join(map(str, shorts))}")
|
|
35
|
+
print(f"Confidence: {result.get('confidence')}")
|
|
36
|
+
if result.get("reason"):
|
|
37
|
+
print(f"Reason : {result['reason']}")
|
|
38
|
+
cites = result.get("citations") or []
|
|
39
|
+
if cites:
|
|
40
|
+
print("\nCitations:")
|
|
41
|
+
for c in cites:
|
|
42
|
+
treatment = c.get("treatment", "")
|
|
43
|
+
quote = (c.get("quote") or "").strip().replace("\n", " ")
|
|
44
|
+
print(f" [{treatment:<11}] {c.get('filename')}: \"{quote}\"")
|
|
45
|
+
if result.get("explanation"):
|
|
46
|
+
print(f"\nWhy: {result['explanation']}")
|
|
47
|
+
print("=" * 72)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def main(argv=None) -> int:
|
|
51
|
+
parser = argparse.ArgumentParser(prog="docresolve", description=__doc__)
|
|
52
|
+
from . import __version__
|
|
53
|
+
parser.add_argument("--version", action="version", version=f"docresolve {__version__}")
|
|
54
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
55
|
+
ask = sub.add_parser("ask", help="index a folder of documents and answer one question")
|
|
56
|
+
ask.add_argument("question")
|
|
57
|
+
ask.add_argument("--docs", required=True, help="folder with .md/.txt/.pdf/.docx files (searched recursively)")
|
|
58
|
+
ask.add_argument("--model", default=None, help="chat model name (default: NEMOTRON_MODEL env or provider default)")
|
|
59
|
+
ask.add_argument("--base-url", default=None, help="OpenAI-compatible endpoint (default: DOCRESOLVE_BASE_URL env or NVIDIA)")
|
|
60
|
+
ask.add_argument("--embed-model", default=None, help="sentence-transformers model (default: BAAI/bge-small-en-v1.5)")
|
|
61
|
+
ask.add_argument("--retrieval", choices=["hybrid", "dense"], default=DEFAULT_RETRIEVAL,
|
|
62
|
+
help="first-stage retrieval; 'dense' is the ablation")
|
|
63
|
+
ask.add_argument("--policy", choices=["answer_and_flag_final", "answer_and_flag", "strict"], default=DEFAULT_POLICY,
|
|
64
|
+
help="resolution policy; 'answer_and_flag' is the first prompt, 'strict' refuses on conflict")
|
|
65
|
+
ask.add_argument("--env-file", default=None, help="KEY=VALUE file to load into the environment (e.g. an .env with NVIDIA_API_KEY)")
|
|
66
|
+
ask.add_argument("--json", action="store_true", help="print the full result as JSON instead of a summary")
|
|
67
|
+
args = parser.parse_args(argv)
|
|
68
|
+
|
|
69
|
+
if args.env_file:
|
|
70
|
+
_load_env_file(Path(args.env_file))
|
|
71
|
+
|
|
72
|
+
# The core prints its progress to stdout; in --json mode keep stdout clean.
|
|
73
|
+
sink = sys.stderr if args.json else sys.stdout
|
|
74
|
+
with contextlib.redirect_stdout(sink):
|
|
75
|
+
documents = load_folder(args.docs)
|
|
76
|
+
pipeline = build_pipeline(documents, model=args.model, base_url=args.base_url, embed_model=args.embed_model)
|
|
77
|
+
result = pipeline.query(args.question, retrieval=args.retrieval, policy=args.policy)
|
|
78
|
+
|
|
79
|
+
if args.json:
|
|
80
|
+
slim = {k: v for k, v in result.items() if k != "candidates"}
|
|
81
|
+
json.dump(slim, sys.stdout, indent=2, default=str)
|
|
82
|
+
print()
|
|
83
|
+
else:
|
|
84
|
+
_print_result(result)
|
|
85
|
+
return 0
|