dsh-watch-together 0.2.3 → 0.2.4

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/dsh.plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-watch-together",
3
3
  "description": "Watch a video together with a text-only agent: follow the user's real playback position and hand over one segment at a time, just before the segment ends.",
4
- "version": "0.2.3",
4
+ "version": "0.2.4",
5
5
  "entry": {
6
6
  "name": "dsh-watch-together",
7
7
  "inject": [
@@ -2,6 +2,14 @@
2
2
 
3
3
  GPU 伴生文件按原始 PR 的布局 `import glass_window as G`;这里的窗口已经改名为
4
4
  `window.py`(交互补全都在里面),所以用这个别名保持 GPU 路径可直接运行。
5
+
6
+ 不再 `from window import *`:那样会在导入时复制一份全局量(W/H/SHAPES/
7
+ OVERLAY/BOX_MAPS),窗口缩放或气泡按文字改宽后,GPU 仍拿旧坐标合成,
8
+ 表现就会和 CPU 不一致。这里改成动态代理,每次访问都回到 window.py。
5
9
  """
6
10
 
7
- from window import * # noqa: F401,F403 (GPU companion expects module-level names)
11
+ import window as _window
12
+
13
+
14
+ def __getattr__(name):
15
+ return getattr(_window, name)
@@ -108,6 +108,7 @@ void main() {
108
108
  float e = texelFetch(edge, p, 0).r;
109
109
  vec2 ec = texelFetch(coord, p, 0).rg + offset;
110
110
  ivec2 ep = clamp(ivec2(floor(ec + 0.5)), ivec2(0), ivec2(src_size) - 1);
111
+ // 边缘从小框自己的原始帧取,避免 warped 在贴边小框上采到黑边。
111
112
  vec3 edgep = texelFetch(raw, ep, 0).rgb;
112
113
  vec3 patch = mix(strong, edgep, e);
113
114
  frag = vec4(mix(base, patch, a), 1.0);
@@ -213,6 +214,7 @@ class GPULens:
213
214
  self._motion = 0.0
214
215
  self.src = None
215
216
  self.geo = None
217
+ self.geo_version = -1
216
218
  self.fbos = {}
217
219
  self.texs = {}
218
220
 
@@ -292,6 +294,7 @@ class GPULens:
292
294
  t = self._tex("union", (HW, HH), 1, "f1", union.tobytes())
293
295
  t.filter = (moderngl.LINEAR, moderngl.LINEAR)
294
296
  self.geo = (W, H, hw, hh, HW, HH)
297
+ self.geo_version = G.SHAPES_VERSION
295
298
  self.fbos.clear()
296
299
  self.texs = {k: v for k, v in self.texs.items()
297
300
  if k in ("alpha", "edge", "coord", "warpcoord", "overlay", "union")}
@@ -306,8 +309,9 @@ class GPULens:
306
309
  self.src.repeat_y = False
307
310
  self.src.write(data)
308
311
 
309
- def render(self, bgra, size, px, py, motion=0.0):
310
- if self.geo is None or self.geo[:2] != (G.W, G.H):
312
+ def render(self, bgra, size, px, py, motion=0.0, moved=False):
313
+ if (self.geo is None or self.geo[:2] != (G.W, G.H)
314
+ or getattr(self, "geo_version", -1) != G.SHAPES_VERSION):
311
315
  self._build_geo()
312
316
  W, H, hw, hh, HW, HH = self.geo
313
317
  gw, gh = size
@@ -407,8 +411,11 @@ class GPULens:
407
411
  prev.color_attachments[0].use(1)
408
412
  p = self.progs["post"]
409
413
  p["texel"] = (1.0 / W, 1.0 / H)
410
- p["blend"] = float(0.55 * max(0.0, min(1.0, motion)) if getattr(self, "_prev_valid", False) else 0.0)
411
- p["chroma"] = 3.6 * (W / 900.0)
414
+ # 和 CPU 一致:只在“本帧检测到移动”时混上一帧,停下立刻干净;
415
+ # 移动帧跳过色散,先把拖动/滚动响应保住。
416
+ p["blend"] = float(0.35 * max(0.0, min(1.0, motion))
417
+ if moved and getattr(self, "_prev_valid", False) else 0.0)
418
+ p["chroma"] = 0.0 if moved else 3.6 * (W / 900.0)
412
419
  self._set(p, curr=0, prev=1)
413
420
  p.vao.render(moderngl.TRIANGLES)
414
421
  self.ctx.copy_framebuffer(prev, out)
@@ -450,20 +457,28 @@ def capture_gpu(self, sct):
450
457
  moved = bool(float(d.mean()) > 0.01 or float(d.max()) > 0.5)
451
458
  if moved:
452
459
  self._last_motion = now
453
- _gpu._motion = min(1.0, _gpu._motion * 0.60 + 0.40)
460
+ _gpu._motion = min(1.0, _gpu._motion * 0.50 + 0.50)
454
461
  else:
455
- _gpu._motion *= 0.80
462
+ _gpu._motion *= 0.55
456
463
  if (not G.FORCE and not moved and box == self._sig_bbox
457
464
  and now - getattr(self, "_last_motion", 0.0) > 0.30):
458
465
  self._sig = sig
459
466
  _gpu._motion = 0.0
467
+ _gpu._prev_valid = False
460
468
  return None
461
469
  self._sig = sig
462
470
  self._sig_bbox = box
463
471
 
464
- panel = _gpu.render(shot.bgra, shot.size, px, py, motion=_gpu._motion)
465
- # 麦克风由 window.py 的 Canvas 图标绘制,GPU 路径不再叠第二层。
466
- return G.finish(panel.convert("RGB"))
472
+ panel = _gpu.render(shot.bgra, shot.size, px, py,
473
+ motion=_gpu._motion, moved=moved)
474
+ out = panel.copy()
475
+ mic_box = out.crop((G.MIC_POS[0], G.MIC_POS[1],
476
+ G.MIC_POS[0] + 28, G.MIC_POS[1] + 28)).convert("L")
477
+ mic_bg = float(np.median(np.asarray(mic_box))) / 255.0
478
+ out = out.convert("RGBA")
479
+ icon = G.MIC_LIGHT if mic_bg < 0.48 else G.MIC_DARK
480
+ out.paste(icon, G.MIC_POS, icon)
481
+ return G.finish(out.convert("RGB"))
467
482
  except Exception as exc:
468
483
  print("GPU capture failed, falling back to CPU:", repr(exc), flush=True)
469
484
  return _orig_capture(self, sct)
@@ -39,6 +39,11 @@ import mss
39
39
  import numpy as np
40
40
  from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageStat, ImageTk
41
41
 
42
+ try:
43
+ import cv2 as _cv2
44
+ except Exception: # OpenCV 只是加速,缺了仍走 PIL
45
+ _cv2 = None
46
+
42
47
  # 悬浮窗接口:插件写 window-events.jsonl,窗口回 window-outbox.jsonl。
43
48
  # 读不到就继续读 chat.jsonl,旧版插件不受影响。
44
49
  try:
@@ -171,9 +176,9 @@ def chat_layout(h):
171
176
 
172
177
 
173
178
  def shapes_for(w, h):
174
- """按窗口尺寸生成内部框位置;宽度横向伸展,底栏贴底。"""
179
+ """按窗口尺寸生成内部框位置;消息气泡的最终宽度由文字测量决定。"""
175
180
  ys, bh, input_top = chat_layout(h)
176
- # 真实聊天流每条长度不可预测,四个气泡统一吃满内容宽度;输入/发送仍分开
181
+ # 这里只给消息区四个纵向槽位;_message_shapes() 会按文字收窄宽度和高度。
177
182
  return [
178
183
  (38, ys[0], w - 38, ys[0] + bh, 30),
179
184
  (38, ys[1], w - 38, ys[1] + bh, 30),
@@ -185,6 +190,7 @@ def shapes_for(w, h):
185
190
 
186
191
 
187
192
  SHAPES = shapes_for(W, H)
193
+ SHAPES_VERSION = 0
188
194
 
189
195
 
190
196
  def rounded_mask():
@@ -266,6 +272,8 @@ BOX_AMP = 8 # 1/4 分辨率下的最大采样偏移
266
272
  def build_box_maps():
267
273
  out = []
268
274
  for x0, y0, x1, y1, r in SHAPES:
275
+ if x1 <= x0 or y1 <= y0:
276
+ continue
269
277
  qx0, qy0 = x0 // 4, y0 // 4
270
278
  qw, qh = max(2, (x1 - x0) // 4), max(2, (y1 - y0) // 4)
271
279
  xx, yy = np.meshgrid(np.arange(qw, dtype=np.float32),
@@ -279,16 +287,18 @@ def build_box_maps():
279
287
  gy, gx = np.gradient(sdf)
280
288
  n = np.maximum(np.hypot(gx, gy), 1e-6)
281
289
  d = -sdf
282
- inside = d >= 0
283
290
  alpha = np.clip((d + 0.6) / 1.2, 0.0, 1.0).astype(np.float32)
284
- edge = inside & (d <= BOX_BAND)
285
291
  t = np.clip(1.0 - d / BOX_BAND, 0.0, 1.0)
286
292
  mag = BOX_AMP * t * t
287
293
  sx = np.rint(qx0 + xx + gx / n * mag).astype(np.int32)
288
294
  sy = np.rint(qy0 + yy + gy / n * mag).astype(np.int32)
289
295
  np.clip(sx, 0, W // 4 - 1, out=sx)
290
296
  np.clip(sy, 0, H // 4 - 1, out=sy)
291
- out.append((qx0, qy0, qw, qh, alpha, edge, sx, sy))
297
+ # 边缘到中心用平滑权重过渡,不再用二值 edge 在“原始帧”和
298
+ # “强模糊帧”之间硬切;系数不一致会看到一圈割裂。
299
+ w = np.clip(d / BOX_BAND, 0.0, 1.0).astype(np.float32)
300
+ w = (w * w * (3.0 - 2.0 * w)).astype(np.float32)
301
+ out.append((qx0, qy0, qw, qh, alpha, w, sx, sy))
292
302
  return out
293
303
 
294
304
 
@@ -316,6 +326,7 @@ def rebuild_geometry(w, h):
316
326
  """窗口尺寸变化后重建所有和 W/H 绑定的贴图/遮罩。"""
317
327
  global W, H, SHAPES, MASK, MASK_HARD, OVERLAY, OVERLAY_2X
318
328
  global WARP_X, WARP_Y, EDGE_MASK, BOX_MAPS, HW, HH, BOX_UNION_2X, MIC_POS
329
+ _CHROMA_CACHE.clear() # 旧尺寸的索引图不再用,避免每次缩放都攒一份
319
330
  W, H = w, h
320
331
  SHAPES = shapes_for(w, h)
321
332
  MASK = rounded_mask()
@@ -329,6 +340,21 @@ def rebuild_geometry(w, h):
329
340
  BOX_UNION_2X = build_box_union(HW, HH)
330
341
 
331
342
 
343
+ def apply_shapes(shapes):
344
+ """消息气泡宽度/高度变化后,只重建和内部框有关的贴图。
345
+
346
+ 窗口尺寸不变,所以不用碰 WARP/MASK;只更新染色层、四分之一透镜
347
+ 坐标和 2x 联合遮罩。调用方负责持有 _geo_lock。
348
+ """
349
+ global SHAPES, OVERLAY, OVERLAY_2X, BOX_MAPS, BOX_UNION_2X, SHAPES_VERSION
350
+ SHAPES = list(shapes)
351
+ OVERLAY = build_overlay()
352
+ OVERLAY_2X = OVERLAY.resize((W // 2, H // 2), Image.Resampling.BILINEAR)
353
+ BOX_MAPS = build_box_maps()
354
+ BOX_UNION_2X = build_box_union(HW, HH)
355
+ SHAPES_VERSION += 1
356
+
357
+
332
358
  def finish(panel):
333
359
  """只做圆角遮罩;染色已经在 1/4 分辨率合成过。"""
334
360
  out = Image.new("RGB", (W, H), KEY)
@@ -336,6 +362,60 @@ def finish(panel):
336
362
  return out
337
363
 
338
364
 
365
+ def _smoothstep(a, b, x):
366
+ t = np.clip((x - a) / (b - a), 0.0, 1.0)
367
+ return t * t * (3.0 - 2.0 * t)
368
+
369
+
370
+ _CHROMA_CACHE = {}
371
+
372
+
373
+ def _chroma_maps(w, h, strength):
374
+ """2x 色散索引图只跟尺寸/强度走,缓存后每帧只做 gather。"""
375
+ key = (w, h, round(float(strength), 2))
376
+ hit = _CHROMA_CACHE.get(key)
377
+ if hit is not None:
378
+ return hit
379
+ yy, xx = np.mgrid[0:h, 0:w].astype(np.float32)
380
+ dx = (xx + 0.5) / w - 0.5
381
+ dy = (yy + 0.5) / h - 0.5
382
+ r = np.hypot(dx, dy) + 1e-6
383
+ edge = _smoothstep(0.38, 0.48, r) * (1.0 - _smoothstep(0.52, 0.585, r))
384
+ k = strength * edge
385
+ ox = np.rint(dx / r * k).astype(np.int32)
386
+ oy = np.rint(dy / r * k).astype(np.int32)
387
+ xi = xx.astype(np.int32)
388
+ yi = yy.astype(np.int32)
389
+ hit = (
390
+ edge.astype(np.float32),
391
+ np.clip(xi + ox, 0, w - 1),
392
+ np.clip(yi + oy, 0, h - 1),
393
+ np.clip(xi - ox, 0, w - 1),
394
+ np.clip(yi - oy, 0, h - 1),
395
+ )
396
+ _CHROMA_CACHE[key] = hit
397
+ return hit
398
+
399
+
400
+ def apply_chroma(im, strength=1.7):
401
+ """外框径向色散:R 向外、B 向内错一位,和 GPU 后处理同一思路。
402
+
403
+ 只在圆角外缘的窄带里做,且按 edge 权重混回原图;否则整张图会变成
404
+ 红蓝重影。CPU 版在 2x 合成图上做,成本远低于全分辨率逐像素采样。
405
+ """
406
+ arr = np.asarray(im.convert("RGB"), dtype=np.float32)
407
+ h, w = arr.shape[:2]
408
+ edge, xr, yr, xb, yb = _chroma_maps(w, h, strength)
409
+ if not np.any(edge > 0.001):
410
+ return im
411
+ rr = arr[yr, xr, 0]
412
+ bb = arr[yb, xb, 2]
413
+ out = arr.copy()
414
+ out[:, :, 0] = arr[:, :, 0] * (1.0 - edge) + rr * edge
415
+ out[:, :, 2] = arr[:, :, 2] * (1.0 - edge) + bb * edge
416
+ return Image.fromarray(np.clip(out, 0, 255).astype(np.uint8))
417
+
418
+
339
419
  class RECT(ctypes.Structure):
340
420
  _fields_ = [("left", ctypes.c_long), ("top", ctypes.c_long),
341
421
  ("right", ctypes.c_long), ("bottom", ctypes.c_long)]
@@ -391,6 +471,8 @@ class LiveGlass:
391
471
 
392
472
  self._img = None
393
473
  self._last_frame = None
474
+ self._prev_out = None
475
+ self._motion_blur = 0.0
394
476
  self._collapsed_frame = None
395
477
  self._bg = None
396
478
  self._hwnd = None
@@ -411,9 +493,11 @@ class LiveGlass:
411
493
  self._frames = 0
412
494
  self._text_items = []
413
495
  self._text_colors = {}
496
+ self._text_pending = {}
414
497
  self._text_shadows = {}
415
498
  self._color_at = 0.0
416
499
  self._aux_at = 0.0
500
+ self._bar_color = "#b8cbe0"
417
501
  self._load_initial()
418
502
  self._build_ui()
419
503
  self._add_text_shadows()
@@ -819,9 +903,15 @@ class LiveGlass:
819
903
  "width": gr - gl, "height": gb - gt})
820
904
  im = Image.frombytes("RGB", shot.size, shot.rgb)
821
905
  sw4, sh4 = max(2, (gr - gl) // 4), max(2, (gb - gt) // 4)
822
- # 60fps 路径:只在 1/4 分辨率做一次模糊和折射,再放大
823
- small_raw = im.resize((sw4, sh4), Image.Resampling.BILINEAR)
824
- arr_raw = np.asarray(small_raw)
906
+ # 60fps 路径:只在 1/4 分辨率做一次模糊和折射,再放大。
907
+ # cv2 的 resize 比 PIL 快一个数量级;没有 OpenCV 时无感回退。
908
+ if _cv2 is not None:
909
+ arr_raw = _cv2.resize(np.asarray(im), (sw4, sh4),
910
+ interpolation=_cv2.INTER_LINEAR)
911
+ small_raw = Image.fromarray(arr_raw)
912
+ else:
913
+ small_raw = im.resize((sw4, sh4), Image.Resampling.BILINEAR)
914
+ arr_raw = np.asarray(small_raw)
825
915
  # 静态跳帧:先用未模糊的 raw 判断,静止时连模糊都不用做。
826
916
  # 采样 4px、均值 0.01 + 最大差 0.5、运动后保持 0.3s;比原来的
827
917
  # 8px / 0.18 更早触发,慢速滚动不会先停一两帧再动。
@@ -834,9 +924,15 @@ class LiveGlass:
834
924
  moved = bool(float(d.mean()) > 0.01 or float(d.max()) > 0.5)
835
925
  if moved:
836
926
  self._last_motion = now
927
+ self._motion_blur = min(1.0, getattr(self, "_motion_blur", 0.0) * 0.50 + 0.50)
928
+ else:
929
+ self._motion_blur = getattr(self, "_motion_blur", 0.0) * 0.55
837
930
  if (not FORCE and not moved and box == self._sig_bbox
838
931
  and now - getattr(self, "_last_motion", 0.0) > 0.30):
839
932
  self._sig = sig
933
+ # 静态跳帧期间不更新画面;上一帧若带着运动模糊,绝不能在
934
+ # 很久以后重新移动时再被混进来,否则就是“淡淡的旧画面”。
935
+ self._prev_out = None
840
936
  return None
841
937
  self._sig = sig
842
938
  self._sig_bbox = box
@@ -854,28 +950,64 @@ class LiveGlass:
854
950
  # 内部框:边缘折射 + 中心强模糊仍在 1/4 分辨率完成
855
951
  strong_panel = arr_strong[sy, sx]
856
952
  out_panel = warped.copy()
857
- for qx0, qy0, qw, qh, alpha, edge, bsx, bsy in BOX_MAPS:
953
+ for qx0, qy0, qw, qh, alpha, edge_w, bsx, bsy in BOX_MAPS:
858
954
  base_patch = warped[qy0:qy0 + qh, qx0:qx0 + qw]
859
- edge_patch = arr_raw[np.clip(bsy + py, 0, arr_raw.shape[0] - 1),
860
- np.clip(bsx + px, 0, arr_raw.shape[1] - 1)]
955
+ # 边缘也用和主玻璃相同的 1.45 模糊,不再直接拿未模糊的
956
+ # arr_raw;中心再平滑过渡到 2.6 的强模糊。
957
+ edge_patch = arr[np.clip(bsy + py, 0, arr.shape[0] - 1),
958
+ np.clip(bsx + px, 0, arr.shape[1] - 1)]
861
959
  strong_patch = strong_panel[qy0:qy0 + qh, qx0:qx0 + qw]
862
- patch = np.where(edge[..., None], edge_patch, strong_patch)
960
+ we = edge_w[..., None]
961
+ patch = edge_patch * (1.0 - we) + strong_patch * we
863
962
  a = alpha[..., None]
864
963
  out_panel[qy0:qy0 + qh, qx0:qx0 + qw] = (
865
964
  base_patch * (1.0 - a) + patch * a)
866
965
  # 1/4 透镜结果放大后,用全分辨率联合圆角遮罩贴回;
867
966
  # 边界是 PIL 4x 超采样遮罩,不再有 1/4 放大的像素台阶。
868
967
  # 2x 合成:比全分辨率轻,比 1/4 明显平滑,兼顾帧率和圆角
869
- base_2x = Image.fromarray(warped).resize(
870
- (HW, HH), Image.Resampling.BILINEAR)
871
- lens_2x = Image.fromarray(out_panel).resize(
872
- (HW, HH), Image.Resampling.BILINEAR)
968
+ if _cv2 is not None:
969
+ base_2x = Image.fromarray(_cv2.resize(
970
+ warped, (HW, HH), interpolation=_cv2.INTER_LINEAR))
971
+ lens_2x = Image.fromarray(_cv2.resize(
972
+ out_panel, (HW, HH), interpolation=_cv2.INTER_LINEAR))
973
+ else:
974
+ base_2x = Image.fromarray(warped).resize(
975
+ (HW, HH), Image.Resampling.BILINEAR)
976
+ lens_2x = Image.fromarray(out_panel).resize(
977
+ (HW, HH), Image.Resampling.BILINEAR)
873
978
  panel = Image.composite(lens_2x, base_2x, BOX_UNION_2X)
874
979
  panel = Image.alpha_composite(
875
980
  panel.convert("RGBA"), OVERLAY_2X).convert("RGB")
876
- out = panel.convert("RGB").resize((W, H), Image.Resampling.BILINEAR)
877
- # 麦克风由 Canvas 矢量绘制(_build_ui),这里不再叠位图,避免两层图标。
878
- return finish(out)
981
+ # 2x 上做一次显式 R/B 错位;全分辨率逐像素做会把这个 60fps 管线拖慢。
982
+ # 移动中跳过色散(约 3.5ms/帧),优先保证拖动/滚动响应;停下后
983
+ # 的静止帧再补上,最终观感不变。
984
+ if not moved:
985
+ panel = apply_chroma(panel, 1.7)
986
+ if _cv2 is not None:
987
+ out = Image.fromarray(_cv2.resize(
988
+ np.asarray(panel.convert("RGB")), (W, H),
989
+ interpolation=_cv2.INTER_LINEAR))
990
+ else:
991
+ out = panel.convert("RGB").resize((W, H), Image.Resampling.BILINEAR)
992
+ # CPU 也做上一帧混合,但比 GPU 的 0.55 轻、且只在检测到移动时混:
993
+ # 拖动停下后立刻恢复清晰,不会留下淡淡的旧画面。
994
+ # 先混再贴麦克风,避免把上一帧的麦克风位置糊到这一帧。
995
+ if moved and self._prev_out is not None and self._prev_out.size == out.size:
996
+ # 只在“这一帧确实检测到移动”时混上一帧;停下后下一帧
997
+ # 立刻干净,不会留下越拖越淡的残影。
998
+ blend = 0.35 * max(0.0, min(1.0, getattr(self, "_motion_blur", 0.0)))
999
+ if blend > 0.01:
1000
+ out = Image.blend(self._prev_out, out, blend)
1001
+ self._prev_out = out.copy()
1002
+ # 麦克风图标回到仓库的做法:贴进玻璃帧,按背后亮度选浅/深两版。
1003
+ # 位置用 MIC_POS(左上角),不是 Canvas 坐标,缩放时一起重建。
1004
+ mic_box = out.crop((MIC_POS[0], MIC_POS[1],
1005
+ MIC_POS[0] + 28, MIC_POS[1] + 28)).convert("L")
1006
+ mic_bg = float(np.median(np.asarray(mic_box))) / 255.0
1007
+ out = out.convert("RGBA")
1008
+ icon = MIC_LIGHT if mic_bg < 0.48 else MIC_DARK
1009
+ out.paste(icon, MIC_POS, icon)
1010
+ return finish(out.convert("RGB"))
879
1011
 
880
1012
  def _work(self):
881
1013
  """抓取 + 模糊 + 合成全在后台,主线程只负责显示最新一帧。"""
@@ -1112,6 +1244,63 @@ class LiveGlass:
1112
1244
  except Exception:
1113
1245
  pass
1114
1246
 
1247
+ def _message_shapes(self, shown):
1248
+ """把四个固定大框换成按正文文字测量的聊天气泡。
1249
+
1250
+ 时间戳不再算进气泡:它贴在气泡上方,气泡只包正文。先按最大
1251
+ 可用宽度折行,再取实际最长行的宽度;短消息不会撑满整行。
1252
+ """
1253
+ w, h = W, H
1254
+ base = shapes_for(w, h)
1255
+ left, right = base[0][0], base[0][2]
1256
+ max_bubble = min(right - left, max(240, int((right - left) * 0.72)))
1257
+ min_bubble = min(110, max_bubble)
1258
+ pad = 14
1259
+ body_font = f(11)
1260
+ stamp_font = f(9)
1261
+ fbody = tkfont.Font(root=self.root, font=body_font)
1262
+ fstamp = tkfont.Font(root=self.root, font=stamp_font)
1263
+ ls = max(1, fbody.metrics("linespace"))
1264
+ shapes, infos = [], []
1265
+ for i in range(4):
1266
+ if i >= len(shown):
1267
+ # 没有第 5 条消息时留空,不要把固定大框继续画出来。
1268
+ shapes.append((0, 0, 0, 0, 0))
1269
+ continue
1270
+ msg = shown[i]
1271
+ x0, y0, x1, y1, _r = base[i]
1272
+ slot_h = y1 - y0
1273
+ is_user = str(msg.get("role") or "").lower() in ("user", "me", "human")
1274
+ stamp = str(msg.get("stamp") or "")
1275
+ stamp_h = fstamp.metrics("linespace") if stamp else 0
1276
+ body_avail = max(12, slot_h - stamp_h)
1277
+ content_max = max(80, max_bubble - 2 * pad)
1278
+ lines = self._fit_lines(msg.get("text") or "", body_font,
1279
+ content_max, body_avail)
1280
+ inner = max([0] + [fbody.measure(line) for line in lines])
1281
+ bw = min(max_bubble, max(min_bubble, inner + 2 * pad))
1282
+ bh = min(body_avail, max(ls + 4, len(lines) * ls + 4))
1283
+ by0 = y0 + stamp_h
1284
+ by1 = min(y1, by0 + bh)
1285
+ if is_user:
1286
+ bx1 = right
1287
+ bx0 = bx1 - bw
1288
+ tx, ta = bx1 - pad, "ne"
1289
+ else:
1290
+ bx0 = left
1291
+ bx1 = bx0 + bw
1292
+ tx, ta = bx0 + pad, "nw"
1293
+ shape = (bx0, by0, bx1, by1, min(26, max(16, bh // 3)))
1294
+ shapes.append(shape)
1295
+ infos.append({
1296
+ "shape": shape, "is_user": is_user, "stamp": stamp,
1297
+ "tx": tx, "ta": ta, "lines": lines,
1298
+ "body_font": body_font, "ty": by0 + 2,
1299
+ "stamp_y": y0, "ls": ls,
1300
+ })
1301
+ shapes.extend(base[4:])
1302
+ return shapes, infos
1303
+
1115
1304
  def _build_ui(self):
1116
1305
  c = self.canvas
1117
1306
  old_text, old_focus, old_cursor = "", False, 0
@@ -1187,28 +1376,24 @@ class LiveGlass:
1187
1376
  return
1188
1377
 
1189
1378
  shown = self._visible_messages()
1190
- # 每条消息的头部(时间戳)和正文都在自己的框里;正文按框高折行/截断,
1191
- # 不再用气泡中心当基线,否则两行以上会溢出框外(时间也会被顶到框上)。
1192
- for i, msg in enumerate(shown):
1193
- x0, y0, x1, y1, _r = SHAPES[i]
1194
- is_user = str(msg.get("role") or "").lower() in ("user", "me", "human")
1195
- tx = (x1 - 26) if is_user else (x0 + 26)
1196
- ta = "ne" if is_user else "nw"
1197
- stamp = str(msg.get("stamp") or "")
1198
- head_h = 26 if stamp else 4
1199
- if stamp:
1200
- self._text(tx, y0 + 2, stamp, anchor=ta,
1201
- fill="#a8b7c9", font=f(9), tags=("feed",))
1202
- max_w = max(80, x1 - x0 - 52)
1203
- avail_h = max(12, (y1 - y0) - head_h - 2)
1204
- body_font = f(11)
1205
- lines = self._fit_lines(msg.get("text") or "", body_font, max_w, avail_h)
1206
- fobj = tkfont.Font(root=self.root, font=body_font)
1207
- ls = fobj.metrics("linespace")
1208
- ty = y0 + head_h + 2
1209
- for li, line in enumerate(lines):
1210
- self._text(tx, ty + li * ls, line, anchor=ta,
1211
- fill="#edf6ff", font=body_font, tags=("feed",))
1379
+ if shown:
1380
+ shapes, infos = self._message_shapes(shown)
1381
+ else:
1382
+ shapes, infos = shapes_for(w, h), []
1383
+ if shapes != SHAPES:
1384
+ with self._geo_lock:
1385
+ apply_shapes(shapes)
1386
+ # 每条消息只按正文占一块;时间戳贴在气泡上方,不进框。
1387
+ for info in infos:
1388
+ bx0, by0, bx1, by1, _r = info["shape"]
1389
+ if info["stamp"]:
1390
+ self._text(info["tx"], info["stamp_y"], info["stamp"],
1391
+ anchor=info["ta"], fill="#a8b7c9",
1392
+ font=f(9), tags=("feed",))
1393
+ for li, line in enumerate(info["lines"]):
1394
+ self._text(info["tx"], info["ty"] + li * info["ls"], line,
1395
+ anchor=info["ta"], fill="#edf6ff",
1396
+ font=info["body_font"], tags=("feed",))
1212
1397
  if not shown:
1213
1398
  # 空态:`bh` 是旧代码的局部变量,这里只能从 SHAPES 反推第一格高度
1214
1399
  self._text(w // 2, SHAPES[0][1] + (SHAPES[0][3] - SHAPES[0][1]) // 2,
@@ -1239,24 +1424,17 @@ class LiveGlass:
1239
1424
  self._text((x0 + x1) // 2, y0 + 27, "发送", tags=("send", "feed"),
1240
1425
  fill="#ffffff", font=f(12, True))
1241
1426
 
1242
- # 麦克风:直接用 PR #15 的 mic-dsh.png 图标(白色/录音红),
1243
- # 不再用几条线画一个像"i"的代替品;Canvas 图不依赖合成帧,预览也可见。
1244
- if not getattr(self, "_collapsed", False):
1245
- active = self._mic_proc is not None and self._mic_proc.poll() is None
1246
- color = (255, 128, 128, 0) if active else (224, 238, 255, 0)
1247
- icon_img = Image.new("RGBA", MIC_MASK.size, color)
1248
- icon_img.putalpha(MIC_MASK)
1249
- self._mic_icon = ImageTk.PhotoImage(icon_img, master=self.canvas)
1250
- c.create_image(67, H - 58, image=self._mic_icon,
1251
- tags=("mic", "micart"))
1252
- c.tag_bind("mic", "<Button-1>", lambda _e: self._toggle_mic())
1253
-
1427
+ # 麦克风图标和仓库一样贴进玻璃帧(_capture 里按 MIC_POS 合成),
1428
+ # 不在 Canvas 上单独建图;点击仍由 _press 在 MIC_POS 附近识别。
1254
1429
  # 最上面正中的细条,长度随窗口宽度走
1255
1430
  self._bar_len = max(72, int(w * BAR_FRAC))
1256
1431
  self._bar = c.create_line(w // 2 - self._bar_len // 2, BAR_Y,
1257
1432
  w // 2 + self._bar_len // 2, BAR_Y,
1258
1433
  width=BAR_THICK, fill="#b8cbe0",
1259
1434
  capstyle="round")
1435
+ # 新建的条是浅色,缓存也要跟着归位;否则折叠重建后旧色值还在,
1436
+ # `bar_fill == cur` 会把这次同步直接跳过去,条和缓存就对不上了。
1437
+ self._bar_color = "#b8cbe0"
1260
1438
 
1261
1439
  c.tag_bind("close", "<Button-1>", self._close)
1262
1440
  c.tag_bind("send", "<Button-1>", self._send)
@@ -1301,8 +1479,10 @@ class LiveGlass:
1301
1479
  self.canvas.delete("all")
1302
1480
  self._img = None
1303
1481
  self._bg = None
1482
+ self._prev_out = None
1304
1483
  self._text_items = []
1305
1484
  self._text_colors = {}
1485
+ self._text_pending = {}
1306
1486
  self._text_shadows = {}
1307
1487
  self._build_ui()
1308
1488
  self._add_text_shadows()
@@ -1331,9 +1511,12 @@ class LiveGlass:
1331
1511
  self.canvas.delete("all")
1332
1512
  self._img = None
1333
1513
  self._bg = None
1514
+ self._prev_out = None
1515
+ self._motion_blur = 0.0
1334
1516
  self._collapsed_frame = None
1335
1517
  self._text_items = []
1336
1518
  self._text_colors = {}
1519
+ self._text_pending = {}
1337
1520
  self._text_shadows = {}
1338
1521
  self._color_at = 0.0
1339
1522
  self._aux_at = 0.0
@@ -1367,7 +1550,17 @@ class LiveGlass:
1367
1550
  self._text_shadows = {}
1368
1551
 
1369
1552
  def _adapt_text(self, out):
1370
- """按文字背后的暗部/亮部比例选色,并同步描边颜色。"""
1553
+ """按文字背后的暗部/亮部比例选色。
1554
+
1555
+ **必须带滞回**:气泡是透明的,背后就是桌面/视频/网页。画面一动,
1556
+ 这块背景的中位亮度就在 0.5 附近来回穿越,而原来这里是 `p50 < 0.50`
1557
+ 硬切、每 0.12 秒判一次 —— 结果字一秒能翻七八次黑白,肉眼就是"一直闪"。
1558
+
1559
+ 现在两道闸:
1560
+ 1. **滞回**:白的要暗到 0.38 才翻深,深的要亮到 0.62 才翻白;
1561
+ 中间的 0.38~0.62 一律保持现状,不给抖动留门。
1562
+ 2. **连续两次同向才切**:单帧跳变忽略,最坏 0.24 秒才换一次色。
1563
+ """
1371
1564
  now = time.time()
1372
1565
  if now - self._color_at < 0.12:
1373
1566
  return
@@ -1385,21 +1578,29 @@ class LiveGlass:
1385
1578
  p50 = float(np.percentile(gray, 50)) / 255.0
1386
1579
  dark = float(np.mean(gray < 107))
1387
1580
  light = float(np.mean(gray > 158))
1388
- # 先看这块背景是偏暗还是偏亮,混合区域再退回中位亮度
1581
+ cur = self._text_colors.get(item)
1582
+ # 先看这块背景是偏暗还是偏亮(这两支自带 0.08 余量,本身不抖)
1389
1583
  if dark > light + 0.08:
1390
- color = "#f2f8ff"
1584
+ want = "#f2f8ff"
1391
1585
  elif light > dark + 0.08:
1392
- color = "#07111d"
1393
- elif p50 < 0.50:
1394
- color = "#f2f8ff"
1586
+ want = "#07111d"
1587
+ elif cur == "#07111d":
1588
+ want = "#f2f8ff" if p50 < 0.38 else cur
1395
1589
  else:
1396
- color = "#07111d"
1397
- if color != self._text_colors.get(item):
1398
- self.canvas.itemconfigure(item, fill=color)
1399
- self._text_colors[item] = color
1590
+ # 还没定色时先给白字;之后要亮过 0.62 才敢翻深
1591
+ want = "#07111d" if (cur is not None and p50 > 0.62) else (cur or "#f2f8ff")
1592
+ if want == cur:
1593
+ self._text_pending.pop(item, None)
1594
+ continue
1595
+ if self._text_pending.get(item) != want:
1596
+ self._text_pending[item] = want # 第一次:只记下,不换
1597
+ continue
1598
+ self._text_pending.pop(item, None)
1599
+ self.canvas.itemconfigure(item, fill=want)
1600
+ self._text_colors[item] = want
1400
1601
 
1401
1602
  def _adapt_aux(self, out):
1402
- """最上面细条随背景切换深浅。"""
1603
+ """最上面细条随背景切换深浅(同样要滞回,理由见 `_adapt_text`)。"""
1403
1604
  now = time.time()
1404
1605
  if now - self._aux_at < 0.25:
1405
1606
  return
@@ -1409,8 +1610,15 @@ class LiveGlass:
1409
1610
  bar = np.asarray(out.crop(
1410
1611
  (mid - half, BAR_Y - 6, mid + half, BAR_Y + 12)).convert("L"))
1411
1612
  p50 = float(np.median(bar)) / 255.0
1412
- bar_fill = "#b8cbe0" if p50 < 0.48 else "#4e6278"
1413
- self.canvas.itemconfigure(self._bar, fill=bar_fill)
1613
+ cur = self._bar_color
1614
+ if cur == "#4e6278":
1615
+ # 已经很深了:要暗到 0.36 才翻浅,避免在阈值附近来回跳
1616
+ bar_fill = "#b8cbe0" if p50 < 0.36 else cur
1617
+ else:
1618
+ bar_fill = "#4e6278" if p50 > 0.60 else cur
1619
+ if bar_fill != cur:
1620
+ self._bar_color = bar_fill
1621
+ self.canvas.itemconfigure(self._bar, fill=bar_fill)
1414
1622
 
1415
1623
 
1416
1624
 
@@ -1495,7 +1703,9 @@ class LiveGlass:
1495
1703
  # 边缘缩放 / 窗口拖动
1496
1704
  def _edge_at(self, x, y):
1497
1705
  w, h = self.root.winfo_width(), self.root.winfo_height()
1498
- edge, corner = 10, 26
1706
+ # 圆角是透明的,鼠标落在最外侧时命中的是 DWM 非客户区;
1707
+ # 命中带放宽到 20px,用户不必精确到 1px 也能拖边缘/四角。
1708
+ edge, corner = 20, 32
1499
1709
  # 圆角区域是透明的,命中区要往内收够,才能点到可见的角
1500
1710
  if x <= corner and y <= corner:
1501
1711
  return "nw"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-watch-together",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "Watch a video together with a text-only agent: follow the user's real playback position, hand over one segment at a time just before it ends, and keep a single text stream of scripted lines, interjections and the user's replies.",
5
5
  "keywords": [
6
6
  "dsh",