Files
rag-technical-docs-assistant/app/infrastructure/extraction_candidates.py
T
amirhosein mazaheri 5ef02d39a9 feat(ingestion): implement Phase 3 text extraction, OCR, and human review
- Add direct text, DOCX, and PDF text extraction with visual OCR fallback
- Implement Gemini and OpenRouter vision adapters with strict bounded retry
- Implement extraction envelopes, artifacts, and Unicode/Persian normalization
- Add human review workflow, candidate staging, and review repositories
- Add migration 0003_extraction_review for audit events and review tracking
- Add comprehensive unit and integration tests covering extraction and review contracts
2026-10-07 16:21:01 +03:30

102 lines
4.9 KiB
Python

"""Immutable bounded unreferenced artifact candidates. Attachment is Phase 5 only."""
from dataclasses import dataclass
import hashlib
import os
from pathlib import Path
import re
import tempfile
from uuid import UUID, uuid4
from app.modules.documents.extraction_artifacts import validate_artifact, serialize_artifact
from app.modules.documents.settings import canonical_storage_root
@dataclass(frozen=True)
class ExtractionCandidate:
key: str
sha256: str
document_id: UUID
original_sha256: str
extraction_profile_sha256: str
class LocalExtractionCandidates:
def __init__(self, directory, *, original_directory):
self.directory = canonical_storage_root(Path(directory))
original = canonical_storage_root(Path(original_directory))
if (self.directory == original or self.directory in original.parents
or original in self.directory.parents):
raise ValueError("Extraction candidates need a separate non-nested namespace")
def _path(self, key):
if not re.fullmatch(r"[0-9a-f]{32}\.[0-9a-f]{32}\.candidate.json", key):
raise ValueError("Invalid extraction candidate key")
path = self.directory / key
if path.is_symlink():
raise ValueError("Extraction candidates cannot be symlinks")
return path
def put(self, envelope, *, processing_profile):
content = serialize_artifact(envelope, processing_profile)
digest = hashlib.sha256(content).hexdigest()
validate_artifact(content, artifact_sha256=digest, document_id=envelope.document_id,
original_sha256=envelope.original_sha256, processing_profile=processing_profile)
self.directory.mkdir(parents=True, exist_ok=True)
key = envelope.document_id.hex + "." + uuid4().hex + ".candidate.json"
final = self._path(key)
descriptor, temporary = tempfile.mkstemp(prefix=".extraction-", dir=self.directory)
try:
with os.fdopen(descriptor, "wb") as stream:
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
os.link(temporary, final) # atomic no replace, including concurrent attempts
finally:
Path(temporary).unlink(missing_ok=True)
if os.name != "nt":
descriptor = os.open(self.directory, os.O_RDONLY)
try:
os.fsync(descriptor)
finally:
os.close(descriptor)
return ExtractionCandidate(key, digest, envelope.document_id, envelope.original_sha256,
envelope.extraction_profile_sha256)
def inspect(self, candidate, *, processing_profile):
# This is integrity inspection, not authorization to attach/reuse it.
limit = processing_profile["extraction"]["max_extraction_artifact_bytes"]
with self._path(candidate.key).open("rb") as stream:
content = stream.read(limit + 1)
return validate_artifact(content, artifact_sha256=candidate.sha256,
document_id=candidate.document_id, original_sha256=candidate.original_sha256,
processing_profile=processing_profile)
def inspect_pointer(self, pointer, *, document):
fields = {"key", "sha256", "document_id", "original_sha256", "extraction_profile_sha256"}
if (not isinstance(pointer, dict) or set(pointer) != fields
or not all(isinstance(value, str) for value in pointer.values())
or any(len(pointer[key]) != 64 for key in
("sha256", "original_sha256", "extraction_profile_sha256"))):
raise ValueError("Invalid trusted extraction attachment")
candidate = ExtractionCandidate(**{**pointer, "document_id": UUID(pointer["document_id"])})
if (candidate.document_id != document["id"]
or candidate.original_sha256 != document["file_sha256"]):
raise ValueError("Trusted attachment identity mismatch")
envelope = self.inspect(candidate, processing_profile=document["processing_profile"])
if candidate.extraction_profile_sha256 != envelope.extraction_profile_sha256:
raise ValueError("Trusted extraction identity mismatch")
return envelope
def inventory(self):
result = {"candidates": [], "temporary_files": [], "unexpected_entries": []}
if self.directory.exists():
for path in self.directory.iterdir():
category = "unexpected_entries"
if path.is_file() and not path.is_symlink():
if re.fullmatch(r"[0-9a-f]{32}\.[0-9a-f]{32}\.(?:candidate|review).json", path.name):
category = "candidates"
elif path.name.startswith((".extraction-", ".review-")):
category = "temporary_files"
result[category].append(path.name)
return {name: sorted(values) for name, values in result.items()}