164 lines
6.6 KiB
TypeScript
164 lines
6.6 KiB
TypeScript
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 { RouterLink } from '@angular/router';
|
|
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 { domains } from '../api/fn/operations/domains';
|
|
import { studies } from '../api/fn/eeg/studies';
|
|
import { study } from '../api/fn/eeg/study';
|
|
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<string, string> = {
|
|
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,
|
|
RouterLink,
|
|
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<string>();
|
|
|
|
protected readonly labels = DOMAINS as Record<string, string>;
|
|
protected readonly reportNames = REPORTS;
|
|
protected readonly domains = resource({ loader: () => this.api.invoke(domains) });
|
|
private readonly refreshed = signal(0);
|
|
protected readonly models = resource({
|
|
params: () => ({ domain: this.domain() as Domain, at: this.refreshed() }),
|
|
loader: async ({ params: { domain } }) => {
|
|
const names = await this.api.invoke(models, { domain });
|
|
return Promise.all(
|
|
names.map(async (name) => ({
|
|
name,
|
|
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<string, unknown>) : [];
|
|
});
|
|
/** 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<string | undefined>(undefined);
|
|
protected readonly eegMetrics = resource({
|
|
params: () => this.eeg(),
|
|
loader: ({ params }) => this.api.invoke(study, { eeg_id: params }),
|
|
});
|
|
protected readonly metricNames: Record<string, string> = {
|
|
posterior_rhythm: 'Ritmo posterior (Hz)',
|
|
spindles_n2: 'Husos de sueño N2 (por min)',
|
|
spindles_n3: 'Husos de sueño N3 (por min)',
|
|
paroxysmal_spikes: 'Picos paroxísticos (por min)',
|
|
anteroposterior_gradient: 'Gradiente anteroposterior',
|
|
};
|
|
protected readonly asOf = signal('');
|
|
protected readonly run = signal<{ kind: string; status: string } | undefined>(undefined);
|
|
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<void> {
|
|
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 ${name} v${version}.`);
|
|
this.refreshed.update((n) => n + 1);
|
|
}
|
|
|
|
protected async promote(name: string, version: number): Promise<void> {
|
|
try {
|
|
await this.api.invoke(promote, { domain: this.domain() as Domain, name, version });
|
|
this.message.set(`${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;
|
|
this.message.set(`No se promovió: ${detail ?? 'error'}`);
|
|
}
|
|
}
|
|
|
|
protected async analyzeEegs(): Promise<void> {
|
|
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<void> {
|
|
for (;;) {
|
|
const status = (await this.api.invoke(runStatus, { run_id }))['status'] as string;
|
|
this.run.set({ 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 start(kind: 'train' | 'score'): Promise<void> {
|
|
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');
|
|
}
|
|
}
|