chore(backend): save remaining API and deployment changes
Expose frozen factual review policy, update API descriptions and Swagger settings, and adjust local deployment and embedding connectivity. Include the requested extraction candidates and review-policy regression coverage. Validation: 31 OCR policy tests passed; staged diff whitespace checks passed.
This commit is contained in:
@@ -64,6 +64,8 @@ INGEST_EXTRACTION_STRATEGY="direct-quality-fallback-v1"
|
||||
INGEST_VISION_TIMEOUT_SECONDS=60
|
||||
INGEST_FALLBACK_POLICY="affected-pages-v1"
|
||||
INGEST_QUALITY_POLICY="bounded-checks-manual-review-v1"
|
||||
# INGEST_OCR_REVIEW_REQUIRED=true
|
||||
# INGEST_FACTUAL_REVIEW_REQUIRED=true
|
||||
# Preserve existing embedding preprocessing. New Persian normalization requires migration/reindex design.
|
||||
INGEST_NORMALIZATION_POLICY="unicode-line-endings-v1"
|
||||
INGEST_CHUNKING_POLICY="paragraph-v1"
|
||||
|
||||
+18
-3
@@ -31,7 +31,12 @@ class AuthResponse(BaseModel):
|
||||
csrf_token: str
|
||||
expires_at: str
|
||||
|
||||
@router.post('/login', response_model=AuthResponse)
|
||||
@router.post(
|
||||
'/login',
|
||||
response_model=AuthResponse,
|
||||
summary='User Login',
|
||||
description='Authenticate with username and password. On success, issues a secure HTTP-only rag_session cookie and returns user context with CSRF token.',
|
||||
)
|
||||
def login(req: LoginRequest, request: Request, response: Response,
|
||||
auth_service: Annotated[AuthService, Depends(get_auth_service)],
|
||||
config: Annotated[VoiceSettings, Depends(get_voice_settings)]):
|
||||
@@ -55,7 +60,12 @@ def login(req: LoginRequest, request: Request, response: Response,
|
||||
samesite='lax', expires=expiry, path='/')
|
||||
return AuthResponse(user=UserDTO(**user), csrf_token=csrf, expires_at=expiry.isoformat())
|
||||
|
||||
@router.post('/logout', status_code=204)
|
||||
@router.post(
|
||||
'/logout',
|
||||
status_code=204,
|
||||
summary='User Logout',
|
||||
description='Revoke the active authentication session and clear the session cookie.',
|
||||
)
|
||||
def logout(request: Request, response: Response,
|
||||
auth_service: Annotated[AuthService, Depends(get_auth_service)],
|
||||
config: Annotated[VoiceSettings, Depends(get_voice_settings)]):
|
||||
@@ -73,7 +83,12 @@ def logout(request: Request, response: Response,
|
||||
response.status_code = 204
|
||||
return response
|
||||
|
||||
@identity_router.get('/me', response_model=AuthResponse)
|
||||
@identity_router.get(
|
||||
'/me',
|
||||
response_model=AuthResponse,
|
||||
summary='Get Current Identity',
|
||||
description='Retrieve identity and session expiry for the currently authenticated user.',
|
||||
)
|
||||
@router.get('/me', response_model=AuthResponse, include_in_schema=False)
|
||||
def get_me(request: Request, user: Annotated[UserContext, Depends(get_current_user)]):
|
||||
return AuthResponse(user=UserDTO(id=str(user.id), organization_id=str(user.organization_id),
|
||||
|
||||
@@ -37,8 +37,8 @@ class ConversationResponse(BaseModel):
|
||||
"",
|
||||
response_model=ConversationResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="C01: Create Conversation",
|
||||
description="Creates an owned voice conversation container with idempotency protection.",
|
||||
summary="Create Conversation",
|
||||
description="Create an owned conversation container with idempotency protection.",
|
||||
)
|
||||
def create_conversation(
|
||||
req: CreateConversationRequest,
|
||||
|
||||
+41
-9
@@ -54,13 +54,19 @@ def replay_header(response, result):
|
||||
response.headers['Idempotency-Replayed'] = 'true'
|
||||
|
||||
|
||||
@router.post('', status_code=202, openapi_extra={'requestBody': {
|
||||
@router.post(
|
||||
'',
|
||||
status_code=202,
|
||||
summary='Upload Document for Ingestion',
|
||||
description='Upload an original document (.pdf, .md, .docx, or image) to initiate the background ingestion and chunking pipeline.',
|
||||
openapi_extra={'requestBody': {
|
||||
'required': True, 'content': {'multipart/form-data': {'schema': {
|
||||
'type': 'object', 'additionalProperties': False, 'required': ['file'],
|
||||
'properties': {'file': {'type': 'string', 'format': 'binary'},
|
||||
'title': {'type': 'string', 'maxLength': 200}}
|
||||
}}}
|
||||
}})
|
||||
}}
|
||||
)
|
||||
async def upload(request: Request, response: Response, user: Admin, services: Services, key: Key, _csrf: Csrf):
|
||||
settings, store, _, intake, *_ = services
|
||||
previous = None
|
||||
@@ -99,7 +105,11 @@ async def upload(request: Request, response: Response, user: Admin, services: Se
|
||||
raise error(str(exc)) from None
|
||||
|
||||
|
||||
@router.get('')
|
||||
@router.get(
|
||||
'',
|
||||
summary='List Ingested Documents',
|
||||
description='List uploaded documents with optional filtering by status (queued, processing, ready, failed) and active state.',
|
||||
)
|
||||
def documents(user: Admin, services: Services, limit: Annotated[int, Query(ge=1, le=100)] = 20,
|
||||
cursor: Annotated[str | None, Query(max_length=256)] = None,
|
||||
status: Literal['queued', 'processing', 'ready', 'failed'] | None = None,
|
||||
@@ -110,7 +120,11 @@ def documents(user: Admin, services: Services, limit: Annotated[int, Query(ge=1,
|
||||
raise error(exc.code) from None
|
||||
|
||||
|
||||
@router.get('/{document_id}')
|
||||
@router.get(
|
||||
'/{document_id}',
|
||||
summary='Get Document Details',
|
||||
description='Retrieve metadata, processing status, and job information for a specific document.',
|
||||
)
|
||||
def detail(document_id: UUID, user: Admin, services: Services):
|
||||
try:
|
||||
return services.queries.detail(user.id, document_id)
|
||||
@@ -118,7 +132,12 @@ def detail(document_id: UUID, user: Admin, services: Services):
|
||||
raise error(exc.code) from None
|
||||
|
||||
|
||||
@router.post('/{document_id}/retry', status_code=202)
|
||||
@router.post(
|
||||
'/{document_id}/retry',
|
||||
status_code=202,
|
||||
summary='Retry Failed Document Ingestion',
|
||||
description='Trigger a background retry for an eligible failed document ingestion job.',
|
||||
)
|
||||
async def retry(document_id: UUID, request: Request, response: Response, user: Admin, services: Services, key: Key, _csrf: Csrf):
|
||||
await receive_empty(request)
|
||||
try:
|
||||
@@ -130,7 +149,11 @@ async def retry(document_id: UUID, request: Request, response: Response, user: A
|
||||
raise error(exc.code) from None
|
||||
|
||||
|
||||
@router.get('/{document_id}/extraction-review')
|
||||
@router.get(
|
||||
'/{document_id}/extraction-review',
|
||||
summary='Get OCR Extraction Review Items',
|
||||
description='Retrieve pending OCR extraction review items, confidence checks, and evidence hashes for a document.',
|
||||
)
|
||||
def review(document_id: UUID, user: Admin, services: Services,
|
||||
limit: Annotated[int, Query(ge=1, le=20)] = 10,
|
||||
cursor: Annotated[str | None, Query(pattern='^[0-9a-f]{64}$')] = None):
|
||||
@@ -144,7 +167,11 @@ def review(document_id: UUID, user: Admin, services: Services,
|
||||
raise error(exc.code) from None
|
||||
|
||||
|
||||
@router.get('/{document_id}/extraction-review/{evidence_sha256}/preview')
|
||||
@router.get(
|
||||
'/{document_id}/extraction-review/{evidence_sha256}/preview',
|
||||
summary='Preview Extraction Review Artifact',
|
||||
description='Download the visual proof snippet or rendered page image for a specific evidence hash.',
|
||||
)
|
||||
def preview(document_id: UUID, evidence_sha256: str, user: Admin, services: Services):
|
||||
import re
|
||||
if not re.fullmatch('[0-9a-f]{64}', evidence_sha256):
|
||||
@@ -156,12 +183,17 @@ def preview(document_id: UUID, evidence_sha256: str, user: Admin, services: Serv
|
||||
raise error(exc.code) from None
|
||||
|
||||
|
||||
@router.post('/{document_id}/extraction-review/decisions', openapi_extra={
|
||||
@router.post(
|
||||
'/{document_id}/extraction-review/decisions',
|
||||
summary='Submit Extraction Review Decision',
|
||||
description='Approve or reject flagged OCR extraction blocks before proceeding to embedding chunk publication.',
|
||||
openapi_extra={
|
||||
'requestBody': {
|
||||
'required': True,
|
||||
'content': {'application/json': {'schema': ReviewDecision.model_json_schema()}}
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
async def decide(document_id: UUID, request: Request, response: Response, user: Admin, services: Services, key: Key, _csrf: Csrf):
|
||||
payload = await receive_json(request, ReviewDecision, max_bytes=MAX_DECISION_BYTES)
|
||||
try:
|
||||
|
||||
+19
-5
@@ -11,7 +11,7 @@ from app.modules.knowledge.calibration import load_cutoff
|
||||
from app.modules.knowledge.evidence import RETRIEVAL_POLICY
|
||||
from app.infrastructure.database import check_compatibility, CompatibilityError
|
||||
|
||||
router = APIRouter(tags=['Knowledge and configuration'])
|
||||
router = APIRouter(tags=['Knowledge & Configuration'])
|
||||
|
||||
|
||||
class SelectionRequest(BaseModel):
|
||||
@@ -20,7 +20,11 @@ class SelectionRequest(BaseModel):
|
||||
document_ids: list[UUID] = Field(max_length=10000)
|
||||
|
||||
|
||||
@router.get('/knowledge-selection')
|
||||
@router.get(
|
||||
'/knowledge-selection',
|
||||
summary='Get Active Knowledge Selection',
|
||||
description='Retrieve the currently active document IDs and knowledge revision for the organization. Requires administrator privileges.',
|
||||
)
|
||||
def selection(user=Depends(require_admin), engine=Depends(get_engine)):
|
||||
try:
|
||||
return selection_get(engine, user.id)
|
||||
@@ -28,12 +32,17 @@ def selection(user=Depends(require_admin), engine=Depends(get_engine)):
|
||||
raise error(exc.code) from None
|
||||
|
||||
|
||||
@router.patch('/knowledge-selection', openapi_extra={
|
||||
@router.patch(
|
||||
'/knowledge-selection',
|
||||
summary='Update Active Knowledge Selection',
|
||||
description='Atomically replace the active knowledge selection document IDs with revision fencing. Requires administrator privileges and valid CSRF token.',
|
||||
openapi_extra={
|
||||
'requestBody': {
|
||||
'required': True,
|
||||
'content': {'application/json': {'schema': SelectionRequest.model_json_schema()}}
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
async def replace(request: Request, user=Depends(require_admin), engine=Depends(get_engine), _csrf=Depends(require_csrf)):
|
||||
payload = await receive_json(request, SelectionRequest, max_bytes=MAX_SELECTION_BYTES)
|
||||
try:
|
||||
@@ -49,7 +58,11 @@ async def replace(request: Request, user=Depends(require_admin), engine=Depends(
|
||||
raise error(str(exc)) from None
|
||||
|
||||
|
||||
@router.get('/configuration')
|
||||
@router.get(
|
||||
'/configuration',
|
||||
summary='Get Assistant Runtime Configuration',
|
||||
description='Query assistant capabilities, upload format limits, active policies, and live voice availability.',
|
||||
)
|
||||
def configuration(user=Depends(get_current_user), engine=Depends(get_engine),
|
||||
ingest=Depends(get_ingestion_settings), voice=Depends(get_voice_settings)):
|
||||
try:
|
||||
@@ -97,6 +110,7 @@ def configuration(user=Depends(get_current_user), engine=Depends(get_engine),
|
||||
supported_upload_types=list(dict.fromkeys(mime_types[e] for e in ingest.accepted_formats)),
|
||||
max_upload_bytes=ingest.max_original_bytes, max_pdf_pages=ingest.max_pdf_pages,
|
||||
ocr_review_required=ingest.ocr_review_required,
|
||||
factual_review_required=ingest.factual_review_required,
|
||||
supported_structure_notes='Readable Markdown and supported DOCX structures; bounded PDF/image extraction. Factual Q&A requires separate approval.',
|
||||
input_sample_rate=24000, output_sample_rate=24000, channels=1, audio_encoding='pcm16le',
|
||||
max_binary_message_bytes=limits.max_binary_message_bytes,
|
||||
|
||||
+24
-4
@@ -75,7 +75,13 @@ def search_profile(cutoff, settings=None):
|
||||
return dict(embedding=cutoff.profile, calibration_id=cutoff.calibration_id,
|
||||
retrieval_policy=cutoff.retrieval_policy, distance=cutoff.distance)
|
||||
|
||||
@router.post('', response_model=LiveSessionResponse, status_code=201)
|
||||
@router.post(
|
||||
'',
|
||||
response_model=LiveSessionResponse,
|
||||
status_code=201,
|
||||
summary='Create Realtime Voice Session',
|
||||
description='Allocate a new bidirectional realtime voice session for an active conversation. Returns stream_path and poll_url.',
|
||||
)
|
||||
def create_voice_session(req: CreateLiveSessionRequest, response: Response,
|
||||
user: Annotated[UserContext, Depends(get_current_user)],
|
||||
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
|
||||
@@ -111,7 +117,12 @@ def create_voice_session(req: CreateLiveSessionRequest, response: Response,
|
||||
response.headers['Idempotency-Replayed'] = 'true'
|
||||
return result
|
||||
|
||||
@router.get('/by-request/{client_request_id}', response_model=LiveSessionResponse)
|
||||
@router.get(
|
||||
'/by-request/{client_request_id}',
|
||||
response_model=LiveSessionResponse,
|
||||
summary='Recover Voice Session by Request ID',
|
||||
description='Idempotently look up or recover an existing voice session using the client_request_id.',
|
||||
)
|
||||
def recover(client_request_id: UUID, user: Annotated[UserContext, Depends(get_current_user)],
|
||||
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)]):
|
||||
try:
|
||||
@@ -119,7 +130,11 @@ def recover(client_request_id: UUID, user: Annotated[UserContext, Depends(get_cu
|
||||
except ValueError as exc:
|
||||
raise error(str(exc)) from None
|
||||
|
||||
@router.get('/{session_id}')
|
||||
@router.get(
|
||||
'/{session_id}',
|
||||
summary='Poll Voice Session Status',
|
||||
description='Poll current session lifecycle status, stream connection state, and expiry.',
|
||||
)
|
||||
def poll(session_id: UUID, user: Annotated[UserContext, Depends(get_current_user)],
|
||||
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)]):
|
||||
try:
|
||||
@@ -127,7 +142,12 @@ def poll(session_id: UUID, user: Annotated[UserContext, Depends(get_current_user
|
||||
except ValueError as exc:
|
||||
raise error(str(exc)) from None
|
||||
|
||||
@router.post('/{session_id}/close', response_model=CloseLiveSessionResponse)
|
||||
@router.post(
|
||||
'/{session_id}/close',
|
||||
response_model=CloseLiveSessionResponse,
|
||||
summary='Close Voice Session',
|
||||
description='Explicitly close an active voice session and release provider allocations.',
|
||||
)
|
||||
def close(session_id: UUID, user: Annotated[UserContext, Depends(get_current_user)],
|
||||
lifecycle: Annotated[LiveLifecycleService, Depends(get_lifecycle_service)],
|
||||
_csrf: Annotated[None, Depends(require_csrf)] = None):
|
||||
|
||||
@@ -9,7 +9,7 @@ from app.infrastructure.intake_repository import administrator, document_status
|
||||
from app.infrastructure.worker_repository import SqlWorkerRepository
|
||||
from app.modules.documents.errors import IntakeError
|
||||
from app.modules.documents.review import pending_review, reviews_approved
|
||||
from app.modules.documents.extraction_artifacts import ocr_review_required
|
||||
from app.modules.documents.extraction_artifacts import ocr_review_required, factual_review_required
|
||||
|
||||
|
||||
def encode_cursor(document):
|
||||
@@ -57,6 +57,7 @@ class DocumentQueries:
|
||||
review_required=pending_review(state), review_state=review_state,
|
||||
extraction_quality_decision=quality,
|
||||
ocr_review_required=ocr_review_required(row['processing_profile']),
|
||||
factual_review_required=factual_review_required(row['processing_profile']),
|
||||
job=dict(id=job['id'], status=job['status'], stage=job['stage'],
|
||||
attempt_count=job['attempt_count'], retry_generation=job['retry_generation'],
|
||||
can_retry=can_retry, error=(dict(code=job['error_code'],
|
||||
|
||||
@@ -193,7 +193,11 @@ class OpenAICompatibleEmbeddings:
|
||||
body = dict(model=identity.model, input=texts, encoding_format="float")
|
||||
if self.send_dimensions:
|
||||
body["dimensions"] = identity.dimensions
|
||||
request = Request(identity.endpoint.rstrip("/") + "/embeddings",
|
||||
endpoint = identity.endpoint
|
||||
from pathlib import Path
|
||||
if Path("/.dockerenv").exists():
|
||||
endpoint = endpoint.replace("://localhost:", "://host.docker.internal:").replace("://127.0.0.1:", "://host.docker.internal:")
|
||||
request = Request(endpoint.rstrip("/") + "/embeddings",
|
||||
data=json.dumps(body, allow_nan=False).encode("utf-8"),
|
||||
headers={"Authorization": "Bearer " + self._key, "Content-Type": "application/json"})
|
||||
content = self._request_once(request)
|
||||
|
||||
+70
-4
@@ -66,11 +66,76 @@ async def lifespan(app):
|
||||
if startup_error is None:
|
||||
raise
|
||||
|
||||
app = FastAPI(title='Technical Documentation Assistant API', lifespan=lifespan)
|
||||
API_DESCRIPTION = """
|
||||
## 🤖 Technical Documentation Assistant API
|
||||
|
||||
A modular, production-ready backend combining RAG (Retrieval-Augmented Generation) document search with bidirectional live voice streaming.
|
||||
|
||||
---
|
||||
|
||||
### 🔑 Authentication & Security
|
||||
* **Session Cookies:** Authenticated requests rely on the opaque `rag_session` HTTP-only cookie.
|
||||
* **CSRF Protection:** State-changing requests (`POST`, `PATCH`, `DELETE`) require `X-CSRF-Token` header.
|
||||
* **Host & Origin Validation:** Requests are filtered by strict loopback/trusted host gating.
|
||||
|
||||
### 📚 Core Modules
|
||||
1. **Authentication:** User login/logout and session validation.
|
||||
2. **Conversations:** Creation and state tracking for multi-turn chats.
|
||||
3. **Voice Sessions:** Realtime bidirectional voice via WebSocket stream.
|
||||
4. **Documents:** Document upload (PDF, DOCX, Markdown, Images), automated extraction, and quality control.
|
||||
5. **Knowledge & Configuration:** Organizational knowledge selection and runtime capabilities discovery.
|
||||
6. **Health & Monitoring:** Kubernetes/Docker liveness and readiness probes.
|
||||
"""
|
||||
|
||||
TAGS_METADATA = [
|
||||
{
|
||||
"name": "Authentication",
|
||||
"description": "User login, session lifecycle management, CSRF validation, and identity introspection.",
|
||||
},
|
||||
{
|
||||
"name": "Conversations",
|
||||
"description": "Creating and managing multi-turn text and voice conversations.",
|
||||
},
|
||||
{
|
||||
"name": "Voice Sessions",
|
||||
"description": "Bidirectional realtime voice sessions and WebSocket audio streaming endpoints.",
|
||||
},
|
||||
{
|
||||
"name": "Documents",
|
||||
"description": "Document ingestion pipeline, file intake, OCR review workflows, and error retries.",
|
||||
},
|
||||
{
|
||||
"name": "Knowledge & Configuration",
|
||||
"description": "Organizational knowledge selection, revision fencing, and assistant capabilities inquiry.",
|
||||
},
|
||||
{
|
||||
"name": "Health & Monitoring",
|
||||
"description": "Service liveness and readiness probes for orchestrators and monitoring.",
|
||||
},
|
||||
]
|
||||
|
||||
SWAGGER_UI_PARAMETERS = {
|
||||
"defaultModelsExpandDepth": -1, # Collapse Schemas section by default for clean view
|
||||
"docExpansion": "list", # Group endpoints neatly by tag
|
||||
"filter": True, # Real-time search filter bar
|
||||
"syntaxHighlight.theme": "monokai", # Modern dark syntax highlight for JSON
|
||||
"tryItOutEnabled": True, # One-click try it out
|
||||
"persistAuthorization": True, # Persist auth cookies across reloads
|
||||
"displayRequestDuration": True, # Show execution duration in ms
|
||||
}
|
||||
|
||||
app = FastAPI(
|
||||
title='Technical Documentation Assistant API',
|
||||
description=API_DESCRIPTION,
|
||||
version='1.0.0',
|
||||
openapi_tags=TAGS_METADATA,
|
||||
swagger_ui_parameters=SWAGGER_UI_PARAMETERS,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.state.ready = False
|
||||
config = VoiceSettings()
|
||||
app.add_middleware(CORSMiddleware, allow_origins=list(config.trusted_origins), allow_credentials=True,
|
||||
allow_methods=['GET','POST','PATCH'], allow_headers=['Content-Type','X-CSRF-Token','X-Request-ID','Idempotency-Key'],
|
||||
allow_methods=['GET','POST','PATCH','OPTIONS'], allow_headers=['Content-Type','X-CSRF-Token','X-Request-ID','Idempotency-Key','Accept','Authorization'],
|
||||
expose_headers=['X-Request-ID','Idempotency-Replayed'])
|
||||
|
||||
@app.middleware('http')
|
||||
@@ -111,11 +176,12 @@ async def unexpected_error(request, exc):
|
||||
for router in (auth_router, identity_router, conversations_router, voice_router, documents_router, knowledge_router):
|
||||
app.include_router(router, prefix='/api/v1')
|
||||
|
||||
@app.get('/health/live')
|
||||
@app.get('/health/live', tags=['Health & Monitoring'], summary='Liveness Probe', description='Returns HTTP 200 if the API process is alive and receiving traffic.')
|
||||
def live():
|
||||
return {'status': 'ok'}
|
||||
|
||||
@app.get('/health/ready')
|
||||
|
||||
@app.get('/health/ready', tags=['Health & Monitoring'], summary='Readiness Probe', description='Returns HTTP 200 if the database and search dependencies have reconciled and the API is ready to serve requests.')
|
||||
def ready():
|
||||
return JSONResponse(status_code=200 if app.state.ready else 503,
|
||||
content={'status': 'ready', 'ingestion': 'available'} if app.state.ready else {'status': 'not_ready'})
|
||||
|
||||
@@ -19,6 +19,14 @@ def ocr_review_required(profile: Mapping) -> bool:
|
||||
return value
|
||||
|
||||
|
||||
def factual_review_required(profile: Mapping) -> bool:
|
||||
"""Fail closed for legacy snapshots; deployment defaults never reinterpret jobs."""
|
||||
value = profile.get("extraction", {}).get("factual_review_required", True)
|
||||
if type(value) is not bool:
|
||||
raise ValueError("Invalid frozen factual review policy")
|
||||
return value
|
||||
|
||||
|
||||
def processing_profile_kind(profile: Mapping) -> str:
|
||||
if "profile_schema" not in profile and profile.get("extractor") == "pypdf-markdown-v1":
|
||||
return "legacy-v1"
|
||||
@@ -29,6 +37,7 @@ def processing_profile_kind(profile: Mapping) -> str:
|
||||
|
||||
def extraction_profile_digest(profile: Mapping) -> str:
|
||||
ocr_review_required(profile)
|
||||
factual_review_required(profile)
|
||||
if processing_profile_kind(profile) == "legacy-v1":
|
||||
raise LegacyProcessingProfile("Legacy extractor requires explicit legacy dispatch; OCR reinterpretation is forbidden")
|
||||
# Faithful extraction is reusable across chunk/embedding/normalization changes.
|
||||
|
||||
@@ -10,6 +10,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
|
||||
from .chunking import chunk_extraction, factual_context_units
|
||||
from .embeddings import validate_database_string
|
||||
from .extraction import ExtractionError, PLACEHOLDER, REVIEW_CHECKS
|
||||
from .extraction_artifacts import factual_review_required
|
||||
|
||||
FACTUAL_CHECKS = ("factual_authority", "whole_pair_association", "behavioral_separation", "placeholders")
|
||||
|
||||
@@ -105,6 +106,13 @@ def prepare_chunks(envelope, processing_profile, state, artifact_sha256):
|
||||
"""One boundary for worker staging and publication; faithful artifact stays whole."""
|
||||
if not factual_groups(envelope):
|
||||
return chunk_extraction(envelope, processing_profile)
|
||||
if not factual_review_required(processing_profile) and state.get("factual_inclusion") is None:
|
||||
groups = factual_groups(envelope)
|
||||
included = {group for group, blocks, _ in factual_context_units(envelope.blocks)
|
||||
if not any(PLACEHOLDER.search(b.text) for b in blocks) and group in groups}
|
||||
if not included:
|
||||
raise ExtractionError("No eligible factual groups")
|
||||
else:
|
||||
included = included_groups(envelope, state.get("factual_inclusion"), artifact_sha256)
|
||||
return chunk_extraction(envelope, processing_profile, corpus_purpose="approved_factual",
|
||||
included_group_ids=included)
|
||||
|
||||
@@ -59,6 +59,7 @@ class IngestionSettings(BaseSettings):
|
||||
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
|
||||
factual_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)
|
||||
@@ -213,6 +214,7 @@ class IngestionSettings(BaseSettings):
|
||||
"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,
|
||||
"factual_review_required": self.factual_review_required,
|
||||
"render_dpi": self.render_dpi,
|
||||
"max_rendered_page_pixels": self.max_rendered_page_pixels,
|
||||
"max_pdf_pages": self.max_pdf_pages,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Deployment configuration, independent of runtime limits and embedding profiles."""
|
||||
import ipaddress
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
from urllib.parse import urlsplit
|
||||
@@ -63,7 +64,17 @@ class VoiceSettings(BaseSettings):
|
||||
|
||||
@model_validator(mode='after')
|
||||
def cookie_policy(self):
|
||||
if not self.cookie_secure and any(urlsplit(o).hostname not in ('localhost', '127.0.0.1', '::1') for o in self.trusted_origins):
|
||||
for o in self.trusted_origins:
|
||||
h = urlsplit(o).hostname
|
||||
if not self.cookie_secure:
|
||||
is_local = h in ('localhost', '127.0.0.1', '::1')
|
||||
if not is_local and h:
|
||||
try:
|
||||
ip = ipaddress.ip_address(h)
|
||||
is_local = ip.is_loopback or ip.is_private
|
||||
except (ValueError, TypeError):
|
||||
is_local = False
|
||||
if not is_local:
|
||||
raise ValueError('Insecure cookies require loopback-only development origins')
|
||||
return self
|
||||
|
||||
|
||||
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+6
-3
@@ -29,8 +29,9 @@ services:
|
||||
- .env
|
||||
environment:
|
||||
- INGEST_DATABASE_URL=postgresql+psycopg://${POSTGRES_USER:-rag}:${POSTGRES_PASSWORD:-rag_password}@db:5432/${POSTGRES_DB:-rag}
|
||||
- INGEST_EMBEDDING_ENDPOINT=${INGEST_EMBEDDING_ENDPOINT:-http://host.docker.internal:11434/v1}
|
||||
- INGEST_EMBEDDING_ENDPOINT=${INGEST_EMBEDDING_ENDPOINT:-http://localhost:11434/v1}
|
||||
- INGEST_OCR_REVIEW_REQUIRED=${INGEST_OCR_REVIEW_REQUIRED:-true}
|
||||
- INGEST_FACTUAL_REVIEW_REQUIRED=${INGEST_FACTUAL_REVIEW_REQUIRED:-true}
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
depends_on:
|
||||
@@ -50,8 +51,9 @@ services:
|
||||
- .env
|
||||
environment:
|
||||
- INGEST_DATABASE_URL=postgresql+psycopg://${POSTGRES_USER:-rag}:${POSTGRES_PASSWORD:-rag_password}@db:5432/${POSTGRES_DB:-rag}
|
||||
- INGEST_EMBEDDING_ENDPOINT=${INGEST_EMBEDDING_ENDPOINT:-http://host.docker.internal:11434/v1}
|
||||
- INGEST_EMBEDDING_ENDPOINT=${INGEST_EMBEDDING_ENDPOINT:-http://localhost:11434/v1}
|
||||
- INGEST_OCR_REVIEW_REQUIRED=${INGEST_OCR_REVIEW_REQUIRED:-true}
|
||||
- INGEST_FACTUAL_REVIEW_REQUIRED=${INGEST_FACTUAL_REVIEW_REQUIRED:-true}
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
volumes:
|
||||
@@ -77,8 +79,9 @@ services:
|
||||
- .env
|
||||
environment:
|
||||
- INGEST_DATABASE_URL=postgresql+psycopg://${POSTGRES_USER:-rag}:${POSTGRES_PASSWORD:-rag_password}@db:5432/${POSTGRES_DB:-rag}
|
||||
- INGEST_EMBEDDING_ENDPOINT=${INGEST_EMBEDDING_ENDPOINT:-http://host.docker.internal:11434/v1}
|
||||
- INGEST_EMBEDDING_ENDPOINT=${INGEST_EMBEDDING_ENDPOINT:-http://localhost:11434/v1}
|
||||
- INGEST_OCR_REVIEW_REQUIRED=${INGEST_OCR_REVIEW_REQUIRED:-true}
|
||||
- INGEST_FACTUAL_REVIEW_REQUIRED=${INGEST_FACTUAL_REVIEW_REQUIRED:-true}
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
volumes:
|
||||
|
||||
@@ -4,7 +4,7 @@ from uuid import uuid4
|
||||
import pytest
|
||||
from app.modules.documents.extraction import PageBlockExtractor, ReviewRequired, ExtractionError
|
||||
from app.modules.documents.worker import validate_source
|
||||
from app.modules.documents.extraction_artifacts import ocr_review_required
|
||||
from app.modules.documents.extraction_artifacts import ocr_review_required, factual_review_required
|
||||
from app.modules.documents.review import prepare_chunks, FactualReviewRequired
|
||||
from tests.support.extraction import FakeVision, pdf_bytes
|
||||
from tests.support.formats import image_bytes
|
||||
@@ -90,3 +90,32 @@ def test_setting_defaults_and_enqueue_snapshot(settings, monkeypatch):
|
||||
monkeypatch.setenv('INGEST_OCR_REVIEW_REQUIRED', 'true')
|
||||
assert ocr_review_required(frozen) is False
|
||||
assert type(settings)(_env_file=None, **values).ocr_review_required is True
|
||||
|
||||
|
||||
def test_factual_review_policy_disabled_allows_chunking(settings):
|
||||
configured = settings.model_copy(update={'factual_review_required': False})
|
||||
frozen = configured.processing_profile()
|
||||
content = b'Question: fee?\nAnswer: 5%\n'
|
||||
envelope = PageBlockExtractor().extract_for_review(document_id=uuid4(), title='FAQ', original_sha256=hashlib.sha256(content).hexdigest(),
|
||||
content=content, mime_type='text/markdown', processing_profile=frozen)
|
||||
chunks = prepare_chunks(envelope, frozen, {}, 'a' * 64)
|
||||
assert len(chunks) > 0
|
||||
assert any('fee?' in c.text for c in chunks)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad', [None, 'false', 0, 1, []])
|
||||
def test_factual_invalid_snapshot_fails_closed(settings, bad):
|
||||
frozen = profile(settings, False); frozen['extraction']['factual_review_required'] = bad
|
||||
with pytest.raises(ValueError):
|
||||
factual_review_required(frozen)
|
||||
|
||||
|
||||
def test_factual_setting_defaults_and_enqueue_snapshot(settings, monkeypatch):
|
||||
assert settings.factual_review_required is True
|
||||
monkeypatch.setenv('INGEST_FACTUAL_REVIEW_REQUIRED', 'false')
|
||||
values = settings.model_dump(); values.pop('factual_review_required', None)
|
||||
configured = type(settings)(_env_file=None, **values)
|
||||
frozen = configured.processing_profile()
|
||||
monkeypatch.setenv('INGEST_FACTUAL_REVIEW_REQUIRED', 'true')
|
||||
assert factual_review_required(frozen) is False
|
||||
assert type(settings)(_env_file=None, **values).factual_review_required is True
|
||||
|
||||
Reference in New Issue
Block a user