Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy. Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics. Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
268 lines
14 KiB
Python
268 lines
14 KiB
Python
"""Explicitly constructed ingestion settings; unrelated to prototype chat credentials."""
|
|
from dataclasses import asdict
|
|
from pathlib import Path
|
|
import os
|
|
import re
|
|
from urllib.parse import urlsplit
|
|
|
|
from pydantic import Field, SecretStr, ValidationError, field_validator, model_validator
|
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
|
|
from .types import EmbeddingProfile
|
|
from .operational_limits import validate_duration
|
|
from .embeddings import EmbeddingLimits, is_representable_timeout, validate_endpoint_hostname
|
|
|
|
|
|
def canonical_storage_root(value: Path) -> Path:
|
|
resolved = str(value.resolve(strict=False))
|
|
if os.name == "nt":
|
|
# Extended drive/UNC spellings identify the same Windows namespace.
|
|
if resolved.startswith("\\\\?\\UNC\\"):
|
|
resolved = "\\\\" + resolved[8:]
|
|
elif resolved.startswith("\\\\?\\") and len(resolved) > 5 and resolved[5] == ":":
|
|
resolved = resolved[4:]
|
|
return Path(os.path.normcase(resolved))
|
|
|
|
|
|
class IngestionSettings(BaseSettings):
|
|
model_config = SettingsConfigDict(
|
|
env_prefix="INGEST_", env_file=".env", extra="ignore", hide_input_in_errors=True
|
|
)
|
|
database_url: SecretStr
|
|
embedding_model: str = Field(min_length=1)
|
|
embedding_dimensions: int = Field(gt=0)
|
|
embedding_provider: str = Field(min_length=1)
|
|
embedding_endpoint: str = Field(min_length=1)
|
|
embedding_api_key: SecretStr | None = None
|
|
embedding_preprocessing_version: str = Field(default="v1", min_length=1)
|
|
embedding_timeout_seconds: float = Field(default=60, gt=0, allow_inf_nan=False)
|
|
embedding_limits: EmbeddingLimits | None = None
|
|
embedding_send_dimensions: bool = False
|
|
embedding_max_response_bytes: int = Field(default=16 * 1024 * 1024, gt=0)
|
|
original_directory: Path = Path("data/originals")
|
|
extraction_directory: Path = Path("data/extractions")
|
|
accepted_formats: tuple[str, ...] = (".pdf", ".md", ".docx", ".jpg", ".jpeg", ".png")
|
|
max_original_bytes: int = Field(default=20 * 1024 * 1024, gt=0)
|
|
max_docx_entries: int = Field(default=2048, gt=0, le=65534)
|
|
max_docx_member_bytes: int = Field(default=16 * 1024 * 1024, gt=0)
|
|
max_docx_expanded_bytes: int = Field(default=64 * 1024 * 1024, gt=0)
|
|
max_docx_compression_ratio: int = Field(default=200, gt=0)
|
|
max_image_width: int = Field(default=12000, gt=0)
|
|
max_image_height: int = Field(default=12000, gt=0)
|
|
max_image_pixels: int = Field(default=40_000_000, gt=0)
|
|
extraction_strategy: str = Field(default="direct-quality-fallback-v1", min_length=1)
|
|
vision_provider: str | None = None
|
|
vision_endpoint: str | None = None
|
|
vision_model: str | None = None
|
|
vision_api_key: SecretStr | None = None
|
|
vision_timeout_seconds: float = Field(default=60, gt=0, allow_inf_nan=False)
|
|
fallback_policy: str = Field(default="affected-pages-v1", min_length=1)
|
|
quality_policy: str = Field(default="bounded-checks-manual-review-v1", min_length=1)
|
|
ocr_review_required: bool = True
|
|
normalization_policy: str = Field(default="unicode-line-endings-v1", min_length=1)
|
|
chunking_policy: str = Field(default="paragraph-v1", min_length=1)
|
|
render_dpi: int = Field(default=144, gt=0, le=600)
|
|
max_rendered_page_pixels: int = Field(default=20_000_000, gt=0)
|
|
max_extraction_artifact_bytes: int = Field(default=32 * 1024 * 1024, gt=0)
|
|
max_extracted_blocks: int = Field(default=10000, gt=0)
|
|
max_pdf_pages: int = Field(default=200, gt=0)
|
|
max_normalized_characters: int = Field(default=1_000_000, gt=0)
|
|
max_chunks: int = Field(default=2000, gt=0)
|
|
chunk_size_characters: int = Field(default=1000, gt=0)
|
|
chunk_overlap_characters: int = Field(default=200, ge=0)
|
|
embedding_batch_size: int = Field(default=32, gt=0)
|
|
max_staged_bytes: int = Field(default=128 * 1024 * 1024, gt=0)
|
|
worker_concurrency: int = Field(default=1, ge=1, le=1)
|
|
poll_seconds: float = Field(default=2, gt=0, allow_inf_nan=False)
|
|
heartbeat_seconds: float = Field(default=20, gt=0, allow_inf_nan=False)
|
|
lease_seconds: float = Field(default=120, gt=0, allow_inf_nan=False)
|
|
max_automatic_attempts: int = Field(default=3, gt=0)
|
|
retry_base_seconds: float = Field(default=2, gt=0, allow_inf_nan=False)
|
|
retry_cap_seconds: float = Field(default=300, gt=0, allow_inf_nan=False)
|
|
|
|
@field_validator("poll_seconds", "heartbeat_seconds", "lease_seconds",
|
|
"retry_base_seconds", "retry_cap_seconds")
|
|
@classmethod
|
|
def operational_duration(cls, value):
|
|
return validate_duration(value)
|
|
|
|
@field_validator(
|
|
"embedding_model", "embedding_provider",
|
|
"embedding_preprocessing_version", "extraction_strategy", "fallback_policy",
|
|
"quality_policy", "normalization_policy", "chunking_policy"
|
|
)
|
|
@classmethod
|
|
def nonblank(cls, value):
|
|
value = value.strip()
|
|
if not value:
|
|
raise ValueError("Profile identity cannot be blank")
|
|
return value
|
|
|
|
|
|
@field_validator("embedding_endpoint", "vision_endpoint", mode="before")
|
|
@classmethod
|
|
def supported_endpoint(cls, value, info):
|
|
if value is None and info.field_name == "vision_endpoint":
|
|
return None
|
|
message = "Endpoint must be an absolute HTTP(S) host/port/path URL without authentication, query, fragment or encoded components"
|
|
if not isinstance(value, str) or not value or any(
|
|
character.isspace() or ord(character) < 32 for character in value
|
|
) or any(character in value for character in ("@", "?", "#", "%", "\\", ";")):
|
|
raise ValueError(message)
|
|
try:
|
|
parsed = urlsplit(value)
|
|
if (parsed.scheme not in ("http", "https") or not parsed.hostname
|
|
or parsed.username is not None or parsed.password is not None
|
|
or parsed.query or parsed.fragment or parsed.port == 0
|
|
or (":" in parsed.hostname and not parsed.netloc.startswith("["))
|
|
or not validate_endpoint_hostname(parsed.hostname)
|
|
or not re.fullmatch(r"/[A-Za-z0-9._~/-]*|", parsed.path)):
|
|
raise ValueError(message)
|
|
if parsed.netloc.endswith(":"):
|
|
raise ValueError(message)
|
|
except (ValueError, TypeError, UnicodeError, OverflowError):
|
|
raise ValueError(message) from None
|
|
# Preserve scheme, host casing, explicit ports and path identity.
|
|
return value
|
|
|
|
@field_validator("embedding_timeout_seconds", "vision_timeout_seconds")
|
|
@classmethod
|
|
def representable_timeout(cls, value):
|
|
if not is_representable_timeout(value):
|
|
raise ValueError("Timeout must be a finite positive number representable by runtime synchronization and sockets")
|
|
return float(value)
|
|
|
|
@field_validator("database_url")
|
|
@classmethod
|
|
def postgres_only(cls, value):
|
|
from sqlalchemy.engine import make_url
|
|
from sqlalchemy.exc import ArgumentError
|
|
parsed = None
|
|
try:
|
|
parsed = make_url(value.get_secret_value())
|
|
except (ArgumentError, ValueError, TypeError, OverflowError):
|
|
# Do not retain the parser exception: its text/context may contain
|
|
# credentials or a secret supplied as a malformed port.
|
|
pass
|
|
# Raise outside the except block to avoid even a suppressed raw context.
|
|
if (parsed is None or parsed.drivername != "postgresql+psycopg"
|
|
or (parsed.port is not None and not 1 <= parsed.port <= 65535)):
|
|
raise ValueError("Database URL must be a valid postgresql+psycopg URL")
|
|
return value
|
|
|
|
@field_validator("accepted_formats")
|
|
@classmethod
|
|
def supported_formats(cls, value):
|
|
if not value or len(set(value)) != len(value) or not set(value) <= {".pdf", ".md", ".docx", ".jpg", ".jpeg", ".png"}:
|
|
raise ValueError("Accepted formats must be a nonempty subset of .pdf, .md, .docx, .jpg, .jpeg and .png")
|
|
return value
|
|
|
|
@field_validator("vision_provider", "vision_model")
|
|
@classmethod
|
|
def optional_identity(cls, value):
|
|
if value is not None:
|
|
value = value.strip()
|
|
if not value:
|
|
raise ValueError("Profile identity cannot be blank")
|
|
return value
|
|
|
|
@model_validator(mode="after")
|
|
def coherent_limits(self):
|
|
roots = None
|
|
try:
|
|
roots = (canonical_storage_root(self.original_directory),
|
|
canonical_storage_root(self.extraction_directory))
|
|
except (OSError, RuntimeError, ValueError):
|
|
pass
|
|
if roots is None:
|
|
raise ValueError("Storage roots cannot be canonically resolved")
|
|
original, extraction = roots
|
|
if original == extraction or original in extraction.parents or extraction in original.parents:
|
|
raise ValueError("Original and extraction storage roots must be separate, non-nested namespaces")
|
|
if any(v is not None for v in (self.vision_provider, self.vision_endpoint, self.vision_model)) and not all(
|
|
v is not None for v in (self.vision_provider, self.vision_endpoint, self.vision_model)
|
|
):
|
|
raise ValueError("Vision provider, endpoint and model must be configured together")
|
|
# Additional search normalization requires a reviewed embedding migration.
|
|
if self.normalization_policy != "unicode-line-endings-v1":
|
|
raise ValueError("New normalization requires an explicit embedding migration/reindex design")
|
|
if self.chunk_overlap_characters >= self.chunk_size_characters:
|
|
raise ValueError("Chunk overlap must be smaller than chunk size")
|
|
if self.heartbeat_seconds >= self.lease_seconds:
|
|
raise ValueError("Heartbeat must be shorter than lease")
|
|
if self.retry_base_seconds > self.retry_cap_seconds:
|
|
raise ValueError("Retry base must not exceed retry cap")
|
|
return self
|
|
|
|
@property
|
|
def embedding_profile(self) -> EmbeddingProfile:
|
|
return EmbeddingProfile(
|
|
self.embedding_provider, self.embedding_endpoint.rstrip("/"),
|
|
self.embedding_model, self.embedding_dimensions,
|
|
self.embedding_preprocessing_version,
|
|
)
|
|
|
|
def processing_profile(self) -> dict:
|
|
"""Snapshot settings; retries must use this persisted snapshot, not fresh defaults."""
|
|
return {
|
|
"profile_schema": 2,
|
|
"extractor": "page-block-v1",
|
|
"extraction": {
|
|
"strategy": self.extraction_strategy,
|
|
"vision": {"provider": self.vision_provider, "endpoint": self.vision_endpoint,
|
|
"model": self.vision_model, "timeout_seconds": self.vision_timeout_seconds},
|
|
"fallback_policy": self.fallback_policy, "quality_policy": self.quality_policy,
|
|
"ocr_review_required": self.ocr_review_required,
|
|
"render_dpi": self.render_dpi,
|
|
"max_rendered_page_pixels": self.max_rendered_page_pixels,
|
|
"max_pdf_pages": self.max_pdf_pages,
|
|
"max_extracted_blocks": self.max_extracted_blocks,
|
|
"max_extraction_artifact_bytes": self.max_extraction_artifact_bytes,
|
|
},
|
|
"intake": {"accepted_formats": list(self.accepted_formats), **{
|
|
name: getattr(self, name) for name in (
|
|
"max_docx_entries", "max_docx_member_bytes", "max_docx_expanded_bytes",
|
|
"max_docx_compression_ratio", "max_image_width", "max_image_height", "max_image_pixels")}},
|
|
"normalizer": self.normalization_policy,
|
|
"chunker": self.chunking_policy, "size_unit": "characters",
|
|
"chunk_size": self.chunk_size_characters,
|
|
"overlap": self.chunk_overlap_characters,
|
|
"embedding": asdict(self.embedding_profile),
|
|
"embedding_request": {
|
|
"limits": self.embedding_limits.model_dump() if self.embedding_limits else None,
|
|
"timeout_seconds": self.embedding_timeout_seconds,
|
|
"send_dimensions": self.embedding_send_dimensions,
|
|
"max_response_bytes": self.embedding_max_response_bytes,
|
|
},
|
|
"limits": {
|
|
name: getattr(self, name) for name in (
|
|
"max_original_bytes", "max_pdf_pages",
|
|
"max_normalized_characters", "max_chunks",
|
|
"embedding_batch_size", "max_staged_bytes",
|
|
)
|
|
},
|
|
}
|
|
|
|
def require_vision_credentials(self) -> None:
|
|
if self.vision_model is None or self.vision_api_key is None or not self.vision_api_key.get_secret_value().strip():
|
|
raise ValueError("Configured vision identity and INGEST_VISION_API_KEY are required for a hosted adapter")
|
|
|
|
def require_embedding_credentials(self) -> None:
|
|
if self.embedding_api_key is None or not self.embedding_api_key.get_secret_value().strip():
|
|
raise ValueError("INGEST_EMBEDDING_API_KEY is required for a hosted adapter")
|
|
|
|
@model_validator(mode="wrap")
|
|
@classmethod
|
|
def redact_validation_inputs(cls, values, handler):
|
|
try:
|
|
return handler(values)
|
|
except ValidationError as exc:
|
|
# Structured errors otherwise retain raw URL and complete input maps.
|
|
redacted = ValidationError.from_exception_data(
|
|
cls.__name__, exc.errors(include_input=False, include_url=False),
|
|
hide_input=True,
|
|
)
|
|
# Raising after leaving the handler drops the raw ValidationError context,
|
|
# whose structured errors still contain the original settings inputs.
|
|
raise redacted from None
|