import { DatePipe, DecimalPipe, KeyValuePipe } from '@angular/common'; import { Component, computed, effect, inject, input, resource, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { RouterLink } from '@angular/router'; import { Api } from '../api/api'; import { studies } from '../api/fn/eeg/studies'; import { study } from '../api/fn/eeg/study'; import { addClinicalValidation } from '../api/fn/models/add-clinical-validation'; import { analyze } from '../api/fn/models/analyze'; import { curve } from '../api/fn/models/curve'; import { lineage } from '../api/fn/models/lineage'; import { models } from '../api/fn/models/models'; import { promote } from '../api/fn/models/promote'; import { readReport$Any } from '../api/fn/models/read-report-any'; import { readReport$Json } from '../api/fn/models/read-report-json'; import { retire } from '../api/fn/models/retire'; import { score } from '../api/fn/models/score'; import { versionChecks } from '../api/fn/models/version-checks'; import { versions } from '../api/fn/models/versions'; import { domains } from '../api/fn/operations/domains'; import type { Domain } from '../api/models/domain'; import type { Execution as Choice } from '../api/models/execution'; import type { Run } from '../api/models/run'; import { DOMAINS } from '../app'; import { Plot } from '../plot'; import { Bundles, download } from './bundles'; import { Execution } from './execution'; import { interpretabilityFigures, studyPoints, type Centile } from './figures'; import { errorText, RunMonitor } from './run-monitor'; import { EegStudies } from './tea/studies'; import { Training } from './training'; const REPORTS: Record = { technical_validation: 'Validación técnica', interpretability: 'Interpretabilidad', clinical_validation: 'Validación clínica', }; interface VersionKey { name: string; version: number; } interface Checks { status: 'candidate' | 'champion' | 'retired'; promotable: boolean; checks: { report: string; present: boolean }[]; } interface Lineage { params: Record; metrics: Record; tags: Record; imported: Record | null; } export function checkActions(checks: Checks) { return { promote: checks.promotable, retire: checks.status !== 'champion' }; } @Component({ selector: 'app-gobernanza', imports: [ DatePipe, DecimalPipe, KeyValuePipe, FormsModule, MatButtonModule, RouterLink, Plot, Bundles, Execution, RunMonitor, EegStudies, Training, ], templateUrl: './gobernanza.html', styleUrl: './gobernanza.scss', }) export class Gobernanza { private readonly api = inject(Api); readonly domain = input.required(); protected readonly domainKey = computed(() => this.domain() as Domain); protected readonly execution = signal(undefined); protected readonly labels = DOMAINS as Record; protected readonly reportNames = REPORTS; protected readonly errorText = errorText; protected readonly domains = resource({ loader: () => this.api.invoke(domains) }); protected readonly refreshed = signal(0); protected refresh(): void { this.refreshed.update((value) => value + 1); } protected readonly models = resource({ params: () => ({ domain: this.domainKey(), at: this.refreshed() }), loader: async ({ params: { domain } }) => { const found = await this.api.invoke(models, { domain }); return Promise.all( found.map(async ({ name, title }) => ({ name, title, versions: await this.api.invoke(versions, { domain, name }), })), ); }, }); protected readonly training = signal(''); protected readonly run = signal<{ id: string; label: string; autoPromote?: boolean } | undefined>( undefined, ); protected readonly starting = signal(false); protected readonly running = signal(false); protected readonly editing = signal(false); protected readonly message = signal(''); protected readonly chosen = signal(undefined); protected readonly checksFor = signal(undefined); protected readonly lineageFor = signal(undefined); protected readonly checks = resource({ params: () => { const key = this.checksFor(); return key ? { ...key, domain: this.domainKey(), at: this.refreshed() } : undefined; }, loader: async ({ params: { at, ...params } }) => this.getChecks(params.domain, params), }); protected readonly checkActions = checkActions; protected readonly lineage = resource({ params: () => { const key = this.lineageFor(); return key ? { ...key, domain: this.domainKey() } : undefined; }, loader: async ({ params }) => (await this.api.invoke(lineage, params)) as Lineage, }); protected readonly candidates = signal([]); protected readonly report = resource({ params: () => { const key = this.chosen(); return key ? { ...key, domain: this.domainKey() } : undefined; }, loader: ({ params }) => this.api.invoke(readReport$Json, { ...params, report: 'interpretability' }), }); protected readonly ageFeatures = computed(() => { const report = this.report.hasValue() ? this.report.value() : undefined; return report?.kind === 'age_curves' ? Object.keys(report['curves']) : []; }); protected readonly selectedFeature = signal(''); protected readonly feature = computed(() => { const keys = this.ageFeatures(); return keys.includes(this.selectedFeature()) ? this.selectedFeature() : keys.includes('value') ? 'value' : keys[0]; }); protected readonly band = resource({ params: () => { const key = this.chosen(); const feature = this.feature(); if (!key || !feature || !this.report.hasValue()) return undefined; if (this.report.value()['curves'][feature].kind === 'count_rate') return undefined; return { ...key, domain: this.domainKey(), feature }; }, loader: async ({ params }) => (await this.api.invoke(curve, params)) as Centile[], }); protected readonly overlay = signal(false); protected readonly analysed = resource({ params: () => this.overlay() && this.domainKey() === 'tea' && this.feature() ? this.refreshed() + 1 : undefined, loader: async () => { const found = await this.api.invoke(studies); return Promise.all( found .filter((entry) => entry.analysed) .map(({ id }) => this.api.invoke(study, { eeg_id: id })), ); }, }); protected readonly figures = computed(() => { if (!this.report.hasValue()) return []; const report = this.report.value(); const feature = this.feature(); const points = this.analysed.hasValue() && feature ? studyPoints(this.analysed.value(), report['model'], feature) : []; return interpretabilityFigures(report, { feature, centiles: this.band.hasValue() ? this.band.value() : undefined, points, waitForCentiles: report['kind'] === 'age_curves', }); }); constructor() { effect(() => { this.domain(); this.training.set(''); this.run.set(undefined); this.running.set(false); this.starting.set(false); this.editing.set(false); this.message.set(''); this.chosen.set(undefined); this.checksFor.set(undefined); this.lineageFor.set(undefined); this.overlay.set(false); }); } protected async reportDownload(name: string, version: number, report: string): Promise { try { const response = await this.api.invoke$Response(readReport$Any, { domain: this.domainKey(), name, version, report, }); const filename = /filename="([^"]+)"/.exec( response.headers.get('Content-Disposition') ?? '', )?.[1]; download(response.body, filename ?? report); } catch (error) { this.message.set(errorText(error)); } } protected async upload(name: string, version: number, event: Event): Promise { const input = event.target as HTMLInputElement; const file = input.files?.[0]; if (!file) return; const domain = this.domainKey(); try { await this.api.invoke(addClinicalValidation, { domain, name, version, body: { file: file as unknown as string }, }); input.value = ''; if (domain !== this.domainKey()) return; this.message.set(`Validación clínica agregada a ${name} v${version}.`); this.refresh(); } catch (error) { this.message.set(errorText(error)); } } protected showVersion( kind: 'checks' | 'lineage', key: VersionKey, dialog: HTMLDialogElement, ): void { (kind === 'checks' ? this.checksFor : this.lineageFor).set(key); dialog.showModal(); } protected async changeVersion(key: VersionKey, action: 'promote' | 'retire'): Promise { const domain = this.domainKey(); this.editing.set(true); this.message.set(''); try { if (action === 'promote') await this.api.invoke(promote, { domain, ...key }); else await this.api.invoke(retire, { domain, ...key }); this.message.set( `${key.name} v${key.version}: ${action === 'promote' ? 'en producción' : 'retirada'}.`, ); this.refresh(); } catch (error) { this.message.set(errorText(error)); } finally { this.editing.set(false); } } protected async prepareCandidates(dialog: HTMLDialogElement): Promise { if (!this.models.hasValue()) return; const domain = this.domainKey(); this.editing.set(true); this.message.set(''); try { const latest = this.models.value().flatMap(({ name, versions }) => { const newest = versions.reduce<(typeof versions)[number] | undefined>( (current, version) => (!current || version.version > current.version ? version : current), undefined, ); return newest?.status === 'candidate' ? [{ name, version: newest.version }] : []; }); const allowed = await Promise.all( latest.map(async (key) => (await this.getChecks(domain, key)).promotable), ); if (domain !== this.domainKey()) return; const found = latest.filter((_, index) => allowed[index]); this.candidates.set(found); if (found.length) dialog.showModal(); else this.message.set('No hay candidatas que se puedan promover.'); } catch (error) { this.message.set(errorText(error)); } finally { this.editing.set(false); } } protected async promoteCandidates(dialog: HTMLDialogElement): Promise { this.editing.set(true); this.message.set(''); try { await this.promoteVersions(this.domainKey(), this.candidates()); dialog.close(); } finally { this.editing.set(false); } } protected forestHeight(rows: number): number { return Math.max(360, rows * 24 + 72); } protected chooseReport(key: VersionKey): void { this.overlay.set(false); this.selectedFeature.set(''); this.chosen.set(key); } protected follow(id: string, label: string, autoPromote = false): void { this.message.set(''); this.run.set({ id, label, autoPromote }); this.running.set(true); } protected async start(kind: 'score' | 'analyze'): Promise { const domain = this.domainKey(); this.starting.set(true); this.message.set(''); try { const { run_id } = kind === 'score' ? await this.api.invoke(score, { domain }) : await this.api.invoke(analyze, { domain, body: { execution: this.execution() } }); if (domain === this.domainKey()) this.follow(run_id, kind === 'score' ? 'Cálculo de riesgos' : 'Análisis de EEG'); } catch (error) { this.message.set(errorText(error)); } finally { this.starting.set(false); } } protected async finish(run: Run): Promise { const domain = this.domainKey(); const active = this.run(); if (active?.id !== run.id) return; try { if (!active.autoPromote) return; if (run.state !== 'succeeded') { this.message.set('No se promovió: el entrenamiento no terminó correctamente.'); return; } const newVersions = run.info.flatMap((line) => { const match = /^train_models: tea\.(.+): version (\d+)$/.exec(line); return match ? [{ name: match[1], version: Number(match[2]) }] : []; }); if (newVersions.length) await this.promoteVersions(domain, newVersions); else this.message.set('No se promovió: el entrenamiento no registró versiones nuevas.'); } finally { if (domain === this.domainKey() && this.run()?.id === run.id) { this.refresh(); this.running.set(false); } } } private async getChecks(domain: Domain, key: VersionKey): Promise { return (await this.api.invoke(versionChecks, { domain, ...key })) as Checks; } private async promoteVersions(domain: Domain, keys: VersionKey[]): Promise { const messages = await Promise.all( keys.map(async (key) => { const label = `${key.name} v${key.version}`; try { const checks = await this.getChecks(domain, key); if (!checks.promotable) { const missing = checks.checks .filter((check) => !check.present) .map((check) => REPORTS[check.report] ?? check.report); const reason = missing.length ? `faltan ${missing.join(', ')}` : checks.status; return `No se promovió ${label}: ${reason}.`; } await this.api.invoke(promote, { domain, ...key }); return `${label}: en producción.`; } catch (error) { return `No se promovió ${label}: ${errorText(error)}`; } }), ); if (domain !== this.domainKey()) return; this.message.set(messages.join('\n')); this.refresh(); } }