import { METRIC_NAMES } from '../eeg-labels'; import { HttpErrorResponse } from '@angular/common/http'; import { DatePipe, DecimalPipe } from '@angular/common'; import { Component, computed, inject, input, resource, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatInputModule } from '@angular/material/input'; import { Api } from '../api/api'; import { ApiConfiguration } from '../api/api-configuration'; import { addClinicalValidation } from '../api/fn/models/add-clinical-validation'; import { analyze } from '../api/fn/models/analyze'; import { models } from '../api/fn/models/models'; import { promote } from '../api/fn/models/promote'; import { readReport$Json } from '../api/fn/models/read-report-json'; import { score } from '../api/fn/models/score'; import { train } from '../api/fn/models/train'; import { versions } from '../api/fn/models/versions'; import { studies } from '../api/fn/eeg/studies'; import { study } from '../api/fn/eeg/study'; import { terminateRun } from '../api/fn/runs/terminate-run'; import { runStatus } from '../api/fn/runs/run-status'; import type { Domain } from '../api/models/domain'; import type { Version } from '../api/models/version'; import { DOMAINS } from '../app'; import { Plot } from '../plot'; import { interpretabilityFigures } from './figures'; import { Loading } from '../loading'; const REPORTS: Record = { technical_validation: 'Validación técnica', interpretability: 'Interpretabilidad', clinical_validation: 'Validación clínica', }; /** Model governance for a domain: every model's versions with their metrics and reports, * the clinical validation the clinical team uploads, promotion (refused without the three * reports), and the training and scoring runs. */ @Component({ selector: 'app-gobernanza', imports: [ Loading, DatePipe, DecimalPipe, FormsModule, MatButtonModule, MatFormFieldModule, MatInputModule, Plot, ], templateUrl: './gobernanza.html', styleUrl: './gobernanza.scss', }) export class Gobernanza { private readonly api = inject(Api); private readonly root = inject(ApiConfiguration).rootUrl; readonly domain = input.required(); protected readonly labels = DOMAINS as Record; protected readonly reportNames = REPORTS; private readonly refreshed = signal(0); protected readonly models = resource({ params: () => ({ domain: this.domain() as Domain, 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 chosen = signal<{ name: string; version: number } | undefined>(undefined); protected readonly report = resource({ params: () => this.chosen() && { ...this.chosen()!, domain: this.domain() as Domain }, loader: ({ params }) => this.api.invoke(readReport$Json, { ...params, report: 'interpretability' }), }); protected readonly figures = computed(() => { const found = this.report.value(); return found ? interpretabilityFigures(found as Record) : []; }); /** TEA: its EEGs and their analysis. */ protected readonly eegs = resource({ params: () => (this.domain() === 'tea' ? this.refreshed() + 1 : undefined), loader: () => this.api.invoke(studies), }); protected readonly eeg = signal(undefined); protected readonly eegMetrics = resource({ params: () => this.eeg(), loader: ({ params }) => this.api.invoke(study, { eeg_id: params }), }); protected readonly metricNames = METRIC_NAMES; protected readonly asOf = signal(''); protected readonly run = signal<{ id: string; kind: string; status: string } | undefined>( undefined, ); /** The run "Entrenar" or "Calcular riesgos" will start once confirmed. */ protected readonly confirming = signal<'train' | 'score' | undefined>(undefined); protected readonly running = computed(() => { const r = this.run(); return !!r && !['SUCCESS', 'FAILURE', 'CANCELED'].includes(r.status); }); protected readonly STATUS: Record = { QUEUED: 'en cola', NOT_STARTED: 'por iniciar', STARTING: 'iniciando', STARTED: 'en curso', SUCCESS: 'terminado', FAILURE: 'con error', CANCELING: 'deteniéndose', CANCELED: 'detenido', }; /** A model's title by its name, for messages. */ protected titleOf(name: string): string { return this.models.value()?.find((m) => m.name === name)?.title ?? name; } /** What a version learned from, as its metrics say it (each kind of model its own). */ protected sizes(v: Version): string { const m = v.metrics; const n = (x: number) => x.toLocaleString('es-MX'); if (m['n_train'] !== undefined) return `${n(m['n_train'])} entrenamiento / ${n(m['n_test'] ?? 0)} prueba`; if (m['n_reference'] !== undefined) return `${n(m['n_reference'])} EEG de referencia`; if (m['children'] !== undefined) return `${n(m['children'])} niños`; const c = Object.entries(m).find(([k]) => k.endsWith('c_index_cox')); if (c) return `C-index ${c[1].toFixed(3)}`; return '—'; } protected readonly message = signal(''); protected champion(v: Version): boolean { return v.aliases.includes('champion'); } protected reportUrl(name: string, version: number, report: string): string { return `${this.root}/models/${this.domain()}/${name}/versions/${version}/reports/${report}`; } protected async upload(name: string, version: number, event: Event): Promise { const file = (event.target as HTMLInputElement).files?.[0]; if (!file) return; await this.api.invoke(addClinicalValidation, { domain: this.domain() as Domain, name, version, // OpenAPI's binary is typed as a string; the request builder sends the File as is. body: { file: file as unknown as string }, }); this.message.set(`Validación clínica agregada a ${this.titleOf(name)} v${version}.`); this.refreshed.update((n) => n + 1); } protected async promote(name: string, version: number): Promise { try { await this.api.invoke(promote, { domain: this.domain() as Domain, name, version }); this.message.set(`${this.titleOf(name)} v${version} es ahora la versión en producción.`); this.refreshed.update((n) => n + 1); } catch (e) { const detail = e instanceof HttpErrorResponse ? e.error?.detail : undefined; // " v1 has no clinical_validation, interpretability": the reports it lacks const missing = /has no (.+)$/.exec(String(detail ?? ''))?.[1]; this.message.set( missing ? `No se promovió: faltan informes (${missing .split(', ') .map((r) => this.reportNames[r] ?? r) .join(', ')}).` : `No se promovió: ${detail ?? 'error de la plataforma'}`, ); } } protected async analyzeEegs(): Promise { const { run_id } = await this.api.invoke(analyze, { domain: this.domain() as Domain }); await this.follow(run_id, 'Análisis de EEG'); } private async follow(run_id: string, label: string): Promise { for (;;) { const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string; this.run.set({ id: run_id, kind: label, status }); if (['SUCCESS', 'FAILURE', 'CANCELED'].includes(status)) break; await new Promise((r) => setTimeout(r, 2000)); } this.refreshed.update((n) => n + 1); } protected async stop(): Promise { const r = this.run(); if (!r) return; const found = await this.api.invoke(terminateRun, { run_id: r.id }); this.run.set({ ...r, status: found['status'] }); } protected async start(kind: 'train' | 'score'): Promise { this.confirming.set(undefined); const domain = this.domain() as Domain; const { run_id } = kind === 'train' ? await this.api.invoke(train, { domain, body: this.asOf() ? { as_of: this.asOf() } : {} }) : await this.api.invoke(score, { domain }); await this.follow(run_id, kind === 'train' ? 'Entrenamiento' : 'Cálculo de riesgos'); } }