integration layer; merge work on indicators from forks with existing ingestion pipeline
This commit is contained in:
@@ -0,0 +1,247 @@
|
||||
/** Shapes of the WebApi JSON contract for `/imports/*` and `/data/*`. */
|
||||
|
||||
export type Domain = 'cacu' | 'cama' | 'tea';
|
||||
|
||||
export type InferredType = 'string' | 'integer' | 'float' | 'boolean' | 'date' | 'datetime' | 'binary' | 'unknown';
|
||||
|
||||
export type MatchReason = 'exact' | 'normalized' | 'synonym' | 'unprefixed' | 'fuzzy' | 'none';
|
||||
|
||||
export type ConflictStrategy = 'reject' | 'upsert';
|
||||
|
||||
export type ErrorCategory = 'missing' | 'out_of_catalog' | 'type_invalid' | 'conflict' | 'merge_conflict' | 'unknown';
|
||||
|
||||
export type FileKind = 'csv' | 'excel' | 'json';
|
||||
|
||||
export type SourceType = FileKind | 'sql' | 'pdf' | 'edf' | 'document';
|
||||
|
||||
/** Backend connector categories (`GET /imports/connectors`). */
|
||||
export type ConnectorCategory = 'file' | 'database' | 'document' | 'signal';
|
||||
|
||||
export interface SqlEngineInfo {
|
||||
id: string;
|
||||
label: string;
|
||||
description: string;
|
||||
default_port: number;
|
||||
default_schema: string | null;
|
||||
/** Whether the server has the driver installed. */
|
||||
available: boolean;
|
||||
}
|
||||
|
||||
export interface SegmentationInfo {
|
||||
id: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface ConnectorInfo {
|
||||
kind: SourceType;
|
||||
label: string;
|
||||
description: string;
|
||||
category: ConnectorCategory;
|
||||
icon: string;
|
||||
extensions: string[];
|
||||
engines?: SqlEngineInfo[];
|
||||
segmentations?: SegmentationInfo[];
|
||||
}
|
||||
|
||||
/** How a database is reached: form fields, or a raw SQLAlchemy URL. */
|
||||
export type SqlConnectionRef =
|
||||
| { server: { engine: string; host: string; port: number | null; database: string; user: string; password: string } }
|
||||
| { connection_string: string };
|
||||
|
||||
export interface TargetField {
|
||||
name: string;
|
||||
required: boolean;
|
||||
/** JSON-schema type or format: string, integer, number, boolean, date, date-time, binary... */
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface TargetMeta {
|
||||
key: string;
|
||||
domain: Domain;
|
||||
table: string;
|
||||
conflict_fields: string[] | null;
|
||||
fields: TargetField[];
|
||||
}
|
||||
|
||||
export interface SourceColumn {
|
||||
name: string;
|
||||
inferred_type: InferredType;
|
||||
}
|
||||
|
||||
export interface SuggestedMapping {
|
||||
source_column: string;
|
||||
target_field: string | null;
|
||||
confidence: number;
|
||||
reason: MatchReason;
|
||||
}
|
||||
|
||||
export type Row = Record<string, unknown>;
|
||||
|
||||
export interface PreviewResponse {
|
||||
columns: SourceColumn[];
|
||||
sample_rows: Row[];
|
||||
total_rows: number | null;
|
||||
suggested_mapping: SuggestedMapping[];
|
||||
/** Sub-tables the source offers (Excel sheets...), with the options to read each. */
|
||||
tables?: { name: string; options: Record<string, unknown>; kind: string }[];
|
||||
source_metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface FileOptions {
|
||||
sheet_name?: string;
|
||||
delimiter?: string;
|
||||
encoding?: string;
|
||||
record_path?: string;
|
||||
}
|
||||
|
||||
export interface TableCandidate {
|
||||
page_number: number;
|
||||
bbox: [number, number, number, number]; // PDF points
|
||||
column_count: number;
|
||||
row_count: number;
|
||||
preview_grid: (string | null)[][];
|
||||
}
|
||||
|
||||
export interface PdfDetectResponse {
|
||||
page_count: number;
|
||||
has_text_layer: boolean;
|
||||
table_candidates: TableCandidate[];
|
||||
}
|
||||
|
||||
export interface RegionSpec {
|
||||
/** The name this region's text becomes as a source column. */
|
||||
target_field: string;
|
||||
page_numbers: number[];
|
||||
bbox: [number, number, number, number]; // normalized 0..1
|
||||
}
|
||||
|
||||
export interface RegionExtractResponse {
|
||||
columns: SourceColumn[];
|
||||
rows: Row[];
|
||||
warnings: { page_number: number; message: string }[];
|
||||
suggested_mapping: SuggestedMapping[];
|
||||
}
|
||||
|
||||
/** The `{source_type, payload}` part of a source, as built by its SourceTable. */
|
||||
export interface SourceLocator {
|
||||
source_type: SourceType;
|
||||
payload: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** One entry of `/imports/validate`'s `source` / `/imports/commit`'s `sources`. */
|
||||
export interface ImportSourcePayload extends SourceLocator {
|
||||
target: string;
|
||||
label?: string;
|
||||
column_mapping: Record<string, string>;
|
||||
defaults?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// -- documents -----------------------------------------------------------------
|
||||
|
||||
export type OcrMode = 'auto' | 'always' | 'never';
|
||||
|
||||
export interface DocumentSettings {
|
||||
segmentation: string;
|
||||
pages_per_record: number;
|
||||
ocr_mode: OcrMode;
|
||||
key_pattern: string;
|
||||
}
|
||||
|
||||
export interface ExtractedField {
|
||||
value: unknown;
|
||||
confidence: number;
|
||||
/** etiqueta | patron | texto_libre | manual */
|
||||
method: string;
|
||||
raw?: string;
|
||||
document?: string;
|
||||
page_number?: number;
|
||||
line?: string;
|
||||
bbox?: [number, number, number, number] | null;
|
||||
}
|
||||
|
||||
export interface DocumentImage {
|
||||
document: string;
|
||||
page_number: number;
|
||||
bbox: [number, number, number, number];
|
||||
kind: 'scan' | 'figure';
|
||||
}
|
||||
|
||||
export interface ExtractedRecord {
|
||||
index: number;
|
||||
key: string | null;
|
||||
confidence: number;
|
||||
fields: Record<string, ExtractedField>;
|
||||
missing: string[];
|
||||
conflicts: { field: string; kept: ExtractedField; discarded: ExtractedField }[];
|
||||
sources: { document: string; page_numbers: number[] }[];
|
||||
images: DocumentImage[];
|
||||
}
|
||||
|
||||
export interface DocumentFieldSpec {
|
||||
name: string;
|
||||
kind: 'text' | 'identifier' | 'integer' | 'decimal' | 'date' | 'choice';
|
||||
required: boolean;
|
||||
labels: string[];
|
||||
}
|
||||
|
||||
export interface DocumentExtraction extends PreviewResponse {
|
||||
key_field: string | null;
|
||||
fields: DocumentFieldSpec[];
|
||||
records: ExtractedRecord[];
|
||||
}
|
||||
|
||||
export interface RowError {
|
||||
row_index: number;
|
||||
field: string;
|
||||
category: ErrorCategory;
|
||||
message: string;
|
||||
raw_value?: unknown;
|
||||
}
|
||||
|
||||
export interface ValidationResult {
|
||||
total_rows: number;
|
||||
valid_count: number;
|
||||
error_count: number;
|
||||
errors: RowError[];
|
||||
}
|
||||
|
||||
export interface CommitSourceResult {
|
||||
target: string;
|
||||
label: string | null;
|
||||
total: number;
|
||||
created: number;
|
||||
updated: number;
|
||||
rejected: number;
|
||||
errors: RowError[];
|
||||
/** Foreign keys filled from natural keys, e.g. `{pac_id: 12}`. */
|
||||
linked?: Record<string, number>;
|
||||
/** Rows combined into a row of another source (`merge_duplicates`). */
|
||||
merged?: number;
|
||||
warnings?: RowError[];
|
||||
}
|
||||
|
||||
export interface BatchResult {
|
||||
ok: boolean;
|
||||
results: CommitSourceResult[];
|
||||
}
|
||||
|
||||
export interface DataPage {
|
||||
target: string;
|
||||
total: number;
|
||||
limit: number;
|
||||
offset: number;
|
||||
/** Column names in table order. */
|
||||
columns: string[];
|
||||
rows: Row[];
|
||||
}
|
||||
|
||||
export interface ApiError {
|
||||
error: string;
|
||||
}
|
||||
|
||||
/** Pulls the backend's `{error}` message out of an HttpErrorResponse-like value. */
|
||||
export function apiErrorMessage(error: unknown, fallback: string): string {
|
||||
const body = (error as { error?: unknown })?.error;
|
||||
if (body && typeof body === 'object' && typeof (body as ApiError).error === 'string') return (body as ApiError).error;
|
||||
return fallback;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable, map, shareReplay } from 'rxjs';
|
||||
import { ConnectorInfo } from './api.types';
|
||||
|
||||
/** GET /imports/connectors: what the server can read. Fetched once per app. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ConnectorsApi {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly connectors$ = this.http.get<{ connectors: ConnectorInfo[] }>('/imports/connectors').pipe(
|
||||
map((response) => response.connectors),
|
||||
shareReplay({ bufferSize: 1, refCount: false }),
|
||||
);
|
||||
|
||||
list(): Observable<ConnectorInfo[]> {
|
||||
return this.connectors$;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { DataPage } from './api.types';
|
||||
|
||||
/** GET /data/<target>: rows actually stored in the destination database. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class DataApi {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
page(target: string, limit: number, offset: number): Observable<DataPage> {
|
||||
const params = new HttpParams().set('limit', limit).set('offset', offset);
|
||||
return this.http.get<DataPage>(`/data/${encodeURIComponent(target)}`, { params });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { DocumentExtraction } from './api.types';
|
||||
|
||||
/** Clinical documents: field extraction and page/image rendering. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class DocumentSourceApi {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
/** `payload` is the document source payload (files, segmentation, overrides...). */
|
||||
extract(payload: Record<string, unknown>, target: string): Observable<DocumentExtraction> {
|
||||
return this.http.post<DocumentExtraction>('/imports/sources/document/extract', { ...payload, target });
|
||||
}
|
||||
|
||||
/** PNG of a page, or of a normalized region of it (an embedded image). */
|
||||
pageImage(file: File, pageNumber: number, bbox?: [number, number, number, number], dpi = 110): Observable<Blob> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
form.append('page_number', String(pageNumber));
|
||||
form.append('dpi', String(dpi));
|
||||
if (bbox) form.append('bbox', JSON.stringify(bbox));
|
||||
return this.http.post('/imports/sources/document/page-image', form, { responseType: 'blob' });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/** Base64 of a File's bytes, for JSON endpoints that carry a file. */
|
||||
export async function fileToBase64(file: Blob): Promise<string> {
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
const chunk = 0x8000;
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i += chunk) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { FileOptions, PreviewResponse, SourceType } from './api.types';
|
||||
|
||||
/** Previews of uploaded files: multipart for one file, JSON payload for any source. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class FileSourceApi {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
preview(file: File, kind: SourceType, target: string | null, options: FileOptions = {}): Observable<PreviewResponse> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
form.append('source_kind', kind);
|
||||
if (target) form.append('target', target);
|
||||
if (Object.keys(options).length > 0) form.append('options', JSON.stringify(options));
|
||||
return this.http.post<PreviewResponse>('/imports/sources/file/preview', form);
|
||||
}
|
||||
|
||||
/** Same payload an import source carries, e.g. several EDF files at once. */
|
||||
previewPayload(kind: SourceType, payload: Record<string, unknown>, target: string | null): Observable<PreviewResponse> {
|
||||
return this.http.post<PreviewResponse>(`/imports/sources/${kind}/preview`, { payload, ...(target ? { target } : {}) });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { BatchResult, ConflictStrategy, ImportSourcePayload, ValidationResult } from './api.types';
|
||||
|
||||
/** POST /imports/validate (one source, writes nothing) and POST /imports/commit (a batch, one transaction). */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ImportsApi {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
validate(source: ImportSourcePayload): Observable<ValidationResult> {
|
||||
return this.http.post<ValidationResult>('/imports/validate', { source });
|
||||
}
|
||||
|
||||
/** `mergeDuplicates`: rows of different sources with the same natural key become one record. */
|
||||
commit(sources: ImportSourcePayload[], onConflict: ConflictStrategy, mergeDuplicates = false): Observable<BatchResult> {
|
||||
return this.http.post<BatchResult>('/imports/commit', { sources, on_conflict: onConflict, merge_duplicates: mergeDuplicates });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable, from, switchMap } from 'rxjs';
|
||||
import { PdfDetectResponse, PreviewResponse, RegionExtractResponse, RegionSpec } from './api.types';
|
||||
import { fileToBase64 } from './file-encoding';
|
||||
|
||||
/** POST /imports/sources/pdf/... endpoints. Every call resends the file bytes. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class PdfSourceApi {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
detect(file: File): Observable<PdfDetectResponse> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
return this.http.post<PdfDetectResponse>('/imports/sources/pdf/detect', form);
|
||||
}
|
||||
|
||||
/** Raw PNG bytes; the caller turns them into an object URL. */
|
||||
pageImage(file: File, pageNumber: number, dpi?: number): Observable<Blob> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
form.append('page_number', String(pageNumber));
|
||||
if (dpi) form.append('dpi', String(dpi));
|
||||
return this.http.post('/imports/sources/pdf/page-image', form, { responseType: 'blob' });
|
||||
}
|
||||
|
||||
tablePreview(file: File, pageNumber: number, bbox: [number, number, number, number], target: string | null): Observable<PreviewResponse> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
form.append('page_number', String(pageNumber));
|
||||
form.append('bbox', JSON.stringify(bbox));
|
||||
if (target) form.append('target', target);
|
||||
return this.http.post<PreviewResponse>('/imports/sources/pdf/table/preview', form);
|
||||
}
|
||||
|
||||
extractRegions(file: File, regions: RegionSpec[], target: string | null, dpi = 150): Observable<RegionExtractResponse> {
|
||||
return from(fileToBase64(file)).pipe(
|
||||
switchMap((file_base64) =>
|
||||
this.http.post<RegionExtractResponse>('/imports/sources/pdf/regions/extract', {
|
||||
file_base64,
|
||||
regions,
|
||||
dpi,
|
||||
...(target ? { target } : {}),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { DocumentSourceApi } from './document-source.api';
|
||||
import { FileSourceApi } from './file-source.api';
|
||||
import { PdfSourceApi } from './pdf-source.api';
|
||||
import { SqlSourceApi } from './sql-source.api';
|
||||
|
||||
/**
|
||||
* The source endpoints, handed to domain objects (`DataConnection.load`,
|
||||
* `SourceTable.preview`) so each subclass calls the one it needs and the
|
||||
* domain layer stays free of Angular DI.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class SourceGateway {
|
||||
readonly file = inject(FileSourceApi);
|
||||
readonly sql = inject(SqlSourceApi);
|
||||
readonly pdf = inject(PdfSourceApi);
|
||||
readonly document = inject(DocumentSourceApi);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable, map } from 'rxjs';
|
||||
import { PreviewResponse, SourceColumn, SqlConnectionRef } from './api.types';
|
||||
|
||||
/** POST /imports/sources/sql/*. Stateless: every call carries the connection. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class SqlSourceApi {
|
||||
private readonly http = inject(HttpClient);
|
||||
|
||||
testConnection(connection: SqlConnectionRef): Observable<{ ok: true; dialect: string }> {
|
||||
return this.http.post<{ ok: true; dialect: string }>('/imports/sources/sql/test-connection', connection);
|
||||
}
|
||||
|
||||
schemas(connection: SqlConnectionRef): Observable<string[]> {
|
||||
return this.http.post<{ schemas: string[] }>('/imports/sources/sql/schemas', connection).pipe(map((response) => response.schemas));
|
||||
}
|
||||
|
||||
tables(connection: SqlConnectionRef, schema?: string): Observable<string[]> {
|
||||
return this.http
|
||||
.post<{ tables: string[] }>('/imports/sources/sql/tables', { ...connection, ...(schema ? { schema } : {}) })
|
||||
.pipe(map((response) => response.tables));
|
||||
}
|
||||
|
||||
columns(connection: SqlConnectionRef, table: string, schema?: string): Observable<SourceColumn[]> {
|
||||
return this.http
|
||||
.post<{ columns: SourceColumn[] }>('/imports/sources/sql/columns', { ...connection, table, ...(schema ? { schema } : {}) })
|
||||
.pipe(map((response) => response.columns));
|
||||
}
|
||||
|
||||
preview(
|
||||
connection: SqlConnectionRef,
|
||||
source: { table?: string; schema?: string; query?: string },
|
||||
target: string | null,
|
||||
): Observable<PreviewResponse> {
|
||||
return this.http.post<PreviewResponse>('/imports/sources/sql/preview', {
|
||||
...connection,
|
||||
...(source.query ? { query: source.query } : { table: source.table, ...(source.schema ? { schema: source.schema } : {}) }),
|
||||
...(target ? { target } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable, map, shareReplay } from 'rxjs';
|
||||
import { TargetMeta } from './api.types';
|
||||
|
||||
/** GET /imports/targets, fetched once per app and shared. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class TargetsApi {
|
||||
private readonly http = inject(HttpClient);
|
||||
private readonly targets$ = this.http
|
||||
.get<{ targets: TargetMeta[] }>('/imports/targets')
|
||||
.pipe(
|
||||
map((response) => response.targets),
|
||||
shareReplay({ bufferSize: 1, refCount: false }),
|
||||
);
|
||||
|
||||
list(): Observable<TargetMeta[]> {
|
||||
return this.targets$;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user