silicore-knowledge 1.0.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.
Files changed (43) hide show
  1. silicore_knowledge/__init__.py +11 -0
  2. silicore_knowledge/api/__init__.py +4 -0
  3. silicore_knowledge/api/admin.py +263 -0
  4. silicore_knowledge/api/auth.py +106 -0
  5. silicore_knowledge/api/deps.py +21 -0
  6. silicore_knowledge/api/documents.py +131 -0
  7. silicore_knowledge/api/health.py +46 -0
  8. silicore_knowledge/api/search.py +138 -0
  9. silicore_knowledge/cli.py +488 -0
  10. silicore_knowledge/config.py +244 -0
  11. silicore_knowledge/corpus/__init__.py +4 -0
  12. silicore_knowledge/corpus/fetch.py +132 -0
  13. silicore_knowledge/corpus/manifest.py +126 -0
  14. silicore_knowledge/corpus/sync.py +303 -0
  15. silicore_knowledge/corpus/taxonomy.py +91 -0
  16. silicore_knowledge/evaluation.py +198 -0
  17. silicore_knowledge/ingestion/__init__.py +4 -0
  18. silicore_knowledge/ingestion/chunking.py +373 -0
  19. silicore_knowledge/ingestion/extract.py +251 -0
  20. silicore_knowledge/ingestion/importer.py +226 -0
  21. silicore_knowledge/ingestion/ocr.py +75 -0
  22. silicore_knowledge/ingestion/pipeline.py +421 -0
  23. silicore_knowledge/ingestion/screening.py +73 -0
  24. silicore_knowledge/ingestion/svd.py +365 -0
  25. silicore_knowledge/ingestion/tasks.py +142 -0
  26. silicore_knowledge/main.py +156 -0
  27. silicore_knowledge/retrieval/__init__.py +4 -0
  28. silicore_knowledge/retrieval/concepts.py +156 -0
  29. silicore_knowledge/retrieval/embeddings.py +163 -0
  30. silicore_knowledge/retrieval/hybrid.py +176 -0
  31. silicore_knowledge/retrieval/lexical_search.py +285 -0
  32. silicore_knowledge/retrieval/vector_store.py +287 -0
  33. silicore_knowledge/security.py +124 -0
  34. silicore_knowledge/services.py +75 -0
  35. silicore_knowledge/storage/__init__.py +4 -0
  36. silicore_knowledge/storage/catalog.py +656 -0
  37. silicore_knowledge/storage/models.py +140 -0
  38. silicore_knowledge/workspace.py +161 -0
  39. silicore_knowledge-1.0.0.dist-info/METADATA +305 -0
  40. silicore_knowledge-1.0.0.dist-info/RECORD +43 -0
  41. silicore_knowledge-1.0.0.dist-info/WHEEL +5 -0
  42. silicore_knowledge-1.0.0.dist-info/entry_points.txt +2 -0
  43. silicore_knowledge-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,11 @@
