index.ts
6.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
/**
* clean-cli —— 出险数据清洗命令行。
*
* 用法:
* clean-cli <input.xlsx|input.csv>
* [--land <shenzhen-land.geojson>] 陆地掩膜(WGS-84),默认 public/geo/shenzhen-land.geojson
* [--corridors <corridors.geojson>] 海上合法走廊,默认 public/geo/shenzhen-offshore-corridors.geojson
* [--out <dir>] 输出目录,默认 ./clean-output
* [--coord-system GCJ-02|WGS-84] 案件坐标坐标系,默认 GCJ-02
* [--sparse-road N] [--sparse-street N] [--small-radius M] [--small-threshold N]
*
* 输出:
* clean-output/report.md 人类可读的清洗报告(总量 / 拒收 / 各类计数 / 提示)
* clean-output/annotations.csv 逐行标注(案件号 / 地址 / 经纬度 / 位掩码 / 命中类别)
* clean-output/annotations.json 完整结构化结果
*
* 算法全部来自 @hm/clean-core,本工具只是把「文件 → 报告」这一段壳做好。
*/
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { runClean, loadLandMaskFromUrl, loadCorridorsFromUrl, type RunCleanResult } from '@hm/clean-adapters';
import type { CleanThresholds } from '@hm/clean-core';
interface CliOptions {
input: string;
land: string;
corridors: string;
out: string;
coordSystem: 'GCJ-02' | 'WGS-84';
thresholds: Partial<CleanThresholds>;
}
function parseArgs(argv: string[]): CliOptions {
const opts: CliOptions = {
input: '',
land: 'public/geo/shenzhen-land.geojson',
corridors: 'public/geo/shenzhen-offshore-corridors.geojson',
out: './clean-output',
coordSystem: 'GCJ-02',
thresholds: {},
};
const num = (v: string | undefined, fallback: number): number => {
const n = Number(v);
return Number.isFinite(n) ? n : fallback;
};
for (let i = 0; i < argv.length; i += 1) {
const a = argv[i];
switch (a) {
case '--land': opts.land = argv[++i] ?? opts.land; break;
case '--corridors': opts.corridors = argv[++i] ?? opts.corridors; break;
case '--out': opts.out = argv[++i] ?? opts.out; break;
case '--coord-system': opts.coordSystem = (argv[++i] as 'GCJ-02' | 'WGS-84') ?? opts.coordSystem; break;
case '--sparse-road': opts.thresholds.sparseRoad = num(argv[++i], 1); break;
case '--sparse-street': opts.thresholds.sparseStreet = num(argv[++i], 1); break;
case '--small-radius': opts.thresholds.smallRadiusM = num(argv[++i], 1000); break;
case '--small-threshold': opts.thresholds.smallThreshold = num(argv[++i], 10); break;
case '-h':
case '--help':
printHelp();
process.exit(0);
default:
if (!a.startsWith('-') && !opts.input) opts.input = a;
else if (a.startsWith('--')) console.warn(`[warn] 未知参数 ${a},已忽略`);
}
}
if (!opts.input) {
console.error('错误:缺少输入文件(xlsx / csv)。用 --help 查看用法。');
process.exit(2);
}
return opts;
}
function printHelp(): void {
console.log(`clean-cli <input.xlsx|input.csv>
[--land <geojson>] 陆地掩膜(WGS-84),默认 public/geo/shenzhen-land.geojson
[--corridors <geojson>] 海上合法走廊,默认 public/geo/shenzhen-offshore-corridors.geojson
[--out <dir>] 输出目录,默认 ./clean-output
[--coord-system GCJ-02|WGS-84] 案件坐标坐标系,默认 GCJ-02
[--sparse-road N] [--sparse-street N] [--small-radius M] [--small-threshold N]`);
}
function csvCell(v: string | number): string {
const s = String(v ?? '');
return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
function toCsv(result: RunCleanResult): string {
const header = ['caseNo', 'address', 'lng', 'lat', 'flags', 'classes'];
const lines = [header.join(',')];
for (const r of result.rows) {
lines.push(
[r.caseNo, r.address, r.lng, r.lat, r.flags, r.classes.join('|')].map(csvCell).join(','),
);
}
return lines.join('\n');
}
function toMarkdown(result: RunCleanResult): string {
const L: string[] = [];
L.push(`# 出险数据清洗报告`);
L.push('');
L.push(`- 文件:${result.fileName}`);
L.push(`- 原始行数:${result.totalRows}`);
L.push(`- 进入清洗:${result.validRows}`);
const rejected = result.rejected.reduce((s, r) => s + r.count, 0);
L.push(`- 结构性拒收:${rejected}`);
L.push('');
if (result.rejected.length) {
L.push(`## 拒收原因`);
L.push('');
L.push(`| 原因 | 数量 | 样例 |`);
L.push(`| --- | --- | --- |`);
for (const r of result.rejected) L.push(`| ${r.reason} | ${r.count} | ${r.sample ?? ''} |`);
L.push('');
}
L.push(`## 各类处置(勾选后剔除)`);
L.push('');
L.push(`| 类别 | 说明 | 数量 | 默认勾选 |`);
L.push(`| --- | --- | --- | --- |`);
for (const c of result.classes) {
if (c.count > 0) L.push(`| ${c.key} | ${c.label} | ${c.count} | ${c.defaultOn ? '是' : '否'} |`);
}
L.push('');
L.push(`## 汇总`);
L.push('');
L.push(`- 道路低频涉及路数:${result.counts.sparseRoads}`);
L.push(`- 街道低频涉及街道数:${result.counts.sparseStreets}`);
L.push(`- 海上合法走廊豁免落水点:${result.counts.offshoreCorridorExempt}`);
if (result.warnings.length) {
L.push('');
L.push(`## 提示`);
for (const w of result.warnings) L.push(`- ${w}`);
}
return L.join('\n');
}
async function main(): Promise<void> {
const opts = parseArgs(process.argv.slice(2));
console.log(`[clean-cli] 读取输入:${opts.input}`);
const bytes = readFileSync(opts.input);
let landMask = null as Awaited<ReturnType<typeof loadLandMaskFromUrl>> | null;
if (existsSync(opts.land)) {
console.log(`[clean-cli] 加载陆地掩膜:${opts.land}`);
landMask = await loadLandMaskFromUrl(opts.land);
} else {
console.warn(`[clean-cli] 未找到陆地掩膜 ${opts.land},落水判定将跳过`);
}
let corridors = null as Awaited<ReturnType<typeof loadCorridorsFromUrl>> | null;
if (existsSync(opts.corridors)) {
console.log(`[clean-cli] 加载海上合法走廊:${opts.corridors}`);
corridors = await loadCorridorsFromUrl(opts.corridors);
} else {
console.warn(`[clean-cli] 未找到海上走廊 ${opts.corridors},落水点不享受走廊豁免`);
}
const result = runClean({
fileName: opts.input,
bytes,
landMask: landMask ?? undefined,
corridors,
coordSystem: opts.coordSystem,
thresholds: opts.thresholds,
});
mkdirSync(opts.out, { recursive: true });
writeFileSync(`${opts.out}/report.md`, toMarkdown(result), 'utf-8');
writeFileSync(`${opts.out}/annotations.csv`, toCsv(result), 'utf-8');
writeFileSync(`${opts.out}/annotations.json`, JSON.stringify(result, null, 2), 'utf-8');
console.log(
`[clean-cli] 完成:进入清洗 ${result.validRows} 行,报告见 ${opts.out}/report.md、标注见 ${opts.out}/annotations.csv`,
);
}
main().catch((err) => {
console.error('[clean-cli] 失败:', err instanceof Error ? err.message : err);
process.exit(1);
});