Spaces:
Sleeping
Sleeping
| from __future__ import annotations | |
| from fastapi import APIRouter, Depends, HTTPException | |
| from api.common.logging import log_json, setup_logging | |
| from api.common.deps import get_request_id, get_registry, get_store | |
| from api.label_sets.schemas import ActivateResponse, LabelSet, LabelSetCreateResponse, LabelSetInfo | |
| logger = setup_logging() | |
| router = APIRouter(prefix="/api/v1/label-sets", tags=["label-sets"]) | |
| def create_label_set( | |
| payload: LabelSet, | |
| request_id: str = Depends(get_request_id), | |
| store=Depends(get_store), | |
| registry=Depends(get_registry), | |
| ) -> LabelSetCreateResponse: | |
| bank = store.build_bank(payload) | |
| registry.upsert(bank) | |
| label_count = sum(len(b.ids) for b in bank.labels_by_domain.values()) | |
| is_default = registry.default_hash == bank.label_set_hash | |
| log_json( | |
| logger, | |
| event="label_sets.upsert", | |
| request_id=request_id, | |
| label_set_hash=bank.label_set_hash, | |
| name=bank.name, | |
| domain_count=len(bank.domains.ids), | |
| label_count=label_count, | |
| is_default=is_default, | |
| ) | |
| return LabelSetCreateResponse( | |
| label_set_hash=bank.label_set_hash, | |
| name=bank.name, | |
| domain_count=len(bank.domains.ids), | |
| label_count=label_count, | |
| is_default=is_default, | |
| ) | |
| def list_label_sets( | |
| request_id: str = Depends(get_request_id), | |
| registry=Depends(get_registry), | |
| ) -> list[LabelSetInfo]: | |
| out: list[LabelSetInfo] = [] | |
| for bank in registry.banks.values(): | |
| label_count = sum(len(b.ids) for b in bank.labels_by_domain.values()) | |
| out.append( | |
| LabelSetInfo( | |
| label_set_hash=bank.label_set_hash, | |
| name=bank.name, | |
| domain_count=len(bank.domains.ids), | |
| label_count=label_count, | |
| is_default=(registry.default_hash == bank.label_set_hash), | |
| ) | |
| ) | |
| log_json(logger, event="label_sets.list", request_id=request_id, count=len(out)) | |
| return out | |
| def activate_label_set( | |
| label_set_hash: str, | |
| request_id: str = Depends(get_request_id), | |
| registry=Depends(get_registry), | |
| ) -> ActivateResponse: | |
| try: | |
| registry.activate(label_set_hash) | |
| except KeyError: | |
| raise HTTPException(status_code=404, detail="Unknown label_set_hash") | |
| log_json(logger, event="label_sets.activate", request_id=request_id, default_label_set_hash=label_set_hash) | |
| return ActivateResponse(default_label_set_hash=label_set_hash) | |