dsh-watch-together 0.2.10 → 0.2.12
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/CHANGELOG.md +202 -0
- package/README.md +15 -5
- package/docs/INTERFACES.zh.md +29 -12
- package/docs/VOICE.zh.md +49 -1
- package/dsh.plugin.json +12 -12
- package/examples/floating-chat/glass_capture.py +341 -0
- package/examples/floating-chat/glass_cpu.py +174 -0
- package/examples/floating-chat/glass_geometry.py +311 -0
- package/examples/floating-chat/glass_gpu.py +509 -0
- package/examples/floating-chat/glass_window.py +4 -7
- package/examples/floating-chat/glass_window_gpu.py +14 -516
- package/examples/floating-chat/requirements-glass.txt +5 -0
- package/examples/floating-chat/run-glass.cmd +5 -1
- package/examples/floating-chat/window.py +1215 -1932
- package/examples/floating-chat/window_widgets.py +308 -0
- package/examples/voice-edge-tts/index.mjs +65 -2
- package/examples/voice-edge-tts/stream/client.mjs +151 -0
- package/examples/voice-edge-tts/stream/daemon.py +494 -0
- package/examples/voice-edge-tts/stream/warm.mp3 +0 -0
- package/package.json +118 -115
- package/src/watch-loop.js +12 -6
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
"""glass_capture.py — 抓屏、运动判定、所有渲染路径共用的收尾。
|
|
2
|
+
|
|
3
|
+
CPU 与 GPU 两条管线以前各写一份「抓屏 → 算静态签名 → 判断要不要重合成 →
|
|
4
|
+
贴麦克风 → 贴圆角遮罩」,于是同一个 bug 要修两遍(#39、#48 都是这么来的:
|
|
5
|
+
CPU 修了,GPU 漏了)。这里把它们收成一套:
|
|
6
|
+
|
|
7
|
+
- `CaptureSource.grab()`:窗口矩形外扩 PAD、钳位、守卫零尺寸;
|
|
8
|
+
- `MotionTracker.observe()`:返回 `(moved, stale)`,**两个判断一次算完**,
|
|
9
|
+
不会再出现「拖动窗口算不算动」这种两边理解不一致;
|
|
10
|
+
- `finish()` / `paste_mic()`:两条路径的最后两步。
|
|
11
|
+
|
|
12
|
+
渲染器只负责「一张图 → 一张图」,其余都在这里。
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import time
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
from PIL import Image
|
|
23
|
+
|
|
24
|
+
from glass_geometry import KEY, LPF, MIC_SIZE, PAD, Geometry
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
import cv2 as _cv2
|
|
28
|
+
except Exception: # OpenCV 只是加速,缺了仍走 PIL
|
|
29
|
+
_cv2 = None
|
|
30
|
+
|
|
31
|
+
HERE = Path(__file__).resolve().parent
|
|
32
|
+
|
|
33
|
+
# 静态跳帧:像素差超过这个就算「动了」
|
|
34
|
+
SIG_STEP = 4 # 采样步长(像素)
|
|
35
|
+
MOVE_MEAN = 0.01 # 平均差阈值(0~255)
|
|
36
|
+
MOVE_MAX = 0.5 # 单点最大差阈值
|
|
37
|
+
STALE_AFTER = 0.30 # 运动结束后多久允许跳帧
|
|
38
|
+
|
|
39
|
+
FORCE = os.environ.get("GLASS_FORCE") == "1"
|
|
40
|
+
|
|
41
|
+
# 抓屏连续失败时的替身底板颜色。取窗口本体那种深蓝黑:和气泡底板同一套色,
|
|
42
|
+
# 失败时看起来像"玻璃后面是暗背景",而不是一块死黑。
|
|
43
|
+
SOLID_RGB = (18, 22, 30)
|
|
44
|
+
_solid_cache: dict[tuple[int, int], "_SolidShot"] = {}
|
|
45
|
+
_last_warn = [0.0]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _SolidShot:
|
|
49
|
+
"""`mss` 截图的替身:只实现下游用到的 `.size` / `.rgb` / `.bgra`。
|
|
50
|
+
|
|
51
|
+
下游两条路都在这儿取像素:CPU 走 `Image.frombytes("RGB", size, rgb)`,
|
|
52
|
+
GPU 走 `np.frombuffer(shot.shot.bgra).reshape(h, w, 4)`。少给一个属性
|
|
53
|
+
就是「失败时 CPU 能兜、GPU 每帧抛」—— 而 GPU 那条正好是有问题的那台机器
|
|
54
|
+
更可能开的(`DSH_GLASS_GPU=1`)。
|
|
55
|
+
"""
|
|
56
|
+
__slots__ = ("size", "rgb", "bgra")
|
|
57
|
+
|
|
58
|
+
def __init__(self, w: int, h: int, color: tuple[int, int, int] = SOLID_RGB):
|
|
59
|
+
self.size = (w, h)
|
|
60
|
+
r, g, b = color
|
|
61
|
+
self.rgb = bytes((r, g, b)) * (w * h)
|
|
62
|
+
self.bgra = bytes((b, g, r, 255)) * (w * h)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _solid_shot(w: int, h: int) -> "_SolidShot":
|
|
66
|
+
"""同尺寸复用一份(失败时每帧都要一张,别一直分配 1MB+)。"""
|
|
67
|
+
key = (w, h)
|
|
68
|
+
shot = _solid_cache.get(key)
|
|
69
|
+
if shot is None:
|
|
70
|
+
shot = _SolidShot(w, h)
|
|
71
|
+
if len(_solid_cache) > 4:
|
|
72
|
+
_solid_cache.clear()
|
|
73
|
+
_solid_cache[key] = shot
|
|
74
|
+
return shot
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _warn_grab(exc: Exception) -> None:
|
|
78
|
+
"""抓屏失败**只喊一次**(30 秒内不重复)。每帧刷屏等于没有日志。"""
|
|
79
|
+
now = time.monotonic()
|
|
80
|
+
if now - _last_warn[0] < 30:
|
|
81
|
+
return
|
|
82
|
+
_last_warn[0] = now
|
|
83
|
+
print(f"capture failed, using solid plate: {type(exc).__name__}: {exc}", flush=True)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _load_mic() -> tuple[Image.Image, Image.Image]:
|
|
87
|
+
"""麦克风图标:去背景得到 alpha,再做浅色/深色两版(按背后亮度挑)。"""
|
|
88
|
+
try:
|
|
89
|
+
mask = Image.open(HERE / "mic-dsh.png").convert("L")
|
|
90
|
+
mask = mask.resize((MIC_SIZE, MIC_SIZE), Image.Resampling.LANCZOS)
|
|
91
|
+
except Exception:
|
|
92
|
+
mask = Image.new("L", (MIC_SIZE, MIC_SIZE), 200)
|
|
93
|
+
light = Image.new("RGBA", mask.size, (235, 244, 255, 0))
|
|
94
|
+
light.putalpha(mask)
|
|
95
|
+
dark = Image.new("RGBA", mask.size, (24, 48, 72, 0))
|
|
96
|
+
dark.putalpha(mask)
|
|
97
|
+
return light, dark
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
MIC_LIGHT, MIC_DARK = _load_mic()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def resample(arr_or_im, size):
|
|
104
|
+
"""缩放一张图(两个方向都用);有 OpenCV 走 OpenCV,比 PIL 快一个数量级。"""
|
|
105
|
+
if _cv2 is not None:
|
|
106
|
+
src = np.asarray(arr_or_im)
|
|
107
|
+
return _cv2.resize(src, size, interpolation=_cv2.INTER_LINEAR)
|
|
108
|
+
im = arr_or_im if isinstance(arr_or_im, Image.Image) else Image.fromarray(arr_or_im)
|
|
109
|
+
return np.asarray(im.resize(size, Image.Resampling.BILINEAR))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
CORNER_PROBE = 56 # 角块边长:从这个方块里取中位色
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _median_color(arr: np.ndarray, y0: int, y1: int, x0: int, x1: int):
|
|
116
|
+
"""一块区域的三通道中位数(没有像素返回 None)。
|
|
117
|
+
|
|
118
|
+
用中位数而不是均值:桌面图标、文字这类「少数像素」不会把整块颜色带跑,
|
|
119
|
+
均值会被一个白色图标顶到发白。
|
|
120
|
+
"""
|
|
121
|
+
h, w = arr.shape[:2]
|
|
122
|
+
y0, y1 = max(0, min(h, y0)), max(0, min(h, y1))
|
|
123
|
+
x0, x1 = max(0, min(w, x0)), max(0, min(w, x1))
|
|
124
|
+
patch = arr[y0:y1, x0:x1]
|
|
125
|
+
if patch.size == 0:
|
|
126
|
+
return None
|
|
127
|
+
return np.median(patch.reshape(-1, patch.shape[-1]), axis=0).astype(np.float32)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _fill_patch(arr: np.ndarray, box, step: int = 8) -> None:
|
|
131
|
+
"""把窗口矩形填成「四周环境色」的二维渐变(原地)。
|
|
132
|
+
|
|
133
|
+
**不要拿边缘像素插值**。窗口上下左右紧挨着的那一圈里如果正好有桌面图标或
|
|
134
|
+
文字,插值会把它们沿某个方向整条抹开 —— 纵插值是竖条、横插值是横条,换哪种
|
|
135
|
+
都难看(用户两次都撞上了)。
|
|
136
|
+
|
|
137
|
+
现在只取窗口外**四个角块的中位色**,做双线性。角块完全在窗口外面,不含窗口
|
|
138
|
+
自己的内容;中位数又抹掉了图标这类少数像素;四角双线性只有大尺度过渡,
|
|
139
|
+
不存在任何「把东西拉长」的方向。
|
|
140
|
+
|
|
141
|
+
渐变在 `step` 分之一的粗网格上算再放大:这块最后还要被高斯糊一遍,
|
|
142
|
+
8px 的色阶看不出来。全分辨率算一次要 80ms,粗网格是 0.3ms。
|
|
143
|
+
"""
|
|
144
|
+
h, w = arr.shape[:2]
|
|
145
|
+
x0, y0, x1, y1 = (int(v) for v in box)
|
|
146
|
+
x0, x1 = max(0, min(w, x0)), max(0, min(w, x1))
|
|
147
|
+
y0, y1 = max(0, min(h, y0)), max(0, min(h, y1))
|
|
148
|
+
bw, bh = x1 - x0, y1 - y0
|
|
149
|
+
if bw <= 0 or bh <= 0:
|
|
150
|
+
return
|
|
151
|
+
|
|
152
|
+
b = CORNER_PROBE
|
|
153
|
+
tl = _median_color(arr, y0 - b, y0, x0 - b, x0)
|
|
154
|
+
tr = _median_color(arr, y0 - b, y0, x1, x1 + b)
|
|
155
|
+
bl = _median_color(arr, y1, y1 + b, x0 - b, x0)
|
|
156
|
+
br = _median_color(arr, y1, y1 + b, x1, x1 + b)
|
|
157
|
+
# 窗口贴在屏幕边上时角块会缺 —— 用整圈外框的中位色兜底;
|
|
158
|
+
# 连外框都没有(窗口铺满屏幕)才退回窗口自己的中位色。
|
|
159
|
+
ring = _median_color(arr, y0 - b, y1 + b, x0 - b, x0) if x0 > 0 else None
|
|
160
|
+
if ring is None:
|
|
161
|
+
ring = _median_color(arr, y0 - b, y1 + b, x1, x1 + b) if x1 < w else None
|
|
162
|
+
if ring is None:
|
|
163
|
+
ring = _median_color(arr, y0 - b, y0, x0, x1) if y0 > 0 else None
|
|
164
|
+
if ring is None:
|
|
165
|
+
ring = _median_color(arr, y1, y1 + b, x0, x1) if y1 < h else None
|
|
166
|
+
if ring is None:
|
|
167
|
+
ring = _median_color(arr, y0, y1, x0, x1) or np.zeros(3, np.float32)
|
|
168
|
+
tl = ring if tl is None else tl
|
|
169
|
+
tr = ring if tr is None else tr
|
|
170
|
+
bl = ring if bl is None else bl
|
|
171
|
+
br = ring if br is None else br
|
|
172
|
+
|
|
173
|
+
gw, gh = max(2, bw // step), max(2, bh // step)
|
|
174
|
+
ty = ((np.arange(gh, dtype=np.float32) + 0.5) / gh)[:, None, None]
|
|
175
|
+
tx = ((np.arange(gw, dtype=np.float32) + 0.5) / gw)[None, :, None]
|
|
176
|
+
out = (tl * (1 - tx) * (1 - ty) + tr * tx * (1 - ty)
|
|
177
|
+
+ bl * (1 - tx) * ty + br * tx * ty)
|
|
178
|
+
out = np.clip(out, 0, 255)
|
|
179
|
+
big = resample(out, (bw, bh)) if (gw, gh) != (bw, bh) else out
|
|
180
|
+
arr[y0:y1, x0:x1] = big.astype(np.uint8)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def fill_own_rect(im: Image.Image, box) -> Image.Image:
|
|
184
|
+
"""录屏模式下把「窗口自己」在抓屏帧里占的那块填掉。
|
|
185
|
+
|
|
186
|
+
`capturable: true` 会关掉 WDA,于是 mss 抓背景时把窗口也抓进来,玻璃拿它
|
|
187
|
+
当背景就是「透过自己看自己」:背景里带着上一帧的字 → 亮度判据一直抖 →
|
|
188
|
+
字色来回翻;背景一直在变 → `moved` 恒真 → 越滚越浓的假拖尾。
|
|
189
|
+
|
|
190
|
+
窗口外 PAD 一圈仍是真背景,边缘透镜照常取料。
|
|
191
|
+
"""
|
|
192
|
+
arr = np.array(im)
|
|
193
|
+
_fill_patch(arr, box)
|
|
194
|
+
return Image.fromarray(arr)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def fill_own_rect_array(arr: np.ndarray, box) -> None:
|
|
198
|
+
"""`fill_own_rect` 的原地版本,给直接吃 `shot.bgra` 的 GPU 路径用。
|
|
199
|
+
|
|
200
|
+
GPU 不经过 PIL,如果漏了这一步,抓到的背景里永远有自己 —— 每帧都在变,
|
|
201
|
+
静态跳帧一次都不会触发,还叠出自我反馈的拖尾。
|
|
202
|
+
"""
|
|
203
|
+
_fill_patch(arr, box)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class MotionTracker:
|
|
207
|
+
"""静态跳帧 + 运动强度,两条渲染路径共用。
|
|
208
|
+
|
|
209
|
+
语义(和 0.2.9 修过的 CPU 行为一致):
|
|
210
|
+
|
|
211
|
+
- **抓取区域变了就算动**。拖动窗口时 `box` 每帧都不同,旧区域的像素本来
|
|
212
|
+
也不能直接做差;不标 `moved` 的话,拖动全程都走「没在动」分支 ——
|
|
213
|
+
运动模糊一路衰减到 0、反而每帧去做静止才该做的色散。这就是 #48。
|
|
214
|
+
- 静止超过 `STALE_AFTER` 就允许跳帧(`stale=True`),省掉整条合成;
|
|
215
|
+
- `motion` 是 0~1 的平滑值,只有移动帧才拿它去混上一帧。
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
def __init__(self, force: bool = FORCE):
|
|
219
|
+
self.force = force
|
|
220
|
+
self.motion = 0.0
|
|
221
|
+
self._sig: np.ndarray | None = None
|
|
222
|
+
self._bbox = None
|
|
223
|
+
self._last_motion = 0.0
|
|
224
|
+
|
|
225
|
+
def invalidate(self) -> None:
|
|
226
|
+
"""形状/尺寸变了:旧签名和旧背景都不能再用。"""
|
|
227
|
+
self._sig = None
|
|
228
|
+
self._bbox = None
|
|
229
|
+
self._last_motion = 0.0
|
|
230
|
+
self.motion = 0.0
|
|
231
|
+
|
|
232
|
+
def observe(self, small_rgb: np.ndarray, box, now: float | None = None):
|
|
233
|
+
"""`small_rgb` 是未模糊的 1/4 采样图。返回 `(moved, stale)`。"""
|
|
234
|
+
now = time.perf_counter() if now is None else now
|
|
235
|
+
sig = small_rgb[::SIG_STEP, ::SIG_STEP].astype(np.int16).mean(axis=2)
|
|
236
|
+
moved = False
|
|
237
|
+
if self._bbox is not None and box != self._bbox:
|
|
238
|
+
moved = True
|
|
239
|
+
elif self._sig is not None and sig.shape == self._sig.shape:
|
|
240
|
+
d = np.abs(sig - self._sig)
|
|
241
|
+
moved = bool(float(d.mean()) > MOVE_MEAN or float(d.max()) > MOVE_MAX)
|
|
242
|
+
if moved:
|
|
243
|
+
self._last_motion = now
|
|
244
|
+
self.motion = min(1.0, self.motion * 0.50 + 0.50)
|
|
245
|
+
else:
|
|
246
|
+
self.motion *= 0.55
|
|
247
|
+
stale = (not self.force and not moved and box == self._bbox
|
|
248
|
+
and now - self._last_motion > STALE_AFTER)
|
|
249
|
+
self._sig = sig
|
|
250
|
+
self._bbox = box
|
|
251
|
+
return moved, stale
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def blend(self) -> float:
|
|
255
|
+
"""移动帧混上一帧的强度;停下后立刻归零,不留残影。"""
|
|
256
|
+
return 0.35 * max(0.0, min(1.0, self.motion))
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@dataclass(slots=True)
|
|
260
|
+
class Shot:
|
|
261
|
+
"""一次抓屏的结果。CPU 用 `rgb`,GPU 用 `bgra`,避免重复抓。"""
|
|
262
|
+
|
|
263
|
+
shot: object # mss 的 ScreenShot
|
|
264
|
+
box: tuple # 屏幕坐标 (gl, gt, gr, gb)
|
|
265
|
+
offset: tuple # 窗口左上角在抓屏图里的 1/4 分辨率坐标
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
class CaptureSource:
|
|
269
|
+
"""按窗口矩形抓背景,外扩 PAD 供边缘透镜取「框外」的像素。"""
|
|
270
|
+
|
|
271
|
+
def __init__(self, screen: tuple[int, int], pad: int = PAD, cappable: bool = False):
|
|
272
|
+
self.screen = screen
|
|
273
|
+
self.pad = pad
|
|
274
|
+
self.cappable = cappable
|
|
275
|
+
|
|
276
|
+
def grab(self, sct, bbox) -> Shot | None:
|
|
277
|
+
l, t, r, b = (int(v) for v in bbox)
|
|
278
|
+
if r <= l or b <= t:
|
|
279
|
+
return None
|
|
280
|
+
sw, sh = self.screen
|
|
281
|
+
gl = max(0, l - self.pad)
|
|
282
|
+
gt = max(0, t - self.pad)
|
|
283
|
+
gr = min(sw, r + self.pad)
|
|
284
|
+
gb = min(sh, b + self.pad)
|
|
285
|
+
# 多显示器 / DPI 变化 / 被别的程序挪出屏幕时,钳位后宽高可能 <= 0;
|
|
286
|
+
# mss 会抛 "Region has zero or negative size",而 _work() 会每帧吞掉它
|
|
287
|
+
# —— 表现就是日志刷屏、背景永久停在旧帧。没有可抓的区域就别抓。
|
|
288
|
+
if gr - gl <= 0 or gb - gt <= 0:
|
|
289
|
+
return None
|
|
290
|
+
try:
|
|
291
|
+
shot = sct.grab({"left": gl, "top": gt, "width": gr - gl, "height": gb - gt})
|
|
292
|
+
except Exception as exc:
|
|
293
|
+
# **抓不到就别把窗变成一块透明玻璃。**
|
|
294
|
+
# BitBlt 会在几种场景下失败:桌面锁屏 / UAC 安全桌面 / 远程桌面 /
|
|
295
|
+
# 某些 HDR 或全屏独占的机器。以前这里直接把异常抛给 `_work()`,
|
|
296
|
+
# 于是每帧一条 "capture error"、一帧都画不出来 —— 用户看到的是
|
|
297
|
+
# "背景变成透明的了,只剩字"(2026-11-03 社区反馈)。
|
|
298
|
+
# 现在退成一块**纯色底板**:不好看,但字读得清、窗看得见。
|
|
299
|
+
_warn_grab(exc)
|
|
300
|
+
return Shot(shot=_solid_shot(gr - gl, gb - gt), box=(gl, gt, gr, gb),
|
|
301
|
+
offset=(int(round((l - gl) / LPF)), int(round((t - gt) / LPF))))
|
|
302
|
+
return Shot(shot=shot, box=(gl, gt, gr, gb),
|
|
303
|
+
offset=(int(round((l - gl) / LPF)), int(round((t - gt) / LPF))))
|
|
304
|
+
|
|
305
|
+
def to_image(self, shot: Shot, bbox) -> Image.Image:
|
|
306
|
+
"""抓屏帧 → RGB 图;录屏模式下先把自己挖掉。"""
|
|
307
|
+
im = Image.frombytes("RGB", shot.shot.size, shot.shot.rgb)
|
|
308
|
+
if self.cappable:
|
|
309
|
+
l, t, r, b = (int(v) for v in bbox)
|
|
310
|
+
gl, gt = shot.box[0], shot.box[1]
|
|
311
|
+
im = fill_own_rect(im, (l - gl, t - gt, r - gl, b - gt))
|
|
312
|
+
return im
|
|
313
|
+
|
|
314
|
+
def own_rect(self, shot: Shot, bbox) -> tuple[int, int, int, int]:
|
|
315
|
+
gl, gt = shot.box[0], shot.box[1]
|
|
316
|
+
l, t, r, b = bbox
|
|
317
|
+
return (l - gl, t - gt, r - gl, b - gt)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def finish(geo: Geometry, panel: Image.Image) -> Image.Image:
|
|
321
|
+
"""贴二值圆角遮罩;缝隙/圆角外是 KEY,被 Tk 抠成透明。"""
|
|
322
|
+
out = Image.new("RGB", (geo.width, geo.height), KEY)
|
|
323
|
+
out.paste(panel.convert("RGB"), (0, 0), geo.mask_hard)
|
|
324
|
+
return out
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def paste_mic(geo: Geometry, im: Image.Image) -> Image.Image:
|
|
328
|
+
"""麦克风图标贴进玻璃帧,按背后亮度选浅/深两版(和仓库原做法一致)。"""
|
|
329
|
+
x, y = geo.mic_pos
|
|
330
|
+
box = im.crop((x, y, x + MIC_SIZE, y + MIC_SIZE)).convert("L")
|
|
331
|
+
bg = float(np.median(np.asarray(box))) / 255.0
|
|
332
|
+
out = im.convert("RGBA")
|
|
333
|
+
icon = MIC_LIGHT if bg < 0.48 else MIC_DARK
|
|
334
|
+
out.paste(icon, (x, y), icon)
|
|
335
|
+
return out.convert("RGB")
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
__all__ = [
|
|
339
|
+
"CaptureSource", "FORCE", "MIC_DARK", "MIC_LIGHT", "MotionTracker", "Shot",
|
|
340
|
+
"fill_own_rect", "finish", "paste_mic", "resample",
|
|
341
|
+
]
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""glass_cpu.py — CPU 玻璃合成:抓屏 → 模糊 → 边缘折射 → 内框透镜 → 染色 → 色散。
|
|
2
|
+
|
|
3
|
+
这就是原来 `window.LiveGlass._capture()` 那 130 行,拆成一条显式的管线:
|
|
4
|
+
|
|
5
|
+
grab → 缩小 → observe(moved/stale) → 模糊 → 折射 → 内框
|
|
6
|
+
→ 2x 合成 → 染色 → 色散(仅静止帧) → 放大 → 残影(仅移动帧) → 麦克风 → 圆角
|
|
7
|
+
|
|
8
|
+
渲染器不再知道 Tk、配置、聊天流的存在:给一张背景,还一张玻璃。
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
from PIL import Image, ImageFilter
|
|
14
|
+
|
|
15
|
+
from glass_capture import CaptureSource, MotionTracker, finish, paste_mic, resample
|
|
16
|
+
from glass_geometry import LPF, Geometry
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
import cv2 as _cv2
|
|
20
|
+
except Exception:
|
|
21
|
+
_cv2 = None
|
|
22
|
+
|
|
23
|
+
BLUR_EDGE = 1.45 # 1/4 分辨率上,边缘取这一档
|
|
24
|
+
BLUR_CENTER = 2.6 # 内框中心再叠一档(叠在已模糊图上,等效更厚)
|
|
25
|
+
CHROMA = 1.7 # 2x 图上的 R/B 错位像素
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _blur(arr: np.ndarray, sigma: float) -> np.ndarray:
|
|
29
|
+
if _cv2 is not None:
|
|
30
|
+
return _cv2.GaussianBlur(arr, (0, 0), sigmaX=sigma, sigmaY=sigma,
|
|
31
|
+
borderType=_cv2.BORDER_REFLECT)
|
|
32
|
+
return np.asarray(Image.fromarray(arr).filter(ImageFilter.GaussianBlur(sigma)))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _smoothstep(a: float, b: float, x: np.ndarray) -> np.ndarray:
|
|
36
|
+
t = np.clip((x - a) / (b - a), 0.0, 1.0)
|
|
37
|
+
return t * t * (3.0 - 2.0 * t)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class CpuRenderer:
|
|
41
|
+
"""把背景图变成玻璃帧。一个实例对应一套 `Geometry`。"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, geo: Geometry, tracker: MotionTracker | None = None):
|
|
44
|
+
self.geo = geo
|
|
45
|
+
self.tracker = tracker or MotionTracker()
|
|
46
|
+
self._prev: Image.Image | None = None
|
|
47
|
+
self._chroma: dict = {}
|
|
48
|
+
|
|
49
|
+
# ---- 生命周期 ----
|
|
50
|
+
|
|
51
|
+
def set_geometry(self, geo: Geometry) -> None:
|
|
52
|
+
self.geo = geo
|
|
53
|
+
self._chroma.clear() # 旧尺寸的索引图不再用,别每缩放一次攒一份
|
|
54
|
+
self.invalidate()
|
|
55
|
+
|
|
56
|
+
def invalidate(self) -> None:
|
|
57
|
+
"""形状变了:旧签名和上一帧都不能再参与合成。"""
|
|
58
|
+
self.tracker.invalidate()
|
|
59
|
+
self._prev = None
|
|
60
|
+
|
|
61
|
+
# ---- 主入口 ----
|
|
62
|
+
|
|
63
|
+
def render(self, source: CaptureSource, sct, bbox) -> Image.Image | None:
|
|
64
|
+
"""返回一张 `geo.width × geo.height` 的 RGB 图;`None` = 本帧不必更新。"""
|
|
65
|
+
geo = self.geo
|
|
66
|
+
shot = source.grab(sct, bbox)
|
|
67
|
+
if shot is None:
|
|
68
|
+
return None
|
|
69
|
+
im = source.to_image(shot, bbox)
|
|
70
|
+
|
|
71
|
+
gw, gh = shot.shot.size
|
|
72
|
+
sw4, sh4 = max(2, gw // LPF), max(2, gh // LPF)
|
|
73
|
+
raw = resample(np.asarray(im), (sw4, sh4))
|
|
74
|
+
moved, stale = self.tracker.observe(raw, shot.box)
|
|
75
|
+
if stale:
|
|
76
|
+
# 静态跳帧:连模糊都不做。上一帧若带运动残影,绝不能留到下次移动。
|
|
77
|
+
self._prev = None
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
small = _blur(raw, BLUR_EDGE)
|
|
81
|
+
strong = _blur(small, BLUR_CENTER)
|
|
82
|
+
|
|
83
|
+
warped, out_panel = self._lens(small, strong, raw, shot.offset)
|
|
84
|
+
panel = self._compose(warped, out_panel, moved)
|
|
85
|
+
out = resample(np.asarray(panel), (geo.width, geo.height))
|
|
86
|
+
out = Image.fromarray(out.astype(np.uint8))
|
|
87
|
+
|
|
88
|
+
if moved and self._prev is not None and self._prev.size == out.size:
|
|
89
|
+
blend = self.tracker.blend
|
|
90
|
+
if blend > 0.01:
|
|
91
|
+
out = Image.blend(self._prev, out, blend)
|
|
92
|
+
self._prev = out.copy()
|
|
93
|
+
# 先混再贴麦克风,避免把上一帧的麦克风位置糊到这一帧
|
|
94
|
+
return finish(geo, paste_mic(geo, out))
|
|
95
|
+
|
|
96
|
+
# ---- 步骤 ----
|
|
97
|
+
|
|
98
|
+
def _lens(self, small: np.ndarray, strong: np.ndarray, raw: np.ndarray, offset):
|
|
99
|
+
"""边缘折射 + 内框透镜,全在 1/4 分辨率完成。
|
|
100
|
+
|
|
101
|
+
`warped` 是整窗背景按圆角边缘位移后的结果;`out_panel` 在它的基础上
|
|
102
|
+
把每个内框区域换成「边缘折射 → 中心强模糊」的过渡。
|
|
103
|
+
"""
|
|
104
|
+
geo = self.geo
|
|
105
|
+
px, py = offset
|
|
106
|
+
h, w = small.shape[:2]
|
|
107
|
+
sx = np.clip(np.rint(geo.warp_x + px).astype(np.int32), 0, w - 1)
|
|
108
|
+
sy = np.clip(np.rint(geo.warp_y + py).astype(np.int32), 0, h - 1)
|
|
109
|
+
warped = small[sy, sx]
|
|
110
|
+
strong_panel = strong[sy, sx]
|
|
111
|
+
out_panel = warped.copy()
|
|
112
|
+
for qx0, qy0, qw, qh, alpha, weight, bsx, bsy in geo.box_maps:
|
|
113
|
+
base_patch = warped[qy0:qy0 + qh, qx0:qx0 + qw]
|
|
114
|
+
if base_patch.size == 0:
|
|
115
|
+
continue
|
|
116
|
+
edge_patch = raw[np.clip(bsy + py, 0, h - 1), np.clip(bsx + px, 0, w - 1)]
|
|
117
|
+
strong_patch = strong_panel[qy0:qy0 + qh, qx0:qx0 + qw]
|
|
118
|
+
patch = edge_patch * (1.0 - weight[..., None]) + strong_patch * weight[..., None]
|
|
119
|
+
a = alpha[..., None]
|
|
120
|
+
out_panel[qy0:qy0 + qh, qx0:qx0 + qw] = base_patch * (1.0 - a) + patch * a
|
|
121
|
+
return warped, out_panel
|
|
122
|
+
|
|
123
|
+
def _compose(self, warped: np.ndarray, out_panel: np.ndarray, moved: bool) -> Image.Image:
|
|
124
|
+
"""1/4 → 1/2 合成:框内用透镜、框外用底图,再叠染色与色散。
|
|
125
|
+
|
|
126
|
+
在 2x 上做而不是全分辨率:全分辨率逐像素色散会把这条 60fps 管线拖慢。
|
|
127
|
+
移动帧跳过色散(约 3.5ms/帧),优先保证拖动/滚动响应,停下后静止帧补上。
|
|
128
|
+
"""
|
|
129
|
+
geo = self.geo
|
|
130
|
+
hw, hh = geo.half_size
|
|
131
|
+
base_2x = Image.fromarray(resample(warped, (hw, hh)))
|
|
132
|
+
lens_2x = Image.fromarray(resample(out_panel, (hw, hh)))
|
|
133
|
+
panel = Image.composite(lens_2x, base_2x, geo.box_union_half)
|
|
134
|
+
panel = Image.alpha_composite(panel.convert("RGBA"), geo.overlay_half).convert("RGB")
|
|
135
|
+
if not moved:
|
|
136
|
+
panel = self._chroma_shift(panel, CHROMA)
|
|
137
|
+
return panel
|
|
138
|
+
|
|
139
|
+
def _chroma_maps(self, w: int, h: int, strength: float):
|
|
140
|
+
key = (w, h, round(float(strength), 2))
|
|
141
|
+
hit = self._chroma.get(key)
|
|
142
|
+
if hit is not None:
|
|
143
|
+
return hit
|
|
144
|
+
yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
|
|
145
|
+
dx = (xx + 0.5) / w - 0.5
|
|
146
|
+
dy = (yy + 0.5) / h - 0.5
|
|
147
|
+
r = np.hypot(dx, dy) + 1e-6
|
|
148
|
+
edge = _smoothstep(0.38, 0.48, r) * (1.0 - _smoothstep(0.52, 0.585, r))
|
|
149
|
+
k = strength * edge
|
|
150
|
+
ox = np.rint(dx / r * k).astype(np.int32)
|
|
151
|
+
oy = np.rint(dy / r * k).astype(np.int32)
|
|
152
|
+
xi, yi = xx.astype(np.int32), yy.astype(np.int32)
|
|
153
|
+
hit = (edge.astype(np.float32),
|
|
154
|
+
np.clip(xi + ox, 0, w - 1), np.clip(yi + oy, 0, h - 1),
|
|
155
|
+
np.clip(xi - ox, 0, w - 1), np.clip(yi - oy, 0, h - 1))
|
|
156
|
+
if len(self._chroma) > 4:
|
|
157
|
+
self._chroma.clear()
|
|
158
|
+
self._chroma[key] = hit
|
|
159
|
+
return hit
|
|
160
|
+
|
|
161
|
+
def _chroma_shift(self, im: Image.Image, strength: float) -> Image.Image:
|
|
162
|
+
"""外框径向色散:R 向外、B 向内错一位,只在圆角外缘的窄带里做。"""
|
|
163
|
+
arr = np.asarray(im.convert("RGB"), dtype=np.float32)
|
|
164
|
+
h, w = arr.shape[:2]
|
|
165
|
+
edge, xr, yr, xb, yb = self._chroma_maps(w, h, strength)
|
|
166
|
+
if not np.any(edge > 0.001):
|
|
167
|
+
return im
|
|
168
|
+
out = arr.copy()
|
|
169
|
+
out[:, :, 0] = arr[:, :, 0] * (1.0 - edge) + arr[yr, xr, 0] * edge
|
|
170
|
+
out[:, :, 2] = arr[:, :, 2] * (1.0 - edge) + arr[yb, xb, 2] * edge
|
|
171
|
+
return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
__all__ = ["CpuRenderer"]
|