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.
@@ -0,0 +1,79 @@
1
+ """Document parsing and normalization utilities for corpus ingestion."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import os
7
+ import re
8
+ from typing import Tuple
9
+
10
+ from docx import Document as DocxDocument
11
+ from pypdf import PdfReader
12
+
13
+ SUPPORTED_EXTENSIONS = {".md", ".txt", ".pdf", ".docx"}
14
+
15
+
16
+ class DocumentParseError(ValueError):
17
+ """Raised when an uploaded document cannot be parsed safely."""
18
+
19
+
20
+ def sanitize_filename(filename: str) -> str:
21
+ """Sanitize an incoming filename to a safe basename."""
22
+ base = os.path.basename((filename or "").strip())
23
+ if not base:
24
+ raise DocumentParseError("Filename is required")
25
+
26
+ safe = re.sub(r"[^A-Za-z0-9._-]", "_", base)
27
+ safe = safe.strip("._")
28
+ if not safe:
29
+ raise DocumentParseError("Filename is invalid after sanitization")
30
+
31
+ return safe
32
+
33
+
34
+ def validate_extension(filename: str) -> str:
35
+ """Validate supported extension and return normalized extension."""
36
+ _, ext = os.path.splitext(filename)
37
+ ext = ext.lower()
38
+ if ext not in SUPPORTED_EXTENSIONS:
39
+ supported = ", ".join(sorted(SUPPORTED_EXTENSIONS))
40
+ raise DocumentParseError(f"Unsupported file type '{ext}'. Supported: {supported}")
41
+ return ext
42
+
43
+
44
+ def parse_document_bytes(content: bytes, extension: str) -> str:
45
+ """Extract normalized text from supported file bytes."""
46
+ if not content:
47
+ raise DocumentParseError("File is empty")
48
+
49
+ if extension in {".md", ".txt"}:
50
+ return content.decode("utf-8", errors="replace").strip()
51
+
52
+ if extension == ".pdf":
53
+ reader = PdfReader(io.BytesIO(content))
54
+ pages = []
55
+ for page in reader.pages:
56
+ pages.append(page.extract_text() or "")
57
+ return "\n\f\n".join(pages).strip()
58
+
59
+ if extension == ".docx":
60
+ doc = DocxDocument(io.BytesIO(content))
61
+ paragraphs = []
62
+ for paragraph in doc.paragraphs:
63
+ if not paragraph.text or not paragraph.text.strip():
64
+ continue
65
+ if paragraph.style and paragraph.style.name.startswith("Heading"):
66
+ paragraphs.append(f"## {paragraph.text.strip()}")
67
+ else:
68
+ paragraphs.append(paragraph.text.strip())
69
+ return "\n\n".join(paragraphs).strip()
70
+
71
+ raise DocumentParseError(f"Parser not implemented for extension '{extension}'")
72
+
73
+
74
+ def make_normalized_filename(safe_original_filename: str, document_id: str) -> Tuple[str, str]:
75
+ """Build a unique normalized markdown filename and stem."""
76
+ stem, _ = os.path.splitext(safe_original_filename)
77
+ normalized_stem = f"{stem}__{document_id}"
78
+ normalized_filename = f"{normalized_stem}.md"
79
+ return normalized_stem, normalized_filename
@@ -0,0 +1,379 @@
1
+ """Alternative embedding and generation providers for GOV-RAG.
2
+
3
+ These let the pipeline run without Google Cloud:
4
+
5
+ - ``LocalEmbedder``: sentence-transformers model run on this machine
6
+ (default ``BAAI/bge-small-en-v1.5``, which is what the original
7
+ ``code/gov_rag.py`` used). No network calls after the model is cached.
8
+ - ``OpenAICompatGenerator``: any OpenAI-compatible chat endpoint. Used here
9
+ for NVIDIA's hosted Nemotron models (``https://integrate.api.nvidia.com/v1``)
10
+ but works for any endpoint that speaks the same protocol.
11
+
12
+ Both expose the same interface as ``GeminiEmbedder`` / ``GeminiGenerator`` so
13
+ ``GovRAGGemini`` can take them as drop-in replacements.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import hashlib
19
+ import os
20
+ import re
21
+ import sqlite3
22
+ import threading
23
+ import time
24
+ from typing import List, Optional
25
+
26
+ import numpy as np
27
+
28
+ NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
29
+ DEFAULT_NVIDIA_MODEL = "nvidia/nemotron-3.5-lightning-30b-a3b"
30
+ DEFAULT_LOCAL_EMBED_MODEL = "BAAI/bge-small-en-v1.5"
31
+
32
+ # bge models are trained with this instruction prefixed to *queries* only.
33
+ BGE_QUERY_PREFIX = "Represent this sentence for searching relevant passages: "
34
+
35
+ _THINK_BLOCK = re.compile(r"<think>.*?</think>", re.DOTALL | re.IGNORECASE)
36
+
37
+
38
+ class LocalEmbedder:
39
+ """sentence-transformers embedder with the GeminiEmbedder interface."""
40
+
41
+ def __init__(self, model_name: str = DEFAULT_LOCAL_EMBED_MODEL, batch_size: int = 32,
42
+ device: Optional[str] = None, cache_path: Optional[str] = None):
43
+ # If the model is already in the local Hugging Face cache, skip the
44
+ # online freshness check: it can stall indefinitely on some networks.
45
+ cache_dir = os.path.expanduser(
46
+ os.getenv("HF_HUB_CACHE") or os.path.join(os.getenv("HF_HOME", "~/.cache/huggingface"), "hub")
47
+ )
48
+ if os.path.isdir(os.path.join(cache_dir, "models--" + model_name.replace("/", "--"))):
49
+ os.environ.setdefault("HF_HUB_OFFLINE", "1")
50
+ os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
51
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
52
+
53
+ from sentence_transformers import SentenceTransformer
54
+
55
+ self.model_name = model_name
56
+ self.batch_size = batch_size
57
+ # bge-small is fast enough on CPU; defaulting to CPU keeps evaluation
58
+ # runs off the GPU (EMBED_DEVICE=mps|cuda|cpu overrides).
59
+ self.device = device or os.getenv("EMBED_DEVICE", "cpu")
60
+ self.model = SentenceTransformer(model_name, device=self.device)
61
+ self.use_vertex = False
62
+ self.cache = EmbeddingCache.from_env(model_name, cache_path)
63
+ self.cache_hits = 0
64
+ self.cache_misses = 0
65
+ print("✓ Using local sentence-transformers embeddings")
66
+ print(f" Model: {model_name} Device: {self.device}")
67
+ if self.cache is not None:
68
+ print(f" Embedding cache: {self.cache.path} ({self.cache.count()} vectors)")
69
+
70
+ def encode(self, texts, task_type: str = "RETRIEVAL_DOCUMENT"):
71
+ if isinstance(texts, str):
72
+ texts = [texts]
73
+ if task_type == "RETRIEVAL_QUERY" and "bge" in self.model_name.lower():
74
+ texts = [BGE_QUERY_PREFIX + t for t in texts]
75
+ texts = list(texts)
76
+ if self.cache is None:
77
+ return self._encode_uncached(texts)
78
+ cached = self.cache.get_many(texts)
79
+ missing = [i for i, v in enumerate(cached) if v is None]
80
+ self.cache_hits += len(texts) - len(missing)
81
+ self.cache_misses += len(missing)
82
+ if missing:
83
+ fresh = self._encode_uncached([texts[i] for i in missing])
84
+ self.cache.put_many([texts[i] for i in missing], fresh)
85
+ for i, vec in zip(missing, fresh):
86
+ cached[i] = vec
87
+ return np.asarray(np.stack(cached), dtype=np.float64)
88
+
89
+ def _encode_uncached(self, texts: List[str]) -> np.ndarray:
90
+ embeddings = self.model.encode(
91
+ texts,
92
+ batch_size=self.batch_size,
93
+ normalize_embeddings=True,
94
+ show_progress_bar=False,
95
+ convert_to_numpy=True,
96
+ )
97
+ return np.asarray(embeddings, dtype=np.float64)
98
+
99
+
100
+ class EmbeddingCache:
101
+ """Persistent text -> vector store (SQLite) shared by every run.
102
+
103
+ Keyed by SHA-256 of ``model_name`` and the exact text handed to the model
104
+ (query prefix included), so a hit is byte-identical to re-encoding.
105
+ Disable with ``EMBED_CACHE=0``; relocate with ``EMBED_CACHE_PATH``.
106
+ Default location: ``<repo>/data/embeddings/<model-slug>.sqlite``.
107
+ """
108
+
109
+ def __init__(self, path: str, model_name: str):
110
+ self.path = path
111
+ self.model_name = model_name
112
+ os.makedirs(os.path.dirname(path), exist_ok=True)
113
+ self._lock = threading.Lock()
114
+ self._conn = sqlite3.connect(path, check_same_thread=False, timeout=60.0)
115
+ self._conn.execute("PRAGMA journal_mode=WAL")
116
+ self._conn.execute(
117
+ "CREATE TABLE IF NOT EXISTS embeddings (key TEXT PRIMARY KEY, dim INTEGER NOT NULL, vec BLOB NOT NULL)"
118
+ )
119
+ self._conn.commit()
120
+
121
+ @classmethod
122
+ def from_env(cls, model_name: str, path: Optional[str] = None) -> Optional["EmbeddingCache"]:
123
+ if os.getenv("EMBED_CACHE", "1").lower() in ("0", "false", "off"):
124
+ return None
125
+ if path is None:
126
+ path = os.getenv("EMBED_CACHE_PATH")
127
+ if path is None:
128
+ repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
129
+ slug = re.sub(r"[^A-Za-z0-9]+", "-", model_name).strip("-")
130
+ path = os.path.join(repo_root, "data", "embeddings", f"{slug}.sqlite")
131
+ return cls(os.path.expanduser(path), model_name)
132
+
133
+ def _key(self, text: str) -> str:
134
+ return hashlib.sha256((self.model_name + "\x1f" + text).encode("utf-8")).hexdigest()
135
+
136
+ def get_many(self, texts: List[str]) -> List[Optional[np.ndarray]]:
137
+ keys = [self._key(t) for t in texts]
138
+ found = {}
139
+ with self._lock:
140
+ for start in range(0, len(keys), 500):
141
+ chunk = keys[start:start + 500]
142
+ rows = self._conn.execute(
143
+ f"SELECT key, dim, vec FROM embeddings WHERE key IN ({','.join('?' * len(chunk))})", chunk
144
+ ).fetchall()
145
+ for key, dim, blob in rows:
146
+ found[key] = np.frombuffer(blob, dtype=np.float32, count=dim).astype(np.float64)
147
+ return [found.get(k) for k in keys]
148
+
149
+ def put_many(self, texts: List[str], vectors: np.ndarray) -> None:
150
+ rows = []
151
+ for text, vec in zip(texts, vectors):
152
+ arr = np.asarray(vec, dtype=np.float32)
153
+ rows.append((self._key(text), int(arr.shape[0]), arr.tobytes()))
154
+ with self._lock:
155
+ self._conn.executemany("INSERT OR IGNORE INTO embeddings (key, dim, vec) VALUES (?, ?, ?)", rows)
156
+ self._conn.commit()
157
+
158
+ def count(self) -> int:
159
+ with self._lock:
160
+ return int(self._conn.execute("SELECT COUNT(*) FROM embeddings").fetchone()[0])
161
+
162
+
163
+ class OpenAICompatGenerator:
164
+ """Chat-completions generator with the GeminiGenerator interface.
165
+
166
+ ``generate(question, candidates, context=None, baseline=False)`` returns a
167
+ validated decision dict exactly like ``GeminiGenerator.generate``. Prompt
168
+ construction, JSON parsing and citation validation are shared with the
169
+ Gemini path via ``docresolve.core`` so the two providers see the
170
+ same evidence formatting.
171
+ """
172
+
173
+ def __init__(
174
+ self,
175
+ api_key: Optional[str] = None,
176
+ base_url: Optional[str] = None,
177
+ model: Optional[str] = None,
178
+ temperature: float = 0.0,
179
+ max_tokens: int = 16384,
180
+ max_retries: int = 10,
181
+ enable_thinking: Optional[bool] = None,
182
+ ):
183
+ from openai import OpenAI
184
+
185
+ key = api_key or os.getenv("NVIDIA_API_KEY") or os.getenv("OPENAI_API_KEY")
186
+ endpoint = base_url or os.getenv("DOCRESOLVE_BASE_URL") or NVIDIA_BASE_URL
187
+ if not key:
188
+ if endpoint.rstrip("/") == NVIDIA_BASE_URL.rstrip("/"):
189
+ raise ValueError(
190
+ "No API key for the OpenAI-compatible generator. Set NVIDIA_API_KEY or "
191
+ "OPENAI_API_KEY in the environment, or point DOCRESOLVE_BASE_URL at a locally "
192
+ "hosted OpenAI-compatible server (vLLM, Ollama, llama.cpp), which needs no key."
193
+ )
194
+ key = "not-needed" # local servers ignore the key but the client requires one
195
+ self.model = model or os.getenv("NEMOTRON_MODEL") or DEFAULT_NVIDIA_MODEL
196
+ self.temperature = temperature
197
+ # Reasoning models spend part of the budget on thinking before the
198
+ # JSON answer, so the budget is larger than the Gemini path's 4096.
199
+ self.max_tokens = max_tokens
200
+ self.max_retries = max_retries
201
+ if enable_thinking is None:
202
+ enable_thinking = os.getenv("NEMOTRON_THINKING", "1").lower() not in ("0", "false", "off")
203
+ self.enable_thinking = enable_thinking
204
+ # Explicit per-request timeout: a stalled connection otherwise blocks a
205
+ # run indefinitely (seen 26 Nov 2026 with four concurrent runs). The
206
+ # retry loop below treats a timeout as transient and retries it.
207
+ self.base_url = endpoint
208
+ self.client = OpenAI(api_key=key, base_url=self.base_url, max_retries=0,
209
+ timeout=float(os.getenv("NEMOTRON_TIMEOUT_S", "300")))
210
+ self.use_vertex = False
211
+ print("✓ Using OpenAI-compatible generation endpoint")
212
+ print(f" Base URL: {self.base_url}")
213
+ print(f" Model: {self.model}")
214
+ print(f" Thinking: {'on' if self.enable_thinking else 'off'}")
215
+
216
+ def _chat(self, system_prompt: str, user_prompt: str) -> str:
217
+ delay = 2.0
218
+ last_error: Optional[Exception] = None
219
+ for attempt in range(self.max_retries):
220
+ try:
221
+ kwargs = {}
222
+ if not self.enable_thinking:
223
+ # Nemotron 3.x chat templates accept this toggle.
224
+ kwargs["extra_body"] = {"chat_template_kwargs": {"enable_thinking": False}}
225
+ response = self.client.chat.completions.create(
226
+ model=self.model,
227
+ messages=[
228
+ {"role": "system", "content": system_prompt},
229
+ {"role": "user", "content": user_prompt},
230
+ ],
231
+ temperature=self.temperature,
232
+ max_tokens=self.max_tokens,
233
+ **kwargs,
234
+ )
235
+ choice = response.choices[0]
236
+ content = choice.message.content or ""
237
+ if choice.finish_reason not in (None, "stop"):
238
+ print(f" WARNING: completion finish_reason={choice.finish_reason} ({len(content)} chars)")
239
+ # Reasoning models may emit a <think> block before the answer.
240
+ content = _THINK_BLOCK.sub("", content).strip()
241
+ if not content:
242
+ raise RuntimeError(
243
+ f"empty completion (finish_reason={choice.finish_reason}); "
244
+ "the reasoning budget was probably exhausted before the answer"
245
+ )
246
+ return content
247
+ except Exception as exc: # noqa: BLE001 - retry on transient API errors
248
+ last_error = exc
249
+ status = getattr(exc, "status_code", None)
250
+ retryable = status in (408, 409, 429, 500, 502, 503, 504) or status is None
251
+ if not retryable or attempt == self.max_retries - 1:
252
+ raise
253
+ print(f" generation attempt {attempt + 1} failed ({status or type(exc).__name__}); retrying in {delay:.0f}s")
254
+ time.sleep(delay)
255
+ delay = min(delay * 2, 60.0)
256
+ raise RuntimeError(f"generation failed after retries: {last_error}")
257
+
258
+ def closed_book(self, question, context=None):
259
+ """Direct few-shot CoT answer with no passages (``closedbook`` mode).
260
+
261
+ Returns a dict with the ``generate`` result keys that make sense
262
+ without evidence; citations are always empty and nothing is validated
263
+ against passages, but malformed JSON gets one repair attempt.
264
+ """
265
+ from . import core
266
+
267
+ context = {k: v for k, v in (context or {}).items() if v is not None and str(v).strip()}
268
+ user_prompt = f"Question: {question}"
269
+ if context:
270
+ user_prompt += "\nCase context: " + " ".join(f"{k}: {v}" for k, v in context.items())
271
+ repairs = 0
272
+ raw = self._chat(core.CLOSED_BOOK_SYSTEM_PROMPT, user_prompt)
273
+ parsed = core.parse_json_response(raw)
274
+ if not isinstance(parsed, dict) or "answer" not in parsed:
275
+ repairs = 1
276
+ raw = self._chat(core.CLOSED_BOOK_SYSTEM_PROMPT,
277
+ user_prompt + "\n\nReturn only the JSON object described above.")
278
+ parsed = core.parse_json_response(raw)
279
+ if not isinstance(parsed, dict) or "answer" not in parsed:
280
+ failed = core.generation_failure("Closed-book generation returned no parseable JSON answer.")
281
+ failed["repair_attempts"] = repairs
282
+ return failed
283
+ decision = parsed.get("decision", "answered")
284
+ if decision not in ("answered", "insufficient_evidence"):
285
+ decision = "answered"
286
+ short = parsed.get("short_answers") or []
287
+ if not isinstance(short, list):
288
+ short = [short]
289
+ short = [str(x).strip() for x in short if str(x).strip()]
290
+ answer = str(parsed.get("answer") or "").strip()
291
+ if decision == "insufficient_evidence" or not answer:
292
+ decision = "insufficient_evidence"
293
+ short = []
294
+ answer = answer or "I do not know."
295
+ confidence = parsed.get("confidence", "medium")
296
+ if confidence not in ("high", "medium", "low"):
297
+ confidence = "medium"
298
+ reasoning = str(parsed.get("reasoning") or "")
299
+ return {
300
+ "decision": decision,
301
+ "answer": answer,
302
+ "short_answers": short,
303
+ "citations": [],
304
+ "reason": reasoning,
305
+ "explanation": reasoning,
306
+ "selected_source": None,
307
+ "conflict_detected": False,
308
+ "confidence": confidence,
309
+ "validation_error": False,
310
+ "repair_attempts": repairs,
311
+ "dropped_citations": 0,
312
+ }
313
+
314
+ def generate(self, question, candidates, context=None, baseline: bool = False, policy: str = "answer_and_flag_final"):
315
+ # Imported lazily to avoid a circular import at module load time.
316
+ from . import core
317
+
318
+ if not baseline and policy == "two_stage":
319
+ return self._generate_two_stage(core, question, candidates, context)
320
+ if baseline:
321
+ system_prompt = core.BASELINE_SYSTEM_PROMPT
322
+ elif policy == "answer_and_flag":
323
+ system_prompt = core.SYSTEM_PROMPT_ANSWER_AND_FLAG
324
+ elif policy == "answer_and_flag_v2":
325
+ system_prompt = core.SYSTEM_PROMPT_ANSWER_AND_FLAG_V2
326
+ elif policy == "answer_and_flag_a":
327
+ system_prompt = core.SYSTEM_PROMPT_ANSWER_AND_FLAG_A
328
+ elif policy == "answer_and_flag_final":
329
+ system_prompt = core.SYSTEM_PROMPT_ANSWER_AND_FLAG_FINAL
330
+ else:
331
+ system_prompt = core.SYSTEM_PROMPT
332
+ user_prompt = core.build_user_prompt(
333
+ question, candidates, context=context, include_signals=not baseline,
334
+ corroboration=(not baseline and policy in ("answer_and_flag", "answer_and_flag_v2", "answer_and_flag_a", "answer_and_flag_final")),
335
+ )
336
+ try:
337
+ return core.run_generation(self._chat, system_prompt, user_prompt, candidates,
338
+ enforce_committed=(not baseline and policy == "answer_and_flag_final"))
339
+ except Exception as exc: # noqa: BLE001
340
+ print(f"ERROR: generation failed: {exc}")
341
+ return core.generation_failure("Generation failed; no answer was selected.")
342
+
343
+ def _generate_two_stage(self, core, question, candidates, context):
344
+ """Stage 1: plain draft over the governance-ranked passages. Stage 2:
345
+ governance audit of that draft. If the audit output fails validation
346
+ the validated draft is returned, so the audit can add flags but a
347
+ formatting failure never costs the answer."""
348
+ try:
349
+ draft = core.run_generation(
350
+ self._chat, core.BASELINE_SYSTEM_PROMPT,
351
+ core.build_user_prompt(question, candidates, context=context, include_signals=False),
352
+ candidates,
353
+ )
354
+ except Exception as exc: # noqa: BLE001
355
+ print(f"ERROR: generation failed: {exc}")
356
+ return core.generation_failure("Generation failed; no answer was selected.")
357
+ draft_ok = not draft.get("validation_error")
358
+ if not draft_ok:
359
+ # The audit then answers from the evidence on its own.
360
+ print("TWO_STAGE: draft_failed")
361
+ draft = {"decision": "insufficient_evidence", "answer": None, "short_answers": [], "selected_source": None}
362
+ try:
363
+ audited = core.run_generation(
364
+ self._chat, core.SYSTEM_PROMPT_VERIFY,
365
+ core.build_verify_prompt(question, candidates, draft, context=context),
366
+ candidates,
367
+ )
368
+ except Exception as exc: # noqa: BLE001
369
+ print(f"ERROR: audit generation failed: {exc}")
370
+ audited = core.generation_failure("Audit generation failed.")
371
+ if audited.get("validation_error"):
372
+ print(f"TWO_STAGE: audit_failed -> {'draft' if draft_ok else 'failure'}")
373
+ return draft if draft_ok else audited
374
+ same = sorted(s.lower() for s in audited.get("short_answers", [])) == \
375
+ sorted(s.lower() for s in draft.get("short_answers", []))
376
+ status = "kept" if same and audited.get("decision") == draft.get("decision") else "changed"
377
+ print(f"TWO_STAGE: {status} draft={draft.get('decision')}:{draft.get('short_answers')} "
378
+ f"final={audited.get('decision')}:{audited.get('short_answers')}")
379
+ return audited