"""Transfer trained EEG baselines between registries.""" import hashlib import shutil from pathlib import Path from tempfile import NamedTemporaryFile from typing import BinaryIO from zipfile import BadZipFile from models.tea.eeg import bundle from models.tea.eeg.bundle import BundleError from models.tea.eeg.settings import settings class BaselineConflict(BundleError): """Every baseline in the bundle already exists in the registry.""" class BaselineBundles: """Export and register bundles using the configured EEG scenarios.""" def export(self, path: Path, *, environment: str, production: bool) -> bundle.Exported: return bundle.export(settings(), path, environment=environment.upper(), production=production) def import_(self, stream: BinaryIO) -> dict: config = settings() with NamedTemporaryFile(suffix=".zip") as upload: shutil.copyfileobj(stream, upload, length=1024 * 1024) upload.flush() upload.seek(0) sha256 = hashlib.file_digest(upload, "sha256").hexdigest() try: versions = bundle.import_(config, upload.name) except (BadZipFile, KeyError, TypeError, AttributeError, FileNotFoundError) as error: raise BundleError(f"Paquete de baselines inválido: {error}") from error imported = [ {"scenario": scenario, "version": int(version)} for scenario, (version, new) in versions.items() if new ] if versions and not imported: existing = ", ".join(f"{scenario}: {version}" for scenario, (version, _) in versions.items()) raise BaselineConflict(f"Las versiones ya están registradas: {existing}") return {"sha256": sha256, "imported": imported}