feat(backend): deliver Phase 3 document and voice integration
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.
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
"""K01/K02 and read-only F01, with backend-owned organization scope."""
|
||||
from uuid import UUID
|
||||
from app.infrastructure.blocking import blocking
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from app.api.v1.dependencies import (get_engine, get_current_user, get_ingestion_settings,
|
||||
get_voice_settings, require_admin, require_csrf, error,
|
||||
MAX_SELECTION_BYTES, JSON_RECEIVE_SECONDS, receive_json)
|
||||
from app.modules.knowledge.service import selection_get, selection_replace, authority, transaction, KnowledgeError
|
||||
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'])
|
||||
|
||||
|
||||
class SelectionRequest(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
expected_revision: int = Field(ge=1, strict=True)
|
||||
document_ids: list[UUID] = Field(max_length=10000)
|
||||
|
||||
|
||||
@router.get('/knowledge-selection')
|
||||
def selection(user=Depends(require_admin), engine=Depends(get_engine)):
|
||||
try:
|
||||
return selection_get(engine, user.id)
|
||||
except KnowledgeError as exc:
|
||||
raise error(exc.code) from None
|
||||
|
||||
|
||||
@router.patch('/knowledge-selection', 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:
|
||||
return await blocking(selection_replace, engine, user.id, payload.expected_revision, payload.document_ids)
|
||||
except KnowledgeError as exc:
|
||||
failure = error(exc.code)
|
||||
if exc.details:
|
||||
failure.detail['details'] = exc.details
|
||||
raise failure from None
|
||||
except TimeoutError:
|
||||
raise error('DEPENDENCY_UNAVAILABLE') from None
|
||||
except ValueError as exc:
|
||||
raise error(str(exc)) from None
|
||||
|
||||
|
||||
@router.get('/configuration')
|
||||
def configuration(user=Depends(get_current_user), engine=Depends(get_engine),
|
||||
ingest=Depends(get_ingestion_settings), voice=Depends(get_voice_settings)):
|
||||
try:
|
||||
with transaction(engine) as conn:
|
||||
_, settings = authority(conn, user.id)
|
||||
except KnowledgeError as exc:
|
||||
raise error(exc.code) from None
|
||||
# Configuration is availability evidence, not real-provider quality certification.
|
||||
available = False
|
||||
calibration_status = "uncalibrated"
|
||||
try:
|
||||
voice.require_voice()
|
||||
ingest.require_embedding_credentials()
|
||||
with engine.connect() as conn:
|
||||
check_compatibility(conn, ingest.embedding_profile, require_worker=True)
|
||||
if voice.search_calibration_report is not None:
|
||||
import json
|
||||
cutoff = load_cutoff(json.loads(voice.search_calibration_report.read_text(encoding='utf-8')))
|
||||
available = (cutoff.profile == ingest.processing_profile()['embedding']
|
||||
and cutoff.retrieval_policy == RETRIEVAL_POLICY)
|
||||
if available:
|
||||
calibration_status = 'calibrated'
|
||||
except (ValueError, OSError, KeyError, TypeError, AttributeError, CompatibilityError):
|
||||
pass
|
||||
if voice.voice_transport_testing and calibration_status != "calibrated":
|
||||
try:
|
||||
voice.require_voice()
|
||||
ingest.require_embedding_credentials()
|
||||
with engine.connect() as conn:
|
||||
check_compatibility(conn, ingest.embedding_profile, require_worker=True)
|
||||
from app.worker import factories
|
||||
_, provider_factory = factories(ingest)
|
||||
provider_factory(ingest.processing_profile()) # validation only; no inference
|
||||
available = True
|
||||
except (ValueError, CompatibilityError):
|
||||
pass
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
limits = RuntimeSettings()
|
||||
mime_types = {'.pdf': 'application/pdf', '.md': 'text/markdown',
|
||||
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png'}
|
||||
return dict(revision=settings['revision'], assistant_name=settings['assistant_name'], instruction=settings['instruction'],
|
||||
capabilities=dict(text=False, voice=available, captions=available,
|
||||
calibration_status=calibration_status, voice_transport_testing=voice.voice_transport_testing,
|
||||
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,
|
||||
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,
|
||||
max_client_control_bytes=limits.max_client_control_bytes))
|
||||
Reference in New Issue
Block a user