Files
models/models/base.py
T

42 lines
1.6 KiB
Python

import importlib
from abc import ABC, abstractmethod
from typing import Any, ClassVar, Iterator
from persistance.repository import Repository
def resolve_repository(domain: str, entity: str) -> Repository:
"""`entity` is the repository's name in `persistance.<domain>` without
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
module = importlib.import_module(f"persistance.{domain}")
try:
return getattr(module, f"{entity}_repository")
except AttributeError as exc:
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
class ScreeningModel(ABC):
"""Common train()/predict() interface for the CaCu, CaMa and TEA models.
Data is read through the same `persistance.<domain>.<entity>_repository`
objects WebApi writes with, so anything loaded through the import flow
is visible here. `train` may also be given rows fetched by the caller.
"""
domain: ClassVar[str]
def repository(self, entity: str) -> Repository:
return resolve_repository(self.domain, entity)
def dataset(self, entity: str, *, batch_size: int = 500, **filters) -> Iterator[dict[str, Any]]:
"""Every row of `entity` as plain dicts, read in batches."""
return (row.model_dump() for row in self.repository(entity).iter_all(batch_size=batch_size, **filters))
@abstractmethod
def train(self, data: Any = None) -> None:
"""Fit the model, optionally on `data` passed in by the caller."""
@abstractmethod
def predict(self, data: Any) -> Any:
"""Score `data` and return predictions."""