dsh-eplan 0.0.0-stage → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +219 -3
- package/cordis.patch.yml +182 -0
- package/docs/INSTALL.md +86 -0
- package/docs/LESSONS.md +224 -0
- package/docs/interfaces.md +183 -0
- package/docs/merged-skills/eplan-setup.md +63 -0
- package/docs/merged-skills/eplan-troubleshooting.md +149 -0
- package/icon.png +0 -0
- package/icon.svg +13 -0
- package/knowledge/KNOWLEDGE.md +413 -0
- package/knowledge/symbols/BP.png +0 -0
- package/knowledge/symbols/CDPST.png +0 -0
- package/knowledge/symbols/CO.png +0 -0
- package/knowledge/symbols/FA3.png +0 -0
- package/knowledge/symbols/TLRO.png +0 -0
- package/knowledge/symbols/TLRU.png +0 -0
- package/knowledge/symbols/TOUL.png +0 -0
- package/knowledge/symbols/TOUR.png +0 -0
- package/knowledge/symbols/manifest.json +91 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/native/bridge/build.ps1 +73 -0
- package/native/bridge/src/Json.cs +383 -0
- package/native/bridge/src/Program.cs +1133 -0
- package/native/host/build.ps1 +74 -0
- package/native/host/src/ActionsTool.cs +225 -0
- package/native/host/src/BoxTool.cs +196 -0
- package/native/host/src/CheckTool.cs +186 -0
- package/native/host/src/Context.cs +169 -0
- package/native/host/src/DarkScheme.cs +111 -0
- package/native/host/src/DiagnoseTool.cs +115 -0
- package/native/host/src/Dispatcher.cs +51 -0
- package/native/host/src/DrawTool.cs +316 -0
- package/native/host/src/Entry.cs +111 -0
- package/native/host/src/ExportTool.cs +213 -0
- package/native/host/src/InspectTool.cs +367 -0
- package/native/host/src/KnowledgeTool.cs +166 -0
- package/native/host/src/LookTool.cs +257 -0
- package/native/host/src/OpLog.cs +289 -0
- package/native/host/src/PageCreateTool.cs +521 -0
- package/native/host/src/PageOpenTool.cs +62 -0
- package/native/host/src/PagesTool.cs +95 -0
- package/native/host/src/Paths.cs +91 -0
- package/native/host/src/PlacementEditTool.cs +234 -0
- package/native/host/src/ProbePropsTool.cs +152 -0
- package/native/host/src/ProjectCreateTool.cs +176 -0
- package/native/host/src/ProjectTool.cs +167 -0
- package/native/host/src/PropWriter.cs +70 -0
- package/native/host/src/PropsTool.cs +257 -0
- package/native/host/src/StatusTool.cs +168 -0
- package/native/host/src/SymbolInfoTool.cs +144 -0
- package/native/host/src/SymbolInsertTool.cs +261 -0
- package/native/host/src/SymbolsTool.cs +94 -0
- package/native/host/src/TagLocTool.cs +108 -0
- package/native/script/EplanMcpBootstrap.cs +221 -0
- package/native/script/build-symbol-gallery.mjs +231 -0
- package/native/script/prepare-install.ps1 +57 -0
- package/native/script/prune.mjs +132 -0
- package/native/script/verify-bootstrap.ps1 +62 -0
- package/package.json +53 -4
- package/preset/bootstrap.js +498 -0
- package/preset/experience-nudge.js +47 -0
- package/preset/image-budget.js +175 -0
- package/preset/knowledge-tool.js +180 -0
- package/preset/mcp-link.js +100 -0
- package/preset/prompt-surface.js +76 -0
- package/preset/restrict-tools.js +141 -0
- package/preset/skill-docs.js +181 -0
- package/preset/video-digest.js +294 -0
- package/preset/video-tool.js +92 -0
- package/server/compact.mjs +623 -0
- package/server/edit-args.mjs +67 -0
- package/server/fuzzy.mjs +57 -0
- package/server/launch-decision.mjs +26 -0
- package/server/measure.mjs +320 -0
- package/server/pdf.mjs +185 -0
- package/server/pdf2png.ps1 +99 -0
- package/server/server.mjs +3797 -0
- package/server/video.mjs +857 -0
- package/setup.mjs +223 -0
- package/skills/eplan-annotations/SKILL.md +55 -0
- package/skills/eplan-drawing/SKILL.md +206 -0
- package/skills/eplan-project/SKILL.md +41 -0
- package/skills/eplan-review/SKILL.md +80 -0
- package/skills/eplan-symbols/SKILL.md +142 -0
- package/test/check-docs.mjs +106 -0
- package/test/foreground.ps1 +21 -0
- package/test/smoke-all.mjs +229 -0
package/server/fuzzy.mjs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 名字相近度:给「库里没有这个符号」的报错配候选。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独成文件:纯函数,值得单独测,也不想为了测一个编辑距离就把整个 MCP 服务
|
|
5
|
+
* 加载起来(server.mjs 一 import 就连 bridge、注册工具)。
|
|
6
|
+
*
|
|
7
|
+
* 2026-11-24 session-400917a2:模型认定「DCP」是电抗器,连撞 8 次 SYMBOL_NOT_FOUND。
|
|
8
|
+
* 错的不是它重试,是错误只说「没有」不说「库里有这些」。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** 经典 Levenshtein,两行滚动数组,名字都很短,没必要上更花哨的算法。 */
|
|
12
|
+
export function editDistance(a, b) {
|
|
13
|
+
const s = String(a ?? '')
|
|
14
|
+
const t = String(b ?? '')
|
|
15
|
+
if (s === t) return 0
|
|
16
|
+
if (s.length === 0) return t.length
|
|
17
|
+
if (t.length === 0) return s.length
|
|
18
|
+
const prev = new Array(t.length + 1)
|
|
19
|
+
for (let j = 0; j <= t.length; j += 1) prev[j] = j
|
|
20
|
+
for (let i = 1; i <= s.length; i += 1) {
|
|
21
|
+
let diagonal = prev[0]
|
|
22
|
+
prev[0] = i
|
|
23
|
+
for (let j = 1; j <= t.length; j += 1) {
|
|
24
|
+
const saved = prev[j]
|
|
25
|
+
prev[j] = Math.min(
|
|
26
|
+
prev[j] + 1,
|
|
27
|
+
prev[j - 1] + 1,
|
|
28
|
+
diagonal + (s[i - 1] === t[j - 1] ? 0 : 1),
|
|
29
|
+
)
|
|
30
|
+
diagonal = saved
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return prev[t.length]
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 名字相近的候选:先比编辑距离,再比前缀,够不着就返回空。
|
|
38
|
+
*
|
|
39
|
+
* 预算按名字长度放宽,但三字以内的短名只收一位之差:
|
|
40
|
+
* 三个字母的名字差两个字母已经是「另一个词」了,把 SSA 推荐给写 LSW 的人只是噪声。
|
|
41
|
+
* 返回空数组是有意义的结论:「库里没有相近的」,调用方据此换策略而不是原样重试。
|
|
42
|
+
*/
|
|
43
|
+
export function closestSymbolNames(target, names, limit = 5) {
|
|
44
|
+
const want = String(target ?? '').toUpperCase().trim()
|
|
45
|
+
if (!want || !Array.isArray(names)) return []
|
|
46
|
+
const budget = want.length <= 3 ? 1 : Math.ceil(want.length / 2)
|
|
47
|
+
const scored = []
|
|
48
|
+
for (const name of names) {
|
|
49
|
+
if (typeof name !== 'string' || name.length === 0) continue
|
|
50
|
+
const upper = name.toUpperCase()
|
|
51
|
+
let distance = editDistance(want, upper)
|
|
52
|
+
if (upper.startsWith(want) || want.startsWith(upper)) distance -= 1
|
|
53
|
+
if (distance <= budget) scored.push({ name, distance })
|
|
54
|
+
}
|
|
55
|
+
scored.sort((a, b) => a.distance - b.distance || a.name.length - b.name.length)
|
|
56
|
+
return [...new Set(scored.slice(0, limit).map((item) => item.name))]
|
|
57
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* launch 的决策:什么时候可以真的去起一个 EPLAN.exe。
|
|
3
|
+
*
|
|
4
|
+
* 纯函数,单独成文件是为了能测 —— 这段判断出错的实际代价很大:
|
|
5
|
+
* 2026-11-24 实测,一个会话把「status 超时」当成「EPLAN 没开」,于是多起了一个实例,
|
|
6
|
+
* 两个 EPLAN 抢同一个项目和数据目录,两边轮流弹「硬件错误:存储器访问受阻」,
|
|
7
|
+
* 谁都干不了活,最后只能全部杀掉重来。
|
|
8
|
+
*
|
|
9
|
+
* 输入:
|
|
10
|
+
* ready —— status 是否回了 ready:true
|
|
11
|
+
* answered —— status 是否有回话(哪怕回的是 not ready)
|
|
12
|
+
* processes —— 本机 EPLAN.exe 的进程号
|
|
13
|
+
* force —— 调用方是否明确要再起一个
|
|
14
|
+
* 输出:
|
|
15
|
+
* 'already' —— 已经在跑且 API 通了,不用起
|
|
16
|
+
* 'wait' —— 有进程但没回话:等它启动 / 等人关框,不要起第二个
|
|
17
|
+
* 'go' —— 确实没有 EPLAN,可以起
|
|
18
|
+
*/
|
|
19
|
+
export function decideLaunch({ ready = false, answered = true, processes = [], force = false } = {}) {
|
|
20
|
+
if (force) return 'go'
|
|
21
|
+
if (ready === true) return 'already'
|
|
22
|
+
// 关键的一条:探测失败不等于不存在。只要进程在,就宁可让调用方等。
|
|
23
|
+
if (Array.isArray(processes) && processes.length > 0) return 'wait'
|
|
24
|
+
// status 没回话、也没有进程:可能 EPLAN 刚被杀掉,主线程还在收尾;这种情况允许起。
|
|
25
|
+
return 'go'
|
|
26
|
+
}
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
// 量图:把截图/视频帧里的像素距离换算成毫米。
|
|
2
|
+
//
|
|
3
|
+
// 为什么单独做:审计里 42 分钟有 9 分钟花在「数格子再心算 mm」上,而且算错过。
|
|
4
|
+
// 这件事不需要 EPLAN,不需要建模,只要一次调用把结果连校准一起给出来。
|
|
5
|
+
//
|
|
6
|
+
// 只做三件事:
|
|
7
|
+
// calibrate 两点像素 + 已知真实距离 → px/mm
|
|
8
|
+
// edges 沿行/列找明暗跳变(图框线、器件边框、栅格线),给像素与 mm
|
|
9
|
+
// grid 从边缘位置推主导间距(= 栅格或器件极距)
|
|
10
|
+
//
|
|
11
|
+
// 图像解码走 ffmpeg 的 rawvideo 灰度输出,不引第三方图像库。
|
|
12
|
+
import { spawn } from 'node:child_process'
|
|
13
|
+
import { existsSync } from 'node:fs'
|
|
14
|
+
import { findBinary } from './video.mjs'
|
|
15
|
+
|
|
16
|
+
function fail(code, message) {
|
|
17
|
+
const error = new Error(message)
|
|
18
|
+
error.code = code
|
|
19
|
+
return error
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function runBuffer(bin, args) {
|
|
23
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
24
|
+
const child = spawn(bin, args, { windowsHide: true })
|
|
25
|
+
const out = []
|
|
26
|
+
const err = []
|
|
27
|
+
child.stdout?.on('data', (chunk) => out.push(chunk))
|
|
28
|
+
child.stderr?.on('data', (chunk) => err.push(chunk))
|
|
29
|
+
child.on('error', rejectPromise)
|
|
30
|
+
child.on('close', (code) =>
|
|
31
|
+
resolvePromise({
|
|
32
|
+
code,
|
|
33
|
+
stdout: Buffer.concat(out),
|
|
34
|
+
stderr: Buffer.concat(err).toString('utf8'),
|
|
35
|
+
}),
|
|
36
|
+
)
|
|
37
|
+
})
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function probeSize(path) {
|
|
41
|
+
const ffprobe = findBinary('ffprobe')
|
|
42
|
+
const result = await runBuffer(ffprobe, [
|
|
43
|
+
'-v',
|
|
44
|
+
'error',
|
|
45
|
+
'-select_streams',
|
|
46
|
+
'v:0',
|
|
47
|
+
'-show_entries',
|
|
48
|
+
'stream=width,height',
|
|
49
|
+
'-of',
|
|
50
|
+
'csv=p=0',
|
|
51
|
+
path,
|
|
52
|
+
])
|
|
53
|
+
const text = result.stdout.toString('utf8').trim()
|
|
54
|
+
const match = /^(\d+),(\d+)/.exec(text)
|
|
55
|
+
if (result.code !== 0 || !match) {
|
|
56
|
+
throw fail('MEASURE_UNREADABLE', `读不出图片尺寸(${path}):${result.stderr.trim() || text || 'ffprobe 无输出'}`)
|
|
57
|
+
}
|
|
58
|
+
return { width: Number(match[1]), height: Number(match[2]) }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 解码成 8 位灰度。超过 4000 万像素直接拒绝,免得一口气吃掉几百 MB。 */
|
|
62
|
+
async function loadGray(path) {
|
|
63
|
+
if (!existsSync(path)) throw fail('MEASURE_NOT_FOUND', `找不到图片:${path}`)
|
|
64
|
+
const size = await probeSize(path)
|
|
65
|
+
if (size.width * size.height > 40_000_000) {
|
|
66
|
+
throw fail('MEASURE_TOO_LARGE', `图片太大(${size.width}×${size.height}),先裁出要量的区域再试。`)
|
|
67
|
+
}
|
|
68
|
+
const result = await runBuffer(findBinary('ffmpeg'), [
|
|
69
|
+
'-v',
|
|
70
|
+
'error',
|
|
71
|
+
'-i',
|
|
72
|
+
path,
|
|
73
|
+
'-f',
|
|
74
|
+
'rawvideo',
|
|
75
|
+
'-pix_fmt',
|
|
76
|
+
'gray',
|
|
77
|
+
'-',
|
|
78
|
+
])
|
|
79
|
+
if (result.code !== 0 || result.stdout.length < size.width * size.height) {
|
|
80
|
+
throw fail('MEASURE_DECODE', `ffmpeg 解码失败:${result.stderr.trim() || `只拿到 ${result.stdout.length} 字节`}`)
|
|
81
|
+
}
|
|
82
|
+
return { width: size.width, height: size.height, data: result.stdout }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function otsuThreshold(histogram) {
|
|
86
|
+
let total = 0
|
|
87
|
+
let sum = 0
|
|
88
|
+
for (let i = 0; i < histogram.length; i += 1) {
|
|
89
|
+
total += histogram[i]
|
|
90
|
+
sum += i * histogram[i]
|
|
91
|
+
}
|
|
92
|
+
if (total === 0) return 24
|
|
93
|
+
let best = 24
|
|
94
|
+
let bestVariance = -1
|
|
95
|
+
let weightLow = 0
|
|
96
|
+
let sumLow = 0
|
|
97
|
+
for (let level = 1; level < histogram.length; level += 1) {
|
|
98
|
+
weightLow += histogram[level - 1]
|
|
99
|
+
sumLow += (level - 1) * histogram[level - 1]
|
|
100
|
+
const weightHigh = total - weightLow
|
|
101
|
+
if (weightLow === 0 || weightHigh === 0) continue
|
|
102
|
+
const meanLow = sumLow / weightLow
|
|
103
|
+
const meanHigh = (sum - sumLow) / weightHigh
|
|
104
|
+
const variance = weightLow * weightHigh * (meanLow - meanHigh) * (meanLow - meanHigh)
|
|
105
|
+
if (variance > bestVariance) {
|
|
106
|
+
bestVariance = variance
|
|
107
|
+
best = level
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
// 太低的阈值会把压缩噪声当边:起码要 16。
|
|
111
|
+
return Math.max(16, best)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function gradientHistogram(gray, width, region, axis) {
|
|
115
|
+
const [x0, y0, x1, y1] = region
|
|
116
|
+
const histogram = new Array(256).fill(0)
|
|
117
|
+
if (axis === 'x') {
|
|
118
|
+
for (let y = y0; y < y1; y += 1) {
|
|
119
|
+
for (let x = x0 + 1; x < x1; x += 1) {
|
|
120
|
+
histogram[Math.abs(gray[y * width + x] - gray[y * width + x - 1])] += 1
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
} else {
|
|
124
|
+
for (let y = y0 + 1; y < y1; y += 1) {
|
|
125
|
+
for (let x = x0; x < x1; x += 1) {
|
|
126
|
+
histogram[Math.abs(gray[y * width + x] - gray[(y - 1) * width + x])] += 1
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return histogram
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 把相邻的命中像素并成一条线,返回线的中心像素。 */
|
|
134
|
+
function cluster(positions, minGap) {
|
|
135
|
+
const lines = []
|
|
136
|
+
let sum = 0
|
|
137
|
+
let weight = 0
|
|
138
|
+
let last = null
|
|
139
|
+
for (const { at, count } of positions) {
|
|
140
|
+
if (last !== null && at - last > minGap) {
|
|
141
|
+
lines.push(Math.round(sum / Math.max(1, weight)))
|
|
142
|
+
sum = 0
|
|
143
|
+
weight = 0
|
|
144
|
+
}
|
|
145
|
+
sum += at * count
|
|
146
|
+
weight += count
|
|
147
|
+
last = at
|
|
148
|
+
}
|
|
149
|
+
if (weight > 0) lines.push(Math.round(sum / weight))
|
|
150
|
+
return lines
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 找垂直于 axis 的直线:axis=“x” 找竖线(列),"y" 找横线(行)。
|
|
155
|
+
* 判据不是「整行都亮」,而是「这一列/行上足够多的扫描线出现明显跳变」,
|
|
156
|
+
* 所以器件边框、图框线、栅格线都能被找出来,实线虚线都一样。
|
|
157
|
+
*/
|
|
158
|
+
function findLines(image, region, axis, gradientThreshold, minGap) {
|
|
159
|
+
const [x0, y0, x1, y1] = region
|
|
160
|
+
const hits = new Map()
|
|
161
|
+
const threshold = gradientThreshold ?? otsuThreshold(gradientHistogram(image.data, image.width, region, axis))
|
|
162
|
+
let scans = 0
|
|
163
|
+
|
|
164
|
+
if (axis === 'x') {
|
|
165
|
+
for (let y = y0; y < y1; y += 1) {
|
|
166
|
+
let previous = image.data[y * image.width + x0]
|
|
167
|
+
for (let x = x0 + 1; x < x1; x += 1) {
|
|
168
|
+
const value = image.data[y * image.width + x]
|
|
169
|
+
if (Math.abs(value - previous) >= threshold) hits.set(x, (hits.get(x) ?? 0) + 1)
|
|
170
|
+
previous = value
|
|
171
|
+
}
|
|
172
|
+
scans += 1
|
|
173
|
+
}
|
|
174
|
+
} else {
|
|
175
|
+
for (let x = x0; x < x1; x += 1) {
|
|
176
|
+
let previous = image.data[y0 * image.width + x]
|
|
177
|
+
for (let y = y0 + 1; y < y1; y += 1) {
|
|
178
|
+
const value = image.data[y * image.width + x]
|
|
179
|
+
if (Math.abs(value - previous) >= threshold) hits.set(y, (hits.get(y) ?? 0) + 1)
|
|
180
|
+
previous = value
|
|
181
|
+
}
|
|
182
|
+
scans += 1
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// 至少四分之一扫描线都看到跳变才算线;纯噪点过不了这一关。
|
|
187
|
+
const needed = Math.max(2, Math.floor(scans * 0.25))
|
|
188
|
+
const positions = [...hits]
|
|
189
|
+
.filter(([, count]) => count >= needed)
|
|
190
|
+
.map(([at, count]) => ({ at, count }))
|
|
191
|
+
.sort((a, b) => a.at - b.at)
|
|
192
|
+
return { lines: cluster(positions, minGap), threshold }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function toMm(px, axis, calibration) {
|
|
196
|
+
const { pxPerMm, originPx, originMm, flipY } = calibration
|
|
197
|
+
const index = axis === 'x' ? 0 : 1
|
|
198
|
+
const delta = (px - originPx[index]) / pxPerMm
|
|
199
|
+
return Number((originMm[index] + (axis === 'y' && flipY ? -delta : delta)).toFixed(2))
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function normalizeRegion(region, image) {
|
|
203
|
+
if (!region) return [0, 0, image.width, image.height]
|
|
204
|
+
if (!Array.isArray(region) || region.length !== 4) {
|
|
205
|
+
throw fail('BAD_ARGUMENT', 'region 必须是 [x0, y0, x1, y1] 四个像素坐标。')
|
|
206
|
+
}
|
|
207
|
+
const [x0, y0, x1, y1] = region.map((value) => Math.round(Number(value)))
|
|
208
|
+
if (![x0, y0, x1, y1].every(Number.isFinite) || x0 < 0 || y0 < 0 || x1 > image.width || y1 > image.height || x1 - x0 < 4 || y1 - y0 < 4) {
|
|
209
|
+
throw fail('BAD_ARGUMENT', `region 超出图像范围(图 ${image.width}×${image.height}):${JSON.stringify(region)}`)
|
|
210
|
+
}
|
|
211
|
+
return [x0, y0, x1, y1]
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function gridFrom(lines) {
|
|
215
|
+
const gaps = []
|
|
216
|
+
for (let index = 1; index < lines.length; index += 1) {
|
|
217
|
+
const gap = lines[index] - lines[index - 1]
|
|
218
|
+
if (gap >= 3) gaps.push(gap)
|
|
219
|
+
}
|
|
220
|
+
if (gaps.length === 0) return { spacingPx: null, confidence: 0, samples: 0 }
|
|
221
|
+
const sorted = [...gaps].sort((a, b) => a - b)
|
|
222
|
+
const median = sorted[Math.floor(sorted.length / 2)]
|
|
223
|
+
const near = gaps.filter((gap) => Math.abs(gap - median) <= Math.max(2, median * 0.2))
|
|
224
|
+
return {
|
|
225
|
+
spacingPx: median,
|
|
226
|
+
confidence: Number((near.length / gaps.length).toFixed(2)),
|
|
227
|
+
samples: gaps.length,
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export async function measure(args = {}) {
|
|
232
|
+
const action = args.action ?? 'edges'
|
|
233
|
+
const from = args.from
|
|
234
|
+
const to = args.to
|
|
235
|
+
|
|
236
|
+
if (action === 'calibrate') {
|
|
237
|
+
if (!Array.isArray(from) || !Array.isArray(to) || from.length < 2 || to.length < 2) {
|
|
238
|
+
throw fail('BAD_ARGUMENT', 'calibrate 需要 from 和 to 两个像素坐标 [x, y]。')
|
|
239
|
+
}
|
|
240
|
+
const mm = Number(args.mm)
|
|
241
|
+
if (!Number.isFinite(mm) || mm <= 0) {
|
|
242
|
+
throw fail('BAD_ARGUMENT', 'calibrate 需要 mm(这两点在现实里的距离,毫米)。')
|
|
243
|
+
}
|
|
244
|
+
const pxDistance = Math.hypot(Number(to[0]) - Number(from[0]), Number(to[1]) - Number(from[1]))
|
|
245
|
+
if (!(pxDistance > 0.5)) throw fail('BAD_ARGUMENT', 'from 与 to 落在同一个像素上,量不出比例。')
|
|
246
|
+
const pxPerMm = pxDistance / mm
|
|
247
|
+
const payload = {
|
|
248
|
+
action,
|
|
249
|
+
pxDistance: Number(pxDistance.toFixed(2)),
|
|
250
|
+
mm,
|
|
251
|
+
pxPerMm: Number(pxPerMm.toFixed(3)),
|
|
252
|
+
mmPerPx: Number((1 / pxPerMm).toFixed(4)),
|
|
253
|
+
resolutionOk: pxPerMm >= 8,
|
|
254
|
+
}
|
|
255
|
+
if (pxPerMm < 8) {
|
|
256
|
+
payload.warning =
|
|
257
|
+
`这个分辨率下 1 mm 只有 ${pxPerMm.toFixed(2)} px,换算误差约 ±${(0.5 / pxPerMm).toFixed(2)} mm(半个像素)。` +
|
|
258
|
+
'要量到 0.5 mm 以内,请把截图或录屏分辨率提高(至少 8 px/mm 才勉强够用)。'
|
|
259
|
+
}
|
|
260
|
+
return payload
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const image = await loadGray(args.path)
|
|
264
|
+
const region = normalizeRegion(args.region, image)
|
|
265
|
+
const minGap = Math.max(1, Number(args.minGapPx ?? 3))
|
|
266
|
+
|
|
267
|
+
const calibration = (() => {
|
|
268
|
+
const pxPerMm = Number(args.pxPerMm)
|
|
269
|
+
if (!Number.isFinite(pxPerMm) || pxPerMm <= 0) return null
|
|
270
|
+
return {
|
|
271
|
+
pxPerMm,
|
|
272
|
+
originPx: Array.isArray(args.originPx) ? args.originPx.map(Number) : [0, image.height],
|
|
273
|
+
originMm: Array.isArray(args.originMm) ? args.originMm.map(Number) : [0, 0],
|
|
274
|
+
flipY: args.flipY !== false,
|
|
275
|
+
}
|
|
276
|
+
})()
|
|
277
|
+
|
|
278
|
+
const axes = args.axis === 'x' || args.axis === 'y' ? [args.axis] : ['x', 'y']
|
|
279
|
+
const threshold = args.threshold === undefined ? undefined : Math.max(1, Number(args.threshold))
|
|
280
|
+
|
|
281
|
+
const result = {
|
|
282
|
+
action,
|
|
283
|
+
image: { width: image.width, height: image.height },
|
|
284
|
+
region,
|
|
285
|
+
threshold: threshold ?? null,
|
|
286
|
+
axis: axes.length === 2 ? 'both' : axes[0],
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const linesByAxis = {}
|
|
290
|
+
for (const axis of axes) {
|
|
291
|
+
const found = findLines(image, region, axis, threshold, minGap)
|
|
292
|
+
result.threshold = found.threshold
|
|
293
|
+
const lines = found.lines
|
|
294
|
+
linesByAxis[axis] = lines
|
|
295
|
+
if (action === 'grid') {
|
|
296
|
+
const grid = gridFrom(lines)
|
|
297
|
+
result.spacingPx = { ...(result.spacingPx ?? {}), [axis]: grid.spacingPx }
|
|
298
|
+
result.confidence = { ...(result.confidence ?? {}), [axis]: grid.confidence }
|
|
299
|
+
result.samples = { ...(result.samples ?? {}), [axis]: grid.samples }
|
|
300
|
+
if (grid.spacingPx !== null && calibration) {
|
|
301
|
+
result.spacingMm = { ...(result.spacingMm ?? {}), [axis]: Number((grid.spacingPx / calibration.pxPerMm).toFixed(2)) }
|
|
302
|
+
}
|
|
303
|
+
} else {
|
|
304
|
+
const items = lines.slice(0, 60).map((px) => (calibration ? { px, mm: toMm(px, axis, calibration) } : { px }))
|
|
305
|
+
result[axis] = items
|
|
306
|
+
result.count = { ...(result.count ?? {}), [axis]: items.length }
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
if (action === 'edges' && calibration) {
|
|
311
|
+
result.note =
|
|
312
|
+
`换算假设:图上的 (${calibration.originPx[0]}, ${calibration.originPx[1]}) 等于 (${calibration.originMm[0]}, ${calibration.originMm[1]}) mm,` +
|
|
313
|
+
`${calibration.pxPerMm.toFixed(2)} px/mm${calibration.flipY ? ',图片 Y 轴向下而 EPLAN Y 轴向上(已翻转)' : ''}。` +
|
|
314
|
+
'核对首尾两条线是否与已知尺寸对得上,对不上就是标定选错了。'
|
|
315
|
+
}
|
|
316
|
+
if (action === 'edges' && linesByAxis.x?.length === 0 && linesByAxis.y?.length === 0) {
|
|
317
|
+
result.note = '一条线都没找到:可能是阈值太高,或 region 选的是空白区域。传 threshold=16 再试一次。'
|
|
318
|
+
}
|
|
319
|
+
return result
|
|
320
|
+
}
|
package/server/pdf.mjs
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// PDF 读取:把手册变成模型能用的文字和坐标。
|
|
2
|
+
//
|
|
3
|
+
// 为什么需要它:DSH 内置的文档解析器不支持 xref-stream / object-stream 的 PDF
|
|
4
|
+
// (现代 PDF 1.5+ 基本都是这种),而电气手册恰好都是。没有这个模块,
|
|
5
|
+
// 模型连「手册里有哪些图、端子怎么定义」都不知道,只能靠猜。
|
|
6
|
+
//
|
|
7
|
+
// 用 pdfjs-dist 的 legacy 构建:纯 JS,不需要 canvas,不需要原生编译。
|
|
8
|
+
// 迁移到新机器时只要能 npm install 就行,不会卡在编译工具链上。
|
|
9
|
+
import { readFile } from 'node:fs/promises'
|
|
10
|
+
import { existsSync } from 'node:fs'
|
|
11
|
+
|
|
12
|
+
let pdfjsPromise = null
|
|
13
|
+
|
|
14
|
+
async function loadPdfjs() {
|
|
15
|
+
if (!pdfjsPromise) {
|
|
16
|
+
pdfjsPromise = import('pdfjs-dist/legacy/build/pdf.mjs').then((mod) => {
|
|
17
|
+
// 关掉 eval 和字体渲染:我们只要文字,不要安全风险和 canvas 依赖。
|
|
18
|
+
return mod
|
|
19
|
+
})
|
|
20
|
+
}
|
|
21
|
+
return pdfjsPromise
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function openDocument(path) {
|
|
25
|
+
if (!existsSync(path)) {
|
|
26
|
+
const error = new Error(`找不到文件:${path}`)
|
|
27
|
+
error.code = 'PDF_NOT_FOUND'
|
|
28
|
+
throw error
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const pdfjs = await loadPdfjs()
|
|
32
|
+
const data = new Uint8Array(await readFile(path))
|
|
33
|
+
|
|
34
|
+
const task = pdfjs.getDocument({
|
|
35
|
+
data,
|
|
36
|
+
isEvalSupported: false,
|
|
37
|
+
disableFontFace: true,
|
|
38
|
+
useSystemFonts: false,
|
|
39
|
+
// 空密码能打开「仅限制编辑」的 PDF;真正加密的会走 catch 分支。
|
|
40
|
+
password: '',
|
|
41
|
+
verbosity: 0,
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
try {
|
|
45
|
+
return { doc: await task.promise, pdfjs }
|
|
46
|
+
} catch (error) {
|
|
47
|
+
const wrapped = new Error(
|
|
48
|
+
`这个 PDF 打不开:${error.message}。` +
|
|
49
|
+
'如果它加了密码,请先另存一份去掉密码的版本;如果是扫描件(整页是图片),' +
|
|
50
|
+
'文字抽不出来,需要把相关页截图发给我。',
|
|
51
|
+
)
|
|
52
|
+
wrapped.code = 'PDF_UNREADABLE'
|
|
53
|
+
throw wrapped
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 把一页的文字项按行归并。
|
|
59
|
+
*
|
|
60
|
+
* PDF 里没有「行」的概念,只有一个个带坐标的文字块。电气手册的端子表和
|
|
61
|
+
* 接线图说明全靠位置对齐,所以必须按 y 坐标分组成行,否则拼出来是乱的。
|
|
62
|
+
*/
|
|
63
|
+
function groupIntoLines(items, tolerance = 2.2) {
|
|
64
|
+
const rows = []
|
|
65
|
+
for (const item of items) {
|
|
66
|
+
if (!item.str || !item.str.trim()) continue
|
|
67
|
+
const x = item.transform[4]
|
|
68
|
+
const y = item.transform[5]
|
|
69
|
+
let row = rows.find((candidate) => Math.abs(candidate.y - y) <= tolerance)
|
|
70
|
+
if (!row) {
|
|
71
|
+
row = { y, cells: [] }
|
|
72
|
+
rows.push(row)
|
|
73
|
+
}
|
|
74
|
+
row.cells.push({ x, text: item.str })
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
rows.sort((a, b) => b.y - a.y)
|
|
78
|
+
return rows.map((row) => {
|
|
79
|
+
row.cells.sort((a, b) => a.x - b.x)
|
|
80
|
+
return {
|
|
81
|
+
y: Math.round(row.y * 10) / 10,
|
|
82
|
+
// 用多个空格保留横向间隔,读起来更接近原表。
|
|
83
|
+
text: row.cells
|
|
84
|
+
.map((cell, index) => (index === 0 ? cell.text : ' '.repeat(Math.max(1, Math.round((cell.x - row.cells[index - 1].x) / 2.2))) + cell.text))
|
|
85
|
+
.join('')
|
|
86
|
+
.replace(/\s+$/, ''),
|
|
87
|
+
cells: row.cells.map((cell) => ({ x: Math.round(cell.x * 10) / 10, text: cell.text })),
|
|
88
|
+
}
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function describeError(error) {
|
|
93
|
+
const item = { code: error.code ?? 'PDF_ERROR', message: error.message }
|
|
94
|
+
return item
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 手册结构:多少页、每页有多少字、有没有目录。用来决定「画哪些页」。 */
|
|
98
|
+
export async function pdfOutline(path) {
|
|
99
|
+
const { doc } = await openDocument(path)
|
|
100
|
+
|
|
101
|
+
const meta = await doc.getMetadata().catch(() => null)
|
|
102
|
+
const info = meta?.info ?? {}
|
|
103
|
+
|
|
104
|
+
const pages = []
|
|
105
|
+
const total = doc.numPages
|
|
106
|
+
for (let index = 1; index <= total; index += 1) {
|
|
107
|
+
const page = await doc.getPage(index)
|
|
108
|
+
const viewport = page.getViewport({ scale: 1 })
|
|
109
|
+
const text = await page.getTextContent()
|
|
110
|
+
const chars = text.items.reduce((sum, item) => sum + (item.str ? item.str.length : 0), 0)
|
|
111
|
+
pages.push({
|
|
112
|
+
page: index,
|
|
113
|
+
chars,
|
|
114
|
+
width: Math.round(viewport.width),
|
|
115
|
+
height: Math.round(viewport.height),
|
|
116
|
+
// 字数太少通常意味着这是扫描页或整页图,只能靠截图。
|
|
117
|
+
looksScanned: chars < 40,
|
|
118
|
+
})
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const outline = await doc.getOutline().catch(() => null)
|
|
122
|
+
|
|
123
|
+
return {
|
|
124
|
+
path,
|
|
125
|
+
numPages: total,
|
|
126
|
+
info: {
|
|
127
|
+
title: info.Title ?? null,
|
|
128
|
+
author: info.Author ?? null,
|
|
129
|
+
creator: info.Creator ?? null,
|
|
130
|
+
},
|
|
131
|
+
scannedPages: pages.filter((page) => page.looksScanned).map((page) => page.page),
|
|
132
|
+
outline: outline
|
|
133
|
+
? outline.slice(0, 80).map((item) => ({ title: item.title, page: null }))
|
|
134
|
+
: null,
|
|
135
|
+
pages,
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 按页取文字。layout=true 时按坐标分行,适合读端子表;false 时纯文本。 */
|
|
140
|
+
export async function pdfText(path, options = {}) {
|
|
141
|
+
const { doc } = await openDocument(path)
|
|
142
|
+
const from = Math.max(1, options.from ?? 1)
|
|
143
|
+
const to = Math.min(doc.numPages, options.to ?? from)
|
|
144
|
+
const layout = options.layout !== false
|
|
145
|
+
|
|
146
|
+
const out = []
|
|
147
|
+
for (let index = from; index <= to; index += 1) {
|
|
148
|
+
const page = await doc.getPage(index)
|
|
149
|
+
const content = await page.getTextContent()
|
|
150
|
+
const lines = groupIntoLines(content.items)
|
|
151
|
+
out.push({
|
|
152
|
+
page: index,
|
|
153
|
+
text: layout ? lines.map((line) => line.text).join('\n') : content.items.map((item) => item.str).join(' '),
|
|
154
|
+
lines: layout ? lines.length : undefined,
|
|
155
|
+
})
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return { path, from, to, numPages: doc.numPages, pages: out }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** 在一份或几份 PDF 里搜关键词,返回命中页。找「端子」「接线」「主回路」用这个。 */
|
|
162
|
+
export async function pdfSearch(path, queries) {
|
|
163
|
+
const { doc } = await openDocument(path)
|
|
164
|
+
const terms = (queries ?? []).filter((q) => q && q.length > 0)
|
|
165
|
+
if (terms.length === 0) {
|
|
166
|
+
const error = new Error('至少给一个要搜的词(queries)。')
|
|
167
|
+
error.code = 'BAD_ARGUMENT'
|
|
168
|
+
throw error
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const hits = []
|
|
172
|
+
for (let index = 1; index <= doc.numPages; index += 1) {
|
|
173
|
+
const page = await doc.getPage(index)
|
|
174
|
+
const content = await page.getTextContent()
|
|
175
|
+
const text = content.items.map((item) => item.str).join('')
|
|
176
|
+
const matched = terms.filter((term) => text.indexOf(term) >= 0)
|
|
177
|
+
if (matched.length > 0) {
|
|
178
|
+
hits.push({ page: index, matched, snippet: text.slice(0, 160) })
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return { path, queries: terms, numPages: doc.numPages, hits }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export { describeError }
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# 用 Windows 自带的 PDF 引擎把某一页渲染成 PNG。
|
|
2
|
+
#
|
|
3
|
+
# 为什么不用 pdfjs + canvas:pdfjs v4 调 clip() 的方式和 @napi-rs/canvas 不兼容,
|
|
4
|
+
# 而且 node-canvas 在全新机器上要搭编译环境,和「可迁移」的目标冲突。
|
|
5
|
+
# Windows 10/11 自带 Windows.Data.Pdf,零依赖,渲染质量也更好。
|
|
6
|
+
#
|
|
7
|
+
# 用法:
|
|
8
|
+
# powershell -File pdf2png.ps1 -Pdf "C:\a.pdf" -OutDir "C:\out" -From 1 -To 3 -Scale 2
|
|
9
|
+
param(
|
|
10
|
+
[Parameter(Mandatory = $true)][string]$Pdf,
|
|
11
|
+
[Parameter(Mandatory = $true)][string]$OutDir,
|
|
12
|
+
[int]$From = 1,
|
|
13
|
+
[int]$To = 0,
|
|
14
|
+
[double]$Scale = 2.0
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
$ErrorActionPreference = 'Stop'
|
|
18
|
+
|
|
19
|
+
if (-not (Test-Path -LiteralPath $Pdf)) {
|
|
20
|
+
Write-Output "ERROR|PDF_NOT_FOUND|找不到文件:$Pdf"
|
|
21
|
+
exit 2
|
|
22
|
+
}
|
|
23
|
+
if (-not (Test-Path -LiteralPath $OutDir)) {
|
|
24
|
+
New-Item -ItemType Directory -Path $OutDir -Force | Out-Null
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
try {
|
|
28
|
+
# System.Runtime.WindowsRuntime 提供 AsTask 桥接,不显式加载的话
|
|
29
|
+
# [System.WindowsRuntimeSystemExtensions] 会报 TypeNotFound。
|
|
30
|
+
Add-Type -AssemblyName System.Runtime.WindowsRuntime -ErrorAction Stop
|
|
31
|
+
[Windows.Data.Pdf.PdfDocument, Windows.Data.Pdf, ContentType = WindowsRuntime] | Out-Null
|
|
32
|
+
[Windows.Storage.StorageFile, Windows.Storage, ContentType = WindowsRuntime] | Out-Null
|
|
33
|
+
[Windows.Storage.Streams.InMemoryRandomAccessStream, Windows.Storage.Streams, ContentType = WindowsRuntime] | Out-Null
|
|
34
|
+
} catch {
|
|
35
|
+
Write-Output "ERROR|PDF_RUNTIME|这台机器没有 Windows.Data.Pdf,需要 Windows 10 及以上。$($_.Exception.Message)"
|
|
36
|
+
exit 3
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
# WinRT 的异步调用在 PowerShell 里要用 AsTask 包一层才能同步等。
|
|
40
|
+
function Await($task, $resultType) {
|
|
41
|
+
$asTask = ([System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object {
|
|
42
|
+
$_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and
|
|
43
|
+
$_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1'
|
|
44
|
+
})[0]
|
|
45
|
+
$netTask = $asTask.MakeGenericMethod($resultType).Invoke($null, @($task))
|
|
46
|
+
$netTask.Wait(-1) | Out-Null
|
|
47
|
+
return $netTask.Result
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
$full = (Resolve-Path -LiteralPath $Pdf).Path
|
|
51
|
+
$file = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync($full)) ([Windows.Storage.StorageFile])
|
|
52
|
+
$doc = Await ([Windows.Data.Pdf.PdfDocument]::LoadFromFileAsync($file)) ([Windows.Data.Pdf.PdfDocument])
|
|
53
|
+
|
|
54
|
+
$count = [int]$doc.PageCount
|
|
55
|
+
if ($To -le 0 -or $To -gt $count) { $To = $count }
|
|
56
|
+
if ($From -lt 1) { $From = 1 }
|
|
57
|
+
|
|
58
|
+
$base = [System.IO.Path]::GetFileNameWithoutExtension($full)
|
|
59
|
+
$results = @()
|
|
60
|
+
|
|
61
|
+
for ($i = $From; $i -le $To; $i++) {
|
|
62
|
+
$page = $doc.GetPage([uint32]($i - 1))
|
|
63
|
+
|
|
64
|
+
$opts = New-Object Windows.Data.Pdf.PdfPageRenderOptions
|
|
65
|
+
$opts.DestinationWidth = [uint32]([math]::Round($page.Size.Width * $Scale))
|
|
66
|
+
# 透明背景会让线条在深色查看器里消失,先定死白底。
|
|
67
|
+
$opts.BackgroundColor = [Windows.UI.Color]::FromArgb(255, 255, 255, 255)
|
|
68
|
+
|
|
69
|
+
$name = '{0}-p{1}.png' -f $base, ([string]$i).PadLeft(3, '0')
|
|
70
|
+
$target = Join-Path $OutDir $name
|
|
71
|
+
|
|
72
|
+
if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Force }
|
|
73
|
+
|
|
74
|
+
$storageFolder = Await ([Windows.Storage.StorageFolder]::GetFolderFromPathAsync($OutDir)) ([Windows.Storage.StorageFolder])
|
|
75
|
+
$outFile = Await ($storageFolder.CreateFileAsync($name, [Windows.Storage.CreationCollisionOption]::ReplaceExisting)) ([Windows.Storage.StorageFile])
|
|
76
|
+
$stream = Await ($outFile.OpenAsync([Windows.Storage.FileAccessMode]::ReadWrite)) ([Windows.Storage.Streams.IRandomAccessStream])
|
|
77
|
+
|
|
78
|
+
# IAsyncAction 是 COM 对象,不能直接 .AsTask();PowerShell 也选不出
|
|
79
|
+
# AsTask 的哪个重载,所以要按参数类型反射挑。
|
|
80
|
+
$task = $page.RenderToStreamAsync($stream, $opts)
|
|
81
|
+
$asTask = $script:AsTaskAction
|
|
82
|
+
if ($null -eq $asTask) {
|
|
83
|
+
$asTask = [System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object {
|
|
84
|
+
$_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and
|
|
85
|
+
$_.GetParameters()[0].ParameterType.Name -eq 'IAsyncAction'
|
|
86
|
+
} | Select-Object -First 1
|
|
87
|
+
$script:AsTaskAction = $asTask
|
|
88
|
+
}
|
|
89
|
+
if ($null -eq $asTask) { throw '找不到 AsTask(IAsyncAction) 重载' }
|
|
90
|
+
$netAction = $asTask.Invoke($null, @($task))
|
|
91
|
+
$netAction.Wait(-1) | Out-Null
|
|
92
|
+
$stream.Dispose()
|
|
93
|
+
|
|
94
|
+
$results += ('{0}|{1}|{2}' -f $i, $target, [int]([math]::Round($page.Size.Width * $Scale)))
|
|
95
|
+
$page.Dispose()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
Write-Output ("PAGES|" + $count)
|
|
99
|
+
foreach ($line in $results) { Write-Output ("PAGE|" + $line) }
|