runClean.ts 3.58 KB
/**
 * 端到端清洗编排(适配器层)。
 *
 * 把「字节 → 报告 + 标注」这一整条链路串起来:解码(xlsx/csv)→ 归一化(列映射 / 地址拆解)→
 * 调用 @hm/clean-core 的 `cleanRows` 跑 8 类判定 → 汇总成分组报告 + 逐行标注。
 * 这是 B 阶段(CLI / Worker)真正调用的入口;app 端目前仍用自己那份 ingestion(行为等价),
 * 后续可平滑切到这套编排。
 */
import {
  cleanRows,
  FLAG,
  type CleanRow,
  type NamedPolys,
  type CorridorFeature,
  type CleanThresholds,
  type CleanClassKey,
} from '@hm/clean-core';
import { decodeIncidentFile, type RawTable } from './xlsx';
import { normalizeIncidentTable } from './normalize';

const CLASS_KEYS: CleanClassKey[] = [
  'MISSING',
  'MISSING_PARTIAL',
  'OUTSIDE',
  'OFFSHORE_NEAR',
  'OFFSHORE_FAR',
  'ISO_200',
  'ISO_500',
  'ISO_1000',
  'SPARSE',
  'SPARSE_STREET',
  'SMALL',
];

const KEY_BITS: Array<[CleanClassKey, number]> = CLASS_KEYS.map((k) => [k, FLAG[k]]);

export interface RunCleanInput {
  /** 文件名(用于解码分支判断 xlsx/csv) */
  fileName?: string;
  /** 原始文件字节 */
  bytes?: Uint8Array | ArrayBuffer;
  /** 已解码的表(与 bytes 二选一,bytes 优先) */
  table?: RawTable;
  /** 陆地掩膜(WGS-84)。不传 = 跳过落水判定并提示 */
  landMask?: NamedPolys[] | null;
  /** 海上合法走廊(WGS-84) */
  corridors?: CorridorFeature[] | null;
  /** 案件坐标所用坐标系,默认 GCJ-02 */
  coordSystem?: 'GCJ-02' | 'WGS-84';
  /** 阈值覆盖 */
  thresholds?: Partial<CleanThresholds>;
  /** 每类保留样例条数 */
  maxSamples?: number;
}

export interface AnnotatedRow {
  caseNo: string;
  address: string;
  lng: number;
  lat: number;
  /** 逐行处置位掩码 */
  flags: number;
  /** 命中的类别键(人类可读) */
  classes: string[];
}

export interface RunCleanResult {
  fileName: string;
  totalRows: number;
  validRows: number;
  /** 被拒收的行(结构性坏行,不进清洗) */
  rejected: Array<{ reason: string; count: number; sample?: string }>;
  /** 分组报告 */
  classes: Array<{ key: string; label: string; count: number; defaultOn: boolean }>;
  warnings: string[];
  counts: { sparseRoads: number; sparseStreets: number; offshoreCorridorExempt: number };
  /** 逐行标注(仅有效行) */
  rows: AnnotatedRow[];
}

export function runClean(input: RunCleanInput): RunCleanResult {
  const table =
    input.table ??
    (input.bytes && input.fileName
      ? decodeIncidentFile(input.fileName, input.bytes)
      : null);
  if (!table) throw new Error('runClean 需要 bytes+fileName 或 table 之一');

  const norm = normalizeIncidentTable(table);
  const res = cleanRows(norm.rows, {
    landMask: input.landMask ?? undefined,
    corridors: input.corridors ?? null,
    coordSystem: input.coordSystem,
    thresholds: input.thresholds,
    maxSamples: input.maxSamples,
  });

  const annotated: AnnotatedRow[] = norm.rows.map((r: CleanRow, i) => {
    const f = res.flags[i];
    const classes = KEY_BITS.filter(([, b]) => (f & b) !== 0).map(([k]) => k);
    return {
      caseNo: r.caseNo,
      address: r.address,
      lng: r.lng,
      lat: r.lat,
      flags: f,
      classes,
    };
  });

  return {
    fileName: table.fileName,
    totalRows: norm.totalRows,
    validRows: norm.rows.length,
    rejected: norm.rejected,
    classes: res.classes.map((c) => ({
      key: c.key,
      label: c.label,
      count: c.count,
      defaultOn: c.defaultOn,
    })),
    warnings: res.warnings,
    counts: res.counts,
    rows: annotated,
  };
}