Files
WebApp/src/app/connect/domain/document-source.ts
T

111 lines
4.2 KiB
TypeScript

import { Signal, signal } from '@angular/core';
import { Observable, from, of, switchMap, tap } from 'rxjs';
import { DocumentExtraction, DocumentSettings, PreviewResponse, SourceLocator } from '../api/api.types';
import { fileToBase64 } from '../api/file-encoding';
import { SourceGateway } from '../api/source-gateway';
import { DataConnection, EncodedFile, SourceTable, encodeFiles } from './data-source';
/** A connection whose files can be read as clinical documents. */
export interface DocumentFiles {
readonly encodedFiles: EncodedFile[];
}
export const DEFAULT_DOCUMENT_SETTINGS: DocumentSettings = {
segmentation: 'auto',
pages_per_record: 1,
ocr_mode: 'auto',
key_pattern: '',
};
export type FieldOverrides = Record<string, Record<string, unknown>>;
/**
* Reports, forms and notes (PDF or images) that aren't tables. The server
* splits them into one record per patient (however many pages or files
* that takes) and fills the target entity's fields from labels and free
* text; see `DocumentTable`.
*/
export class DocumentConnection extends DataConnection implements DocumentFiles {
readonly icon = 'document_scanner';
readonly typeLabel = 'Documentos clínicos';
readonly encodedFiles: EncodedFile[];
constructor(readonly files: File[]) {
super(files.length === 1 ? files[0].name : `${files.length} documentos`);
this.encodedFiles = files.map((file) => new EncodedFile(file, fileToBase64));
}
override get singleTable(): boolean {
return true;
}
protected discover(): Observable<SourceTable[]> {
return of([new DocumentTable(this, 'Registros por paciente')]);
}
}
/**
* The records extracted from a connection's documents. Extraction depends
* on the target entity (which fields to look for), so the last result and
* the user's corrections are kept per target. Settings and corrections
* travel in the payload; the server re-extracts on every call.
*/
export class DocumentTable extends SourceTable {
readonly icon = 'document_scanner';
readonly kindLabel = 'Extracción de campos';
private readonly _settings = signal<DocumentSettings>(DEFAULT_DOCUMENT_SETTINGS);
private readonly _overrides = signal<Record<string, FieldOverrides>>({});
private readonly _extractions = signal<Record<string, DocumentExtraction>>({});
readonly settings: Signal<DocumentSettings> = this._settings.asReadonly();
readonly extractions = this._extractions.asReadonly();
constructor(
override readonly connection: DataConnection & DocumentFiles,
name: string,
) {
super(connection, name);
}
get files(): File[] {
return this.connection.encodedFiles.map((encoded) => encoded.file);
}
overrides(target: string): FieldOverrides {
return this._overrides()[target] ?? {};
}
/** Settings apply to every target: they decide how pages become records. */
configure(settings: DocumentSettings, overridesByTarget?: Record<string, FieldOverrides>): void {
const resegmented = JSON.stringify(settings) !== JSON.stringify(this._settings());
this._settings.set(settings);
// Record numbers change when the segmentation does; old corrections would land on the wrong patient.
if (resegmented) this._overrides.set({});
if (overridesByTarget) this._overrides.update((all) => ({ ...all, ...overridesByTarget }));
}
preview(gateway: SourceGateway, target: string | null): Observable<PreviewResponse> {
if (!target) return of({ columns: [], sample_rows: [], total_rows: null, suggested_mapping: [] });
return from(this.payload(target)).pipe(
switchMap((payload) => gateway.document.extract(payload, target)),
tap((extraction) => this._extractions.update((all) => ({ ...all, [target]: extraction }))),
);
}
async locator(target?: string): Promise<SourceLocator> {
return { source_type: 'document', payload: await this.payload(target) };
}
private async payload(target?: string): Promise<Record<string, unknown>> {
const { key_pattern, ...settings } = this._settings();
const overrides = target ? this.overrides(target) : {};
return {
files: await encodeFiles(this.connection.encodedFiles),
...settings,
...(key_pattern.trim() ? { key_pattern: key_pattern.trim() } : {}),
...(Object.keys(overrides).length ? { overrides } : {}),
};
}
}