1
+ # SPDX-FileCopyrightText: 2026 H2Lab Development Team
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Local knowledge server for pyGdbToolkit."""
5
+
6
+ from importlib.metadata import PackageNotFoundError, version
7
+
8
+ try:
9
+ __version__ = version("silicore-knowledge")
10
+ except PackageNotFoundError: # running from a source tree that is not installed
11
+ __version__ = "0+unknown"
@@ -0,0 +1,4 @@
1
+ # SPDX-FileCopyrightText: 2026 H2Lab Development Team
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """HTTP API routes."""
@@ -0,0 +1,263 @@
1
+ # SPDX-FileCopyrightText: 2026 H2Lab Development Team
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Administration endpoints: document import and indexing task status (admin token only)."""
5
+
6
+ import hashlib
7
+ import logging
8
+ import os
9
+ import tempfile
10
+ from pathlib import Path
11
+ from typing import Annotated
12
+
13
+ from fastapi import APIRouter, Depends, HTTPException, Path as PathParam, Query, Request
14
+ from fastapi.concurrency import run_in_threadpool
15
+ from pydantic import BaseModel, ConfigDict, Field
16
+
17
+ from ..config import Settings
18
+ from ..ingestion.importer import DocumentMetadata, ImportResult, IngestError, import_pdf
19
+ from ..ingestion.pipeline import Indexer, IndexingError
20
+ from ..ingestion.tasks import TaskCapacityError, TaskInfo, TaskRegistry
21
+ from ..security import audit_logger
22
+ from ..storage.catalog import Catalog, CatalogError
23
+ from ..storage.models import ID_PATTERN, MAX_KEYWORDS, DocumentStatus, Keyword, SourceType
24
+ from ..workspace import Area, Workspace
25
+ from .deps import get_catalog, get_settings
26
+
27
+ logger = logging.getLogger("silicore_knowledge")
28
+
29
+ router = APIRouter(prefix="/admin")
30
+
31
+ _CHUNK = 1024 * 1024
32
+ _Text = Annotated[str | None, Field(default=None, max_length=300)]
33
+
34
+
35
+ class ImportMetadata(BaseModel):
36
+ """Operator-supplied provenance and classification of a document."""
37
+
38
+ model_config = ConfigDict(extra="forbid")
39
+
40
+ source_type: SourceType
41
+ title: _Text = None
42
+ manufacturer: _Text = None
43
+ device_family: _Text = None
44
+ device: _Text = None
45
+ document_type: _Text = None
46
+ revision: _Text = None
47
+ source_url: Annotated[str | None, Field(default=None, max_length=2000)] = None
48
+ keywords: tuple[Keyword, ...] = Field(default=(), max_length=MAX_KEYWORDS)
49
+
50
+ def to_metadata(self) -> DocumentMetadata:
51
+ """Convert to the importer's metadata."""
52
+ data = self.model_dump()
53
+ data["keywords"] = tuple(data["keywords"])
54
+ return DocumentMetadata(**data)
55
+
56
+
57
+ class PathImport(ImportMetadata):
58
+ """Import of a file located under one of the configured import directories."""
59
+
60
+ path: Annotated[str, Field(min_length=1, max_length=4096)]
61
+
62
+
63
+ class IngestAccepted(BaseModel):
64
+ """Answer of an import request."""
65
+
66
+ document_id: str
67
+ created: bool
68
+ status: DocumentStatus
69
+ task: TaskInfo | None
70
+
71
+
72
+ class ScreeningResult(BaseModel):
73
+ """Heuristic findings on a quarantined document."""
74
+
75
+ document_id: str
76
+ rules: tuple[str, ...]
77
+
78
+
79
+ def _tasks(request: Request) -> TaskRegistry:
80
+ tasks: TaskRegistry = request.app.state.tasks
81
+ return tasks
82
+
83
+
84
+ def _workspace(request: Request) -> Workspace:
85
+ workspace: Workspace = request.app.state.workspace
86
+ return workspace
87
+
88
+
89
+ def _submit(request: Request, document_id: str, *, release: bool = False) -> TaskInfo:
90
+ try:
91
+ return _tasks(request).submit(document_id, release=release)
92
+ except TaskCapacityError as exc:
93
+ raise HTTPException(status_code=429, detail="indexing task capacity reached") from exc
94
+
95
+
96
+ def _finish(
97
+ request: Request,
98
+ channel: str,
99
+ result: ImportResult,
100
+ ) -> IngestAccepted:
101
+ document = result.document
102
+ audit_logger.info(
103
+ "event=ingest channel=%s document_id=%s sha256=%s source_type=%s created=%s "
104
+ "request_id=%s",
105
+ channel,
106
+ document.document_id,
107
+ document.content_hash,
108
+ document.source_type.value,
109
+ result.created,
110
+ getattr(request.state, "request_id", "-"),
111
+ )
112
+ task = (
113
+ _submit(request, document.document_id) if document.status is DocumentStatus.ACTIVE else None
114
+ )
115
+ return IngestAccepted(
116
+ document_id=document.document_id, created=result.created, status=document.status, task=task
117
+ )
118
+
119
+
120
+ async def _import(
121
+ workspace: Workspace,
122
+ catalog: Catalog,
123
+ source: Path,
124
+ metadata: ImportMetadata,
125
+ max_bytes: int,
126
+ channel: str,
127
+ ) -> ImportResult:
128
+ try:
129
+ return await run_in_threadpool(
130
+ import_pdf, workspace, catalog, source, metadata.to_metadata(), max_bytes, channel
131
+ )
132
+ except IngestError as exc:
133
+ logger.warning("import rejected: %s", exc)
134
+ raise HTTPException(status_code=422, detail="file or metadata rejected") from exc
135
+ except CatalogError as exc:
136
+ logger.error("catalog error during import: %s", exc)
137
+ raise HTTPException(status_code=500, detail="internal server error") from exc
138
+
139
+
140
+ @router.post("/ingest", status_code=202, response_model=IngestAccepted)
141
+ async def ingest_upload(
142
+ request: Request,
143
+ metadata: Annotated[ImportMetadata, Query()],
144
+ settings: Annotated[Settings, Depends(get_settings)],
145
+ catalog: Annotated[Catalog, Depends(get_catalog)],
146
+ ) -> IngestAccepted:
147
+ """Import a PDF sent as the raw request body into quarantine.
148
+
149
+ Metadata travels in the query string; the body is the PDF itself (streamed to disk and
150
+ bounded by ``limits.max_upload_bytes``).
151
+ """
152
+ limit = settings.limits.max_upload_bytes
153
+ declared = request.headers.get("content-length")
154
+ if declared is not None and declared.isdigit() and int(declared) > limit:
155
+ raise HTTPException(status_code=413, detail="upload too large")
156
+ workspace = _workspace(request)
157
+ fd, name = tempfile.mkstemp(dir=workspace.area(Area.TMP), suffix=".upload")
158
+ tmp = Path(name)
159
+ try:
160
+ total = 0
161
+ with os.fdopen(fd, "wb") as out:
162
+ async for block in request.stream():
163
+ total += len(block)
164
+ if total > limit:
165
+ raise HTTPException(status_code=413, detail="upload too large")
166
+ out.write(block)
167
+ if total == 0:
168
+ raise HTTPException(status_code=422, detail="empty upload")
169
+ result = await _import(workspace, catalog, tmp, metadata, limit, "upload")
170
+ finally:
171
+ tmp.unlink(missing_ok=True)
172
+ return _finish(request, "upload", result)
173
+
174
+
175
+ @router.post("/ingest/path", status_code=202, response_model=IngestAccepted)
176
+ async def ingest_path(
177
+ request: Request,
178
+ body: PathImport,
179
+ settings: Annotated[Settings, Depends(get_settings)],
180
+ catalog: Annotated[Catalog, Depends(get_catalog)],
181
+ ) -> IngestAccepted:
182
+ """Import a server-side PDF located under an allowed import directory."""
183
+ try:
184
+ source = Path(body.path).resolve(strict=True)
185
+ except (OSError, RuntimeError, ValueError) as exc:
186
+ raise HTTPException(status_code=422, detail="file or metadata rejected") from exc
187
+ allowed = [directory.resolve() for directory in settings.ingestion.import_dirs]
188
+ if not any(source.is_relative_to(directory) for directory in allowed):
189
+ audit_logger.warning(
190
+ "event=ingest_refused reason=path_not_allowed path_sha=%s",
191
+ hashlib.sha256(body.path.encode()).hexdigest()[:12],
192
+ )
193
+ raise HTTPException(status_code=403, detail="path not allowed")
194
+ metadata = ImportMetadata.model_validate(body.model_dump(exclude={"path"}))
195
+ result = await _import(
196
+ _workspace(request), catalog, source, metadata, settings.limits.max_upload_bytes, "path"
197
+ )
198
+ return _finish(request, "path", result)
199
+
200
+
201
+ @router.post("/documents/{document_id}/screen", response_model=ScreeningResult)
202
+ async def screen_document(
203
+ request: Request,
204
+ document_id: Annotated[str, PathParam(pattern=ID_PATTERN)],
205
+ ) -> ScreeningResult:
206
+ """Screen a quarantined document for review without releasing it."""
207
+ indexer: Indexer = request.app.state.indexer
208
+ try:
209
+ rules = await run_in_threadpool(indexer.inspect, document_id)
210
+ except IndexingError as exc:
211
+ logger.warning("screening failed: %s", exc)
212
+ raise HTTPException(status_code=422, detail="document cannot be screened") from exc
213
+ return ScreeningResult(document_id=document_id, rules=rules)
214
+
215
+
216
+ @router.post("/documents/{document_id}/release", status_code=202, response_model=TaskInfo)
217
+ def release_document(
218
+ request: Request,
219
+ document_id: Annotated[str, PathParam(pattern=ID_PATTERN)],
220
+ ) -> TaskInfo:
221
+ """Approve a reviewed quarantined document and queue indexing."""
222
+ catalog: Catalog = request.app.state.catalog
223
+ document = catalog.get_document(document_id)
224
+ if document is None:
225
+ raise HTTPException(status_code=404, detail="document not found")
226
+ if document.status is not DocumentStatus.QUARANTINED:
227
+ raise HTTPException(status_code=409, detail="document is not quarantined")
228
+ task = _submit(request, document_id, release=True)
229
+ audit_logger.info(
230
+ "event=release_queued request_id=%s task_id=%s document_id=%s",
231
+ getattr(request.state, "request_id", "-"),
232
+ task.task_id,
233
+ document_id,
234
+ )
235
+ return task
236
+
237
+
238
+ @router.delete("/documents/{document_id}", status_code=204)
239
+ def delete_document(
240
+ request: Request,
241
+ document_id: Annotated[str, PathParam(pattern=ID_PATTERN)],
242
+ ) -> None:
243
+ """Remove a document with its file, passages and vectors."""
244
+ indexer: Indexer = request.app.state.indexer
245
+ try:
246
+ removed = indexer.delete_document(document_id)
247
+ except IndexingError as exc:
248
+ logger.error("deletion failed: %s", exc)
249
+ raise HTTPException(status_code=500, detail="deletion failed") from exc
250
+ if not removed:
251
+ raise HTTPException(status_code=404, detail="document not found")
252
+
253
+
254
+ @router.get("/tasks/{task_id}", response_model=TaskInfo)
255
+ def task_status(
256
+ request: Request,
257
+ task_id: Annotated[str, PathParam(pattern=r"^[0-9a-f]{32}$")],
258
+ ) -> TaskInfo:
259
+ """Return the status of an indexing task."""
260
+ info = _tasks(request).get(task_id)
261
+ if info is None:
262
+ raise HTTPException(status_code=404, detail="task not found")
263
+ return info
@@ -0,0 +1,106 @@
1
+ # SPDX-FileCopyrightText: 2026 H2Lab Development Team
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Bearer-token authentication with separate read and admin credentials (ANSSI R20, R21)."""
5
+
6
+ import hmac
7
+ from dataclasses import dataclass
8
+ from enum import StrEnum, auto, unique
9
+ from typing import Annotated
10
+
11
+ from fastapi import Depends, HTTPException, Request
12
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
13
+
14
+ from ..config import Settings
15
+ from ..security import audit_logger
16
+ from .deps import get_settings
17
+
18
+ _bearer = HTTPBearer(auto_error=False)
19
+
20
+
21
+ @unique
22
+ class Role(StrEnum):
23
+ """Privilege level of a caller."""
24
+
25
+ READ = auto()
26
+ ADMIN = auto()
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class Principal:
31
+ """Authenticated identity and its server-side document grants."""
32
+
33
+ name: str
34
+ role: Role
35
+ allowed_document_ids: tuple[str, ...] | None
36
+
37
+ def allows(self, document_id: str) -> bool:
38
+ """Return whether this identity can read a document."""
39
+ return self.allowed_document_ids is None or document_id in self.allowed_document_ids
40
+
41
+
42
+ def _matches(supplied: str, expected: str) -> bool:
43
+ return hmac.compare_digest(supplied.encode(), expected.encode())
44
+
45
+
46
+ def _identify(
47
+ settings: Settings, credentials: HTTPAuthorizationCredentials | None
48
+ ) -> Principal | None:
49
+ """Return the caller identity, or None if credentials are invalid."""
50
+ auth = settings.auth
51
+ if credentials is not None:
52
+ if auth.admin_token is not None and _matches(
53
+ credentials.credentials, auth.admin_token.get_secret_value()
54
+ ):
55
+ return Principal("admin", Role.ADMIN, None)
56
+ for name, principal in auth.principals.items():
57
+ if _matches(credentials.credentials, principal.token.get_secret_value()):
58
+ grants = principal.allowed_documents
59
+ return Principal(name, Role.READ, None if grants == ("*",) else grants)
60
+ return None
61
+ return None
62
+
63
+
64
+ def _authorize(request: Request, principal: Principal | None, needed: Role) -> Principal:
65
+ allowed = principal is not None and (
66
+ principal.role is Role.ADMIN or (principal.role is Role.READ and needed is Role.READ)
67
+ )
68
+ client = request.client.host if request.client else "-"
69
+ audit_logger.log(
70
+ 20 if allowed else 30,
71
+ "event=auth decision=%s needed=%s role=%s identity=%s request_id=%s client=%s method=%s path=%s",
72
+ "allow" if allowed else "deny",
73
+ needed.value,
74
+ principal.role.value if principal else "invalid",
75
+ principal.name if principal else "-",
76
+ getattr(request.state, "request_id", "-"),
77
+ client,
78
+ request.method,
79
+ request.url.path,
80
+ )
81
+ if not allowed or principal is None:
82
+ # Same answer for a missing, wrong or under-privileged token.
83
+ raise HTTPException(
84
+ status_code=401,
85
+ detail="authentication required",
86
+ headers={"WWW-Authenticate": "Bearer"},
87
+ )
88
+ return principal
89
+
90
+
91
+ def require_read(
92
+ request: Request,
93
+ settings: Annotated[Settings, Depends(get_settings)],
94
+ credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(_bearer)],
95
+ ) -> Principal:
96
+ """Allow an authenticated read or admin identity."""
97
+ return _authorize(request, _identify(settings, credentials), Role.READ)
98
+
99
+
100
+ def require_admin(
101
+ request: Request,
102
+ settings: Annotated[Settings, Depends(get_settings)],
103
+ credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(_bearer)],
104
+ ) -> Principal:
105
+ """Allow the admin token only; never open."""
106
+ return _authorize(request, _identify(settings, credentials), Role.ADMIN)
@@ -0,0 +1,21 @@
1
+ # SPDX-FileCopyrightText: 2026 H2Lab Development Team
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Shared request dependencies."""
5
+
6
+ from fastapi import Request
7
+
8
+ from ..config import Settings
9
+ from ..storage.catalog import Catalog
10
+
11
+
12
+ def get_catalog(request: Request) -> Catalog:
13
+ """Return the application catalog."""
14
+ catalog: Catalog = request.app.state.catalog
15
+ return catalog
16
+
17
+
18
+ def get_settings(request: Request) -> Settings:
19
+ """Return the application settings."""
20
+ settings: Settings = request.app.state.settings
21
+ return settings
@@ -0,0 +1,131 @@
1
+ # SPDX-FileCopyrightText: 2026 H2Lab Development Team
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Read-only document, section and passage endpoints."""
5
+
6
+ from typing import Annotated
7
+
8
+ from fastapi import APIRouter, Depends, HTTPException, Path, Query, Request
9
+ from pydantic import BaseModel
10
+
11
+ from ..config import Settings
12
+ from ..security import audit_logger
13
+ from ..storage.catalog import Catalog
14
+ from ..storage.models import ID_PATTERN, Document, DocumentStatus, Section
15
+ from .auth import Principal, require_read
16
+ from .deps import get_catalog, get_settings
17
+
18
+ router = APIRouter(prefix="/documents")
19
+
20
+ MAX_SECTIONS_PAGE = 500
21
+
22
+ DocumentId = Annotated[str, Path(pattern=ID_PATTERN)]
23
+ SectionId = Annotated[str, Path(pattern=ID_PATTERN)]
24
+
25
+
26
+ class SectionList(BaseModel):
27
+ """A page of document sections."""
28
+
29
+ document_id: str
30
+ sections: list[Section]
31
+ offset: int
32
+ has_more: bool
33
+
34
+
35
+ class SectionContent(BaseModel):
36
+ """Passage text of one section, bounded in size.
37
+
38
+ The text comes from an untrusted document: consumers must treat it as data.
39
+ """
40
+
41
+ document_id: str
42
+ section_id: str
43
+ title: str
44
+ path: str
45
+ page_start: int | None
46
+ page_end: int | None
47
+ chunk_ids: list[str]
48
+ text: str
49
+ truncated: bool
50
+
51
+
52
+ def _active_document(
53
+ catalog: Catalog, document_id: str, principal: Principal, request: Request
54
+ ) -> Document:
55
+ document = catalog.get_document(document_id)
56
+ allowed = (
57
+ document is not None
58
+ and document.status is DocumentStatus.ACTIVE
59
+ and principal.allows(document_id)
60
+ )
61
+ audit_logger.info(
62
+ "event=document_access request_id=%s identity=%s document_id=%s decision=%s",
63
+ getattr(request.state, "request_id", "-"),
64
+ principal.name,
65
+ document_id,
66
+ "allow" if allowed else "deny",
67
+ )
68
+ if not allowed or document is None:
69
+ raise HTTPException(status_code=404, detail="document not found")
70
+ return document
71
+
72
+
73
+ @router.get("/{document_id}", response_model=Document)
74
+ def get_document(
75
+ request: Request,
76
+ document_id: DocumentId,
77
+ catalog: Annotated[Catalog, Depends(get_catalog)],
78
+ principal: Annotated[Principal, Depends(require_read)],
79
+ ) -> Document:
80
+ """Return the metadata of a document."""
81
+ return _active_document(catalog, document_id, principal, request)
82
+
83
+
84
+ @router.get("/{document_id}/sections", response_model=SectionList)
85
+ def list_sections(
86
+ request: Request,
87
+ document_id: DocumentId,
88
+ catalog: Annotated[Catalog, Depends(get_catalog)],
89
+ principal: Annotated[Principal, Depends(require_read)],
90
+ limit: Annotated[int, Query(ge=1, le=MAX_SECTIONS_PAGE)] = 100,
91
+ offset: Annotated[int, Query(ge=0)] = 0,
92
+ ) -> SectionList:
93
+ """Return a page of the sections of a document, in reading order."""
94
+ _active_document(catalog, document_id, principal, request)
95
+ page = catalog.list_sections(document_id, limit=limit + 1, offset=offset)
96
+ return SectionList(
97
+ document_id=document_id,
98
+ sections=page[:limit],
99
+ offset=offset,
100
+ has_more=len(page) > limit,
101
+ )
102
+
103
+
104
+ @router.get("/{document_id}/section/{section_id}", response_model=SectionContent)
105
+ def get_section(
106
+ request: Request,
107
+ document_id: DocumentId,
108
+ section_id: SectionId,
109
+ catalog: Annotated[Catalog, Depends(get_catalog)],
110
+ settings: Annotated[Settings, Depends(get_settings)],
111
+ principal: Annotated[Principal, Depends(require_read)],
112
+ ) -> SectionContent:
113
+ """Return the text of a section, truncated to the configured size limit."""
114
+ _active_document(catalog, document_id, principal, request)
115
+ section = catalog.get_section(document_id, section_id)
116
+ if section is None:
117
+ raise HTTPException(status_code=404, detail="section not found")
118
+ chunks = catalog.section_chunks(document_id, section_id)
119
+ text = "\n\n".join(chunk.text for chunk in chunks)
120
+ limit = settings.limits.max_text_chars
121
+ return SectionContent(
122
+ document_id=document_id,
123
+ section_id=section_id,
124
+ title=section.title,
125
+ path=section.path,
126
+ page_start=section.page_start,
127
+ page_end=section.page_end,
128
+ chunk_ids=[chunk.chunk_id for chunk in chunks],
129
+ text=text[:limit],
130
+ truncated=len(text) > limit,
131
+ )
@@ -0,0 +1,46 @@
1
+ # SPDX-FileCopyrightText: 2026 H2Lab Development Team
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Health and statistics endpoints."""
5
+
6
+ from typing import Annotated
7
+
8
+ from fastapi import APIRouter, Depends
9
+ from pydantic import BaseModel
10
+
11
+ from .. import __version__
12
+ from ..storage.catalog import Catalog
13
+ from ..storage.models import CatalogStats
14
+ from .auth import Principal, Role, require_read
15
+ from .deps import get_catalog
16
+
17
+ router = APIRouter()
18
+ stats_router = APIRouter()
19
+
20
+
21
+ class HealthResponse(BaseModel):
22
+ """Service health report."""
23
+
24
+ status: str
25
+ version: str
26
+
27
+
28
+ @router.get("/health", response_model=HealthResponse)
29
+ def health() -> HealthResponse:
30
+ """Report that the service is up.
31
+
32
+ Returns
33
+ -------
34
+ HealthResponse
35
+ Status and service version; no corpus or configuration detail is disclosed.
36
+ """
37
+ return HealthResponse(status="ok", version=__version__)
38
+
39
+
40
+ @stats_router.get("/stats", response_model=CatalogStats)
41
+ def stats(
42
+ catalog: Annotated[Catalog, Depends(get_catalog)],
43
+ principal: Annotated[Principal, Depends(require_read)],
44
+ ) -> CatalogStats:
45
+ """Return catalog counters (schema version, documents, sections, chunks)."""
46
+ return catalog.stats(principal.allowed_document_ids, active_only=principal.role is Role.READ)