Spaces:
Running
collector: 更新采集工程至 v1.3.10(夹爪 RGB 帧空洞可见化 6/6 全部落地;普通版一键部署自带实时骨架解算与 D435)
Browse files【夹爪 RGB 帧空洞可见化 6/6】episode-099 录到第 45 帧丢了 4.68s,而当时所有计数器都是 0——相机侧没帧可读、emit 帧槽被覆盖、GUI 主线程卡顿这三条路在 parquet 里留下完全相同的空洞签名。本次让每条路各记各的账,只装仪表、不动录制通路行为。
1/6 指标底座 —— core/frame_gap.py::GapWatch(相邻两帧时间差超出标称帧间隔的部分记为空洞,只报「断了多久」不反推「丢了几帧」;录制侧与离线审计脚本共用这一个类,口径只此一份。两处防呆:首帧锁定时间基座、之后 source 不符的帧一律跳过——混源会把设备钟与宿主钟的基准差当成天文数字级假空洞;0 是「无时间戳」哨兵;时间倒退只重锚不报洞)。core/gripper/rgb_quality.py::RgbReadWatch + MaxLagWatch(去抖契约照抄 slam/process_controller.py 的 FaysRateAlarm:健康态静默、进入报一次、持续按 repeat 限频、恢复报一次;类内自锁、无 IO、不 emit)。core/pipeline.py::DropStats 加 note_max,并加 is_frame_drop_key / frame_drop_total 钉死「帧数 vs 时长」口径——ext:<slot>/sensor_queue 可加总,*_ms/*_ns/*_count 不可,新键混进 sum() 会虚增丢帧数并把用户指去调编码器。config/settings.py 四个新旋钮。
2/6 落盘侧空洞 —— front `_note_ext_gap` 在写线程取到帧之后、写进视频之前记一次,只统计「确实进了队列、确实写进了视频」的帧(队列满丢的帧由 ext: 计数认领,两边不重复也不互相掩盖,判据可互推)。基座每段首帧锁定:带 hardware_ns 的槽位走 hw、恒传 0 的 lite 槽位退化为宿主单调钟 mono,两者绝不混用。空洞闭合到 500ms 当场 emit recording_log。每段重置看门狗(不重置则第二段换基座,钟差会被记成一次天文数字级假空洞)。CameraPipeline.note_drop_stats() 让 UI 把采集侧计数并进来。
3/6 采集侧三层计数 + 实时告警 + UI 汇总 —— bridge._rgb_run 的 read() 失败分支此前睡 5ms 接着来,不记不报不重连,是整条链上唯二彻底静默的点之一;现交给 RgbReadWatch,停摆/恢复各打一行并点明后果(「本段视频该处会有一段静止」)。latest-wins 单槽覆盖此前连一行日志都没有,现按 kind 记。三个读数分开记才能分辨责任:emit 滞后大=emitter 没排上队;派发滞后大=主线程堵了(GUI 卡顿本身不产生空洞,它是**导致**覆盖才产生空洞);覆盖数大=帧采到了但没人及时取走。UI 侧 rgb_quality_snapshot() 必须在 finish_recording **之前**并入 drop_stats(那一步会快照并回写 writer 元数据,晚一步就只进日志不进 parquet)。
4/6 camera-service 日志留档 + 告警摘录 —— 相机侧「为什么停摆」全写在服务自己那份日志里,而它随 runtime_dir 一起被删,干净退出的会话等于没写过。契约与 core/gripper/fays_single.py 里已验证的 slam_native 留档逐字同构:先留档再 rmtree、失败只记一行、keep 20。摘录判据从 camera_service.c 的实际字符串里挑,**刻意不收裸 [LIBUVC-QUIRK]**——其中 xfers= 那行每次成功开流都会打、正是判断真实档位的权威行;同理不用裸 dropped / stalls=,收进来摘录在任何一次正常会话里都非空、等于噪声(测试配了反向断言:健康日志零命中)。健康会话不占 main.log。
5/6 全库审计脚本 + 文档 —— tools/audit_frame_gaps.py 判据是**内容优先**不是钟优先(mad(row-1,row) 与同段近邻中位、远邻中位比)。只看钟会错两次:早期段的设备钟是**有符号 32 位**纳秒计数器、每 4.295s 回卷,不按 2^32 解卷会把真间隔抹平(段099 的 4.68s 解错成 385ms);而解卷只对 trunc32 段做,hw64 段上解卷反而会把真空洞折没。两个时间戳的出身查清了:hardware_ns 是**采集线程**在 read() 返回后盖的,wall_time 是**写线程**在 _build_row 里盖的,Δwall−Δhw 就是队列滞留的变化量,实测台阶证实两侧是两件不同的事。基准(2026-09-18,95 段):**画面证实丢了 25 段 / 37412.6ms**(最大 4647.5ms @段099),全部 25 起都落在开录后 0.13~1.47s;钟跳但画面连续 72 段 / 20076.2ms;写侧打嗝 43 段 / 9944.8ms;mp4 帧数 == 行数 95/95。顺带两处口径修正:frame_gap 的 0 哨兵判据由 `<= 0` 收紧成 `== 0`(trunc32 段的设备钟值**可为负**,按 `<= 0` 跳过会把整段负区当「无戳」,一次真空洞凭空消失;旧测试那条是假绿);键名后缀是**硬约束**不是风格——readfail 计数原名不在 _ms/_count 后缀表里,UI 加前缀落进 drop_stats 后会被当成帧数加进「丢帧统计」,改名 readfail_stall_count 并加结构性守卫逐键走一遍快照。
6/6 frame_gap.py 补进 lite 闭包 —— pack_lite.py 的 MODULE_FILES["core"] 是手写白名单,core/pipeline.py 顶层 import 了 GapWatch 而 lite 收 pipeline.py ⇒ 缺这一个文件就是「包能打出来、客户机起不来」。--force 的 import main_lite 自检把它拦在打包阶段(正是 [错误 B] 那套自检存在的理由)。顺带把 frame_gap.py 加进 _verify_payload 的 Windows 包清单。
【普通版一键部署自带实时骨架解算与 D435】scripts/pack_toolkit.py 按白名单裁 2181MB→6.0MB(90 文件,**零 .so/.pyd/.dll**,纯 Python + 数据 ⇒ Windows/Linux 行为一致),start 脚本 [4/7] 自动展开并**实跑**校验解算链。★ polars 是隐式硬依赖:只在 glove_fk/fitting.py 出现,但 glove_fk/__init__.py 有 `from .fitting import fit_calibration_file`、runtime_backend 导入 glove_fk.kinematics ⇒ 连带导入 polars;静态扫描漏、实测 dump sys.modules 才现形(静态扫描还会误报 torch/polyscope/open3d/manotorch/sklearn 一堆不需要的,别照单全收)。校验不是「目录在不在」而是实跑:导入 → 构造 HandSolver → 喂帧到 warmup → 断言 (21,3) 且手尺寸合理,左右手各一遍。标定**只随包两个 imu_calibration_{left,right}_default.json**:带上开发机那只手套的带时间戳标定,客户机接自己的手套时会被静默优先选中、骨架解成别人的手。pyrealsense2 提升为 requirements.txt 默认依赖,extras 只剩 mediapipe。顺手修 .gitignore:`wheels/ # 注释` 这种写法不成立——gitignore 只认**行首**的 #,行尾的算模式正文,整行成了谁也匹配不上的路径名,从写下那天起就没生效过;另加 *.docx 忽略,防并发会话的 git add -A 把对外接口文档扫进来。
【新增 core/startup_guard.py 环境隔离、core/timing.py、scripts/pack_toolkit.py、tools/audit_frame_gaps.py、tools/audit_slam_divergence.py 与 9 份测试】验证:pack_toolkit.py 实跑解算链通过;start.sh 四分支 + start.bat 在 Wine 的真 cmd 下四分支全过(★ for /d 的集合加引号不展开通配符,只在真 cmd 暴露,bash 对照测不出);pack_lite.py --force 收集 36 文件 + import main_lite 自检通过;lite_import_guard_test.py 20 个白名单模块就位。
未收录:cylinder_grasping(1)/(101MB 录制测试数据)、数据采集手套_数据接口说明_v1.2.14.docx(对外接口文档,已加 *.docx 忽略规则)。
Co-Authored-By: Claude Code <noreply@anthropic.com>
- collector/.gitignore +6 -1
- collector/README.md +88 -14
- collector/config/settings.py +8 -0
- collector/core/egodata_writer.py +67 -7
- collector/core/frame_gap.py +109 -0
- collector/core/gripper/bridge.py +157 -2
- collector/core/gripper/devices/uvc_camera_service.py +140 -2
- collector/core/gripper/recording/fays_raw_client.py +33 -0
- collector/core/gripper/rgb_quality.py +230 -0
- collector/core/gripper_codec.py +32 -4
- collector/core/pipeline.py +155 -7
- collector/core/startup_guard.py +144 -0
- collector/core/timing.py +72 -0
- collector/docs/config.md +3 -0
- collector/docs/core.md +77 -0
- collector/docs/data.md +2 -2
- collector/docs/file_format.md +16 -4
- collector/docs/index.md +6 -4
- collector/docs/postmortem_trajectory_and_rgb.md +161 -3
- collector/docs/scripts.md +31 -6
- collector/docs/tools.md +56 -2
- collector/main.py +8 -0
- collector/main_lite.py +8 -0
- collector/requirements-lite.txt +1 -1
- collector/requirements.txt +11 -1
- collector/scripts/pack_lite.py +12 -3
- collector/scripts/pack_toolkit.py +260 -0
- collector/scripts/pack_wheels.py +35 -12
- collector/start.bat +166 -36
- collector/start.sh +157 -28
- collector/start_lite.bat +88 -12
- collector/start_lite.sh +83 -8
- collector/tools/audit_frame_gaps.py +641 -0
- collector/tools/audit_slam_divergence.py +754 -0
- collector/tools/demos/pooled_viewer_demo/README.md +26 -10
- collector/tools/demos/pooled_viewer_demo/pooled_viewer_demo.py +55 -43
- collector/tools/tests/test_audit_frame_gaps.py +471 -0
- collector/tools/tests/test_audit_slam_divergence.py +248 -0
- collector/tools/tests/test_camera_log_archive.py +321 -0
- collector/tools/tests/test_deploy_shell_env_guard.py +259 -0
- collector/tools/tests/test_drop_stats.py +50 -3
- collector/tools/tests/test_ext_frame_gap.py +244 -0
- collector/tools/tests/test_force_matrix_schema_contract.py +369 -0
- collector/tools/tests/test_frame_gap.py +155 -0
- collector/tools/tests/test_gripper_bridge.py +103 -1
- collector/tools/tests/test_imu_pending.py +11 -3
- collector/tools/tests/test_pooled_viewer_demo.py +110 -4
- collector/tools/tests/test_raw_stall_watch.py +127 -0
- collector/tools/tests/test_rgb_quality.py +174 -0
- collector/tools/tests/test_stopwatch.py +95 -0
|
@@ -36,7 +36,9 @@ exports/
|
|
| 36 |
# 本地取回的录制素材与上色产物(双目原视频等,体积大且属外部数据)
|
| 37 |
rec001(1)/
|
| 38 |
tools/weights/
|
| 39 |
-
|
|
|
|
|
|
|
| 40 |
imgui.ini
|
| 41 |
.polyscope.ini
|
| 42 |
tools/stereo_s80m/offline_slam_output/
|
|
@@ -94,3 +96,6 @@ core/gripper/orb_slam_src/FaysSense_VI_Kit_Release/config
|
|
| 94 |
# scripts/pack_lite.py 收集时复制进去的产物,同样不入库——原先的 !负向规则
|
| 95 |
# 已随之删除,否则每次重打包都会留下未跟踪副本。
|
| 96 |
lite_package/*
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
# 本地取回的录制素材与上色产物(双目原视频等,体积大且属外部数据)
|
| 37 |
rec001(1)/
|
| 38 |
tools/weights/
|
| 39 |
+
# scripts/pack_wheels.py 生成的离线部署包(不入库,拷给客户用)
|
| 40 |
+
# 注意: 行尾不能写 # 注释 —— gitignore 只认行首的 #,行尾的会被当成模式正文
|
| 41 |
+
wheels/
|
| 42 |
imgui.ini
|
| 43 |
.polyscope.ini
|
| 44 |
tools/stereo_s80m/offline_slam_output/
|
|
|
|
| 96 |
# scripts/pack_lite.py 收集时复制进去的产物,同样不入库——原先的 !负向规则
|
| 97 |
# 已随之删除,否则每次重打包都会留下未跟踪副本。
|
| 98 |
lite_package/*
|
| 99 |
+
|
| 100 |
+
# 对外接口文档等 Word 产物:随包发送,不入代码库
|
| 101 |
+
*.docx
|
|
@@ -81,28 +81,33 @@ python -m venv venv
|
|
| 81 |
venv/bin/pip install -r requirements.txt
|
| 82 |
```
|
| 83 |
|
| 84 |
-
> Optional dependencies such as `
|
| 85 |
-
>
|
| 86 |
-
>
|
|
|
|
|
|
|
| 87 |
|
| 88 |
#### Windows one-click deployment (recommended for customers)
|
| 89 |
|
| 90 |
Double-click **`start.bat`** in the repo root: it installs Python 3.12
|
| 91 |
-
(silent download if absent), creates the venv, installs dependencies,
|
|
|
|
|
|
|
| 92 |
launches the main program; already-deployed machines start instantly. Common
|
| 93 |
commands:
|
| 94 |
|
| 95 |
```bat
|
| 96 |
start.bat deploy and launch (default)
|
| 97 |
start.bat reinstall delete venv and reinstall (first resort when broken)
|
| 98 |
-
start.bat extras additionally install mediapipe
|
| 99 |
start.bat extras-torch additionally install CPU torch (hand-keypoint RTMPose backend)
|
| 100 |
start.bat help open the operation guide and troubleshooting doc
|
| 101 |
```
|
| 102 |
|
| 103 |
> Full operation guide, error-code reference, and intranet offline delivery
|
| 104 |
> procedure: [使用说明.md](使用说明.md) / [使用说明_EN.md](使用说明_EN.md)
|
| 105 |
-
> (offline wheel bundles are produced by `python scripts/pack_wheels.py`
|
|
|
|
| 106 |
|
| 107 |
**Lite edition** (capture + upload only — no login / playback / task page /
|
| 108 |
skeleton solving): double-click **`start_lite.bat`** (Windows) or run
|
|
@@ -151,7 +156,7 @@ venv/bin/python tools/hand_detection/demo_stereo_hands.py # stereo + MediaPipe
|
|
| 151 |
| Device | Interface | Notes |
|
| 152 |
|---|---|---|
|
| 153 |
| UVC camera | `/dev/videoN` (OpenCV V4L2) | MJPG pixel format; up to 8 cameras |
|
| 154 |
-
| Intel RealSense D435 / D405 | `pyrealsense2` | RGB + depth dual slots; depth recorded as 12-bit gray HEVC MP4 (log depth codes) + live JET heatmap; built-in stall/framerate watchdog with auto-reconnect; D405 has a dedicated near-range capture profile |
|
| 155 |
| S80C / S80M stereo | FaysSense VI Kit SDK (bundled in-repo, incl. FT602 bridge driver) | No SDK install needed; camera profile `STEREO_CAM_FPS` (default 50 fps) decimated to 30 fps recording via wall-clock 1/30 s buckets (burst backfill + empty-bucket watchdog, ~3% empty-bucket rate on healthy recordings); callback frame capture (same as the official GUI); carries hardware nanosecond timestamps and IMU samples; since v1.0.11 the subprocess runs the SDK depth engine → third-tile live depth heatmap + 12-bit gray depth video recording |
|
| 156 |
| BLE data gloves | `bleak` | one per hand; parquet column names bound (`right_glove` / `left_glove`) |
|
| 157 |
| UMI gripper (Fays S80M) | in-repo native stack (`core/gripper/native/`, ~460 MB, not in git) | Linux only (the native stack is ELF x86-64); up to 2 grippers (second one gets the `gripper_2_*` column prefix); records left-lens RGB video + `observation.gripper_{left,right}_force` / `_force_matrix` (10×10×3 force matrix) + `observation.slam_trajectory` + gripper state, no stereo video / IMU; new grippers auto-generate their per-serial factory calibration on open |
|
|
@@ -183,7 +188,8 @@ data/recordings/<task>/
|
|
| 183 |
columns (`episode_index` / `frame_index` / `timestamp` / `wall_time` /
|
| 184 |
`hardware_ns`) plus sparse observations (`observation.<sensor>` per
|
| 185 |
frame, `observation.imu` variable-length sample lists aligned by
|
| 186 |
-
`imu_ts_ns`, `observation.*hand_pose`
|
|
|
|
| 187 |
post-processing). The full interface contract lives in
|
| 188 |
[docs/file_format.md](docs/file_format.md)
|
| 189 |
- Device naming follows the EgoData `<location>_<modality>` convention, e.g.
|
|
@@ -314,6 +320,14 @@ venv/bin/python tools/tests/glove_widget_test.py
|
|
| 314 |
venv/bin/python tools/tests/grid_drag_fps_test.py
|
| 315 |
venv/bin/python tools/tests/device_panel_gui_smoke_test.py
|
| 316 |
venv/bin/python tools/tests/test_device_detector.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
# hardware tests require the corresponding device attached: d405_worker_test,
|
| 318 |
# d435_e2e_test, d435_gui_smoke_test, mono_regression, d435_playback_test, etc.
|
| 319 |
```
|
|
@@ -375,6 +389,35 @@ are documented in [docs/index.md](docs/index.md#开发约定).
|
|
| 375 |
|
| 376 |
### Changelog
|
| 377 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
- **v1.3.9** — connecting a gripper now puts every DECXIN's exposure/white balance
|
| 379 |
back to *auto*; until now each newly plugged gripper needed a manual
|
| 380 |
`v4l2-ctl -c auto_exposure=3,white_balance_automatic=1`. The dark picture is
|
|
@@ -861,24 +904,27 @@ python -m venv venv
|
|
| 861 |
venv/bin/pip install -r requirements.txt
|
| 862 |
```
|
| 863 |
|
| 864 |
-
> `
|
| 865 |
> (代码内惰性导入,缺失时对应功能不可用;一键安装见下方 `start.bat extras`)。
|
|
|
|
| 866 |
|
| 867 |
#### Windows 一键部署(推荐客户使用)
|
| 868 |
|
| 869 |
双击根目录 **`start.bat`**:自动安装 Python 3.12(无则静默下载安装)、创建 venv、
|
| 870 |
-
安装依赖
|
|
|
|
| 871 |
|
| 872 |
```bat
|
| 873 |
start.bat 部署并启动(默认)
|
| 874 |
start.bat reinstall 删除 venv 重装(出问题首选)
|
| 875 |
-
start.bat extras 追加安装 mediapipe
|
| 876 |
start.bat extras-torch 追加安装 CPU 版 torch(手部关键点 RTMPose 后端)
|
| 877 |
start.bat help 打开操作指引与异常排查文档
|
| 878 |
```
|
| 879 |
|
| 880 |
> 完整操作指引、错误码对照与内网离线交付方式见 [使用说明.md](使用说明.md) /
|
| 881 |
-
> [使用说明_EN.md](使用说明_EN.md)(离线安装包由 `python scripts/pack_wheels.py` 生成
|
|
|
|
| 882 |
|
| 883 |
**极简版**(只做连接设备 → 采集 → 上传,无登录/回放/任务页/骨架解算):
|
| 884 |
Windows 双击 **`start_lite.bat`**、Linux 跑 `./start_lite.sh`,用独立环境
|
|
@@ -922,7 +968,7 @@ venv/bin/python tools/hand_detection/demo_stereo_hands.py # 双目 + MediaPipe
|
|
| 922 |
| 设备 | 接入方式 | 说明 |
|
| 923 |
|---|---|---|
|
| 924 |
| UVC 相机 | `/dev/videoN`(OpenCV V4L2) | MJPG 像素格式;最多 8 路 |
|
| 925 |
-
| Intel RealSense D435 / D405 | `pyrealsense2` | RGB + depth 双路槽位;深度以 12-bit 灰度 HEVC MP4 录制(对数深度码)+ 实时 JET 热力图;内置停滞/帧率看门狗自动重连;D405 有独立近距采集配置 |
|
| 926 |
| S80C / S80M 双目 | FaysSense VI Kit SDK(仓库自带,含 FT602 桥驱动) | 无需安装 SDK;相机档 `STEREO_CAM_FPS`(默认 50fps)按 wall 时钟 1/30s 桶抽帧录制 30fps(突发补录 + 空桶看门狗,健康录制空桶率 ~3%),回调取帧(官方 GUI 同款);携带硬件纳秒时间戳与 IMU 样本;v1.0.11 起子进程内置 SDK 深度引擎 → 第三格实时深度热力图 + 12-bit 灰度深度视频录制 |
|
| 927 |
| BLE 数据手套 | `bleak` | 左右手各一只,parquet 列名绑定(`right_glove` / `left_glove`) |
|
| 928 |
| UMI 夹爪(Fays S80M) | 仓库自带原生栈(`core/gripper/native/`,约 460MB,不入库) | 仅 Linux(原生栈是 ELF x86-64);最多 2 台(第二台的数据列自动加 `gripper_2_*` 前缀);录左目 RGB 视频 + `observation.gripper_{left,right}_force` / `_force_matrix`(10×10×3 力矩阵)+ `observation.slam_trajectory` + 夹爪状态,不存双目视频/IMU;新夹爪开启时自动生成逐台出厂标定 |
|
|
@@ -953,7 +999,8 @@ data/recordings/<任务>/
|
|
| 953 |
(`episode_index` / `frame_index` / `timestamp` / `wall_time` /
|
| 954 |
`hardware_ns`)+ 稀疏观测列(`observation.<传感器>` 逐帧、
|
| 955 |
`observation.imu` 变长样本列表按 `imu_ts_ns` 对齐、
|
| 956 |
-
`observation.*hand_pose`
|
|
|
|
| 957 |
[docs/file_format.md](docs/file_format.md)
|
| 958 |
- 设备命名遵循 EgoData 标准 `<位置>_<模态>`:如 `head_left_rgb`、
|
| 959 |
`head_right_rgb`、`head_depth`、`right_glove`、`right_hand_pose`
|
|
@@ -1074,6 +1121,14 @@ venv/bin/python tools/tests/glove_widget_test.py
|
|
| 1074 |
venv/bin/python tools/tests/grid_drag_fps_test.py
|
| 1075 |
venv/bin/python tools/tests/device_panel_gui_smoke_test.py
|
| 1076 |
venv/bin/python tools/tests/test_device_detector.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1077 |
# 真机相关测试需连接对应设备:d405_worker_test、d435_e2e_test、
|
| 1078 |
# d435_gui_smoke_test、mono_regression、d435_playback_test 等
|
| 1079 |
```
|
|
@@ -1125,6 +1180,25 @@ i18n 文案经 `tr()` 翻译、PyQt5 信号参数用 `object` 封送大整数、
|
|
| 1125 |
|
| 1126 |
### 更新记录
|
| 1127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1128 |
- **v1.3.9** — 连夹爪时自动把 DECXIN 的曝光/白平衡写回「自动」:此前每接一台新
|
| 1129 |
夹爪都要人工跑一次 `v4l2-ctl -c auto_exposure=3,white_balance_automatic=1`。
|
| 1130 |
画面暗的根因不在采集链,而在**相机机身**——`auto_exposure=1`(手动)+ AWB=0
|
|
|
|
| 81 |
venv/bin/pip install -r requirements.txt
|
| 82 |
```
|
| 83 |
|
| 84 |
+
> Optional dependencies such as `mediapipe` and `torch` are not listed in
|
| 85 |
+
> `requirements.txt` (lazily imported; the corresponding feature is unavailable
|
| 86 |
+
> if missing — one-click installs via `start.bat extras` below). `pyrealsense2`
|
| 87 |
+
> (D435/D405) and the glove-skeleton solver dependencies are part of the
|
| 88 |
+
> default install.
|
| 89 |
|
| 90 |
#### Windows one-click deployment (recommended for customers)
|
| 91 |
|
| 92 |
Double-click **`start.bat`** in the repo root: it installs Python 3.12
|
| 93 |
+
(silent download if absent), creates the venv, installs dependencies, unpacks
|
| 94 |
+
the bundled glove toolkit ([4/7] — needed for the live hand skeleton; if it is
|
| 95 |
+
missing only a warning is printed and the program still starts), and
|
| 96 |
launches the main program; already-deployed machines start instantly. Common
|
| 97 |
commands:
|
| 98 |
|
| 99 |
```bat
|
| 100 |
start.bat deploy and launch (default)
|
| 101 |
start.bat reinstall delete venv and reinstall (first resort when broken)
|
| 102 |
+
start.bat extras additionally install mediapipe
|
| 103 |
start.bat extras-torch additionally install CPU torch (hand-keypoint RTMPose backend)
|
| 104 |
start.bat help open the operation guide and troubleshooting doc
|
| 105 |
```
|
| 106 |
|
| 107 |
> Full operation guide, error-code reference, and intranet offline delivery
|
| 108 |
> procedure: [使用说明.md](使用说明.md) / [使用说明_EN.md](使用说明_EN.md)
|
| 109 |
+
> (offline wheel bundles are produced by `python scripts/pack_wheels.py`,
|
| 110 |
+
> which by default also trims the glove toolkit into `wheels/toolkit/glove_toolkit.zip`).
|
| 111 |
|
| 112 |
**Lite edition** (capture + upload only — no login / playback / task page /
|
| 113 |
skeleton solving): double-click **`start_lite.bat`** (Windows) or run
|
|
|
|
| 156 |
| Device | Interface | Notes |
|
| 157 |
|---|---|---|
|
| 158 |
| UVC camera | `/dev/videoN` (OpenCV V4L2) | MJPG pixel format; up to 8 cameras |
|
| 159 |
+
| Intel RealSense D435 / D405 | `pyrealsense2` (default install) | RGB + depth dual slots; depth recorded as 12-bit gray HEVC MP4 (log depth codes) + live JET heatmap; built-in stall/framerate watchdog with auto-reconnect; D405 has a dedicated near-range capture profile |
|
| 160 |
| S80C / S80M stereo | FaysSense VI Kit SDK (bundled in-repo, incl. FT602 bridge driver) | No SDK install needed; camera profile `STEREO_CAM_FPS` (default 50 fps) decimated to 30 fps recording via wall-clock 1/30 s buckets (burst backfill + empty-bucket watchdog, ~3% empty-bucket rate on healthy recordings); callback frame capture (same as the official GUI); carries hardware nanosecond timestamps and IMU samples; since v1.0.11 the subprocess runs the SDK depth engine → third-tile live depth heatmap + 12-bit gray depth video recording |
|
| 161 |
| BLE data gloves | `bleak` | one per hand; parquet column names bound (`right_glove` / `left_glove`) |
|
| 162 |
| UMI gripper (Fays S80M) | in-repo native stack (`core/gripper/native/`, ~460 MB, not in git) | Linux only (the native stack is ELF x86-64); up to 2 grippers (second one gets the `gripper_2_*` column prefix); records left-lens RGB video + `observation.gripper_{left,right}_force` / `_force_matrix` (10×10×3 force matrix) + `observation.slam_trajectory` + gripper state, no stereo video / IMU; new grippers auto-generate their per-serial factory calibration on open |
|
|
|
|
| 188 |
columns (`episode_index` / `frame_index` / `timestamp` / `wall_time` /
|
| 189 |
`hardware_ns`) plus sparse observations (`observation.<sensor>` per
|
| 190 |
frame, `observation.imu` variable-length sample lists aligned by
|
| 191 |
+
`imu_ts_ns`, `observation.*hand_pose` placeholders filled live from the
|
| 192 |
+
glove IMU when solving is available, zero otherwise / backfilled by
|
| 193 |
post-processing). The full interface contract lives in
|
| 194 |
[docs/file_format.md](docs/file_format.md)
|
| 195 |
- Device naming follows the EgoData `<location>_<modality>` convention, e.g.
|
|
|
|
| 320 |
venv/bin/python tools/tests/grid_drag_fps_test.py
|
| 321 |
venv/bin/python tools/tests/device_panel_gui_smoke_test.py
|
| 322 |
venv/bin/python tools/tests/test_device_detector.py
|
| 323 |
+
# gripper RGB frame-gap instrumentation (v1.3.10)
|
| 324 |
+
venv/bin/python tools/tests/test_frame_gap.py
|
| 325 |
+
venv/bin/python tools/tests/test_rgb_quality.py
|
| 326 |
+
venv/bin/python tools/tests/test_ext_frame_gap.py
|
| 327 |
+
venv/bin/python tools/tests/test_camera_log_archive.py
|
| 328 |
+
venv/bin/python tools/tests/test_audit_frame_gaps.py
|
| 329 |
+
# whole-library frame-gap audit (read-only; exit 1 when picture loss is proven)
|
| 330 |
+
venv/bin/python tools/audit_frame_gaps.py
|
| 331 |
# hardware tests require the corresponding device attached: d405_worker_test,
|
| 332 |
# d435_e2e_test, d435_gui_smoke_test, mono_regression, d435_playback_test, etc.
|
| 333 |
```
|
|
|
|
| 389 |
|
| 390 |
### Changelog
|
| 391 |
|
| 392 |
+
- **v1.3.10** — silent holes in the gripper RGB stream are now instrumented,
|
| 393 |
+
alarmed and archived. `episode-099.mp4`'s frozen opening is not a missing
|
| 394 |
+
stream at the start: the first 45 frames are real (the scene is simply still)
|
| 395 |
+
and **4.68s vanished between row44 and row45** (`hardware_ns` +4680.8ms and
|
| 396 |
+
`wall_time` +4666.4ms jump together) — while *every* counter read 0 and the log
|
| 397 |
+
held nothing. Three different paths leave the **same** hole signature in the
|
| 398 |
+
parquet: the camera having no frame to read, the emit frame slot being
|
| 399 |
+
overwritten, and the GUI main thread stalling. They are counted separately now
|
| 400 |
+
(ten `*_ms`/`*_count` keys in `drop_stats` — seven from the bridge, three from
|
| 401 |
+
the writer — all excluded from the frame-drop totals by
|
| 402 |
+
`core.pipeline.is_frame_drop_key`, with a test that walks the whole snapshot so
|
| 403 |
+
a key can never fall outside that suffix rule again), with a live alarm on the
|
| 404 |
+
acquisition side and a per-episode summary line. The camera service's own log
|
| 405 |
+
— where stalls, altsetting downgrades and USB resets are written — used to die
|
| 406 |
+
with its `runtime_dir` on every clean shutdown, so the sessions most worth
|
| 407 |
+
keeping left no evidence at all; it is archived to
|
| 408 |
+
`logs/camera_service/<time>_<tag>_camera-service.log` (last 20) with a warning
|
| 409 |
+
excerpt in `main.log`. And the read-only `tools/audit_frame_gaps.py` settles
|
| 410 |
+
the whole library: **25 of 95 episodes really lost picture, 37412.6ms total
|
| 411 |
+
(max 4647.5ms @ 099), and all 25 sit 0.13–1.47s after recording start** — the
|
| 412 |
+
window before the ~1s queue buffer has built up. Counting clocks alone would
|
| 413 |
+
have booked 20.1s of "frames arrived late" as loss; the verdict comes from the
|
| 414 |
+
*picture* (boundary mad against a same-window control), and the clock signature
|
| 415 |
+
only names which side stalled (`Δwall − Δhw` = queue-latency change: positive =
|
| 416 |
+
writer backlog, negative = reader gap draining it). Decoupling recording from
|
| 417 |
+
display, camera-side self-healing, and shrinking the external queue are
|
| 418 |
+
explicitly **not** part of this change; the two timestamps' semantics are now
|
| 419 |
+
written down in `docs/file_format.md` §7.3 and the whole post-mortem in
|
| 420 |
+
`docs/postmortem_trajectory_and_rgb.md` §4.
|
| 421 |
- **v1.3.9** — connecting a gripper now puts every DECXIN's exposure/white balance
|
| 422 |
back to *auto*; until now each newly plugged gripper needed a manual
|
| 423 |
`v4l2-ctl -c auto_exposure=3,white_balance_automatic=1`. The dark picture is
|
|
|
|
| 904 |
venv/bin/pip install -r requirements.txt
|
| 905 |
```
|
| 906 |
|
| 907 |
+
> `mediapipe`、`torch` 等可选依赖未列入 `requirements.txt`
|
| 908 |
> (代码内惰性导入,缺失时对应功能不可用;一键安装见下方 `start.bat extras`)。
|
| 909 |
+
> `pyrealsense2`(D435/D405)与手套骨架解算依赖属默认安装。
|
| 910 |
|
| 911 |
#### Windows 一键部署(推荐客户使用)
|
| 912 |
|
| 913 |
双击根目录 **`start.bat`**:自动安装 Python 3.12(无则静默下载安装)、创建 venv、
|
| 914 |
+
安装依赖、展开随包的手套工具包([4/7],实时骨架解算用;缺了只打印警告、主程序照常
|
| 915 |
+
启动)并启动主程序;已部署过则秒开。常用命令:
|
| 916 |
|
| 917 |
```bat
|
| 918 |
start.bat 部署并启动(默认)
|
| 919 |
start.bat reinstall 删除 venv 重装(出问题首选)
|
| 920 |
+
start.bat extras 追加安装 mediapipe
|
| 921 |
start.bat extras-torch 追加安装 CPU 版 torch(手部关键点 RTMPose 后端)
|
| 922 |
start.bat help 打开操作指引与异常排查文档
|
| 923 |
```
|
| 924 |
|
| 925 |
> 完整操作指引、错误码对照与内网离线交付方式见 [使用说明.md](使用说明.md) /
|
| 926 |
+
> [使用说明_EN.md](使用说明_EN.md)(离线安装包由 `python scripts/pack_wheels.py` 生成,
|
| 927 |
+
> 默认同时把手套工具包裁剪进 `wheels/toolkit/glove_toolkit.zip`)。
|
| 928 |
|
| 929 |
**极简版**(只做连接设备 → 采集 → 上传,无登录/回放/任务页/骨架解算):
|
| 930 |
Windows 双击 **`start_lite.bat`**、Linux 跑 `./start_lite.sh`,用独立环境
|
|
|
|
| 968 |
| 设备 | 接入方式 | 说明 |
|
| 969 |
|---|---|---|
|
| 970 |
| UVC 相机 | `/dev/videoN`(OpenCV V4L2) | MJPG 像素格式;最多 8 路 |
|
| 971 |
+
| Intel RealSense D435 / D405 | `pyrealsense2`(默认安装) | RGB + depth 双路槽位;深度以 12-bit 灰度 HEVC MP4 录制(对数深度码)+ 实时 JET 热力图;内置停滞/帧率看门狗自动重连;D405 有独立近距采集配置 |
|
| 972 |
| S80C / S80M 双目 | FaysSense VI Kit SDK(仓库自带,含 FT602 桥驱动) | 无需安装 SDK;相机档 `STEREO_CAM_FPS`(默认 50fps)按 wall 时钟 1/30s 桶抽帧录制 30fps(突发补录 + 空桶看门狗,健康录制空桶率 ~3%),回调取帧(官方 GUI 同款);携带硬件纳秒时间戳与 IMU 样本;v1.0.11 起子进程内置 SDK 深度引擎 → 第三格实时深度热力图 + 12-bit 灰度深度视频录制 |
|
| 973 |
| BLE 数据手套 | `bleak` | 左右手各一只,parquet 列名绑定(`right_glove` / `left_glove`) |
|
| 974 |
| UMI 夹爪(Fays S80M) | 仓库自带原生栈(`core/gripper/native/`,约 460MB,不入库) | 仅 Linux(原生栈是 ELF x86-64);最多 2 台(第二台的数据列自动加 `gripper_2_*` 前缀);录左目 RGB 视频 + `observation.gripper_{left,right}_force` / `_force_matrix`(10×10×3 力矩阵)+ `observation.slam_trajectory` + 夹爪状态,不存双目视频/IMU;新夹爪开启时自动生成逐台出厂标定 |
|
|
|
|
| 999 |
(`episode_index` / `frame_index` / `timestamp` / `wall_time` /
|
| 1000 |
`hardware_ns`)+ 稀疏观测列(`observation.<传感器>` 逐帧、
|
| 1001 |
`observation.imu` 变长样本列表按 `imu_ts_ns` 对齐、
|
| 1002 |
+
`observation.*hand_pose` 解算可用时由手套 IMU 实时回填、否则为零占位,
|
| 1003 |
+
也可由后处理回填)。完整接口契约见
|
| 1004 |
[docs/file_format.md](docs/file_format.md)
|
| 1005 |
- 设备命名遵循 EgoData 标准 `<位置>_<模态>`:如 `head_left_rgb`、
|
| 1006 |
`head_right_rgb`、`head_depth`、`right_glove`、`right_hand_pose`
|
|
|
|
| 1121 |
venv/bin/python tools/tests/grid_drag_fps_test.py
|
| 1122 |
venv/bin/python tools/tests/device_panel_gui_smoke_test.py
|
| 1123 |
venv/bin/python tools/tests/test_device_detector.py
|
| 1124 |
+
# 夹爪 RGB 帧空洞可见化(v1.3.10)
|
| 1125 |
+
venv/bin/python tools/tests/test_frame_gap.py
|
| 1126 |
+
venv/bin/python tools/tests/test_rgb_quality.py
|
| 1127 |
+
venv/bin/python tools/tests/test_ext_frame_gap.py
|
| 1128 |
+
venv/bin/python tools/tests/test_camera_log_archive.py
|
| 1129 |
+
venv/bin/python tools/tests/test_audit_frame_gaps.py
|
| 1130 |
+
# 全库帧空洞审计(只读;画面证实丢帧时退出码 1)
|
| 1131 |
+
venv/bin/python tools/audit_frame_gaps.py
|
| 1132 |
# 真机相关测试需连接对应设备:d405_worker_test、d435_e2e_test、
|
| 1133 |
# d435_gui_smoke_test、mono_regression、d435_playback_test 等
|
| 1134 |
```
|
|
|
|
| 1180 |
|
| 1181 |
### 更新记录
|
| 1182 |
|
| 1183 |
+
- **v1.3.10** — 夹爪 RGB 的**静默空洞**从此有仪表、有告警、有留档。`episode-099.mp4`
|
| 1184 |
+
开头那一段静止不是「开头没流」:前 45 帧是真帧(场景本身静止),真正丢的是
|
| 1185 |
+
**row44→row45 之间的 4.68 秒**(`hardware_ns` +4680.8ms 与 `wall_time` +4666.4ms
|
| 1186 |
+
同步跳)—— 而当时**所有计数器都是 0**、日志里一行都没有。「相机侧没帧可读」
|
| 1187 |
+
「emit 帧槽被顶掉」「GUI 主线程卡顿」这三条路在 parquet 里留下的是**同一个签名**,
|
| 1188 |
+
现在各记各的账(`drop_stats` 里十个 `*_ms`/`*_count` 键——桥接七个 + 落盘三个,
|
| 1189 |
+
全部由 `core.pipeline.is_frame_drop_key` 挡在「丢帧统计」之外;`test_gripper_bridge`
|
| 1190 |
+
逐个键走一遍这份后缀规则,免得再有一个键漏到帧数里去),采集侧当场出声、录制结束
|
| 1191 |
+
再打一行汇总。相机服务自己那份日志(停摆/降档/USB 复位全写在那里)原先随
|
| 1192 |
+
`runtime_dir` 一起被删——一次干净退出的会话(正是最该留证据的那种)等于没写过;
|
| 1193 |
+
现在留档到 `logs/camera_service/<时刻>_<tag>_camera-service.log`(最近 20 份),
|
| 1194 |
+
告警行摘录进 `main.log`。只读的 `tools/audit_frame_gaps.py` 把全库一次数清楚:
|
| 1195 |
+
**95 段里 25 段画面真的丢了,累计 37412.6ms(最大 4647.5ms @ 099),且 25 起
|
| 1196 |
+
全部落在开录后 0.13~1.47s** —— 也就是那 ~1 秒队列缓冲还没垫起来的窗口。只按钟
|
| 1197 |
+
算会把 20.1s 的「帧到得晚」记成损失;结论现在由**画面**给出(事件处帧差对同窗
|
| 1198 |
+
对照),钟只用来指认**哪一侧停了**(`Δwall − Δhw` = 队列滞留变化:正 = 写侧积压,
|
| 1199 |
+
负 = 读侧空窗排空)。录制与显示解耦、相机侧自愈、外部队列改小**本次都不做**;
|
| 1200 |
+
两个时间戳的语义写进了 `docs/file_format.md` §7.3,完整复盘见
|
| 1201 |
+
`docs/postmortem_trajectory_and_rgb.md` 第四节。
|
| 1202 |
- **v1.3.9** — 连夹爪时自动把 DECXIN 的曝光/白平衡写回「自动」:此前每接一台新
|
| 1203 |
夹爪都要人工跑一次 `v4l2-ctl -c auto_exposure=3,white_balance_automatic=1`。
|
| 1204 |
画面暗的根因不在采集链,而在**相机机身**——`auto_exposure=1`(手动)+ AWB=0
|
|
@@ -56,6 +56,14 @@ IMU_PENDING_MAX_SAMPLES = 18000 # 双目 IMU 防丢缓冲上限(~1 分钟 @
|
|
| 56 |
DROP_WARN_RATIO = 0.01 # 丢帧提示阈值:丢帧 > 总帧数×该比例 或
|
| 57 |
DROP_WARN_MIN_COUNT = 30 # 丢帧 > 该帧数 → 提示换编码器/降分辨率
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
# ── 设备命名规范 (EgoData 标准) ───────────────────────
|
| 60 |
# 命名约定: <位置>_<模态>
|
| 61 |
# 头戴左目: head_left_rgb
|
|
|
|
| 56 |
DROP_WARN_RATIO = 0.01 # 丢帧提示阈值:丢帧 > 总帧数×该比例 或
|
| 57 |
DROP_WARN_MIN_COUNT = 30 # 丢帧 > 该帧数 → 提示换编码器/降分辨率
|
| 58 |
|
| 59 |
+
# ── 夹爪 RGB 帧空洞可见化(v1.3.10;见 docs/postmortem_trajectory_and_rgb.md)──
|
| 60 |
+
# 2026-09-18 episode-099 丢了 4.68s 而所有计数器都是 0:静默丢帧无处可查。
|
| 61 |
+
# 这四个值是「同一现象在三层各自的门槛」,改动前先读那一节。
|
| 62 |
+
GRIPPER_RGB_GAP_MIN_MS = 100 # 计入「空洞」的**间隔**下限(≈3 帧);实测正常帧距 29.9~37.5ms
|
| 63 |
+
GRIPPER_RGB_GAP_ALERT_MS = 500 # 空洞闭合时当场告警门槛(低于此只落 parquet 不打日志)
|
| 64 |
+
GRIPPER_RGB_STALL_ALERT_MS = 1000 # read() 失败连击告警门槛(停摆多久才开始喊)
|
| 65 |
+
GRIPPER_RGB_STALL_REPEAT_S = 30.0 # 持续故障的重复告警间隔(进入一次 / 限频 / 恢复一次)
|
| 66 |
+
|
| 67 |
# ── 设备命名规范 (EgoData 标准) ───────────────────────
|
| 68 |
# 命名约定: <位置>_<模态>
|
| 69 |
# 头戴左目: head_left_rgb
|
|
@@ -39,6 +39,7 @@ from core.encoder_probe import (select_encoder, list_working_ffmpegs,
|
|
| 39 |
find_depth_12bit_ffmpeg)
|
| 40 |
from core.depth_codec import quantize_depth, depth_video_encoder_args
|
| 41 |
from core.calibration import StereoCalibration
|
|
|
|
| 42 |
from core.helpers import (
|
| 43 |
task_dir_of, episode_chunk_file, POOLED_CHUNK_SIZE,
|
| 44 |
pooled_video_path, pooled_video_dir,
|
|
@@ -104,6 +105,38 @@ def _episode_rows_table(rows: List[dict]) -> pa.Table:
|
|
| 104 |
return pa.table(arrs, schema=_EPISODE_SCHEMA)
|
| 105 |
|
| 106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
def _read_episode_rows(path: str) -> List[dict]:
|
| 108 |
"""读 episodes 文件为行 dict 列表;文件缺失/损坏返回 []。"""
|
| 109 |
if not os.path.isfile(path) or os.path.getsize(path) == 0:
|
|
@@ -183,6 +216,9 @@ class EgoDataWriter(QObject):
|
|
| 183 |
self._depth_enabled: bool = False # 业务开关:是否录制深度
|
| 184 |
self._encoder_choice = None # 本会话编码器选择(v1.0.9)
|
| 185 |
self._drop_stats: Dict[str, int] = {} # 丢帧统计(pipeline 注入)
|
|
|
|
|
|
|
|
|
|
| 186 |
# abort 清理清单:本 episode 落盘的最终文件 + 创建的目录
|
| 187 |
self._created_files: List[str] = []
|
| 188 |
self._created_dirs: List[str] = []
|
|
@@ -595,15 +631,24 @@ class EgoDataWriter(QObject):
|
|
| 595 |
def _note_matrix_dtype(self, key: str, value) -> None:
|
| 596 |
"""按首帧实际元素类型锁定该力矩阵列的落盘规格。
|
| 597 |
|
| 598 |
-
int16 行差分编码
|
| 599 |
-
float32 原值
|
| 600 |
首帧空样本时不定型(后续有样本再定);定型后若类型变了说明
|
| 601 |
录制中切了开关——parquet 一列只能一种类型,这里显式报错而不是
|
| 602 |
让 pyarrow 抛难懂的转换异常。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 603 |
"""
|
| 604 |
-
if
|
|
|
|
| 605 |
return # 空样本:不定型
|
| 606 |
-
|
|
|
|
| 607 |
prev = self._matrix_dtype.get(key)
|
| 608 |
if prev is None:
|
| 609 |
self._matrix_dtype[key] = dtype
|
|
@@ -768,14 +813,24 @@ class EgoDataWriter(QObject):
|
|
| 768 |
# ── 结束 ──────────────────────────────────────────
|
| 769 |
|
| 770 |
def end_episode(self):
|
| 771 |
-
"""关闭 ffmpeg,写出全部文件(顺序见 docs/data.md 写入流程)。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 772 |
self._close_ffmpeg()
|
|
|
|
| 773 |
self._write_data_parquet()
|
|
|
|
| 774 |
self._append_episode_row()
|
| 775 |
self._write_info_json()
|
| 776 |
self._merge_stats()
|
| 777 |
self._write_tasks_jsonl()
|
| 778 |
clear_recycled_episode(self._task_dir)
|
|
|
|
|
|
|
| 779 |
self.episode_finished.emit(self._task_dir)
|
| 780 |
|
| 781 |
@property
|
|
@@ -801,7 +856,12 @@ class EgoDataWriter(QObject):
|
|
| 801 |
if getattr(self, "_episode_index", 0) > 0 and getattr(
|
| 802 |
self, "_task_dir", ""):
|
| 803 |
mark_recycled_episode(self._task_dir, self._episode_index)
|
|
|
|
|
|
|
|
|
|
| 804 |
self._close_ffmpeg()
|
|
|
|
|
|
|
| 805 |
for p in list(self._created_files):
|
| 806 |
try:
|
| 807 |
if os.path.isfile(p):
|
|
@@ -937,8 +997,8 @@ class EgoDataWriter(QObject):
|
|
| 937 |
elif key.endswith("_force_matrix"):
|
| 938 |
item = (pa.float32() if self._matrix_dtype.get(key) == "float32"
|
| 939 |
else pa.int16())
|
| 940 |
-
cols[name] =
|
| 941 |
-
[r.get(name, []) for r in rows],
|
| 942 |
elif key.endswith("slam_trajectory"):
|
| 943 |
cols[name] = pa.array(
|
| 944 |
[r.get(name, []) for r in rows], pa.list_(pa.float64()))
|
|
|
|
| 39 |
find_depth_12bit_ffmpeg)
|
| 40 |
from core.depth_codec import quantize_depth, depth_video_encoder_args
|
| 41 |
from core.calibration import StereoCalibration
|
| 42 |
+
from core.timing import Stopwatch
|
| 43 |
from core.helpers import (
|
| 44 |
task_dir_of, episode_chunk_file, POOLED_CHUNK_SIZE,
|
| 45 |
pooled_video_path, pooled_video_dir,
|
|
|
|
| 105 |
return pa.table(arrs, schema=_EPISODE_SCHEMA)
|
| 106 |
|
| 107 |
|
| 108 |
+
def _list_column(values: List[object], item: pa.DataType) -> pa.Array:
|
| 109 |
+
"""变长行 → `list<item>`,行内元素摊平进**一条 numpy 缓冲**再包成 arrow。
|
| 110 |
+
|
| 111 |
+
行可以是 ndarray(生产路径:`encode_gripper_force_matrix_array`)或
|
| 112 |
+
Python list(历史调用方 / 测试),两者结果逐位相同。
|
| 113 |
+
|
| 114 |
+
**为什么不用 `pa.array([...], pa.list_(item))`**:pyarrow 对 Python
|
| 115 |
+
list 逐值装箱,实测 185 帧 × 187500 点 = **538ms 且全程持 GIL**,
|
| 116 |
+
正好在收尾窗口把原始流接收线程挡在 `recv()` 外——服务端 16 包队列
|
| 117 |
+
(≈0.53s)填满即主动 close,这就是「点停止就断链」的成因
|
| 118 |
+
(2026-09-18:55 次「完成」54 次断链;中止路径不写 parquet ⇒ 0/11)。
|
| 119 |
+
走缓冲后同一列 13.5ms、最长停摆 3.6ms(噪声底 0.9ms)。
|
| 120 |
+
|
| 121 |
+
语义与旧实现**逐位一致**:缺键行与空行都落成**空 list**(不是 null),
|
| 122 |
+
行序、行长、元素值都不变——由
|
| 123 |
+
`tools/tests/test_force_matrix_schema_contract.py` 对着冻结的旧表达式钉死。
|
| 124 |
+
"""
|
| 125 |
+
np_dtype = np.float32 if item == pa.float32() else np.int16
|
| 126 |
+
sizes = np.fromiter((len(v) for v in values), np.int32, len(values))
|
| 127 |
+
offsets = np.zeros(len(values) + 1, np.int32)
|
| 128 |
+
np.cumsum(sizes, out=offsets[1:])
|
| 129 |
+
flat = np.empty(int(offsets[-1]), np_dtype)
|
| 130 |
+
pos = 0
|
| 131 |
+
for v in values:
|
| 132 |
+
n = v.size if isinstance(v, np.ndarray) else len(v)
|
| 133 |
+
if n:
|
| 134 |
+
# 同型 ndarray ⇒ memcpy;list ⇒ numpy 的逐值转换(老调用方照旧)
|
| 135 |
+
flat[pos:pos + n] = v
|
| 136 |
+
pos += n
|
| 137 |
+
return pa.ListArray.from_arrays(offsets, pa.array(flat))
|
| 138 |
+
|
| 139 |
+
|
| 140 |
def _read_episode_rows(path: str) -> List[dict]:
|
| 141 |
"""读 episodes 文件为行 dict 列表;文件缺失/损坏返回 []。"""
|
| 142 |
if not os.path.isfile(path) or os.path.getsize(path) == 0:
|
|
|
|
| 216 |
self._depth_enabled: bool = False # 业务开关:是否录制深度
|
| 217 |
self._encoder_choice = None # 本会话编码器选择(v1.0.9)
|
| 218 |
self._drop_stats: Dict[str, int] = {} # 丢帧统计(pipeline 注入)
|
| 219 |
+
# v1.3.11(L0-1)收尾各段耗时(flush/parquet/meta,毫秒)——
|
| 220 |
+
# 由 end_episode / abort_episode 写入,pipeline 读它打一行日志
|
| 221 |
+
self.finalize_timing: Dict[str, int] = {}
|
| 222 |
# abort 清理清单:本 episode 落盘的最终文件 + 创建的目录
|
| 223 |
self._created_files: List[str] = []
|
| 224 |
self._created_dirs: List[str] = []
|
|
|
|
| 631 |
def _note_matrix_dtype(self, key: str, value) -> None:
|
| 632 |
"""按首帧实际元素类型锁定该力矩阵列的落盘规格。
|
| 633 |
|
| 634 |
+
int16 行差分编码 → np.int16(或 Python int);
|
| 635 |
+
float32 原值 → np.float32(或 Python float)。
|
| 636 |
首帧空样本时不定型(后续有样本再定);定型后若类型变了说明
|
| 637 |
录制中切了开关——parquet 一列只能一种类型,这里显式报错而不是
|
| 638 |
让 pyarrow 抛难懂的转换异常。
|
| 639 |
+
|
| 640 |
+
★ 两个坑(2026-09-18 换成 ndarray 交付时踩出来的):
|
| 641 |
+
* **判空不能用 `if not value`**:对真数组 numpy 抛
|
| 642 |
+
「truth value of an array is ambiguous」——每帧都炸;
|
| 643 |
+
* **`isinstance(np.float32(x), float)` 是 False**:只看 Python
|
| 644 |
+
标量会把 float32 档判成 int16 ⇒ 列类型错 + 精度真丢(不报错,
|
| 645 |
+
是悄悄截断)。所以必须同时认 numpy 标量家族。
|
| 646 |
"""
|
| 647 |
+
n = value.size if isinstance(value, np.ndarray) else len(value)
|
| 648 |
+
if n == 0:
|
| 649 |
return # 空样本:不定型
|
| 650 |
+
first = value.reshape(-1)[0] if isinstance(value, np.ndarray) else value[0]
|
| 651 |
+
dtype = "float32" if isinstance(first, (float, np.floating)) else "int16"
|
| 652 |
prev = self._matrix_dtype.get(key)
|
| 653 |
if prev is None:
|
| 654 |
self._matrix_dtype[key] = dtype
|
|
|
|
| 813 |
# ── 结束 ──────────────────────────────────────────
|
| 814 |
|
| 815 |
def end_episode(self):
|
| 816 |
+
"""关闭 ffmpeg,写出全部文件(顺序见 docs/data.md 写入流程)。
|
| 817 |
+
|
| 818 |
+
v1.3.11(L0-1):各段耗时写进 ``finalize_timing`` 供 pipeline 打一行
|
| 819 |
+
——停止瞬间的断链(raw 接收线程被 GIL 挡住)与位姿发散(SLAM 分区
|
| 820 |
+
的 SMT 兄弟核被抢)都发生在这个窗口里,先量再修(见 core/timing.py)。
|
| 821 |
+
"""
|
| 822 |
+
sw = Stopwatch()
|
| 823 |
self._close_ffmpeg()
|
| 824 |
+
sw.lap("flush")
|
| 825 |
self._write_data_parquet()
|
| 826 |
+
sw.lap("parquet")
|
| 827 |
self._append_episode_row()
|
| 828 |
self._write_info_json()
|
| 829 |
self._merge_stats()
|
| 830 |
self._write_tasks_jsonl()
|
| 831 |
clear_recycled_episode(self._task_dir)
|
| 832 |
+
sw.lap("meta")
|
| 833 |
+
self.finalize_timing = sw.snapshot()
|
| 834 |
self.episode_finished.emit(self._task_dir)
|
| 835 |
|
| 836 |
@property
|
|
|
|
| 856 |
if getattr(self, "_episode_index", 0) > 0 and getattr(
|
| 857 |
self, "_task_dir", ""):
|
| 858 |
mark_recycled_episode(self._task_dir, self._episode_index)
|
| 859 |
+
# 中止路径同样收尾 ffmpeg(不做 parquet/meta)——这一段的耗时与
|
| 860 |
+
# 「完成」路径对比,正是 2026-09-18 那条判据的来源:中止 0/6 断链
|
| 861 |
+
sw = Stopwatch()
|
| 862 |
self._close_ffmpeg()
|
| 863 |
+
sw.lap("flush")
|
| 864 |
+
self.finalize_timing = sw.snapshot()
|
| 865 |
for p in list(self._created_files):
|
| 866 |
try:
|
| 867 |
if os.path.isfile(p):
|
|
|
|
| 997 |
elif key.endswith("_force_matrix"):
|
| 998 |
item = (pa.float32() if self._matrix_dtype.get(key) == "float32"
|
| 999 |
else pa.int16())
|
| 1000 |
+
cols[name] = _list_column(
|
| 1001 |
+
[r.get(name, []) for r in rows], item)
|
| 1002 |
elif key.endswith("slam_trajectory"):
|
| 1003 |
cols[name] = pa.array(
|
| 1004 |
[r.get(name, []) for r in rows], pa.list_(pa.float64()))
|
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""帧间隔空洞看门狗 —— 纯类,无 Qt / 无 IO / 无第三方依赖。
|
| 2 |
+
|
| 3 |
+
录制侧(core/pipeline.py 的写入线程)与离线审计脚本(tools/audit_frame_gaps.py)
|
| 4 |
+
共用同一个类:**空洞的定义只此一份**,否则两边口径迟早漂移。
|
| 5 |
+
|
| 6 |
+
术语
|
| 7 |
+
----
|
| 8 |
+
空洞 = 相邻两帧的时间差**超出标称帧间隔**的部分。只报「断了多久」,不判
|
| 9 |
+
「丢了几帧」——帧率本就不恒定,反推帧数会给出看似精确实则错的数字。
|
| 10 |
+
|
| 11 |
+
时间基座(本类唯一容易踩的坑)
|
| 12 |
+
------------------------------
|
| 13 |
+
note() 每段录制只喂一个时间源。**首帧决定基座**,之后 source 与基座不符的帧
|
| 14 |
+
一律跳过空洞计算(只累加 frames)。混源(设备钟 vs 宿主单调钟)会把两个时钟
|
| 15 |
+
的基准差当成一次天文数字级的空洞——2026-09 排查 4.68s 空洞时差点因此误判。
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class GapWatch:
|
| 20 |
+
"""相邻帧间隔的空洞累计 / 峰值 / 次数。
|
| 21 |
+
|
| 22 |
+
参数
|
| 23 |
+
----
|
| 24 |
+
nominal_ns : 标称帧间隔(30fps → 33_333_333)。只用于算「超出部分」。
|
| 25 |
+
min_gap_ns : **间隔**下限(不是超出量):相邻帧时间差 ≥ 该值才记为空洞。
|
| 26 |
+
默认 100ms ≈ 3 帧,实测正常帧距 29.9~37.5ms,有 3 倍余量。
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, nominal_ns: int, min_gap_ns: int):
|
| 30 |
+
self._nominal_ns = int(nominal_ns)
|
| 31 |
+
self._min_gap_ns = int(min_gap_ns)
|
| 32 |
+
self.reset()
|
| 33 |
+
|
| 34 |
+
# ── 记账 ────────────────────────────────────────────────
|
| 35 |
+
def reset(self):
|
| 36 |
+
self._source = None # 本段基座(首次 note 锁定)
|
| 37 |
+
self._last_ns = None # 上一帧时刻
|
| 38 |
+
self._first_ns = 0 # 本段首帧时刻(相对时间的原点)
|
| 39 |
+
self._frames = 0
|
| 40 |
+
self._span_ns = 0 # 相邻帧时间差之和(连续跨度)
|
| 41 |
+
self._gap_ns = 0 # 空洞累计(已扣除标称间隔)
|
| 42 |
+
self._gap_max_ns = 0
|
| 43 |
+
self._gap_count = 0
|
| 44 |
+
self._gap_max_at_ns = 0 # 最大空洞的**起点**(洞前最后一帧的时刻)
|
| 45 |
+
self._resyncs = 0 # 时间倒退(时钟跳变)次数,不计空洞
|
| 46 |
+
|
| 47 |
+
def note(self, ts_ns: int, source: str = "hw") -> int:
|
| 48 |
+
"""记录一帧;返回本次空洞 ns(0 = 正常/跳过)。
|
| 49 |
+
|
| 50 |
+
source : "hw" 帧自带的采集时刻(parquet 的 hardware_ns 同源)
|
| 51 |
+
"mono" 取出队瞬间取宿主单调钟(hw_ns=0 的无时间戳槽位,
|
| 52 |
+
如 lite 路径恒传 0)
|
| 53 |
+
"""
|
| 54 |
+
ts_ns = int(ts_ns)
|
| 55 |
+
# 0 是「无时间戳」哨兵,不是时刻 0。**负值是合法时刻**:早期段的设备钟
|
| 56 |
+
# 是有符号 32 位纳秒计数器、值可为负(见 tools/audit_frame_gaps.py 的
|
| 57 |
+
# trunc32),按 <= 0 跳过会把整段负值区当成「无戳」并凭空造出假空洞。
|
| 58 |
+
if ts_ns == 0:
|
| 59 |
+
return 0
|
| 60 |
+
if self._source is None:
|
| 61 |
+
self._source = source
|
| 62 |
+
elif source != self._source:
|
| 63 |
+
# 基座不符:本帧不参与空洞计算(混源只会造出假空洞)
|
| 64 |
+
self._frames += 1
|
| 65 |
+
return 0
|
| 66 |
+
|
| 67 |
+
if self._last_ns is None:
|
| 68 |
+
self._last_ns = ts_ns
|
| 69 |
+
self._first_ns = ts_ns
|
| 70 |
+
self._frames += 1
|
| 71 |
+
return 0
|
| 72 |
+
|
| 73 |
+
delta = ts_ns - self._last_ns
|
| 74 |
+
if delta < 0: # 时间倒退:重新锚定,不报空洞
|
| 75 |
+
self._last_ns = ts_ns
|
| 76 |
+
self._resyncs += 1
|
| 77 |
+
self._frames += 1
|
| 78 |
+
return 0
|
| 79 |
+
|
| 80 |
+
start_ns = self._last_ns
|
| 81 |
+
self._last_ns = ts_ns
|
| 82 |
+
self._frames += 1
|
| 83 |
+
self._span_ns += delta
|
| 84 |
+
|
| 85 |
+
if delta < self._min_gap_ns:
|
| 86 |
+
return 0
|
| 87 |
+
gap = delta - self._nominal_ns
|
| 88 |
+
if gap <= 0:
|
| 89 |
+
return 0
|
| 90 |
+
self._gap_ns += gap
|
| 91 |
+
self._gap_count += 1
|
| 92 |
+
if gap > self._gap_max_ns:
|
| 93 |
+
self._gap_max_ns = gap
|
| 94 |
+
self._gap_max_at_ns = start_ns
|
| 95 |
+
return gap
|
| 96 |
+
|
| 97 |
+
# ── 读数 ────────────────────────────────────────────────
|
| 98 |
+
def snapshot(self) -> dict:
|
| 99 |
+
return {
|
| 100 |
+
"source": self._source or "",
|
| 101 |
+
"first_ns": self._first_ns,
|
| 102 |
+
"frames": self._frames,
|
| 103 |
+
"span_ns": self._span_ns,
|
| 104 |
+
"gap_ns": self._gap_ns,
|
| 105 |
+
"gap_max_ns": self._gap_max_ns,
|
| 106 |
+
"gap_count": self._gap_count,
|
| 107 |
+
"gap_max_at_ns": self._gap_max_at_ns,
|
| 108 |
+
"resyncs": self._resyncs,
|
| 109 |
+
}
|
|
@@ -55,6 +55,7 @@ from core.gripper.devices.tactile_process_manager import (
|
|
| 55 |
)
|
| 56 |
from core.gripper.devices.uvc_camera_service import UvcCameraServiceManager
|
| 57 |
from core.gripper.recording.fays_raw_client import FaysRawStreamClient
|
|
|
|
| 58 |
from core.gripper.slam.process_controller import (
|
| 59 |
SlamProcessController,
|
| 60 |
SlamState,
|
|
@@ -216,6 +217,19 @@ class GripperBridge(QObject):
|
|
| 216 |
"elapsed": 0,
|
| 217 |
"alerted": False,
|
| 218 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
self._lock = threading.RLock()
|
| 220 |
self._stop = threading.Event()
|
| 221 |
self._open_thread = None
|
|
@@ -269,10 +283,17 @@ class GripperBridge(QObject):
|
|
| 269 |
self._events.put((name, args))
|
| 270 |
|
| 271 |
def _post_frame(self, kind, *payload):
|
| 272 |
-
"""latest-wins 帧槽:GUI 卡顿时丢旧帧不积压。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
with self._frame_lock:
|
| 274 |
self._frame_slots[kind] = payload
|
| 275 |
if kind in self._frame_pending:
|
|
|
|
|
|
|
| 276 |
return
|
| 277 |
self._frame_pending.add(kind)
|
| 278 |
self._events.put(("frame", (kind,)))
|
|
@@ -290,6 +311,13 @@ class GripperBridge(QObject):
|
|
| 290 |
self._frame_pending.discard(kind)
|
| 291 |
if payload is None:
|
| 292 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
emitter = _FRAME_EMITTERS.get(kind)
|
| 294 |
if emitter is not None:
|
| 295 |
emitter(self, payload)
|
|
@@ -526,13 +554,53 @@ class GripperBridge(QObject):
|
|
| 526 |
self._post("error", str(exc))
|
| 527 |
|
| 528 |
def _rgb_run(self):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 529 |
while not self._stop.is_set():
|
| 530 |
ok, frame = self._rgb_camera.read()
|
| 531 |
if not ok:
|
| 532 |
if not self._stop.is_set():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 533 |
time.sleep(0.005)
|
| 534 |
continue
|
| 535 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 536 |
|
| 537 |
def _on_tactile_result(self, side, heatmap, force, force_matrix):
|
| 538 |
# 采集时刻在回调入口取(最接近样本真实到达时刻),随信号一起送到
|
|
@@ -744,6 +812,93 @@ class GripperBridge(QObject):
|
|
| 744 |
"alerted": False,
|
| 745 |
}
|
| 746 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 747 |
def clear_trajectory(self):
|
| 748 |
"""录制开始清空 GUI 轨迹滚动窗口(只显示本段录制的点)。
|
| 749 |
|
|
|
|
| 55 |
)
|
| 56 |
from core.gripper.devices.uvc_camera_service import UvcCameraServiceManager
|
| 57 |
from core.gripper.recording.fays_raw_client import FaysRawStreamClient
|
| 58 |
+
from core.gripper.rgb_quality import MaxLagWatch, RgbReadWatch
|
| 59 |
from core.gripper.slam.process_controller import (
|
| 60 |
SlamProcessController,
|
| 61 |
SlamState,
|
|
|
|
| 217 |
"elapsed": 0,
|
| 218 |
"alerted": False,
|
| 219 |
}
|
| 220 |
+
# v1.3.10 RGB 采集质量仪表(core/gripper/rgb_quality.py):面板上
|
| 221 |
+
# 「RGB 卡住/跳帧」此前完全无迹可查——_rgb_run 的 read() 失败分支
|
| 222 |
+
# 不记不报、latest-wins 覆盖连一行日志都没有,事后只能看到视频里
|
| 223 |
+
# 一段静止,说不清是相机侧没帧、emit 侧没人取还是 GUI 主线程卡了。
|
| 224 |
+
# 三层各记一份,判据见 docs/postmortem_trajectory_and_rgb.md。
|
| 225 |
+
self._rgb_watch = RgbReadWatch(
|
| 226 |
+
alert_ns=settings.GRIPPER_RGB_STALL_ALERT_MS * 1_000_000,
|
| 227 |
+
repeat_ns=int(settings.GRIPPER_RGB_STALL_REPEAT_S * 1e9))
|
| 228 |
+
self._rgb_emit_lag = MaxLagWatch("emit")
|
| 229 |
+
self._rgb_dispatch_lag = MaxLagWatch("dispatch")
|
| 230 |
+
# 相机对象的 reconnect_count 是跨段累计的,对外只报段内增量
|
| 231 |
+
self._rgb_reconnect_base = 0
|
| 232 |
+
self._raw_reconnect_base = 0
|
| 233 |
self._lock = threading.RLock()
|
| 234 |
self._stop = threading.Event()
|
| 235 |
self._open_thread = None
|
|
|
|
| 283 |
self._events.put((name, args))
|
| 284 |
|
| 285 |
def _post_frame(self, kind, *payload):
|
| 286 |
+
"""latest-wins 帧槽:GUI 卡顿时丢旧帧不积压。
|
| 287 |
+
|
| 288 |
+
v1.3.10:被顶掉的帧记进 RGB 采集质量仪表——这是「帧采到了、但没人
|
| 289 |
+
及时取走」的唯一证据,此前是彻底静默的。只记 RGB(双目有自己的空桶
|
| 290 |
+
看门狗,触觉不走本槽进录制)。
|
| 291 |
+
"""
|
| 292 |
with self._frame_lock:
|
| 293 |
self._frame_slots[kind] = payload
|
| 294 |
if kind in self._frame_pending:
|
| 295 |
+
if kind == "rgb":
|
| 296 |
+
self._rgb_watch.note_overwrite()
|
| 297 |
return
|
| 298 |
self._frame_pending.add(kind)
|
| 299 |
self._events.put(("frame", (kind,)))
|
|
|
|
| 311 |
self._frame_pending.discard(kind)
|
| 312 |
if payload is None:
|
| 313 |
continue
|
| 314 |
+
# v1.3.10:从投递到真正 emit 的滞留(RGB 的 payload[1] 是
|
| 315 |
+
# 采集时刻,与这里是同一个宿主单调钟)。它衡量「emit 线程
|
| 316 |
+
# 自己排到队了没有」,与 GUI 派发滞后分开记——两个数一起看
|
| 317 |
+
# 才能分辨是 emitter 堵了还是主线程堵了。
|
| 318 |
+
if kind == "rgb" and len(payload) >= 2 and payload[1]:
|
| 319 |
+
self._rgb_emit_lag.note(
|
| 320 |
+
time.monotonic_ns() - int(payload[1]))
|
| 321 |
emitter = _FRAME_EMITTERS.get(kind)
|
| 322 |
if emitter is not None:
|
| 323 |
emitter(self, payload)
|
|
|
|
| 554 |
self._post("error", str(exc))
|
| 555 |
|
| 556 |
def _rgb_run(self):
|
| 557 |
+
# v1.3.10:失败连击与恢复都由 _rgb_watch 记账并按门槛出日志行
|
| 558 |
+
# (健康态静默,一次抽风只留「停摆」「已恢复」两行)。read() 成功时
|
| 559 |
+
# 相机会清掉 last_transport_error,所以停摆期间的错误信息本地留一份
|
| 560 |
+
# 带给恢复行——否则最有用的那句「为什么坏」正好在恢复时丢掉。
|
| 561 |
+
last_error = ""
|
| 562 |
while not self._stop.is_set():
|
| 563 |
ok, frame = self._rgb_camera.read()
|
| 564 |
if not ok:
|
| 565 |
if not self._stop.is_set():
|
| 566 |
+
last_error = self._rgb_error() or last_error
|
| 567 |
+
for line in self._rgb_watch.note_fail(
|
| 568 |
+
time.monotonic_ns(),
|
| 569 |
+
reconnects=self._rgb_reconnects(),
|
| 570 |
+
error=last_error):
|
| 571 |
+
self._log(line)
|
| 572 |
time.sleep(0.005)
|
| 573 |
continue
|
| 574 |
+
now_ns = time.monotonic_ns()
|
| 575 |
+
for line in self._rgb_watch.note_ok(
|
| 576 |
+
now_ns, reconnects=self._rgb_reconnects(),
|
| 577 |
+
error=last_error or self._rgb_error()):
|
| 578 |
+
self._log(line)
|
| 579 |
+
last_error = ""
|
| 580 |
+
self._post_frame("rgb", frame, now_ns)
|
| 581 |
+
|
| 582 |
+
def _rgb_cam_attr(self, name, default):
|
| 583 |
+
"""读相机客户端的仪表字段(客户端缺失/换实现时降级为默认值)。"""
|
| 584 |
+
cam = self._rgb_camera
|
| 585 |
+
if cam is None:
|
| 586 |
+
return default
|
| 587 |
+
try:
|
| 588 |
+
value = getattr(cam, name, default)
|
| 589 |
+
except Exception:
|
| 590 |
+
return default
|
| 591 |
+
return default if value is None else value
|
| 592 |
+
|
| 593 |
+
def _rgb_reconnects(self) -> int:
|
| 594 |
+
"""本段录制内的重连次数(相机对象的计数是跨段累计的)。"""
|
| 595 |
+
try:
|
| 596 |
+
total = int(self._rgb_cam_attr("reconnect_count", 0))
|
| 597 |
+
except (TypeError, ValueError):
|
| 598 |
+
return 0
|
| 599 |
+
return max(0, total - self._rgb_reconnect_base)
|
| 600 |
+
|
| 601 |
+
def _rgb_error(self) -> str:
|
| 602 |
+
value = self._rgb_cam_attr("last_transport_error", "")
|
| 603 |
+
return value if isinstance(value, str) else ""
|
| 604 |
|
| 605 |
def _on_tactile_result(self, side, heatmap, force, force_matrix):
|
| 606 |
# 采集时刻在回调入口取(最接近样本真实到达时刻),随信号一起送到
|
|
|
|
| 812 |
"alerted": False,
|
| 813 |
}
|
| 814 |
|
| 815 |
+
# ── v1.3.10 RGB 采集质量(录制开始归零,录制结束并入 drop_stats)──
|
| 816 |
+
|
| 817 |
+
def reset_rgb_quality(self):
|
| 818 |
+
"""录制开始重置 RGB 采集质量仪表(与空桶看门狗同一时刻)。
|
| 819 |
+
|
| 820 |
+
重连基座也在此刻取——相机对象的 reconnect_count 是跨段累计的,
|
| 821 |
+
不取基座会把上一段的账算到本次录制头上。
|
| 822 |
+
"""
|
| 823 |
+
try:
|
| 824 |
+
self._rgb_reconnect_base = int(
|
| 825 |
+
self._rgb_cam_attr("reconnect_count", 0))
|
| 826 |
+
except (TypeError, ValueError):
|
| 827 |
+
self._rgb_reconnect_base = 0
|
| 828 |
+
self._rgb_watch.reset()
|
| 829 |
+
self._rgb_emit_lag.reset()
|
| 830 |
+
self._rgb_dispatch_lag.reset()
|
| 831 |
+
# L0-2:原始流侧同期归零(重连数同样跨段累计,须取基座)
|
| 832 |
+
try:
|
| 833 |
+
self._raw_reconnect_base = int(
|
| 834 |
+
getattr(self._raw_client, "reconnect_count", 0) or 0)
|
| 835 |
+
except (TypeError, ValueError):
|
| 836 |
+
self._raw_reconnect_base = 0
|
| 837 |
+
if self._raw_client is not None:
|
| 838 |
+
try:
|
| 839 |
+
self._raw_client.reset_stall_watch()
|
| 840 |
+
except Exception:
|
| 841 |
+
pass
|
| 842 |
+
|
| 843 |
+
def note_rgb_dispatch_lag(self, lag_ns: int):
|
| 844 |
+
"""主线程收到 RGB 帧时记一次派发滞后(UI 各窗口调用)。
|
| 845 |
+
|
| 846 |
+
``lag_ns`` = 收到帧的宿主单调钟 − 帧自带的采集时刻。它单独不产生
|
| 847 |
+
视频空洞(帧在 FIFO 里排着,时间戳仍连续),是**导致** latest-wins
|
| 848 |
+
覆盖才产生空洞——所以必须与 overwrite_count 分开计。
|
| 849 |
+
"""
|
| 850 |
+
self._rgb_dispatch_lag.note(lag_ns)
|
| 851 |
+
|
| 852 |
+
def rgb_quality_snapshot(self, now_ns: int = None) -> dict:
|
| 853 |
+
"""本 rig 采集链各层读数(全 int;键名见 ``is_frame_drop_key`` 约定)。
|
| 854 |
+
|
| 855 |
+
readfail_* / reconnect_count = RGB 相机链(相机/服务侧停摆)
|
| 856 |
+
overwrite_count / emit_lag_* = emit 侧(采集到但没及时取走)
|
| 857 |
+
dispatch_lag_* = GUI 侧(主线程滞后)
|
| 858 |
+
raw_recv_* / raw_reconnect_count = 原始流接收线程(本进程客户端侧
|
| 859 |
+
卡顿——服务端队列溢出就主动断开)
|
| 860 |
+
|
| 861 |
+
**每个键都必须以 `_ms` / `_count` 结尾**:UI 原样加槽位前缀塞进
|
| 862 |
+
`drop_stats`,不带后缀的键会被 `frame_drop_total` 当成帧数(这里曾
|
| 863 |
+
有过一个 `readfail_episodes`,见 tools/tests/test_drop_stats.py 的真值表)。
|
| 864 |
+
"""
|
| 865 |
+
reads = self._rgb_watch.snapshot(now_ns)
|
| 866 |
+
emit = self._rgb_emit_lag.snapshot()
|
| 867 |
+
dispatch = self._rgb_dispatch_lag.snapshot()
|
| 868 |
+
stall = self._raw_stall()
|
| 869 |
+
return {
|
| 870 |
+
"readfail_ms": int(round(reads["readfail_ns"] / 1e6)),
|
| 871 |
+
"readfail_max_ms": int(round(reads["readfail_max_ns"] / 1e6)),
|
| 872 |
+
"readfail_stall_count": reads["readfail_stall_count"],
|
| 873 |
+
"reconnect_count": self._rgb_reconnects(),
|
| 874 |
+
"overwrite_count": reads["overwrite_count"],
|
| 875 |
+
"emit_lag_max_ms": int(round(emit["lag_max_ns"] / 1e6)),
|
| 876 |
+
"dispatch_lag_max_ms": int(round(dispatch["lag_max_ns"] / 1e6)),
|
| 877 |
+
"raw_recv_gap_max_ms": int(round(stall["gap_max_ns"] / 1e6)),
|
| 878 |
+
"raw_recv_stall_count": int(stall["stall_count"]),
|
| 879 |
+
"raw_reconnect_count": self._raw_reconnects(),
|
| 880 |
+
}
|
| 881 |
+
|
| 882 |
+
def _raw_stall(self) -> dict:
|
| 883 |
+
"""原始流接收停滞读数(客户端缺失时全零)。"""
|
| 884 |
+
raw = self._raw_client
|
| 885 |
+
if raw is None:
|
| 886 |
+
return {"gap_max_ns": 0, "stall_ns": 0, "stall_count": 0}
|
| 887 |
+
try:
|
| 888 |
+
snap = raw.stall_snapshot()
|
| 889 |
+
except Exception:
|
| 890 |
+
return {"gap_max_ns": 0, "stall_ns": 0, "stall_count": 0}
|
| 891 |
+
return snap if isinstance(snap, dict) else {
|
| 892 |
+
"gap_max_ns": 0, "stall_ns": 0, "stall_count": 0}
|
| 893 |
+
|
| 894 |
+
def _raw_reconnects(self) -> int:
|
| 895 |
+
"""本段录制内的原始流重连次数(客户端计数是跨段累计的)。"""
|
| 896 |
+
try:
|
| 897 |
+
total = int(getattr(self._raw_client, "reconnect_count", 0) or 0)
|
| 898 |
+
except (TypeError, ValueError):
|
| 899 |
+
return 0
|
| 900 |
+
return max(0, total - self._raw_reconnect_base)
|
| 901 |
+
|
| 902 |
def clear_trajectory(self):
|
| 903 |
"""录制开始清空 GUI 轨迹滚动窗口(只显示本段录制的点)。
|
| 904 |
|
|
@@ -15,6 +15,7 @@ import json
|
|
| 15 |
import math
|
| 16 |
import os
|
| 17 |
from pathlib import Path
|
|
|
|
| 18 |
import shutil
|
| 19 |
import subprocess
|
| 20 |
import tempfile
|
|
@@ -24,6 +25,7 @@ import sys
|
|
| 24 |
|
| 25 |
import cv2
|
| 26 |
|
|
|
|
| 27 |
from core.gripper.fays_runtime import PROJECT_ROOT
|
| 28 |
from core.gripper.paths import CAMERA_MODE_STATE_DIR
|
| 29 |
from core.gripper.runtime.device_access import device_access_guard
|
|
@@ -89,6 +91,129 @@ def _native_env(binary=None):
|
|
| 89 |
return env
|
| 90 |
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
class UvcCameraServiceError(RuntimeError):
|
| 93 |
"""The live libusb/libuvc camera set cannot be used."""
|
| 94 |
|
|
@@ -776,6 +901,9 @@ class UvcCameraServiceManager:
|
|
| 776 |
"runtime_dir": runtime_dir,
|
| 777 |
"sockets": sockets,
|
| 778 |
"leases": 0,
|
|
|
|
|
|
|
|
|
|
| 779 |
}
|
| 780 |
self._logger(
|
| 781 |
"[UVC] libusb/libuvc camera-service started: "
|
|
@@ -891,8 +1019,7 @@ class UvcCameraServiceManager:
|
|
| 891 |
on_release=lambda sig=signature: self._release_lease(sig),
|
| 892 |
)
|
| 893 |
|
| 894 |
-
|
| 895 |
-
def _stop_entry_locked(entry):
|
| 896 |
process = entry["process"]
|
| 897 |
runtime_dir = entry["runtime_dir"]
|
| 898 |
if process is not None and process.poll() is None:
|
|
@@ -902,6 +1029,17 @@ class UvcCameraServiceManager:
|
|
| 902 |
except subprocess.TimeoutExpired:
|
| 903 |
process.kill()
|
| 904 |
process.wait(timeout=2.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 905 |
shutil.rmtree(runtime_dir, ignore_errors=True)
|
| 906 |
|
| 907 |
def _stop_locked(self):
|
|
|
|
| 15 |
import math
|
| 16 |
import os
|
| 17 |
from pathlib import Path
|
| 18 |
+
import re
|
| 19 |
import shutil
|
| 20 |
import subprocess
|
| 21 |
import tempfile
|
|
|
|
| 25 |
|
| 26 |
import cv2
|
| 27 |
|
| 28 |
+
from config import settings
|
| 29 |
from core.gripper.fays_runtime import PROJECT_ROOT
|
| 30 |
from core.gripper.paths import CAMERA_MODE_STATE_DIR
|
| 31 |
from core.gripper.runtime.device_access import device_access_guard
|
|
|
|
| 91 |
return env
|
| 92 |
|
| 93 |
|
| 94 |
+
# camera-service 原生日志留档(契约与 core/gripper/fays_single.py 的
|
| 95 |
+
# _archive_native_log 逐字同构)。runtime_dir 在 _stop_entry_locked 里被
|
| 96 |
+
# rmtree,而相机侧的停摆/降档/USB 复位**只**写这个文件:客户端日志里只有
|
| 97 |
+
# 「read 失败」,服务侧「为什么」全在这里。2026-09-18 排查 episode-099 那
|
| 98 |
+
# 4.68 秒空洞时就撞在这上面——一次干净退出的会话(正是最该留证据的那种)
|
| 99 |
+
# 其日志随目录一起没了。留档放 logs/ 下的独立子目录,免得和 main.log 混放。
|
| 100 |
+
_CAMERA_LOG_NAME = "camera-service.log"
|
| 101 |
+
_CAMERA_LOG_ARCHIVE_KEEP = 20
|
| 102 |
+
|
| 103 |
+
# 摘录只认「出事」的行。健康的每 5 秒 stats 行(fps_in=… dropped=… queue=…)
|
| 104 |
+
# 与退出时的汇总行(… retries=… stalls=… usb_resets=…)**都不匹配**——拿裸
|
| 105 |
+
# 的 dropped / stalls= 当判据的话,摘录在任何一次正常会话里都非空,等于噪声。
|
| 106 |
+
# 刻意不收裸 [LIBUVC-QUIRK]:其中 `xfers=` 那行是每次成功开流都会打的(它正是
|
| 107 |
+
# 判断真实档位的权威行),收进来同样破坏「健康即静默」。出了事要看那些行时,
|
| 108 |
+
# 存档文件里有全文。
|
| 109 |
+
_CAMERA_LOG_EVIDENCE = re.compile("|".join([
|
| 110 |
+
r"stream stalled: no frame for",
|
| 111 |
+
r"restarting UVC stream",
|
| 112 |
+
r"rebuilding libusb context after stall",
|
| 113 |
+
r"usb reset: rc=",
|
| 114 |
+
r"cannot reset device",
|
| 115 |
+
r"stalls at alt=",
|
| 116 |
+
r"stalls but alt=",
|
| 117 |
+
r"failed opens at alt=",
|
| 118 |
+
r"failed opens but alt=",
|
| 119 |
+
r"remembered altsetting=",
|
| 120 |
+
r"open failed:",
|
| 121 |
+
r"unavailable", # 设备打不开 / 档位端点不可用(含 QUIRK 那条)
|
| 122 |
+
r"cannot apply altsetting override",
|
| 123 |
+
r"negotiation failed",
|
| 124 |
+
r"startup failed",
|
| 125 |
+
r"uvc_start_streaming failed",
|
| 126 |
+
r"uvc_init failed",
|
| 127 |
+
r"output write failed",
|
| 128 |
+
r"dropped incomplete MJPEG",
|
| 129 |
+
r"thread creation failed",
|
| 130 |
+
r"收尾超时",
|
| 131 |
+
]))
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _camera_log_archive_dir():
|
| 135 |
+
return os.path.join(settings.LOGS_DIR, "camera_service")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _prune_camera_log_archive():
|
| 139 |
+
"""只保留最近 _CAMERA_LOG_ARCHIVE_KEEP 份留档(长期运行不撑爆磁盘)。"""
|
| 140 |
+
directory = _camera_log_archive_dir()
|
| 141 |
+
try:
|
| 142 |
+
names = sorted(
|
| 143 |
+
name for name in os.listdir(directory)
|
| 144 |
+
if name.endswith(_CAMERA_LOG_NAME)
|
| 145 |
+
)
|
| 146 |
+
except OSError:
|
| 147 |
+
return
|
| 148 |
+
# 文件名前缀是 %Y%m%d_%H%M%S,字典序即时间序,不必逐个 stat
|
| 149 |
+
for name in names[:-_CAMERA_LOG_ARCHIVE_KEEP]:
|
| 150 |
+
try:
|
| 151 |
+
os.unlink(os.path.join(directory, name))
|
| 152 |
+
except OSError:
|
| 153 |
+
pass
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _camera_log_evidence(path, limit=6):
|
| 157 |
+
"""摘出告警行(取最后 ``limit`` 行;健康的会话返回空表)。
|
| 158 |
+
|
| 159 |
+
取末尾而不是开头:一次会话里最要紧的是**结束前**发生了什么。
|
| 160 |
+
"""
|
| 161 |
+
try:
|
| 162 |
+
with open(path, "r", encoding="utf-8", errors="replace") as stream:
|
| 163 |
+
lines = [line.rstrip() for line in stream]
|
| 164 |
+
except OSError:
|
| 165 |
+
return []
|
| 166 |
+
hits = [line for line in lines if _CAMERA_LOG_EVIDENCE.search(line)]
|
| 167 |
+
return hits[-limit:]
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _archive_camera_log(runtime_dir, tag, logger=None):
|
| 171 |
+
"""把即将被 rmtree 的 camera-service.log 拷进 logs/camera_service/。
|
| 172 |
+
|
| 173 |
+
纯取证手段:任何失败只记一行日志,绝不打断 _stop_entry_locked 的清理
|
| 174 |
+
(留档丢了是少一份证据,清理半途而废会留下脏的运行时目录)。成功且无
|
| 175 |
+
告警时**不出声**——健康会话的日志只在存档目录里,不占 main.log。
|
| 176 |
+
"""
|
| 177 |
+
source = os.path.join(str(runtime_dir), _CAMERA_LOG_NAME)
|
| 178 |
+
if not os.path.isfile(source):
|
| 179 |
+
return None
|
| 180 |
+
key = re.sub(r"[^A-Za-z0-9_.-]+", "-", str(tag or "unknown"))
|
| 181 |
+
try:
|
| 182 |
+
directory = _camera_log_archive_dir()
|
| 183 |
+
os.makedirs(directory, exist_ok=True)
|
| 184 |
+
stamp = time.strftime("%Y%m%d_%H%M%S", time.localtime())
|
| 185 |
+
target = os.path.join(directory, f"{stamp}_{key}_{_CAMERA_LOG_NAME}")
|
| 186 |
+
sequence = 0
|
| 187 |
+
while os.path.exists(target):
|
| 188 |
+
# 同一秒里同一台相机停了两次(服务起来就崩、连着两轮):留档的
|
| 189 |
+
# 意义就是「证据不会没了」,所以宁可多一个后缀也不覆盖已有证据
|
| 190 |
+
sequence += 1
|
| 191 |
+
target = os.path.join(
|
| 192 |
+
directory, f"{stamp}_{key}-{sequence}_{_CAMERA_LOG_NAME}")
|
| 193 |
+
shutil.copy2(source, target)
|
| 194 |
+
except OSError as exc:
|
| 195 |
+
if logger is not None:
|
| 196 |
+
logger(f"[UVC] camera-service 日志留档失败: {exc}")
|
| 197 |
+
return None
|
| 198 |
+
_prune_camera_log_archive()
|
| 199 |
+
return target
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _service_tag(records):
|
| 203 |
+
"""留档文件名里的身份:``bus<bus>-port<外口路径>``。
|
| 204 |
+
|
| 205 |
+
同一台机器上双 rig 靠总线号 + 外口路径区分;取不到时退化成 unknown,
|
| 206 |
+
只是文件名不好认,不影响留档本身。
|
| 207 |
+
"""
|
| 208 |
+
record = records[0] if records else {}
|
| 209 |
+
try:
|
| 210 |
+
bus = int(record.get("bus"))
|
| 211 |
+
except (TypeError, ValueError):
|
| 212 |
+
bus = 0
|
| 213 |
+
port = str(record.get("outer_path") or "").strip() or "unknown"
|
| 214 |
+
return f"bus{bus}-port{port}"
|
| 215 |
+
|
| 216 |
+
|
| 217 |
class UvcCameraServiceError(RuntimeError):
|
| 218 |
"""The live libusb/libuvc camera set cannot be used."""
|
| 219 |
|
|
|
|
| 901 |
"runtime_dir": runtime_dir,
|
| 902 |
"sockets": sockets,
|
| 903 |
"leases": 0,
|
| 904 |
+
# 留档文件名里的身份(停服务时 runtime_dir 连同日志
|
| 905 |
+
# 一起删,所以要在这里先把「这是哪台相机」定下来)
|
| 906 |
+
"tag": _service_tag(records),
|
| 907 |
}
|
| 908 |
self._logger(
|
| 909 |
"[UVC] libusb/libuvc camera-service started: "
|
|
|
|
| 1019 |
on_release=lambda sig=signature: self._release_lease(sig),
|
| 1020 |
)
|
| 1021 |
|
| 1022 |
+
def _stop_entry_locked(self, entry):
|
|
|
|
| 1023 |
process = entry["process"]
|
| 1024 |
runtime_dir = entry["runtime_dir"]
|
| 1025 |
if process is not None and process.poll() is None:
|
|
|
|
| 1029 |
except subprocess.TimeoutExpired:
|
| 1030 |
process.kill()
|
| 1031 |
process.wait(timeout=2.0)
|
| 1032 |
+
# 先留档再删:camera-service.log 只活在这个目录里。停摆/降档/复位
|
| 1033 |
+
# 的「为什么」全在服务侧日志里,客户端只能看到 read() 失败
|
| 1034 |
+
target = _archive_camera_log(
|
| 1035 |
+
runtime_dir, entry.get("tag"), self._logger)
|
| 1036 |
+
if target is not None:
|
| 1037 |
+
evidence = _camera_log_evidence(target)
|
| 1038 |
+
if evidence:
|
| 1039 |
+
self._logger("[UVC] camera-service 告警摘录:")
|
| 1040 |
+
for line in evidence:
|
| 1041 |
+
self._logger(f" {line}")
|
| 1042 |
+
self._logger(f"[UVC] camera-service 日志留档: {target}")
|
| 1043 |
shutil.rmtree(runtime_dir, ignore_errors=True)
|
| 1044 |
|
| 1045 |
def _stop_locked(self):
|
|
@@ -14,6 +14,8 @@ import threading
|
|
| 14 |
import time
|
| 15 |
from typing import Callable, Optional
|
| 16 |
|
|
|
|
|
|
|
| 17 |
|
| 18 |
RAW_HEADER = struct.Struct("<6I3Q4i2hi2I")
|
| 19 |
RAW_STREAM_MAGIC = 0x53544F55
|
|
@@ -26,6 +28,14 @@ IMU_PAYLOAD_SIZE = 48
|
|
| 26 |
RECONNECT_ATTEMPT_INTERVAL_S = 1.0
|
| 27 |
RECONNECT_TOTAL_TIMEOUT_S = 60.0
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
class FaysRawStreamError(RuntimeError):
|
| 31 |
"""The native raw stream is incomplete or malformed."""
|
|
@@ -60,6 +70,12 @@ class FaysRawStreamClient:
|
|
| 60 |
self._last_stereo_sequence: Optional[int] = None
|
| 61 |
self._last_stereo_timestamp_ns = 0
|
| 62 |
self._reconnect_count = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
self.imu_packets = 0
|
| 64 |
self.stereo_packets = 0
|
| 65 |
self.connected = threading.Event()
|
|
@@ -71,6 +87,19 @@ class FaysRawStreamClient:
|
|
| 71 |
thread = self._thread
|
| 72 |
return bool(thread and thread.is_alive())
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
def start(self) -> None:
|
| 75 |
with self._lock:
|
| 76 |
if self._thread is not None:
|
|
@@ -194,6 +223,10 @@ class FaysRawStreamClient:
|
|
| 194 |
payload = self._recv_exact(sock, payload_size)
|
| 195 |
if len(payload) != payload_size:
|
| 196 |
break
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
if kind == RAW_PACKET_IMU:
|
| 198 |
if payload_size != IMU_PAYLOAD_SIZE:
|
| 199 |
raise FaysRawStreamError(
|
|
|
|
| 14 |
import time
|
| 15 |
from typing import Callable, Optional
|
| 16 |
|
| 17 |
+
from core.gripper.rgb_quality import RawStallWatch
|
| 18 |
+
|
| 19 |
|
| 20 |
RAW_HEADER = struct.Struct("<6I3Q4i2hi2I")
|
| 21 |
RAW_STREAM_MAGIC = 0x53544F55
|
|
|
|
| 28 |
RECONNECT_ATTEMPT_INTERVAL_S = 1.0
|
| 29 |
RECONNECT_TOTAL_TIMEOUT_S = 60.0
|
| 30 |
|
| 31 |
+
# 接收停滞口径(L0-2,v1.3.11)。正常包间隔 ~1ms 级(双目 30fps + IMU
|
| 32 |
+
# 1kHz 交替),100ms 已不可能是调度抖动;服务端队列 16 包 ≈0.53s 满即
|
| 33 |
+
# 主动 close,所以 300ms 是「差一档就要被断链」的预警位——不是为了当场
|
| 34 |
+
# 做什么,而是把「客户端到底卡了多久」变成 parquet 里的一个数。
|
| 35 |
+
RAW_STALL_NS = 100_000_000 # >100ms 计入停滞
|
| 36 |
+
RAW_STALL_ALERT_NS = 300_000_000 # ≥300ms 打一行(去抖)
|
| 37 |
+
RAW_STALL_REPEAT_NS = 5_000_000_000
|
| 38 |
+
|
| 39 |
|
| 40 |
class FaysRawStreamError(RuntimeError):
|
| 41 |
"""The native raw stream is incomplete or malformed."""
|
|
|
|
| 70 |
self._last_stereo_sequence: Optional[int] = None
|
| 71 |
self._last_stereo_timestamp_ns = 0
|
| 72 |
self._reconnect_count = 0
|
| 73 |
+
# L0-2:接收侧停滞仪表(录制开始时由 bridge 归零,见 reset_stall_watch)
|
| 74 |
+
self._stall_watch = RawStallWatch(
|
| 75 |
+
stall_ns=RAW_STALL_NS,
|
| 76 |
+
alert_ns=RAW_STALL_ALERT_NS,
|
| 77 |
+
repeat_ns=RAW_STALL_REPEAT_NS,
|
| 78 |
+
)
|
| 79 |
self.imu_packets = 0
|
| 80 |
self.stereo_packets = 0
|
| 81 |
self.connected = threading.Event()
|
|
|
|
| 87 |
thread = self._thread
|
| 88 |
return bool(thread and thread.is_alive())
|
| 89 |
|
| 90 |
+
@property
|
| 91 |
+
def reconnect_count(self) -> int:
|
| 92 |
+
"""累计重连次数(跨录制段累计;bridge 在录制开始时取基座)。"""
|
| 93 |
+
return int(self._reconnect_count)
|
| 94 |
+
|
| 95 |
+
def reset_stall_watch(self) -> None:
|
| 96 |
+
"""录制开始归零接收停滞读数(与 bridge.reset_rgb_quality 同一时刻)。"""
|
| 97 |
+
self._stall_watch.reset()
|
| 98 |
+
|
| 99 |
+
def stall_snapshot(self) -> dict:
|
| 100 |
+
"""接收停滞读数(ns/count;线程安全,主线程在录制结束时读)。"""
|
| 101 |
+
return self._stall_watch.snapshot()
|
| 102 |
+
|
| 103 |
def start(self) -> None:
|
| 104 |
with self._lock:
|
| 105 |
if self._thread is not None:
|
|
|
|
| 223 |
payload = self._recv_exact(sock, payload_size)
|
| 224 |
if len(payload) != payload_size:
|
| 225 |
break
|
| 226 |
+
# L0-2:包间隔停滞(在 kind 分支之前记,双目/IMU 一起算)。
|
| 227 |
+
# 只记账 + 超门槛时递出一行日志,绝不在这里阻塞接收循环
|
| 228 |
+
for line in self._stall_watch.note_recv(time.monotonic_ns()):
|
| 229 |
+
self._logger(line)
|
| 230 |
if kind == RAW_PACKET_IMU:
|
| 231 |
if payload_size != IMU_PAYLOAD_SIZE:
|
| 232 |
raise FaysRawStreamError(
|
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""夹爪 RGB 采集链路的静默丢帧可见化 —— 纯类,无 Qt / 无 IO。
|
| 2 |
+
|
| 3 |
+
2026-09-18 的 episode-099 在录到第 45 帧时**丢了 4.68 秒**(两个时钟同时跳),
|
| 4 |
+
而当时所有计数器都是 0:`_rgb_run` 的 `read()` 失败分支只睡 5ms 接着来,
|
| 5 |
+
latest-wins 帧槽的覆盖更是连一行日志都没有。事后翻遍日志也无法判断是
|
| 6 |
+
「相机侧没帧可读」还是「帧来了被 emit/GUI 侧吞掉」。
|
| 7 |
+
|
| 8 |
+
这里的两个类就是那两处的计数器。它们只记账、只产出日志行,不做 IO、不发信号
|
| 9 |
+
——调用方(bridge)把日志行交给 ``_log``(内部走 _events 队列,任意线程安全)。
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import threading
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class RgbReadWatch:
|
| 16 |
+
"""采集侧看门狗:``read()`` 失败连击 + latest-wins 覆盖计数。
|
| 17 |
+
|
| 18 |
+
去抖契约照抄 ``core/gripper/slam/process_controller.py`` 的 FaysRateAlarm:
|
| 19 |
+
健康态静默;进入停摆打一行(带重连次数与最近错误);持续停摆每
|
| 20 |
+
``repeat_ns`` 重复一行;恢复再打一行收尾。这样一次抽风只留两行,长时间
|
| 21 |
+
故障也不刷屏,而恢复行让「抽了一下还是一直坏」一眼可辨。
|
| 22 |
+
|
| 23 |
+
``note_fail`` / ``note_ok`` 返回**要写进日志的行列表**(多数时候为空)。
|
| 24 |
+
线程契约:RGB 线程写、主线程读快照,类内自锁。
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, *, alert_ns: int, repeat_ns: int, tag: str = "夹爪-RGB"):
|
| 28 |
+
self._alert_ns = int(alert_ns)
|
| 29 |
+
self._repeat_ns = int(repeat_ns)
|
| 30 |
+
self._tag = tag
|
| 31 |
+
self._lock = threading.Lock()
|
| 32 |
+
self.reset()
|
| 33 |
+
|
| 34 |
+
def reset(self):
|
| 35 |
+
with self._lock:
|
| 36 |
+
self._fail_since_ns = None # 本次停摆起点(None = 正常)
|
| 37 |
+
self._fail_ns = 0 # 停摆累计时长
|
| 38 |
+
self._fail_max_ns = 0
|
| 39 |
+
self._fail_stalls = 0
|
| 40 |
+
self._alerted = False # 已经在日志里报过停摆(尚未恢复)
|
| 41 |
+
self._last_alert_ns = None
|
| 42 |
+
self._overwrites = 0
|
| 43 |
+
|
| 44 |
+
# ── 采集侧 ──────────────────────────────────────────────
|
| 45 |
+
def note_fail(self, mono_ns: int, *, reconnects: int = 0,
|
| 46 |
+
error: str = "") -> list:
|
| 47 |
+
"""read() 返回 not ok。停摆未达门槛时静默。"""
|
| 48 |
+
with self._lock:
|
| 49 |
+
if self._fail_since_ns is None:
|
| 50 |
+
self._fail_since_ns = int(mono_ns)
|
| 51 |
+
elapsed = int(mono_ns) - self._fail_since_ns
|
| 52 |
+
if elapsed < self._alert_ns:
|
| 53 |
+
return []
|
| 54 |
+
first = not self._alerted
|
| 55 |
+
if not first and (self._last_alert_ns is not None
|
| 56 |
+
and int(mono_ns) - self._last_alert_ns < self._repeat_ns):
|
| 57 |
+
return []
|
| 58 |
+
self._alerted = True
|
| 59 |
+
self._last_alert_ns = int(mono_ns)
|
| 60 |
+
secs = elapsed / 1e9
|
| 61 |
+
if first:
|
| 62 |
+
return [f"[{self._tag}告警] RGB 采集停摆 {secs:.1f}s——read() "
|
| 63 |
+
f"连续失败,相机侧已无帧可读"
|
| 64 |
+
f"(重连 {int(reconnects)} 次{self._err(error)})"]
|
| 65 |
+
return [f"[{self._tag}告警] RGB 采集仍未恢复(已停摆 {secs:.1f}s,"
|
| 66 |
+
f"重连 {int(reconnects)} 次)"]
|
| 67 |
+
|
| 68 |
+
def note_ok(self, mono_ns: int, *, reconnects: int = 0,
|
| 69 |
+
error: str = "") -> list:
|
| 70 |
+
"""read() 拿到帧。健康帧不会产生任何日志行。"""
|
| 71 |
+
with self._lock:
|
| 72 |
+
if self._fail_since_ns is None:
|
| 73 |
+
return []
|
| 74 |
+
stall = int(mono_ns) - self._fail_since_ns
|
| 75 |
+
self._fail_since_ns = None
|
| 76 |
+
self._fail_ns += stall
|
| 77 |
+
self._fail_stalls += 1
|
| 78 |
+
if stall > self._fail_max_ns:
|
| 79 |
+
self._fail_max_ns = stall
|
| 80 |
+
if not self._alerted:
|
| 81 |
+
return []
|
| 82 |
+
self._alerted = False
|
| 83 |
+
return [f"[{self._tag}] RGB 采集已恢复(停摆 {stall / 1e9:.1f}s,"
|
| 84 |
+
f"重连 {int(reconnects)} 次{self._err(error)})"
|
| 85 |
+
f"——本段视频该处会有一段静止"]
|
| 86 |
+
|
| 87 |
+
def note_overwrite(self, n: int = 1):
|
| 88 |
+
"""latest-wins 帧槽被更新的帧顶掉(帧确实采到了,只是没人及时取走)。"""
|
| 89 |
+
with self._lock:
|
| 90 |
+
self._overwrites += int(n)
|
| 91 |
+
|
| 92 |
+
@staticmethod
|
| 93 |
+
def _err(error: str) -> str:
|
| 94 |
+
"""最近一次的传输错误(空则整段省略;截断免得刷屏)。"""
|
| 95 |
+
if not error:
|
| 96 |
+
return ""
|
| 97 |
+
return f";最近错误: {str(error)[:60]}"
|
| 98 |
+
|
| 99 |
+
# ── 读数 ────────────────────────────────────────────────
|
| 100 |
+
def snapshot(self, now_ns: int = None) -> dict:
|
| 101 |
+
"""now_ns 传入时,尚未恢复的停摆也计入(否则进行中的停摆会少报)。"""
|
| 102 |
+
with self._lock:
|
| 103 |
+
fail_ns = self._fail_ns
|
| 104 |
+
fail_max_ns = self._fail_max_ns
|
| 105 |
+
stalls = self._fail_stalls
|
| 106 |
+
if self._fail_since_ns is not None and now_ns is not None:
|
| 107 |
+
ongoing = max(0, int(now_ns) - self._fail_since_ns)
|
| 108 |
+
fail_ns += ongoing
|
| 109 |
+
fail_max_ns = max(fail_max_ns, ongoing)
|
| 110 |
+
stalls += 1
|
| 111 |
+
return {
|
| 112 |
+
"readfail_ns": fail_ns,
|
| 113 |
+
"readfail_max_ns": fail_max_ns,
|
| 114 |
+
"readfail_stall_count": stalls,
|
| 115 |
+
"overwrite_count": self._overwrites,
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class MaxLagWatch:
|
| 120 |
+
"""滞后峰值 + 样本数(emit 侧滞后 / GUI 派发滞后共用)。
|
| 121 |
+
|
| 122 |
+
只记峰值:这两个量的价值在「最坏卡了多久」,平均值会被 30Hz 的正常
|
| 123 |
+
小抖动稀释到看不出问题。线程安全(可能由采集线程写、主线程读)。
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
def __init__(self, tag: str = ""):
|
| 127 |
+
self._tag = tag
|
| 128 |
+
self._lock = threading.Lock()
|
| 129 |
+
self.reset()
|
| 130 |
+
|
| 131 |
+
def reset(self):
|
| 132 |
+
with self._lock:
|
| 133 |
+
self._lag_max_ns = 0
|
| 134 |
+
self._samples = 0
|
| 135 |
+
|
| 136 |
+
def note(self, lag_ns: int):
|
| 137 |
+
lag_ns = int(lag_ns)
|
| 138 |
+
if lag_ns < 0:
|
| 139 |
+
return
|
| 140 |
+
with self._lock:
|
| 141 |
+
self._samples += 1
|
| 142 |
+
if lag_ns > self._lag_max_ns:
|
| 143 |
+
self._lag_max_ns = lag_ns
|
| 144 |
+
|
| 145 |
+
def snapshot(self) -> dict:
|
| 146 |
+
with self._lock:
|
| 147 |
+
return {"lag_max_ns": self._lag_max_ns, "lag_samples": self._samples}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class RawStallWatch:
|
| 151 |
+
"""原始流**接收侧**停滞:相邻两个完整包的间隔峰值 + 超门槛次数。
|
| 152 |
+
|
| 153 |
+
L0-2(v1.3.11)。SLAM 进程是原始流的**服务端**,本进程的接收线程是
|
| 154 |
+
Python 线程:它一旦因为 GIL 被别人占住而进不去 ``recv()``,服务端
|
| 155 |
+
16 包队列(≈0.53s)填满就判 ``stereo loss`` 并**主动 close**。实测
|
| 156 |
+
2026-09-18:43 次完成录制里 37 次在收尾窗口断链,而 6 次中止(不做
|
| 157 |
+
parquet 落盘)一次都没断——怀疑是 ``_write_data_parquet`` 建两条
|
| 158 |
+
``list<int16>`` 力矩阵列时各持 GIL 1.6s。这类读数此前完全没有:
|
| 159 |
+
接收线程卡住就是卡住,没人记账。
|
| 160 |
+
|
| 161 |
+
与 ``RgbReadWatch`` 的差别:那边抓的是「``read()`` 失败」这种显式
|
| 162 |
+
事件,这边只能靠**间隔**——所以用间隔峰值 + 超门槛计数表达。
|
| 163 |
+
跨断链的间隔也算(那正是重连黑洞的真实时长)。
|
| 164 |
+
|
| 165 |
+
线程契约:接收线程写、主线程读快照,类内自锁。``note_recv`` 返回
|
| 166 |
+
**要写进日志的行列表**(多数时候为空),本类自己不碰 IO。
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
def __init__(self, *, stall_ns: int, alert_ns: int, repeat_ns: int,
|
| 170 |
+
tag: str = "Gripper-Raw"):
|
| 171 |
+
self._stall_ns = int(stall_ns)
|
| 172 |
+
self._alert_ns = int(alert_ns)
|
| 173 |
+
self._repeat_ns = int(repeat_ns)
|
| 174 |
+
self._tag = tag
|
| 175 |
+
self._lock = threading.Lock()
|
| 176 |
+
self.reset()
|
| 177 |
+
|
| 178 |
+
def reset(self):
|
| 179 |
+
with self._lock:
|
| 180 |
+
self._last_ns = None
|
| 181 |
+
self._packets = 0
|
| 182 |
+
self._gap_max_ns = 0
|
| 183 |
+
self._stall_ns_total = 0
|
| 184 |
+
self._stalls = 0
|
| 185 |
+
self._alerted = False # 已在日志里报过(尚未恢复)
|
| 186 |
+
self._last_alert_ns = None
|
| 187 |
+
|
| 188 |
+
def note_recv(self, mono_ns: int) -> list:
|
| 189 |
+
"""收到一个完整包。返回要打的行(健康时恒为空列表)。"""
|
| 190 |
+
with self._lock:
|
| 191 |
+
now = int(mono_ns)
|
| 192 |
+
last = self._last_ns
|
| 193 |
+
self._last_ns = now
|
| 194 |
+
self._packets += 1
|
| 195 |
+
if last is None:
|
| 196 |
+
return []
|
| 197 |
+
gap = now - last
|
| 198 |
+
if gap < 0: # 单调钟倒退(不该发生,防御)
|
| 199 |
+
return []
|
| 200 |
+
if gap > self._gap_max_ns:
|
| 201 |
+
self._gap_max_ns = gap
|
| 202 |
+
if gap < self._stall_ns:
|
| 203 |
+
self._alerted = False # 流已恢复,下次抽风重新报
|
| 204 |
+
return []
|
| 205 |
+
self._stalls += 1
|
| 206 |
+
self._stall_ns_total += gap
|
| 207 |
+
if gap < self._alert_ns:
|
| 208 |
+
return []
|
| 209 |
+
first = not self._alerted
|
| 210 |
+
if not first and (self._last_alert_ns is not None
|
| 211 |
+
and now - self._last_alert_ns < self._repeat_ns):
|
| 212 |
+
return []
|
| 213 |
+
self._alerted = True
|
| 214 |
+
self._last_alert_ns = now
|
| 215 |
+
ms = gap / 1e6
|
| 216 |
+
if first:
|
| 217 |
+
return [f"[{self._tag}] 原始流接收停滞 {ms:.0f}ms"
|
| 218 |
+
f"——服务端队列 ≈0.53s 满即主动断开"
|
| 219 |
+
f"(本段已停顿 {self._stalls} 次)"]
|
| 220 |
+
return [f"[{self._tag}] 原始流接收仍未恢复(本次停顿 {ms:.0f}ms,"
|
| 221 |
+
f"累计 {self._stalls} 次)"]
|
| 222 |
+
|
| 223 |
+
def snapshot(self) -> dict:
|
| 224 |
+
with self._lock:
|
| 225 |
+
return {
|
| 226 |
+
"gap_max_ns": self._gap_max_ns,
|
| 227 |
+
"stall_ns": self._stall_ns_total,
|
| 228 |
+
"stall_count": self._stalls,
|
| 229 |
+
"packets": self._packets,
|
| 230 |
+
}
|
|
@@ -24,6 +24,10 @@ from config.i18n import tr
|
|
| 24 |
def encode_gripper_force_matrix(m: np.ndarray, spec: str = "int16") -> list:
|
| 25 |
"""触觉力矩阵编码(P4 泵线程,返回扁平数值列表)。
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
spec 取 settings.GRIPPER_FORCE_MATRIX_SPECS 之一。
|
| 28 |
|
| 29 |
**注意**:省略 spec 时走的是函数签名默认 "int16"(兼容历史调用的冻结
|
|
@@ -56,13 +60,36 @@ def encode_gripper_force_matrix(m: np.ndarray, spec: str = "int16") -> list:
|
|
| 56 |
倍率必须由 info.json features.scale 携带,writer 与 demo 都按
|
| 57 |
scale + 列类型共同判别,不要只看元素类型。
|
| 58 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
if spec not in settings.GRIPPER_FORCE_MATRIX_SPECS:
|
| 60 |
raise ValueError(f"未知力矩阵规格 {spec!r}")
|
| 61 |
arr = np.asarray(m, dtype=np.float32)
|
| 62 |
if spec == "float32":
|
| 63 |
-
# 与整数档同为「扁平 250×750
|
| 64 |
-
# 读取端统一 reshape(-1,750) 后再按 dtype 决定是否 cumsum
|
| 65 |
-
|
|
|
|
| 66 |
scale = settings.GRIPPER_FORCE_MATRIX_SCALES[spec]
|
| 67 |
rows = int(arr.shape[0])
|
| 68 |
flat = arr.reshape(rows, -1)
|
|
@@ -75,7 +102,8 @@ def encode_gripper_force_matrix(m: np.ndarray, spec: str = "int16") -> list:
|
|
| 75 |
d = np.empty_like(q)
|
| 76 |
d[:, 0] = q[:, 0]
|
| 77 |
d[:, 1:] = q[:, 1:] - q[:, :-1] # int16 mod 2^16 回绕
|
| 78 |
-
|
|
|
|
| 79 |
|
| 80 |
|
| 81 |
def describe_gripper_matrix_spec(spec: str) -> str:
|
|
|
|
| 24 |
def encode_gripper_force_matrix(m: np.ndarray, spec: str = "int16") -> list:
|
| 25 |
"""触觉力矩阵编码(P4 泵线程,返回扁平数值列表)。
|
| 26 |
|
| 27 |
+
**只是 `encode_gripper_force_matrix_array(...).tolist()` 的皮**:编码只有
|
| 28 |
+
一份实现(在 array 版里),本函数保证与它逐位同值。落盘主路径已改走
|
| 29 |
+
array 版(见那边的说明),本函数留给历史调用方与测试。
|
| 30 |
+
|
| 31 |
spec 取 settings.GRIPPER_FORCE_MATRIX_SPECS 之一。
|
| 32 |
|
| 33 |
**注意**:省略 spec 时走的是函数签名默认 "int16"(兼容历史调用的冻结
|
|
|
|
| 60 |
倍率必须由 info.json features.scale 携带,writer 与 demo 都按
|
| 61 |
scale + 列类型共同判别,不要只看元素类型。
|
| 62 |
"""
|
| 63 |
+
return encode_gripper_force_matrix_array(m, spec).tolist()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def encode_gripper_force_matrix_array(m: np.ndarray,
|
| 67 |
+
spec: str = "int16") -> np.ndarray:
|
| 68 |
+
"""同上,但返回**一维 ndarray**(不 .tolist(),值逐位相同)。
|
| 69 |
+
|
| 70 |
+
为什么要多这一版(2026-09-18 实测):writer 建 `list<int16>` 列时,
|
| 71 |
+
pyarrow 对 Python list 是**逐值装箱**——185 帧 × 187500 点 = 538ms 且
|
| 72 |
+
全程持 GIL;换成 ndarray 后同一列 13.5ms、最长停摆 3.6ms(噪声底
|
| 73 |
+
0.9ms)。那 538ms 正好落在收尾窗口,把原始流接收线程挡在 `recv()`
|
| 74 |
+
外面,服务端 16 包队列(≈0.53s)一满就主动 close ⇒ 停止即断链
|
| 75 |
+
(实测 55 次「完成」54 次断链,中止路径不写 parquet ⇒ 0/11)。
|
| 76 |
+
所以省掉的不只是 0.6s,是那条断链的成因。
|
| 77 |
+
|
| 78 |
+
★ **返回值一定是自己的副本**,绝不是 `m` 的视图:`m` 来自桥接的
|
| 79 |
+
latest-wins 单槽(下一帧原地改写),交视图出去会让整段落盘变成
|
| 80 |
+
最后一帧的值——不报错、只是数据全错。
|
| 81 |
+
|
| 82 |
+
★ 落盘契约没变:元素仍是 int16 系 / float32 系两家族,倍率照旧只靠
|
| 83 |
+
info.json features.scale 携带(见上面 list 版的说明)。
|
| 84 |
+
"""
|
| 85 |
if spec not in settings.GRIPPER_FORCE_MATRIX_SPECS:
|
| 86 |
raise ValueError(f"未知力矩阵规格 {spec!r}")
|
| 87 |
arr = np.asarray(m, dtype=np.float32)
|
| 88 |
if spec == "float32":
|
| 89 |
+
# 与整数档同为「扁平 250×750」,只有元素类型不同:
|
| 90 |
+
# 读取端统一 reshape(-1,750) 后再按 dtype 决定是否 cumsum。
|
| 91 |
+
# copy=True:m 可能就是调用方那块复用缓冲,必须拷出来。
|
| 92 |
+
return np.array(arr.reshape(-1), dtype=np.float32, copy=True)
|
| 93 |
scale = settings.GRIPPER_FORCE_MATRIX_SCALES[spec]
|
| 94 |
rows = int(arr.shape[0])
|
| 95 |
flat = arr.reshape(rows, -1)
|
|
|
|
| 102 |
d = np.empty_like(q)
|
| 103 |
d[:, 0] = q[:, 0]
|
| 104 |
d[:, 1:] = q[:, 1:] - q[:, :-1] # int16 mod 2^16 回绕
|
| 105 |
+
# d 是这里新分配的,直接当返回值交出去(不是 m 的视图)
|
| 106 |
+
return d.reshape(-1)
|
| 107 |
|
| 108 |
|
| 109 |
def describe_gripper_matrix_spec(spec: str) -> str:
|
|
@@ -16,6 +16,8 @@ from PyQt5.QtCore import QObject, pyqtSignal, QTimer
|
|
| 16 |
from config import settings
|
| 17 |
from core.camera import CameraWorker, CameraState
|
| 18 |
from core.egodata_writer import EgoDataWriter
|
|
|
|
|
|
|
| 19 |
|
| 20 |
|
| 21 |
class DropStats:
|
|
@@ -33,6 +35,14 @@ class DropStats:
|
|
| 33 |
with self._lock:
|
| 34 |
self._counts[key] = self._counts.get(key, 0) + n
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
def clear(self):
|
| 37 |
with self._lock:
|
| 38 |
self._counts.clear()
|
|
@@ -42,6 +52,33 @@ class DropStats:
|
|
| 42 |
return dict(self._counts)
|
| 43 |
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
class CameraSlot(QObject):
|
| 46 |
"""
|
| 47 |
一个摄像机槽位 —— 相机采集 + 帧缓冲。
|
|
@@ -141,6 +178,10 @@ class CameraPipeline(QObject):
|
|
| 141 |
# 样本;夹爪链路不存 IMU/双目视频,只落盘 SLAM 位姿/轨迹)
|
| 142 |
self._imu_external_slots = {"stereo_left"}
|
| 143 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
# 已注册的传感器名称列表(决定 parquet 中 observation.<name> 列)
|
| 145 |
self._sensor_names: List[str] = []
|
| 146 |
self._device_meta: List[dict] = [] # start_recording(device_meta=…) 透传
|
|
@@ -567,6 +608,8 @@ class CameraPipeline(QObject):
|
|
| 567 |
self._codec_name = f"{w.encoder_label} | EgoData + LeRobot v3 Parquet"
|
| 568 |
# 丢帧统计/IMU 防丢:每 episode 重置
|
| 569 |
self._drop_stats.clear()
|
|
|
|
|
|
|
| 570 |
self._pending_imu.clear()
|
| 571 |
with self._glove_imu_lock:
|
| 572 |
self._glove_imu.clear()
|
|
@@ -605,6 +648,78 @@ class CameraPipeline(QObject):
|
|
| 605 |
self.recording_started.emit(self._recording_slot)
|
| 606 |
self.session_changed.emit(self)
|
| 607 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 608 |
def _write_loop(self):
|
| 609 |
"""独立写入线程 —— 用 time.perf_counter() 精确按 30fps 写入帧。"""
|
| 610 |
frame_interval = 1.0 / settings.RECORDING_FPS # ~0.0333s
|
|
@@ -674,6 +789,11 @@ class CameraPipeline(QObject):
|
|
| 674 |
frame, hw_ns, imu_s = item
|
| 675 |
else: # 兼容旧格式(仅帧)
|
| 676 |
frame, hw_ns, imu_s = item, 0, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 677 |
# IMU 样本只随主槽位写入(左右目共享同一份,
|
| 678 |
# 避免 data/imu/ 出现重复行;S80M/夹爪各自的主槽)
|
| 679 |
if sid not in self._imu_external_slots:
|
|
@@ -1008,6 +1128,11 @@ class CameraPipeline(QObject):
|
|
| 1008 |
self._timer_running = False
|
| 1009 |
self._duration_timer.stop()
|
| 1010 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1011 |
# 等待写入线程退出
|
| 1012 |
if self._write_thread is not None and self._write_thread.is_alive():
|
| 1013 |
self._write_thread.join(timeout=3.0)
|
|
@@ -1024,17 +1149,31 @@ class CameraPipeline(QObject):
|
|
| 1024 |
|
| 1025 |
# v1.0.9 丢帧统计快照(含 IMU 溢出次数):供录制完成回调提示与
|
| 1026 |
# writer 元数据回写;在 _finish_async(end_episode)之前注入
|
|
|
|
|
|
|
| 1027 |
self._last_drop_stats = self._drop_stats.snapshot()
|
| 1028 |
self._last_drop_stats["imu_overflow"] = self._imu_overflow_count
|
| 1029 |
if self._writer is not None:
|
| 1030 |
self._writer.set_drop_stats(self._last_drop_stats)
|
| 1031 |
|
|
|
|
| 1032 |
path = self._session_path
|
| 1033 |
-
threading.Thread(target=self._finish_async, args=(path,
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1038 |
self._writer = None
|
| 1039 |
self._session_path = None
|
| 1040 |
self.session_changed.emit(None)
|
|
@@ -1059,8 +1198,17 @@ class CameraPipeline(QObject):
|
|
| 1059 |
threading.Thread(target=self._abort_async, daemon=True).start()
|
| 1060 |
|
| 1061 |
def _abort_async(self):
|
| 1062 |
-
|
| 1063 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1064 |
self._writer = None
|
| 1065 |
self._session_path = None
|
| 1066 |
self.session_changed.emit(None)
|
|
|
|
| 16 |
from config import settings
|
| 17 |
from core.camera import CameraWorker, CameraState
|
| 18 |
from core.egodata_writer import EgoDataWriter
|
| 19 |
+
from core.frame_gap import GapWatch
|
| 20 |
+
from core.timing import Stopwatch
|
| 21 |
|
| 22 |
|
| 23 |
class DropStats:
|
|
|
|
| 35 |
with self._lock:
|
| 36 |
self._counts[key] = self._counts.get(key, 0) + n
|
| 37 |
|
| 38 |
+
def note_max(self, key: str, value: int):
|
| 39 |
+
"""峰值类指标(最大滞后/最大空洞毫秒)——inc 只能累加,装不下峰值。"""
|
| 40 |
+
value = int(value)
|
| 41 |
+
with self._lock:
|
| 42 |
+
current = self._counts.get(key)
|
| 43 |
+
if current is None or value > current:
|
| 44 |
+
self._counts[key] = value
|
| 45 |
+
|
| 46 |
def clear(self):
|
| 47 |
with self._lock:
|
| 48 |
self._counts.clear()
|
|
|
|
| 52 |
return dict(self._counts)
|
| 53 |
|
| 54 |
|
| 55 |
+
# drop_stats 键命名约定(新增键必须遵守;消费端一律用下面的判据,别再手写
|
| 56 |
+
# `!= "imu_overflow"` 这类排除逻辑):
|
| 57 |
+
# ext:<slot> / uvc:<slot> / sensor_queue 队列满丢帧 —— 帧数,可加总
|
| 58 |
+
# *_ms / *_ns / *_count 时长/次数 —— **不可**加进帧数
|
| 59 |
+
# imu_overflow 遗留键:防丢缓冲超限次数,非帧
|
| 60 |
+
_NON_FRAME_SUFFIXES = ("_ms", "_ns", "_count")
|
| 61 |
+
_LEGACY_NON_FRAME_KEYS = frozenset({"imu_overflow"})
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def is_frame_drop_key(key: str) -> bool:
|
| 65 |
+
"""该键是否表示「可加总的帧数」。
|
| 66 |
+
|
| 67 |
+
DROP_WARN 告警的语义是「丢帧 ⇒ 编码器跟不上 ⇒ 换编码器/降分辨率」。
|
| 68 |
+
采集停摆时长、latest-wins 覆盖次数、帧空洞毫秒都与编码器无关,混进
|
| 69 |
+
sum() 会把用户指去调错东西——2026-09-18 那次 4.68s 空洞正是被这类
|
| 70 |
+
混淆掩盖的(所有计数器都是 0,谁也说不清帧丢在哪一层)。
|
| 71 |
+
"""
|
| 72 |
+
if key in _LEGACY_NON_FRAME_KEYS:
|
| 73 |
+
return False
|
| 74 |
+
return not key.endswith(_NON_FRAME_SUFFIXES)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def frame_drop_total(stats: Dict[str, int]) -> int:
|
| 78 |
+
"""帧数口径的丢帧总数(消费端唯一入口:main_window / lite_window)。"""
|
| 79 |
+
return sum(v for k, v in stats.items() if is_frame_drop_key(k))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
class CameraSlot(QObject):
|
| 83 |
"""
|
| 84 |
一个摄像机槽位 —— 相机采集 + 帧缓冲。
|
|
|
|
| 178 |
# 样本;夹爪链路不存 IMU/双目视频,只落盘 SLAM 位姿/轨迹)
|
| 179 |
self._imu_external_slots = {"stereo_left"}
|
| 180 |
|
| 181 |
+
# v1.3.10 落盘侧帧空洞:slot → GapWatch(写线程私有,主线程只在
|
| 182 |
+
# join 之后读;见 core/frame_gap.py 与 docs/postmortem_trajectory_and_rgb.md)
|
| 183 |
+
self._ext_gap_watches: Dict[str, GapWatch] = {}
|
| 184 |
+
|
| 185 |
# 已注册的传感器名称列表(决定 parquet 中 observation.<name> 列)
|
| 186 |
self._sensor_names: List[str] = []
|
| 187 |
self._device_meta: List[dict] = [] # start_recording(device_meta=…) 透传
|
|
|
|
| 608 |
self._codec_name = f"{w.encoder_label} | EgoData + LeRobot v3 Parquet"
|
| 609 |
# 丢帧统计/IMU 防丢:每 episode 重置
|
| 610 |
self._drop_stats.clear()
|
| 611 |
+
# v1.3.10 落盘侧空洞看门狗同样每段重置(连同时间基座,见 GapWatch)
|
| 612 |
+
self._ext_gap_watches.clear()
|
| 613 |
self._pending_imu.clear()
|
| 614 |
with self._glove_imu_lock:
|
| 615 |
self._glove_imu.clear()
|
|
|
|
| 648 |
self.recording_started.emit(self._recording_slot)
|
| 649 |
self.session_changed.emit(self)
|
| 650 |
|
| 651 |
+
# ── v1.3.10 落盘侧帧空洞(写线程私有,无锁无 IO)──────────
|
| 652 |
+
def _note_ext_gap(self, sid: str, hw_ns: int) -> int:
|
| 653 |
+
"""记一帧、返回本次空洞 ns(0 = 正常)。空洞闭合到告警门槛就打一行。
|
| 654 |
+
|
| 655 |
+
时间基座由本段首帧锁定:``hw_ns > 0`` 用帧自带时刻(与 parquet 的
|
| 656 |
+
hardware_ns 同源,口径与 tools/audit_frame_gaps.py 逐字一致);
|
| 657 |
+
``hw_ns = 0``(无时间戳的槽位,如 lite 路径恒传 0)退化为出队瞬间的
|
| 658 |
+
宿主单调钟。**两者绝不混用**——混源会把两个时钟的基准差当成一次天文
|
| 659 |
+
数字级的空洞,这正是 GapWatch 内部拦掉的那种误判。
|
| 660 |
+
|
| 661 |
+
标称间隔恒取 RECORDING_FPS 的倒数:写线程对每个外部槽位每 tick 只取
|
| 662 |
+
一帧,输出行的间距就是 tick 的整数倍,与源的帧率无关。因此日志报的
|
| 663 |
+
毫秒数与事后原样重算 parquet 得到的数字相同。
|
| 664 |
+
"""
|
| 665 |
+
nominal_ns = int(1e9 / max(1.0, float(settings.RECORDING_FPS)))
|
| 666 |
+
watch = self._ext_gap_watches.get(sid)
|
| 667 |
+
if watch is None:
|
| 668 |
+
watch = GapWatch(
|
| 669 |
+
nominal_ns, settings.GRIPPER_RGB_GAP_MIN_MS * 1_000_000)
|
| 670 |
+
self._ext_gap_watches[sid] = watch
|
| 671 |
+
|
| 672 |
+
if hw_ns and hw_ns > 0:
|
| 673 |
+
ts_ns, source = int(hw_ns), "hw"
|
| 674 |
+
else:
|
| 675 |
+
ts_ns, source = time.monotonic_ns(), "mono"
|
| 676 |
+
gap_ns = watch.note(ts_ns, source)
|
| 677 |
+
if gap_ns < settings.GRIPPER_RGB_GAP_ALERT_MS * 1_000_000:
|
| 678 |
+
return gap_ns
|
| 679 |
+
|
| 680 |
+
# 洞起点 = 本帧时刻 − 空洞 − 标称间隔;相对首帧即「开录后多久」
|
| 681 |
+
snap = watch.snapshot()
|
| 682 |
+
start_ns = ts_ns - gap_ns - nominal_ns
|
| 683 |
+
rel_s = (start_ns - snap["first_ns"]) / 1e9 if snap["first_ns"] else 0.0
|
| 684 |
+
self.recording_log.emit(
|
| 685 |
+
f"[录制] RGB 帧空洞 {gap_ns / 1e6:.0f}ms(槽 {sid},"
|
| 686 |
+
f"开录后 {rel_s:.1f}s 起)——该段视频静止后跳变")
|
| 687 |
+
return gap_ns
|
| 688 |
+
|
| 689 |
+
def _inject_ext_gap_stats(self):
|
| 690 |
+
"""把落盘侧空洞并入本段 drop_stats(在 end_episode 之前调用)。
|
| 691 |
+
|
| 692 |
+
键一律以 ``_ms`` / ``_count`` 结尾 ⇒ 被 ``is_frame_drop_key`` 排除在
|
| 693 |
+
帧数口径之外(见 core/pipeline.py 顶部的键命名约定)。
|
| 694 |
+
"""
|
| 695 |
+
for sid, watch in self._ext_gap_watches.items():
|
| 696 |
+
snap = watch.snapshot()
|
| 697 |
+
if not snap["frames"]:
|
| 698 |
+
continue
|
| 699 |
+
# 走 note_drop_stats:零值不落键、*_max_ms 走峰值的规则只此一份
|
| 700 |
+
self.note_drop_stats({
|
| 701 |
+
f"{sid}_gap_ms": int(round(snap["gap_ns"] / 1e6)),
|
| 702 |
+
f"{sid}_gap_max_ms": int(round(snap["gap_max_ns"] / 1e6)),
|
| 703 |
+
f"{sid}_gap_count": snap["gap_count"],
|
| 704 |
+
})
|
| 705 |
+
|
| 706 |
+
def note_drop_stats(self, stats: Dict[str, int]):
|
| 707 |
+
"""外部(UI/bridge)把采集侧的计数并入本段 drop_stats。
|
| 708 |
+
|
| 709 |
+
``*_max_ms`` 结尾的键是峰值(走 note_max),其余累加。零值不落键——
|
| 710 |
+
与既有各计数器一致(只有出过事才会有键)。由 UI 在 finish_recording
|
| 711 |
+
**之前**调用;落盘侧的空洞由 pipeline 自己注入,两边合起来才是
|
| 712 |
+
「相机 → 视频文件」这条链的完整账。
|
| 713 |
+
"""
|
| 714 |
+
for key, value in (stats or {}).items():
|
| 715 |
+
value = int(value)
|
| 716 |
+
if value == 0:
|
| 717 |
+
continue
|
| 718 |
+
if key.endswith("_max_ms"):
|
| 719 |
+
self._drop_stats.note_max(key, value)
|
| 720 |
+
else:
|
| 721 |
+
self._drop_stats.inc(key, value)
|
| 722 |
+
|
| 723 |
def _write_loop(self):
|
| 724 |
"""独立写入线程 —— 用 time.perf_counter() 精确按 30fps 写入帧。"""
|
| 725 |
frame_interval = 1.0 / settings.RECORDING_FPS # ~0.0333s
|
|
|
|
| 789 |
frame, hw_ns, imu_s = item
|
| 790 |
else: # 兼容旧格式(仅帧)
|
| 791 |
frame, hw_ns, imu_s = item, 0, None
|
| 792 |
+
# v1.3.10 落盘侧空洞计量。放在这里(取到帧之后、写之前)
|
| 793 |
+
# 而非生产者侧:只统计「确实进了队列、确实写进了视频」的
|
| 794 |
+
# 帧,队列满丢掉的帧已由 write_external_frame 的 ext: 计数
|
| 795 |
+
# 认领,两边不重复也不互相掩盖。
|
| 796 |
+
self._note_ext_gap(sid, hw_ns)
|
| 797 |
# IMU 样本只随主槽位写入(左右目共享同一份,
|
| 798 |
# 避免 data/imu/ 出现重复行;S80M/夹爪各自的主槽)
|
| 799 |
if sid not in self._imu_external_slots:
|
|
|
|
| 1128 |
self._timer_running = False
|
| 1129 |
self._duration_timer.stop()
|
| 1130 |
|
| 1131 |
+
# v1.3.11(L0-1):收尾窗口计时。这一段(join + 排空 + 快照)与
|
| 1132 |
+
# 后台的 flush/parquet 合起来就是「点停止 → 落盘完成」的全长;
|
| 1133 |
+
# 2026-09-18 的断链与位姿发散都发生在这个窗口里,先量再修
|
| 1134 |
+
sw = Stopwatch()
|
| 1135 |
+
|
| 1136 |
# 等待写入线程退出
|
| 1137 |
if self._write_thread is not None and self._write_thread.is_alive():
|
| 1138 |
self._write_thread.join(timeout=3.0)
|
|
|
|
| 1149 |
|
| 1150 |
# v1.0.9 丢帧统计快照(含 IMU 溢出次数):供录制完成回调提示与
|
| 1151 |
# writer 元数据回写;在 _finish_async(end_episode)之前注入
|
| 1152 |
+
# v1.3.10:写线程已 join,此处读 _ext_gap_watches 无竞态
|
| 1153 |
+
self._inject_ext_gap_stats()
|
| 1154 |
self._last_drop_stats = self._drop_stats.snapshot()
|
| 1155 |
self._last_drop_stats["imu_overflow"] = self._imu_overflow_count
|
| 1156 |
if self._writer is not None:
|
| 1157 |
self._writer.set_drop_stats(self._last_drop_stats)
|
| 1158 |
|
| 1159 |
+
sw.lap("join")
|
| 1160 |
path = self._session_path
|
| 1161 |
+
threading.Thread(target=self._finish_async, args=(path, sw),
|
| 1162 |
+
daemon=True).start()
|
| 1163 |
+
|
| 1164 |
+
def _finish_async(self, path: str, sw: Optional[Stopwatch] = None):
|
| 1165 |
+
writer = self._writer
|
| 1166 |
+
if writer:
|
| 1167 |
+
writer.end_episode()
|
| 1168 |
+
if sw is not None:
|
| 1169 |
+
# 一行给出整条收尾路径的分段耗时(flush = 编码器收尾,
|
| 1170 |
+
# parquet = 力矩阵列建数组那段,meta = 元数据/统计合并)。
|
| 1171 |
+
# getattr:测试里的假 writer 没有这个属性,不能让它把
|
| 1172 |
+
# 收尾线程带下去(daemon 线程静默死掉=数据不落盘)
|
| 1173 |
+
for stage, ms in (getattr(writer, "finalize_timing", None)
|
| 1174 |
+
or {}).items():
|
| 1175 |
+
sw.add(stage, ms)
|
| 1176 |
+
self.recording_log.emit(f"[录制] 收尾 {sw.format()}")
|
| 1177 |
self._writer = None
|
| 1178 |
self._session_path = None
|
| 1179 |
self.session_changed.emit(None)
|
|
|
|
| 1198 |
threading.Thread(target=self._abort_async, daemon=True).start()
|
| 1199 |
|
| 1200 |
def _abort_async(self):
|
| 1201 |
+
writer = self._writer
|
| 1202 |
+
if writer:
|
| 1203 |
+
writer.abort_episode()
|
| 1204 |
+
# 中止也要有耗时读数:与「完成」路径的 flush/parquet 对比,
|
| 1205 |
+
# 是判断「断链到底由哪一段引起」的那条判据(2026-09-18:中止
|
| 1206 |
+
# 同样收尾 ffmpeg 却 0/6 断链)
|
| 1207 |
+
timing = getattr(writer, "finalize_timing", None) or {}
|
| 1208 |
+
if timing:
|
| 1209 |
+
self.recording_log.emit(
|
| 1210 |
+
"[录制] 收尾(中止) " +
|
| 1211 |
+
" ".join(f"{k}={v}ms" for k, v in timing.items()))
|
| 1212 |
self._writer = None
|
| 1213 |
self._session_path = None
|
| 1214 |
self.session_changed.emit(None)
|
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""启动环境守卫 —— 拦住「用错 Python 解释器」这一类启动失败。
|
| 2 |
+
|
| 3 |
+
客户现场最常见的两类「一启动就报错」都不是程序问题:
|
| 4 |
+
|
| 5 |
+
① 没激活 venv —— 直接 `python main.py`,或双击 .py 文件(Windows 用
|
| 6 |
+
系统 Python 打开);
|
| 7 |
+
② 已经激活了别的环境 —— conda / 另一个项目的 venv,依赖装到了别处。
|
| 8 |
+
|
| 9 |
+
这两种情况的真实报错是 ``ModuleNotFoundError: No module named 'PyQt5'``
|
| 10 |
+
之类,用户既看不懂也不知道该做什么。本模块在**任何重依赖 import 之前**
|
| 11 |
+
做一次体检: 缺关键依赖就打印可照抄的启动命令并以退出码 2 退出,而不是
|
| 12 |
+
让它崩在后面某个 import 上。
|
| 13 |
+
|
| 14 |
+
判定只看「关键依赖是不是真的缺」,所以:
|
| 15 |
+
* 开发机用自己的 Python 环境跑(依赖齐全)→ 只多一行提示,不拦截;
|
| 16 |
+
* 真正坏掉的环境(空壳 venv、从别的机器拷来的 venv、依赖装错地方)
|
| 17 |
+
→ 一定拦得住。
|
| 18 |
+
|
| 19 |
+
设 ``DAQ_SKIP_VENV_GUARD=1`` 可完全跳过 —— 工具脚本 / 单元测试需要
|
| 20 |
+
import 入口模块时不希望被拦。
|
| 21 |
+
|
| 22 |
+
本模块必须保持「零第三方依赖」(只用标准库),否则它就自身难保了。
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import os
|
| 28 |
+
import sys
|
| 29 |
+
|
| 30 |
+
# 每个入口一份规格: 自带 venv 目录名、关键依赖、入口文件名、分发脚本名。
|
| 31 |
+
# 关键依赖清单只放「本入口顶层就要用、且客户环境不会恰好自带」的包。
|
| 32 |
+
SPECS = {
|
| 33 |
+
"main": {
|
| 34 |
+
"venv": "venv",
|
| 35 |
+
"modules": ("PyQt5.QtWidgets", "qt_material"),
|
| 36 |
+
"entry": "main.py",
|
| 37 |
+
"launcher_win": "start.bat",
|
| 38 |
+
"launcher_unix": "./start.sh",
|
| 39 |
+
},
|
| 40 |
+
"lite": {
|
| 41 |
+
"venv": "venv_lite",
|
| 42 |
+
"modules": ("PyQt5.QtWidgets", "pyarrow"),
|
| 43 |
+
"entry": "main_lite.py",
|
| 44 |
+
"launcher_win": "start_lite.bat",
|
| 45 |
+
"launcher_unix": "./start_lite.sh",
|
| 46 |
+
},
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
_ASCII_FALLBACK = """\
|
| 50 |
+
============================================================
|
| 51 |
+
WRONG PYTHON INTERPRETER
|
| 52 |
+
============================================================
|
| 53 |
+
interpreter: {exe}
|
| 54 |
+
missing: {missing}
|
| 55 |
+
|
| 56 |
+
Launch with one of these instead:
|
| 57 |
+
* Windows: {launcher_win}
|
| 58 |
+
* Linux: {launcher_unix}
|
| 59 |
+
* or run the bundled venv directly:
|
| 60 |
+
Windows: {venv}\\Scripts\\python.exe {entry}
|
| 61 |
+
Linux: {venv}/bin/python {entry}
|
| 62 |
+
|
| 63 |
+
First run deploys dependencies (3-10 min): {launcher_win} / {launcher_unix}
|
| 64 |
+
An activated conda/other venv is ignored by these launchers.
|
| 65 |
+
============================================================
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def in_project_venv(base_dir: str, venv_name: str) -> bool:
|
| 70 |
+
"""当前解释器是不是项目自带的那只 venv(仅用于提示,不用于拦截)。"""
|
| 71 |
+
|
| 72 |
+
expected = os.path.normcase(
|
| 73 |
+
os.path.realpath(os.path.join(base_dir, venv_name)))
|
| 74 |
+
current = os.path.normcase(os.path.realpath(sys.prefix))
|
| 75 |
+
return current == expected
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def missing_modules(modules) -> list:
|
| 79 |
+
"""逐个试着 import,返回缺的那些(不装、不改 sys.path)。"""
|
| 80 |
+
|
| 81 |
+
missing = []
|
| 82 |
+
for name in modules:
|
| 83 |
+
try:
|
| 84 |
+
__import__(name)
|
| 85 |
+
except ImportError:
|
| 86 |
+
missing.append(name)
|
| 87 |
+
return missing
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _print(text: str, fallback: str) -> None:
|
| 91 |
+
"""打印;控制台编码装不下时(英文 Windows 的 cp437 等)退到 ASCII 版。"""
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
print(text)
|
| 95 |
+
except UnicodeEncodeError:
|
| 96 |
+
print(fallback)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def enforce(base_dir: str, app: str) -> None:
|
| 100 |
+
"""体检 ``app``("main" / "lite")需要的运行环境。
|
| 101 |
+
|
| 102 |
+
依赖齐全: 只在「用的不是项目 venv」时打一行提示,然后正常返回。
|
| 103 |
+
依赖缺失: 打印启动指引并以退出码 2 结束进程。
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
if os.environ.get("DAQ_SKIP_VENV_GUARD") == "1":
|
| 107 |
+
return
|
| 108 |
+
|
| 109 |
+
spec = SPECS[app]
|
| 110 |
+
venv_name = spec["venv"]
|
| 111 |
+
missing = missing_modules(spec["modules"])
|
| 112 |
+
fallback = _ASCII_FALLBACK.format(
|
| 113 |
+
exe=sys.executable, missing=", ".join(missing),
|
| 114 |
+
launcher_win=spec["launcher_win"], launcher_unix=spec["launcher_unix"],
|
| 115 |
+
venv=venv_name, entry=spec["entry"])
|
| 116 |
+
|
| 117 |
+
if missing:
|
| 118 |
+
indented = "\n".join(f" {line}" for line in fallback.splitlines())
|
| 119 |
+
_print(f"""
|
| 120 |
+
============================================================
|
| 121 |
+
启动环境不对: 当前用的 Python 不是本项目的运行环境
|
| 122 |
+
============================================================
|
| 123 |
+
解释器: {sys.executable}
|
| 124 |
+
缺少依赖: {", ".join(missing)}
|
| 125 |
+
|
| 126 |
+
请改用下面任一方式启动(任选其一):
|
| 127 |
+
· Windows: 双击 {spec["launcher_win"]}
|
| 128 |
+
· Linux: {spec["launcher_unix"]}
|
| 129 |
+
· 或用项目自带 venv 的解释器直接跑:
|
| 130 |
+
Windows: {venv_name}\\Scripts\\python.exe {spec["entry"]}
|
| 131 |
+
Linux: {venv_name}/bin/python {spec["entry"]}
|
| 132 |
+
|
| 133 |
+
首次运行需要先部署依赖(约 3-10 分钟),上面两个脚本会自动完成。
|
| 134 |
+
|
| 135 |
+
已经激活了别的虚拟环境(conda / 其它 venv)也没关系 ——
|
| 136 |
+
本项目不使用它,上面两条命令不受影响,直接执行即可。
|
| 137 |
+
============================================================
|
| 138 |
+
""", indented)
|
| 139 |
+
sys.exit(2)
|
| 140 |
+
|
| 141 |
+
if not in_project_venv(base_dir, venv_name):
|
| 142 |
+
print(f"[提示] 未使用项目自带 {venv_name}(当前: {sys.prefix})"
|
| 143 |
+
f" —— 仅开发调试时这样运行;交付/客户环境请用 "
|
| 144 |
+
f"{spec['launcher_win']} / {spec['launcher_unix']}")
|
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""收尾路径的分阶段计时 —— 纯 stdlib,无锁、无 IO、不在这里做重活。
|
| 2 |
+
|
| 3 |
+
**为什么有这个东西**(2026-09-18 查实的「SLAM 崩溃」):用户报的轨迹冻结 +
|
| 4 |
+
日志刷屏,根因是点「停止录制」之后那段收尾窗口里,我们自己的进程既持了
|
| 5 |
+
GIL、又抢了 SLAM 分区的 SMT 兄弟核:
|
| 6 |
+
|
| 7 |
+
* ``_write_data_parquet`` 的两条 ``list<int16>`` 力矩阵列走 pyarrow 逐值
|
| 8 |
+
装箱慢路径,实测**各持 GIL 1.6s**(本机实测,同表其余列全 <50ms)⇒
|
| 9 |
+
客户端 raw 接收线程连 ``recv()`` 都进不去 ⇒ 服务端 16 包队列(≈0.53s)
|
| 10 |
+
被填满 ⇒ ``g_raw_stereo_dropped != 0`` ⇒ 服务端**主动断链**(当天
|
| 11 |
+
43 次完成录制里 37 次断链;6 次中止不做 parquet,0 次断链)。
|
| 12 |
+
* 同一窗口 x265 flush 不限线程,吃满我们的掩码,而掩码里含 SLAM 分区
|
| 13 |
+
{4,5,7,8,9} 的 SMT 兄弟 {16..21} ⇒ 同秒 ``image=32.3 imu=203.1``。
|
| 14 |
+
|
| 15 |
+
修法(numpy 扁平缓冲 / 线程上限 / 掩码收窄)都依赖这段窗口的**实测**时长,
|
| 16 |
+
所以先落地这个仪表、先留档。口径:``monotonic_ns`` 计时(不受墙钟跳变
|
| 17 |
+
影响);单位毫秒、取整;调用点都在停止通路上,必须 O(1)。
|
| 18 |
+
|
| 19 |
+
用法::
|
| 20 |
+
|
| 21 |
+
sw = Stopwatch()
|
| 22 |
+
self._close_ffmpeg(); sw.lap("flush")
|
| 23 |
+
self._write_data_parquet(); sw.lap("parquet")
|
| 24 |
+
...
|
| 25 |
+
self._log(f"[录制] 收尾 {sw.format()}")
|
| 26 |
+
"""
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import time
|
| 30 |
+
from typing import Dict, Iterable, Optional
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class Stopwatch:
|
| 34 |
+
"""顺序分阶段计时:``lap()`` 记的是「距上一次 lap」的耗时。
|
| 35 |
+
|
| 36 |
+
同名 lap 累加(收尾里同一段可能被调用多次,如多路 ffmpeg),
|
| 37 |
+
所以 ``snapshot()`` 里一个阶段一个数、语义是「该阶段总耗时」。
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
__slots__ = ("_last_ns", "_stages")
|
| 41 |
+
|
| 42 |
+
def __init__(self) -> None:
|
| 43 |
+
self._last_ns = time.monotonic_ns()
|
| 44 |
+
self._stages: Dict[str, int] = {}
|
| 45 |
+
|
| 46 |
+
def lap(self, name: str) -> int:
|
| 47 |
+
"""记一段(自上一次 lap 或构造起算),返回本次毫秒。"""
|
| 48 |
+
now = time.monotonic_ns()
|
| 49 |
+
ms = int((now - self._last_ns) // 1_000_000)
|
| 50 |
+
self._last_ns = now
|
| 51 |
+
self._stages[name] = self._stages.get(name, 0) + ms
|
| 52 |
+
return ms
|
| 53 |
+
|
| 54 |
+
def add(self, name: str, ms: int) -> None:
|
| 55 |
+
"""并入一段在别处测得的耗时(writer 自己算的那几段走这里)。"""
|
| 56 |
+
self._stages[name] = self._stages.get(name, 0) + int(ms)
|
| 57 |
+
|
| 58 |
+
def snapshot(self) -> Dict[str, int]:
|
| 59 |
+
"""阶段 → 毫秒(插入序;副本)。"""
|
| 60 |
+
return dict(self._stages)
|
| 61 |
+
|
| 62 |
+
def total_ms(self) -> int:
|
| 63 |
+
return sum(self._stages.values())
|
| 64 |
+
|
| 65 |
+
def format(self, order: Optional[Iterable[str]] = None) -> str:
|
| 66 |
+
"""``flush=12ms parquet=34ms``;``order`` 可钉死显示顺序。
|
| 67 |
+
|
| 68 |
+
未命中的阶段显示 ``0ms``(不是省略)——「这段没跑」与「没测到」
|
| 69 |
+
要能一眼分开。
|
| 70 |
+
"""
|
| 71 |
+
keys = list(order) if order is not None else list(self._stages)
|
| 72 |
+
return " ".join(f"{k}={self._stages.get(k, 0)}ms" for k in keys)
|
|
@@ -109,6 +109,9 @@ config/ 是应用全局配置、国际化与版本号所在的配置包。版本
|
|
| 109 |
| 录制编码 | `ENCODER_X265_MIN_FPS_RATIO` | float | 1.5 | x265 达标门槛 = 录制帧率 × 该比值(不达标回退 x264) |
|
| 110 |
| 录制编码 | `IMU_PENDING_MAX_SAMPLES` | int | 18000 | 双目 IMU 防丢缓冲上限(约 1 分钟 @300Hz;队列满时丢帧保 IMU) |
|
| 111 |
| 录制编码 | `DROP_WARN_RATIO` / `DROP_WARN_MIN_COUNT` | float / int | 0.01 / 30 | 录制结束丢帧告警阈值(占比 1% 或 30 帧) |
|
|
|
|
|
|
|
|
|
|
| 112 |
| 任务服务 | `TASK_POLL_INTERVAL_MS` / `TASK_API_URL` / `DEVICE_NAME` | int / str / str | 30000 / `SERVER_URL` / `"EGO_001"` | 轮询间隔 / API 地址 / 设备认领名 |
|
| 113 |
| 手部追踪 | `HAND_TRACK_ENABLED` / `HAND_TRACK_MODE` | bool / str | `False` / `"glove"` | 需 ultralytics;`"glove"` 黑色手套 / `"bare"` 裸手 |
|
| 114 |
| 手部追踪 | `HAND_DETECTION_DIR` / `HAND_DET_MODEL` / `HAND_MEDIAPIPE_MODEL` | str | 根下 `tools/hand_detection` / 其内 `best.pt` / `hand_landmarker.task` | YOLO 手套模型 / MediaPipe 裸手模型 |
|
|
|
|
| 109 |
| 录制编码 | `ENCODER_X265_MIN_FPS_RATIO` | float | 1.5 | x265 达标门槛 = 录制帧率 × 该比值(不达标回退 x264) |
|
| 110 |
| 录制编码 | `IMU_PENDING_MAX_SAMPLES` | int | 18000 | 双目 IMU 防丢缓冲上限(约 1 分钟 @300Hz;队列满时丢帧保 IMU) |
|
| 111 |
| 录制编码 | `DROP_WARN_RATIO` / `DROP_WARN_MIN_COUNT` | float / int | 0.01 / 30 | 录制结束丢帧告警阈值(占比 1% 或 30 帧) |
|
| 112 |
+
| 帧空洞 | `GRIPPER_RGB_GAP_MIN_MS` | int | 100 | 计入「空洞」的**间隔**下限(≈3 帧;实测正常帧距 29.9~37.5ms)。审计脚本 `--min-gap-ms` 默认同值 |
|
| 113 |
+
| 帧空洞 | `GRIPPER_RGB_GAP_ALERT_MS` | int | 500 | 落盘侧空洞闭合时的当场告警门槛(低于此只落 parquet 不打日志) |
|
| 114 |
+
| 帧空洞 | `GRIPPER_RGB_STALL_ALERT_MS` / `GRIPPER_RGB_STALL_REPEAT_S` | int / float | 1000 / 30.0 | 采集侧 `read()` 失败连击的告警门槛与持续故障的重复告警间隔(进入一次 / 限频 / 恢复一次) |
|
| 115 |
| 任务服务 | `TASK_POLL_INTERVAL_MS` / `TASK_API_URL` / `DEVICE_NAME` | int / str / str | 30000 / `SERVER_URL` / `"EGO_001"` | 轮询间隔 / API 地址 / 设备认领名 |
|
| 116 |
| 手部追踪 | `HAND_TRACK_ENABLED` / `HAND_TRACK_MODE` | bool / str | `False` / `"glove"` | 需 ultralytics;`"glove"` 黑色手套 / `"bare"` 裸手 |
|
| 117 |
| 手部追踪 | `HAND_DETECTION_DIR` / `HAND_DET_MODEL` / `HAND_MEDIAPIPE_MODEL` | str | 根下 `tools/hand_detection` / 其内 `best.pt` / `hand_landmarker.task` | YOLO 手套模型 / MediaPipe 裸手模型 |
|
|
@@ -51,6 +51,7 @@
|
|
| 51 |
| `core/sensor_config_dialogs.py` | PyQt5 传感器配置对话框(矩阵行列 / 仿生手掌逐部位) |
|
| 52 |
| `core/sensor_hand_config.py` | 仿生手掌配置加载/传感器列有效性过滤(纯函数,零 Qt) |
|
| 53 |
| `core/helpers.py` | 通用工具函数(约 47 个:ID/时间/格式化/路径/会话扫描) |
|
|
|
|
| 54 |
| `core/gripper/` | UMI 夹爪 rig 自包含**子包**(Fays SLAM + Sightac 触觉 + 出厂标定生成),与上面平铺模块分开,见下文「夹爪」节 |
|
| 55 |
|
| 56 |
(`core/__init__.py` 为空包标记;`core/gripper/__init__.py` 为其子包标记。)
|
|
@@ -178,6 +179,24 @@ RGB(BGR 三通道)+ 深度(uint16,归一化毫米)两路信号。左
|
|
| 178 |
|
| 179 |
**关键数据**:写入线程节拍 `frame_interval = 1.0 / settings.RECORDING_FPS`(30fps),sleep 到目标前 ~1ms 后 busy-wait 补齐;每帧先排空传感器队列取最新数据,CameraSlot 队列"排空取最新帧"、外部帧源队列"取一帧不排空"(输出均匀无抖动);单目路径写 MP4 时上下翻转、外部双目帧路径已在 `ui/main_window._on_stereo_frame` 翻转故 `flip_vertical=False`;IMU 样本只随 `stereo_left` 写入(左右目共享一份,避免 `data/imu/` 重复行);可选 `settings.CAMERA_MIRROR_HORIZONTAL` 水平镜像。**深度 MP4 补拍**(v1.0.11):`_write_one_frame` 每个 master 槽节拍至多消费一帧深度——队列有新帧则写热力图 MP4 +(raw_depth 时)PNG16 并缓存于 `_last_depth_frames`;队列空(S80C 深度引擎 ~20fps 低于录制 30fps)则重写缓存帧到热力图 MP4(不落 PNG、不推进序号),保证深度 MP4 时长与 RGB 对齐。
|
| 180 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
**调用关系**:被 `ui/main_window.py`(主程序)、`tools/tests/d435_e2e_test.py`、`tools/tests/device_panel_gui_smoke_test.py`、`tools/tests/exposure_control_test.py` 引用;调用了 `core/camera.py` 与 `core/egodata_writer.py`。
|
| 182 |
|
| 183 |
## 设备管理器与口径(v1.0.3 从 ui 抽出)
|
|
@@ -933,6 +952,36 @@ rows/cols 映射,点击"选择"弹出子级 `MatrixConfigDialog` 逐部位编
|
|
| 933 |
|
| 934 |
**调用关系**:被 `core/`(`recording_record.py`、`egodata_writer.py`、`hand_tracking.py`、`session_timeline.py`、`session_catalog.py`)、`ui/`(`main_window.py`、`camera_widget.py`、`playback_dialog.py`、`upload_dialog.py`)、`scripts/process_hands.py`、`tools/tests/` 各 import 点引用;其中 `session_summary` 供录制历史面板生成"摄像机"列摘要,`send_to_recycle_bin` 供回放对话框删除会话。自身 `from config import settings`。
|
| 935 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 936 |
### core/stereo_depth.py
|
| 937 |
|
| 938 |
**作用**:双目深度计算模块。`StereoDepthComputer` 基于手写 OpenCV
|
|
@@ -972,6 +1021,7 @@ rows/cols 映射,点击"选择"弹出子级 `MatrixConfigDialog` 逐部位编
|
|
| 972 |
| `core/gripper/fays_serial_probe.py` | 经官方 VI Kit SDK 读 S80M 产品序列号 |
|
| 973 |
| `core/gripper/bridge.py` | 夹爪 rig 与主程序的 Qt 桥(后台线程采集 → 队列信号回主线程) |
|
| 974 |
| `core/gripper/decxin_exposure.py` | 连夹爪时把 DECXIN 的曝光/白平衡写回自动档(状态存在相机机身里、逐台各一份) |
|
|
|
|
| 975 |
| `core/gripper/affinity.py` | 夹爪 CPU 预留(主进程掩码收窄 + raw 流接收线程专用核) |
|
| 976 |
| `core/gripper/tactile_process_worker.py` | Sightac 触觉计算子进程 |
|
| 977 |
| `core/gripper/slam/` | 桥接进程控制器与 stdout 协议解析(`process_controller.py` / `protocol.py`) |
|
|
@@ -1070,6 +1120,33 @@ WBTmp=6500/ET=312 是原厂存储态。异常一律不外泄:枚举失败=
|
|
| 1070 |
大事)。离线回归 `tools/tests/test_decxin_exposure.py`,含「调用点必须早于
|
| 1071 |
`select()`」的静态断言。
|
| 1072 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1073 |
## 数据流
|
| 1074 |
|
| 1075 |
**采集链路**:`ui/main_window.py` 经 `core/device_detector.py`(复用
|
|
|
|
| 51 |
| `core/sensor_config_dialogs.py` | PyQt5 传感器配置对话框(矩阵行列 / 仿生手掌逐部位) |
|
| 52 |
| `core/sensor_hand_config.py` | 仿生手掌配置加载/传感器列有效性过滤(纯函数,零 Qt) |
|
| 53 |
| `core/helpers.py` | 通用工具函数(约 47 个:ID/时间/格式化/路径/会话扫描) |
|
| 54 |
+
| `core/frame_gap.py` | 帧间隔空洞看门狗 `GapWatch`(纯算术,零 Qt/零 IO;录制侧与 `tools/audit_frame_gaps.py` 共用同一份空洞定义) |
|
| 55 |
| `core/gripper/` | UMI 夹爪 rig 自包含**子包**(Fays SLAM + Sightac 触觉 + 出厂标定生成),与上面平铺模块分开,见下文「夹爪」节 |
|
| 56 |
|
| 57 |
(`core/__init__.py` 为空包标记;`core/gripper/__init__.py` 为其子包标记。)
|
|
|
|
| 179 |
|
| 180 |
**关键数据**:写入线程节拍 `frame_interval = 1.0 / settings.RECORDING_FPS`(30fps),sleep 到目标前 ~1ms 后 busy-wait 补齐;每帧先排空传感器队列取最新数据,CameraSlot 队列"排空取最新帧"、外部帧源队列"取一帧不排空"(输出均匀无抖动);单目路径写 MP4 时上下翻转、外部双目帧路径已在 `ui/main_window._on_stereo_frame` 翻转故 `flip_vertical=False`;IMU 样本只随 `stereo_left` 写入(左右目共享一份,避免 `data/imu/` 重复行);可选 `settings.CAMERA_MIRROR_HORIZONTAL` 水平镜像。**深度 MP4 补拍**(v1.0.11):`_write_one_frame` 每个 master 槽节拍至多消费一帧深度——队列有新帧则写热力图 MP4 +(raw_depth 时)PNG16 并缓存于 `_last_depth_frames`;队列空(S80C 深度引擎 ~20fps 低于录制 30fps)则重写缓存帧到热力图 MP4(不落 PNG、不推进序号),保证深度 MP4 时长与 RGB 对齐。
|
| 181 |
|
| 182 |
+
**帧空洞与丢帧口径(v1.3.10)**:写入线程对每个外部槽跑一个 `core.frame_gap.GapWatch`
|
| 183 |
+
(`_ext_gap_watches`,每槽一个,基座由该槽首帧锁定),取帧成功后、`_write_one_frame`
|
| 184 |
+
之前记账——
|
| 185 |
+
不 sleep、不 IO、不加锁,空洞 ≥ `settings.GRIPPER_RGB_GAP_ALERT_MS` 时经既有
|
| 186 |
+
`recording_log` 信号当场告警(`[录制] RGB 帧空洞 …ms`)。`DropStats` 另有
|
| 187 |
+
`note_max(key, value)`(峰值语义)与两个共用 helper:
|
| 188 |
+
|
| 189 |
+
```python
|
| 190 |
+
is_frame_drop_key(key) # 帧数键才为真:ext:<slot> / sensor_queue / imu_overflow
|
| 191 |
+
frame_drop_total(stats) # 两处 UI 汇总共用,替代各自硬编的排除逻辑
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
键约定:`*_ms` / `*_ns` / `*_count` 后缀一律是**时长/次数,不是帧数**(`imu_overflow`
|
| 195 |
+
是遗留的次数键)。`CameraPipeline.note_drop_stats(mapping)` 由 UI 在停止录制前把
|
| 196 |
+
桥接的采集侧仪表(`bridge.rgb_quality_snapshot()`)推进 `drop_stats`。**parquet 只是
|
| 197 |
+
多几个 JSON 键,列与录制时序一个没动**——「丢帧统计」与「换编码器」提示的文案也
|
| 198 |
+
一个字没改。
|
| 199 |
+
|
| 200 |
**调用关系**:被 `ui/main_window.py`(主程序)、`tools/tests/d435_e2e_test.py`、`tools/tests/device_panel_gui_smoke_test.py`、`tools/tests/exposure_control_test.py` 引用;调用了 `core/camera.py` 与 `core/egodata_writer.py`。
|
| 201 |
|
| 202 |
## 设备管理器与口径(v1.0.3 从 ui 抽出)
|
|
|
|
| 952 |
|
| 953 |
**调用关系**:被 `core/`(`recording_record.py`、`egodata_writer.py`、`hand_tracking.py`、`session_timeline.py`、`session_catalog.py`)、`ui/`(`main_window.py`、`camera_widget.py`、`playback_dialog.py`、`upload_dialog.py`)、`scripts/process_hands.py`、`tools/tests/` 各 import 点引用;其中 `session_summary` 供录制历史面板生成"摄像机"列摘要,`send_to_recycle_bin` 供回放对话框删除会话。自身 `from config import settings`。
|
| 954 |
|
| 955 |
+
### core/frame_gap.py
|
| 956 |
+
|
| 957 |
+
**作用**:帧间隔**空洞**看门狗,纯算术类(零 Qt、零 IO、零第三方依赖,故离线
|
| 958 |
+
审计脚本能直接 import)。录制侧(`core/pipeline.py` 的写入线程)与
|
| 959 |
+
`tools/audit_frame_gaps.py` **共用这一个类**——空洞的定义只此一份,否则两边口径
|
| 960 |
+
迟早漂移。
|
| 961 |
+
|
| 962 |
+
```
|
| 963 |
+
空洞 = 相邻两帧时间差 − 标称帧间隔(30fps → 33_333_333 ns)
|
| 964 |
+
```
|
| 965 |
+
|
| 966 |
+
只报「断了多久」,不判「丢了几帧」(帧率本就不恒定,反推帧数会给出看似精确实则错
|
| 967 |
+
的数字)。日志里 `[录制] RGB 帧空洞 4648ms` 与 parquet 的 `*_gap_ms` 报的就是这个数。
|
| 968 |
+
|
| 969 |
+
| 名称 | 签名要点 | 作用 |
|
| 970 |
+
|---|---|---|
|
| 971 |
+
| `GapWatch` | `(nominal_ns, min_gap_ns)` | `min_gap_ns` 是**间隔**下限(不是超出量),默认取 `settings.GRIPPER_RGB_GAP_MIN_MS`;间隔 ≥ 它才记为空洞 |
|
| 972 |
+
| `GapWatch.note` | `(ts_ns, source) -> int` | 记一帧,返回本次空洞 ns(0 = 正常/跳过)。`source`:`"hw"`(帧自带的采集时刻)/ `"mono"`(出队瞬间的宿主单调钟,用于无时间戳槽位);**本段首帧决定基座**,之后 source 不符的帧只累加 `frames`、不参与空洞计算 |
|
| 973 |
+
| `GapWatch.snapshot` | `() -> dict` | `frames / span_ns / gap_ns / gap_max_ns / gap_count / gap_max_at_ns / resyncs …`(全 int) |
|
| 974 |
+
| `GapWatch.reset` | `()` | 每段录制开始时归零 |
|
| 975 |
+
|
| 976 |
+
**两个坑(都写进了回归用例)**:① `ts_ns == 0` 是「无时间戳」哨兵,但**负值是合法
|
| 977 |
+
时刻**——早年段的设备钟是有符号 32 位计数器,按 `<= 0` 跳过会把整段负值区当「无戳」
|
| 978 |
+
并凭空造出假空洞;② 混源(设备钟与宿主钟混喂)会把两个时钟的基准差当成一次天文
|
| 979 |
+
数字级的空洞,所以基座一旦锁定就不再接受另一种 source。
|
| 980 |
+
|
| 981 |
+
**调用关系**:被 `core/pipeline.py`(`_ext_gap_watch`)与 `tools/audit_frame_gaps.py`
|
| 982 |
+
import;回归 `tools/tests/test_frame_gap.py`。背景见
|
| 983 |
+
[postmortem 第四节](postmortem_trajectory_and_rgb.md)。
|
| 984 |
+
|
| 985 |
### core/stereo_depth.py
|
| 986 |
|
| 987 |
**作用**:双目深度计算模块。`StereoDepthComputer` 基于手写 OpenCV
|
|
|
|
| 1021 |
| `core/gripper/fays_serial_probe.py` | 经官方 VI Kit SDK 读 S80M 产品序列号 |
|
| 1022 |
| `core/gripper/bridge.py` | 夹爪 rig 与主程序的 Qt 桥(后台线程采集 → 队列信号回主线程) |
|
| 1023 |
| `core/gripper/decxin_exposure.py` | 连夹爪时把 DECXIN 的曝光/白平衡写回自动档(状态存在相机机身里、逐台各一份) |
|
| 1024 |
+
| `core/gripper/rgb_quality.py` | RGB 采集质量仪表:`RgbReadWatch`(read() 失败连击的进入/限频/恢复三态告警)+ `MaxLagWatch`(emit 与派发滞后峰值);纯记账,日志行由调用方 `_log` |
|
| 1025 |
| `core/gripper/affinity.py` | 夹爪 CPU 预留(主进程掩码收窄 + raw 流接收线程专用核) |
|
| 1026 |
| `core/gripper/tactile_process_worker.py` | Sightac 触觉计算子进程 |
|
| 1027 |
| `core/gripper/slam/` | 桥接进程控制器与 stdout 协议解析(`process_controller.py` / `protocol.py`) |
|
|
|
|
| 1120 |
大事)。离线回归 `tools/tests/test_decxin_exposure.py`,含「调用点必须早于
|
| 1121 |
`select()`」的静态断言。
|
| 1122 |
|
| 1123 |
+
### core/gripper/rgb_quality.py
|
| 1124 |
+
|
| 1125 |
+
**作用(v1.3.10)**:RGB 采集质量的**纯记账**仪表。2026-09-18 那 4.68s 空洞当时
|
| 1126 |
+
在所有计数器里都是 0——因为「相机侧没帧可读」「emit 帧槽被顶掉」「GUI 主线程卡顿」
|
| 1127 |
+
这三条路在 parquet 里留下**完全相同的签名**,日志里一行都没写。本模块把三条路分开
|
| 1128 |
+
记账,只返回日志行列表,由调用方(`bridge._log`)落地。
|
| 1129 |
+
|
| 1130 |
+
| 类 | 接口 | 语义 |
|
| 1131 |
+
|---|---|---|
|
| 1132 |
+
| `RgbReadWatch` | `note_fail(mono_ns, *, reconnects, error)` / `note_ok(mono_ns, *, reconnects, error)` / `snapshot()` | `read()` 失败连击的**进入一次 / 按 `GRIPPER_RGB_STALL_REPEAT_S` 限频 / 恢复一次**三态告警(去抖契约照抄 `slam/process_controller.py` 的 `FaysRateAlarm`);停摆期间的错误信息本地留一份带进恢复行(`read()` 一成功相机会清掉 `last_transport_error`,否则最有用的那句正好在恢复时丢掉) |
|
| 1133 |
+
| `MaxLagWatch` | `note(lag_ns)` / `snapshot()` | 滞后峰值 + 样本数,emit 滞后与 GUI 派发滞后各一个实例 |
|
| 1134 |
+
| `RgbReadWatch.note_overwrite()` | `()` | latest-wins 帧槽被顶掉的计数(「帧采到了、但没人及时取走」的唯一证据) |
|
| 1135 |
+
|
| 1136 |
+
`snapshot()` 的键全为 int,直接喂 `CameraPipeline.note_drop_stats` 落进 parquet
|
| 1137 |
+
的 `drop_stats`(键带 `_ms`/`_count` 后缀,**不加进帧数**,见
|
| 1138 |
+
`core/pipeline.is_frame_drop_key`)。
|
| 1139 |
+
|
| 1140 |
+
**线程契约**:类内自带锁(O(1)、无分配,除告警那一次);`bridge` 侧只在 RGB 线程
|
| 1141 |
+
写、主线程读;`reconnect_count` 是普通 int、**只算段内增量**(reset 时记基座)。
|
| 1142 |
+
**RGB 线程绝不做文件 IO、绝不 emit**(`_emit_loop` 是桥接唯一的信号出口)。
|
| 1143 |
+
|
| 1144 |
+
**调用关系**:`core/gripper/bridge.py`(`_rgb_run` 的失败/成功分支、`_post_frame`
|
| 1145 |
+
的早退分支、`_emit_loop` 的滞留测量)、`ui/main_window.py` 与 `ui/lite_window.py`
|
| 1146 |
+
(派发滞后 + 录制结束汇总);离线回归 `tools/tests/test_rgb_quality.py`,含
|
| 1147 |
+
「门槛差 1ms 不许开火」的反向用例。判据表见
|
| 1148 |
+
[postmortem §4.6](postmortem_trajectory_and_rgb.md)。
|
| 1149 |
+
|
| 1150 |
## 数据流
|
| 1151 |
|
| 1152 |
**采集链路**:`ui/main_window.py` 经 `core/device_detector.py`(复用
|
|
@@ -248,7 +248,7 @@ data/recordings/ # 录制根目录(settings.RECORDING
|
|
| 248 |
| `created_at` | 创建时间(Unix 时间) |
|
| 249 |
| `codebase_version` | 程序版本(`config.__version__`) |
|
| 250 |
| `video_codec` | v1.0.9:本会话视频编码信息 `{encoder, codec, crf, ffmpeg, selected_by, probe}`;`selected_by` = `"auto"` 或显式指定名,`probe` = 录前速度探针结果(x265 路径) |
|
| 251 |
-
| `drop_stats` | v1.0.9:录制丢帧统计 `{队列键: 丢弃帧数}` + `imu_overflow`(IMU 防丢缓冲溢出次数);无丢帧时全为 0 |
|
| 252 |
|
| 253 |
### 4.4 `timestamps.json`
|
| 254 |
|
|
@@ -274,7 +274,7 @@ data/recordings/ # 录制根目录(settings.RECORDING
|
|
| 274 |
| `timestamp` | float32 | 会话时间(秒) |
|
| 275 |
| `task_index` | int64 | 任务序号(当前固定 0) |
|
| 276 |
| `observation.<sensor>` | list<float32, 256> | 传感器读数(16×16 展平;缺帧补零) |
|
| 277 |
-
| `observation.left_hand_pose` / `observation.right_hand_pose` | list<float32, 63> | 手部关键点(21 关节 × xyz;录制时
|
| 278 |
| `action` | list<float32, 1> | 动作(当前固定 `[0.0]`) |
|
| 279 |
| `status.<device_id>` | string | 该设备在本帧的连接状态(默认 `"connected"`) |
|
| 280 |
|
|
|
|
| 248 |
| `created_at` | 创建时间(Unix 时间) |
|
| 249 |
| `codebase_version` | 程序版本(`config.__version__`) |
|
| 250 |
| `video_codec` | v1.0.9:本会话视频编码信息 `{encoder, codec, crf, ffmpeg, selected_by, probe}`;`selected_by` = `"auto"` 或显式指定名,`probe` = 录前速度探针结果(x265 路径) |
|
| 251 |
+
| `drop_stats` | v1.0.9:录制丢帧统计 `{队列键: 丢弃帧数}` + `imu_overflow`(IMU 防丢缓冲溢出次数);无丢帧时全为 0。v1.3.10 起另有**带后缀**的键:`*_ms`(时长)/ `*_count`(次数)——夹爪 RGB 的帧空洞与采集侧仪表(`<槽>_gap_ms`、`_readfail_ms`、`_overwrite_count`、`_emit_lag_max_ms`、`_dispatch_lag_max_ms` 等)。**`_ms`/`_count` 后缀的键不是帧数**,加总帧数前必须过 `core.pipeline.is_frame_drop_key`(见 [file_format](file_format.md) §7.3、[postmortem](postmortem_trajectory_and_rgb.md) §4.6) |
|
| 252 |
|
| 253 |
### 4.4 `timestamps.json`
|
| 254 |
|
|
|
|
| 274 |
| `timestamp` | float32 | 会话时间(秒) |
|
| 275 |
| `task_index` | int64 | 任务序号(当前固定 0) |
|
| 276 |
| `observation.<sensor>` | list<float32, 256> | 传感器读数(16×16 展平;缺帧补零) |
|
| 277 |
+
| `observation.left_hand_pose` / `observation.right_hand_pose` | list<float32, 63> | 手部关键点(21 关节 × xyz;USB 手套录制时由 IMU 实时解算回填,无手套或未解算时为零占位) |
|
| 278 |
| `action` | list<float32, 1> | 动作(当前固定 `[0.0]`) |
|
| 279 |
| `status.<device_id>` | string | 该设备在本帧的连接状态(默认 `"connected"`) |
|
| 280 |
|
|
@@ -120,8 +120,8 @@ fnum = (N - 1) % 1000 # 三位零起:episode-000 .. episode-999
|
|
| 120 |
`data/` 重建一次再增量合并(参考 `core.helpers.recalc_stats`)。
|
| 121 |
- `action` 恒为占位块(`count:0`,仅声明列形状,不参与统计)。
|
| 122 |
- 只统计实际存在的列:帧级 `observation.<sn>`(逐行计数,含全零行)、样本级
|
| 123 |
-
`observation.imu`(按样本计数);`observation.*hand_pose` 为恒写
|
| 124 |
-
|
| 125 |
- 语义:删除 episode 不回退 stats(与任务进度水位一致);stats.json 是全任务
|
| 126 |
聚合快照,不是逐 episode 重建值。
|
| 127 |
|
|
@@ -165,7 +165,7 @@ fnum = (N - 1) % 1000 # 三位零起:episode-000 .. episode-999
|
|
| 165 |
| `length` | int64 | 帧数 = data parquet 行数 |
|
| 166 |
| `created_at` | float64 | episode 开始时间(Unix 秒) |
|
| 167 |
| `duration_sec` | float64 | 时长(秒) |
|
| 168 |
-
| `drop_stats` | str | **JSON 字符串**(如 `{"imu_overflow": 0}`),读取方须 `json.loads` |
|
| 169 |
| `video_codec` | str | **JSON 字符串**:本机原始编码信息(encoder/codec/crf/ffmpeg 路径/probe);上传 zip 中的 mp4 可能已被再编码,见 §8 |
|
| 170 |
| `calibration` | str | **JSON 字符串**:本 episode 标定(结构与 info.json 的 calibration 同型),保每 episode 标定保真 |
|
| 171 |
| `force_matrix_specs` | str | **JSON 字符串**:本段力矩阵列规格(列名 → 描述),**倍率的权威来源**,见 §7.2.1。v1.3.x 新增;旧 episode 无此列(读侧按缺列容忍,退回 info.json) |
|
|
@@ -196,7 +196,7 @@ fnum = (N - 1) % 1000 # 三位零起:episode-000 .. episode-999
|
|
| 196 |
| `observation.<sn>` | list<float32, 256> | 每帧一个传感器读数(维度 = info.json `sensor_dim`) |
|
| 197 |
| `imu_ts_ns` | list<int64> | 与 `observation.imu` **一一对应**的样本时间戳 |
|
| 198 |
| `observation.imu` | list<list<float32, 6>> | 挂在帧行上的**变长样本列表**(1000Hz/400Hz 只是 list 长短变化) |
|
| 199 |
-
| `observation.left_hand_pose` | list<float32, 63> | **恒写
|
| 200 |
| `observation.right_hand_pose` | list<float32, 63> | 同上 |
|
| 201 |
| `action` | list<float32, 1> | 恒写(现为 0) |
|
| 202 |
| `status.<did>` | str | 稀疏设备状态列(`"connected"`/`"disconnected"` 等) |
|
|
@@ -241,6 +241,18 @@ meta 行,不碰 data 字节)。
|
|
| 241 |
`hardware_ns` 设备时钟窗口挂靠。读取零重采样;宿主时间锚定靠 `timestamp` +
|
| 242 |
`wall_time`。客户 9 列平表由导出工具展开插值合成,非本契约内容。
|
| 243 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
### 7.4 meta/episodes/.lock(运行时辅助文件,非数据)
|
| 245 |
|
| 246 |
`meta/episodes/.lock` 是**空文件**,flock 锁锚点——旧分片回退的读-改-写用
|
|
|
|
| 120 |
`data/` 重建一次再增量合并(参考 `core.helpers.recalc_stats`)。
|
| 121 |
- `action` 恒为占位块(`count:0`,仅声明列形状,不参与统计)。
|
| 122 |
- 只统计实际存在的列:帧级 `observation.<sn>`(逐行计数,含全零行)、样本级
|
| 123 |
+
`observation.imu`(按样本计数);`observation.*hand_pose` 为恒写列(USB 手套
|
| 124 |
+
录制时由 IMU 实时解算回填,无解算时为零占位),**不入统计**。
|
| 125 |
- 语义:删除 episode 不回退 stats(与任务进度水位一致);stats.json 是全任务
|
| 126 |
聚合快照,不是逐 episode 重建值。
|
| 127 |
|
|
|
|
| 165 |
| `length` | int64 | 帧数 = data parquet 行数 |
|
| 166 |
| `created_at` | float64 | episode 开始时间(Unix 秒) |
|
| 167 |
| `duration_sec` | float64 | 时长(秒) |
|
| 168 |
+
| `drop_stats` | str | **JSON 字符串**(如 `{"imu_overflow": 0}`),读取方须 `json.loads`。v1.3.10 起含**带后缀**的键:`*_ms`/`*_count` 是时长/次数(夹爪 RGB 帧空洞与采集侧仪表),**不是帧数**——加总帧数前须过 `core.pipeline.is_frame_drop_key`(见 §7.3) |
|
| 169 |
| `video_codec` | str | **JSON 字符串**:本机原始编码信息(encoder/codec/crf/ffmpeg 路径/probe);上传 zip 中的 mp4 可能已被再编码,见 §8 |
|
| 170 |
| `calibration` | str | **JSON 字符串**:本 episode 标定(结构与 info.json 的 calibration 同型),保每 episode 标定保真 |
|
| 171 |
| `force_matrix_specs` | str | **JSON 字符串**:本段力矩阵列规格(列名 → 描述),**倍率的权威来源**,见 §7.2.1。v1.3.x 新增;旧 episode 无此列(读侧按缺列容忍,退回 info.json) |
|
|
|
|
| 196 |
| `observation.<sn>` | list<float32, 256> | 每帧一个传感器读数(维度 = info.json `sensor_dim`) |
|
| 197 |
| `imu_ts_ns` | list<int64> | 与 `observation.imu` **一一对应**的样本时间戳 |
|
| 198 |
| `observation.imu` | list<list<float32, 6>> | 挂在帧行上的**变长样本列表**(1000Hz/400Hz 只是 list 长短变化) |
|
| 199 |
+
| `observation.left_hand_pose` | list<float32, 63> | **恒写列**:USB 手套录制时由 IMU 实时解算回填,无解算时为零占位;裸手 63 维 world landmarks 由后处理回填 |
|
| 200 |
| `observation.right_hand_pose` | list<float32, 63> | 同上 |
|
| 201 |
| `action` | list<float32, 1> | 恒写(现为 0) |
|
| 202 |
| `status.<did>` | str | 稀疏设备状态列(`"connected"`/`"disconnected"` 等) |
|
|
|
|
| 241 |
`hardware_ns` 设备时钟窗口挂靠。读取零重采样;宿主时间锚定靠 `timestamp` +
|
| 242 |
`wall_time`。客户 9 列平表由导出工具展开插值合成,非本契约内容。
|
| 243 |
|
| 244 |
+
**两个时间戳分别是谁盖的(MUST 理解,v1.3.10 明确)**:
|
| 245 |
+
|
| 246 |
+
| 列 | 盖戳者 | 语义 |
|
| 247 |
+
|---|---|---|
|
| 248 |
+
| `wall_time` | **写入线程**,建行落盘处 `time.time()` | 该行**写下来**的时刻(宿主墙钟,绝对 Unix 秒) |
|
| 249 |
+
| `hardware_ns` | **采集侧**,相机/传感器取到帧处 | 该帧**取到**的时刻。双目是 SDK 硬件戳(与 IMU 同源);夹爪 RGB 是采集线程的宿主单调钟(≤078 段被截成有符号 32 位、每 4.295s 锯齿一次,读取方须按 2^32 解卷 —— `tools/audit_frame_gaps.py` 的 `trunc32`) |
|
| 250 |
+
|
| 251 |
+
两者之差 = 中间队列的滞留(+ 两钟固定偏移)。**空洞**(相邻行 `hardware_ns` 间隔
|
| 252 |
+
超出标称帧间隔的部分)不等于画面丢了:夹爪 RGB 的空洞要走画面复核才能定性
|
| 253 |
+
(真丢 / 帧晚到 / 判不了),口径与全库基线见
|
| 254 |
+
[postmortem §4](postmortem_trajectory_and_rgb.md)。
|
| 255 |
+
|
| 256 |
### 7.4 meta/episodes/.lock(运行时辅助文件,非数据)
|
| 257 |
|
| 258 |
`meta/episodes/.lock` 是**空文件**,flock 锁锚点——旧分片回退的读-改-写用
|
|
@@ -25,7 +25,8 @@ Windows 下用 `run.bat`(自动设置 Qt 平台插件路径后运行 `main.py`
|
|
| 25 |
python -m venv venv && venv/bin/pip install -r requirements.txt
|
| 26 |
```
|
| 27 |
|
| 28 |
-
说明:`
|
|
|
|
| 29 |
(按需在 venv 内安装;`main.py` 对 torch 做可选导入,缺失时自动跳过)。
|
| 30 |
|
| 31 |
首次运行无需手动建配置:`data/tasks.json` 在首次读取时由程序写入内置种子
|
|
@@ -130,7 +131,7 @@ VENV_PY=/path/to/python ./tools/hand_3d_d435/run_live_d435.sh
|
|
| 130 |
| `data/` | 本地配置(仓库提供 `*.example.json` 模板与出厂默认 `device_params.json`;其余配置、录制数据、SQLite 均 gitignore) | `docs/data.md`(本文档集) |
|
| 131 |
| `tools/demos/` | 交付版 demo:S80M 深度引擎 demo、双目 2D demo、手套关键点 demo、hdf5 演示、标定自检脚本 | `docs/demos.md` |
|
| 132 |
| `tools/hand_detection/` | 手部检测:YOLO 手套检测(`best.pt`、`world_detector.py`)、MediaPipe 裸手管线、`demo_stereo_hands.py` | `docs/hand_detection.md` |
|
| 133 |
-
| `scripts/` | 录制后离线处理:手部关键点提取/标注/可视化导出(`process_hands.py`) | `docs/scripts.md` |
|
| 134 |
| `tools/stereo_s80m/` | S80M 双目工具:`read_stereo_rgb.py`、`stereo_triangulate.py`、`render_stereo.py`、`hand_3d/`、离线 SLAM 导出(`export_offline_slam_dataset.py`、`validate_offline_dataset.py`) | `docs/stereo_s80m.md` |
|
| 135 |
| `tools/` | 诊断与手部 3D 工具:`diag_*.py`、`hand_3d_d435/`(独立 D435 3D 手部管线模块)、`hand_3d_s80c/`(S80C 双目实时裸手/手套关键点 demo,含自包含 SDK)、`fayssense_depth_sdk/`(FaysSense VI Kit 深度引擎 SDK,专有)、`glove_package/`、`tests/`(回归/冒烟测试)、`weights/`(大权重)、`models/`(模型权重) | `docs/tools.md` |
|
| 136 |
| `ui/` | PyQt5 界面:`main_window.py`、`camera_grid.py`、`playback_dialog.py`(回放)、`upload_dialog.py`、`task_page.py`、`device_panel.py`(设备检测面板)等 | `docs/ui.md` |
|
|
@@ -138,6 +139,7 @@ VENV_PY=/path/to/python ./tools/hand_3d_d435/run_live_d435.sh
|
|
| 138 |
| `keypoints_output/` | 录制后手部关键点输出(镜像录制目录结构,gitignore) | — |
|
| 139 |
| `dist/` | 自包含 demo 发布包(gitignore) | — |
|
| 140 |
| `venv/`、`tools/weights/` | 虚拟环境、CLIP 等大权重(均 gitignore) | — |
|
|
|
|
| 141 |
| `docs/` | 本文档目录 | — |
|
| 142 |
|
| 143 |
### 根目录文件
|
|
@@ -145,9 +147,9 @@ VENV_PY=/path/to/python ./tools/hand_3d_d435/run_live_d435.sh
|
|
| 145 |
| 文件 | 说明 |
|
| 146 |
|---|---|
|
| 147 |
| `main.py` | 主入口:qt-material `dark_teal` 暗色主题;先做 torch 可选导入(避免 DLL 冲突),并修复 cv2 覆盖 `QT_QPA_PLATFORM_PLUGIN_PATH` 导致的 Qt 平台插件加载问题,然后启动 `ui.main_window.MainWindow` |
|
| 148 |
-
| `start.bat` / `start.sh` | Windows / Linux 一键部署:无 Python 时自动安装、建 venv、装依赖并启动主程序;子命令 `reinstall` / `extras` / `extras-torch` / `help` |
|
| 149 |
| `.gitattributes` | 换行符规范化:`*.bat` 强制 CRLF,保证客户从 GitLab 下载后双击可用 |
|
| 150 |
-
| `requirements.txt` | 核心依赖:PyQt5、numpy(<2)、pyarrow、imageio-ffmpeg、bleak、qt-material、h5py、requests、pygrabber、comtypes、pyvista、pyvistaqt |
|
| 151 |
| `.gitignore` | 排除录制数据(`data/recordings/`、`data/*.db`)、真实配置文件、venv、keypoints_output、大权重等 |
|
| 152 |
| `run.sh` / `run.bat` | Linux / Windows 启动脚本(使用 venv 解释器运行 `main.py`) |
|
| 153 |
| `README.md` | 仓库说明(开发者向,中英双语合并版:英文在前、中文在后,顶部章节导航表) |
|
|
|
|
| 25 |
python -m venv venv && venv/bin/pip install -r requirements.txt
|
| 26 |
```
|
| 27 |
|
| 28 |
+
说明:`opencv-python`、`pyrealsense2`、`scipy` / `pydantic` / `polars` / `loguru`
|
| 29 |
+
(手套骨架解算)均在 `requirements.txt` 内;`mediapipe`、`torch` 等可选依赖未列入
|
| 30 |
(按需在 venv 内安装;`main.py` 对 torch 做可选导入,缺失时自动跳过)。
|
| 31 |
|
| 32 |
首次运行无需手动建配置:`data/tasks.json` 在首次读取时由程序写入内置种子
|
|
|
|
| 131 |
| `data/` | 本地配置(仓库提供 `*.example.json` 模板与出厂默认 `device_params.json`;其余配置、录制数据、SQLite 均 gitignore) | `docs/data.md`(本文档集) |
|
| 132 |
| `tools/demos/` | 交付版 demo:S80M 深度引擎 demo、双目 2D demo、手套关键点 demo、hdf5 演示、标定自检脚本 | `docs/demos.md` |
|
| 133 |
| `tools/hand_detection/` | 手部检测:YOLO 手套检测(`best.pt`、`world_detector.py`)、MediaPipe 裸手管线、`demo_stereo_hands.py` | `docs/hand_detection.md` |
|
| 134 |
+
| `scripts/` | 录制后离线处理:手部关键点提取/标注/可视化导出(`process_hands.py`);离线部署打包(`pack_wheels.py`)与手套工具包裁剪(`pack_toolkit.py`) | `docs/scripts.md` |
|
| 135 |
| `tools/stereo_s80m/` | S80M 双目工具:`read_stereo_rgb.py`、`stereo_triangulate.py`、`render_stereo.py`、`hand_3d/`、离线 SLAM 导出(`export_offline_slam_dataset.py`、`validate_offline_dataset.py`) | `docs/stereo_s80m.md` |
|
| 136 |
| `tools/` | 诊断与手部 3D 工具:`diag_*.py`、`hand_3d_d435/`(独立 D435 3D 手部管线模块)、`hand_3d_s80c/`(S80C 双目实时裸手/手套关键点 demo,含自包含 SDK)、`fayssense_depth_sdk/`(FaysSense VI Kit 深度引擎 SDK,专有)、`glove_package/`、`tests/`(回归/冒烟测试)、`weights/`(大权重)、`models/`(模型权重) | `docs/tools.md` |
|
| 137 |
| `ui/` | PyQt5 界面:`main_window.py`、`camera_grid.py`、`playback_dialog.py`(回放)、`upload_dialog.py`、`task_page.py`、`device_panel.py`(设备检测面板)等 | `docs/ui.md` |
|
|
|
|
| 139 |
| `keypoints_output/` | 录制后手部关键点输出(镜像录制目录结构,gitignore) | — |
|
| 140 |
| `dist/` | 自包含 demo 发布包(gitignore) | — |
|
| 141 |
| `venv/`、`tools/weights/` | 虚拟环境、CLIP 等大权重(均 gitignore) | — |
|
| 142 |
+
| `stouch_glove_toolkit*/` | 手套工具包(骨架解算运行时;由 `start.bat`/`start.sh` 的 `[4/7]` 从 `wheels/toolkit/glove_toolkit.zip` 展开到项目根,gitignore) | `docs/scripts.md`(`pack_toolkit.py`) |
|
| 143 |
| `docs/` | 本文档目录 | — |
|
| 144 |
|
| 145 |
### 根目录文件
|
|
|
|
| 147 |
| 文件 | 说明 |
|
| 148 |
|---|---|
|
| 149 |
| `main.py` | 主入口:qt-material `dark_teal` 暗色主题;先做 torch 可选导入(避免 DLL 冲突),并修复 cv2 覆盖 `QT_QPA_PLATFORM_PLUGIN_PATH` 导致的 Qt 平台插件加载问题,然后启动 `ui.main_window.MainWindow` |
|
| 150 |
+
| `start.bat` / `start.sh` | Windows / Linux 一键部署(7 步):无 Python 时自动安装、建 venv、装依赖、展开随包手套工具包(`[4/7]`,缺失只告警)、冒烟自检并启动主程序;子命令 `reinstall` / `extras` / `extras-torch` / `help` |
|
| 151 |
| `.gitattributes` | 换行符规范化:`*.bat` 强制 CRLF,保证客户从 GitLab 下载后双击可用 |
|
| 152 |
+
| `requirements.txt` | 核心依赖:PyQt5、numpy(<2)、opencv-python、pyarrow、imageio-ffmpeg、bleak、qt-material、h5py、requests、pygrabber、comtypes、pyvista、pyvistaqt、pyserial、**pyrealsense2**(D435/D405)+ 骨架解算组 **scipy / pydantic / polars / loguru**(共 19 项) |
|
| 153 |
| `.gitignore` | 排除录制数据(`data/recordings/`、`data/*.db`)、真实配置文件、venv、keypoints_output、大权重等 |
|
| 154 |
| `run.sh` / `run.bat` | Linux / Windows 启动脚本(使用 venv 解释器运行 `main.py`) |
|
| 155 |
| `README.md` | 仓库说明(开发者向,中英双语合并版:英文在前、中文在后,顶部章节导航表) |
|
|
@@ -1,8 +1,8 @@
|
|
| 1 |
-
# 复盘:轨迹「有棱有角」
|
| 2 |
|
| 3 |
-
2026-09-11
|
| 4 |
|
| 5 |
-
两个问题都是在「录下来/显示出来的东西不对」这一层被发现的,而且**都被先怀疑
|
| 6 |
成数据生成侧的故障**(SLAM 出点变慢、相机多投了帧)。实测结论都是:数据本身
|
| 7 |
没问题,问题出在**消费侧的一处边界处理**。
|
| 8 |
|
|
@@ -367,3 +367,161 @@ FAIL: 11 段疑似以「录制开始前」的帧开头
|
|
| 367 |
队列却漏了第三条。
|
| 368 |
4. **都必须有反向验证的回归测试**:`check_decimation` 把上限改回 400 必失败;
|
| 369 |
新测试去掉三处排空必失败、且复现原始症状。只在正向通过的测试不算数。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 复盘:轨迹「有棱有角」、RGB 段首旧帧与帧空洞
|
| 2 |
|
| 3 |
+
2026-09-11(一、二、三节);2026-09-18 续写第四节(RGB 帧空洞,v1.3.10)
|
| 4 |
|
| 5 |
+
前两个问题都是在「录下来/显示出来的东西不对」这一层被发现的,而且**都被先怀疑
|
| 6 |
成数据生成侧的故障**(SLAM 出点变慢、相机多投了帧)。实测结论都是:数据本身
|
| 7 |
没问题,问题出在**消费侧的一处边界处理**。
|
| 8 |
|
|
|
|
| 367 |
队列却漏了第三条。
|
| 368 |
4. **都必须有反向验证的回归测试**:`check_decimation` 把上限改回 400 必失败;
|
| 369 |
新测试去掉三处排空必失败、且复现原始症状。只在正向通过的测试不算数。
|
| 370 |
+
|
| 371 |
+
---
|
| 372 |
+
|
| 373 |
+
## 四、RGB 帧空洞(v1.3.10)
|
| 374 |
+
|
| 375 |
+
2026-09-18
|
| 376 |
+
|
| 377 |
+
### 4.1 现象与「空洞」的口径
|
| 378 |
+
|
| 379 |
+
用户报:`episode-099.mp4` 开头约 40 帧**静止不动**,像是「刚开始录制的视频流没存下来」。
|
| 380 |
+
实测两件事:
|
| 381 |
+
|
| 382 |
+
- 开头那 45 帧**是真帧**:场景本身静止(帧间差 mad 0.45 = 传感器噪声,不是编码器
|
| 383 |
+
重复帧的 0),且正好从按下录制那一刻开始 —— 老 bug(段首混入上一段残留帧)没有复发。
|
| 384 |
+
- 真正的缺陷是 **row44→row45 之间丢了 4.68 秒**:`hardware_ns` +4680.8ms、
|
| 385 |
+
`wall_time` +4666.4ms 同步跳。mp4 是定 30fps 容器,500 帧只播 16.67s,实际跨
|
| 386 |
+
21.32s ⇒ 播放表现为「静止 1.47s → 已经握在手里」,丢的正是操作者拿起夹爪那一段。
|
| 387 |
+
- 当时**全部计数器都是 0**(队列丢帧、重连、SLAM 丢帧……),日志里也没有一行异常
|
| 388 |
+
—— 事后翻遍日志也判断不出是相机侧没帧可读、emit 帧槽被覆盖,还是 GUI 主线程卡顿:
|
| 389 |
+
这三条路在 parquet 里留下**完全相同的空洞签名**。
|
| 390 |
+
|
| 391 |
+
口径(`core/frame_gap.GapWatch`,录制侧与离线审计**共用同一个类**,避免口径漂移):
|
| 392 |
+
|
| 393 |
+
```
|
| 394 |
+
空洞 = 相邻两帧时间差 − 标称帧间隔(30fps → 33.3ms)
|
| 395 |
+
```
|
| 396 |
+
|
| 397 |
+
只报「断了多久」,不判「丢了几帧」(帧率本就不恒定,反推帧数会给出看似精确实则错的
|
| 398 |
+
数字)。日志里 `[录制] RGB 帧空洞 4648ms` 报的是**空洞**不是间隔(4680.8 − 33.3)。
|
| 399 |
+
|
| 400 |
+
### 4.2 两个戳分别是谁盖的(本节最要紧的一条)
|
| 401 |
+
|
| 402 |
+
| parquet 列 | 谁盖的 | 量的是 |
|
| 403 |
+
|---|---|---|
|
| 404 |
+
| `hardware_ns` | **采集线程**,相机 `read()` 返回处(`bridge._rgb_run` 的 `time.monotonic_ns()`) | **取到帧的时刻**(宿主单调钟;帧晚到、读侧停顿都记在这里) |
|
| 405 |
+
| `wall_time` | **写入线程**,建行落盘处(`egodata_writer.py` 的 `time.time()`) | **写下来的时刻**(宿主墙钟) |
|
| 406 |
+
|
| 407 |
+
于是 **Δwall − Δhw = 中间那段队列的滞留变化量**(两个钟的固定偏移在差里抵消)。
|
| 408 |
+
2026-09-18 在全库上验过,`episode-011`:
|
| 409 |
+
|
| 410 |
+
| 行 | Δhw | Δwall | 偏移阶跃 | 读法 |
|
| 411 |
+
|---|---|---|---|---|
|
| 412 |
+
| row162 | 28.6ms | 167.2ms | **+138.7ms** | 写侧积压 139ms(帧没少,只是写晚) |
|
| 413 |
+
| row180 | 164.7ms | 33.5ms | **−131.3ms** | 读侧一段空窗把积压排空(帧晚到) |
|
| 414 |
+
|
| 415 |
+
两侧各停一次,**是两件事**,不是「同一个洞的两半」——这一点直接改掉了审计脚本早期的
|
| 416 |
+
一个设计(曾把相隔十几行的一墙一戳「配对」成一次事件,等于把两次停顿捏成一次、把账
|
| 417 |
+
记到错的桶里;该层已删除)。`episode-014 / 018 / 007` 是同一种形状(+220.7/−217.7、
|
| 418 |
+
+235.2/−224.8、+238.0/−228.5)。墙钟单独跳一下也可能是 NTP 校时,但本库的墙钟事件
|
| 419 |
+
都成对出现且互相抵消,不是校时。
|
| 420 |
+
|
| 421 |
+
**早年段的坑**:`trunc32` 段(≤078,74/95 段)的 `hardware_ns` 是同一个宿主单调钟被
|
| 422 |
+
截成**有符号 32 位**纳秒(±2^31,每 4.295 秒锯齿一次)。判空洞前必须先按 2^32 解卷;
|
| 423 |
+
反过来,对 64 位戳(≥079)也解卷会把真空洞折叠 —— ep-099 的 4680.8ms 会变成 385ms。
|
| 424 |
+
`tools/tests/test_audit_frame_gaps.py` 对这两种反向错误各有用例钉住。
|
| 425 |
+
|
| 426 |
+
### 4.3 判据:画面是硬证据,钟只用来定性
|
| 427 |
+
|
| 428 |
+
单看时钟只能得出「有一段时间没有帧」,**是不是画面上真断了一截,必须看画面**。
|
| 429 |
+
审计脚本把整段视频降采样成灰度,比较事件前后两帧的差(mad)与两个参照:
|
| 430 |
+
|
| 431 |
+
```
|
| 432 |
+
boundary = mad(第 row−1 帧, 第 row 帧) ← 事件处
|
| 433 |
+
near = 同段 ±15 帧内相邻帧差的中位数 ← 「正常一帧动多少」
|
| 434 |
+
sat = 每隔 60 帧取一对的中位差 ← 「这段视频能动到多大」
|
| 435 |
+
```
|
| 436 |
+
|
| 437 |
+
| 判据 | 结论 |
|
| 438 |
+
|---|---|
|
| 439 |
+
| `boundary ≤ 2.0 × near` | **画面连续** ⇒ 这一起不是丢帧 |
|
| 440 |
+
| `boundary ≥ 3.0 × near` 或 `≥ 0.7 × sat` | **画面跳变** ⇒ 丢了 |
|
| 441 |
+
| 介于两者之间 | **不定** ⇒ 回落钟口径,进「待复核」 |
|
| 442 |
+
| `near` 与 `boundary` 都 < 1.5(8 位灰度噪声地板,静止场景实测 0.45) | **不定** —— 静止画面里丢一段也看不出来,**不许反着判「没丢」** |
|
| 443 |
+
|
| 444 |
+
标定(2026-09-18):真丢的两处 `ep-099 row45 = 18.6×`、`ep-098 row40 = 91.6×`
|
| 445 |
+
(对饱和 0.75 / 1.62×);而 15 个「双钟都跳 ~250ms」的事件全是 0.16~1.60×,
|
| 446 |
+
即 boundary **正好是一帧的运动量**(钟却说过了 8 帧)——它们不是丢帧。
|
| 447 |
+
`diag_frame_trace.py` 那条经验同样适用:**判据必须带同窗对照,裸 mad 会判错**。
|
| 448 |
+
|
| 449 |
+
### 4.4 全库基线(95 段,2026-09-18)
|
| 450 |
+
|
| 451 |
+
```
|
| 452 |
+
venv/bin/python tools/audit_frame_gaps.py # 只读;有画面证实丢帧时退出码 1
|
| 453 |
+
```
|
| 454 |
+
|
| 455 |
+
| 归账 | 段数 | 累计 | 含义 |
|
| 456 |
+
|---|---|---|---|
|
| 457 |
+
| **画面证实丢了** | **25** | **37412.6ms** | 画面真断了一截(最大 4647.5ms @ 段099) |
|
| 458 |
+
| 钟跳但画面连续 | 72 | 20076.2ms | 有停顿、画面接得上(帧到得晚 / 写得晚) |
|
| 459 |
+
| 写侧打嗝 | 43 | 9944.8ms | 墙钟洞而戳只走一帧 ⇒ 帧没少、只是写晚 |
|
| 460 |
+
| 待复核 | 0 | 0ms | 画面判不了或未复核 |
|
| 461 |
+
|
| 462 |
+
- 25 起丢帧 = **23 段早年段(006~055)+ 2 段(098 / 099)**,**全部落在开录后
|
| 463 |
+
0.13~1.47s**;其中 18 起 ≥1s、7 起 <1s。这不是随机掉帧,是启动窗口的问题。
|
| 464 |
+
- 画面复核实际覆盖 85 段(有事件的段才解码;95 段的 mp4 帧数与 parquet 行数**全部一致**)。
|
| 465 |
+
- 与「只按钟算」的差别:钟口径会把「戳跳了但画面是连的」也算成丢(那 20.1s 全是这
|
| 466 |
+
一类),又会把早年段启动窗口里只有戳跳、没有墙钟跳的洞判成「判不了」。**数字变了
|
| 467 |
+
是因为口径从「钟说跳了」换成了「画面真断了」** —— 后者才是用户看得见、也才是
|
| 468 |
+
数据集真正损失的那部分。
|
| 469 |
+
|
| 470 |
+
### 4.5 为什么全落在启动窗口(机制,数字自洽)
|
| 471 |
+
|
| 472 |
+
2.7 节量过:RGB 生产者实际跑 30.84fps(30.5~31.1),写线程恒定 30.0fps ⇒ 外部队列
|
| 473 |
+
(`maxsize=30`)按 **~0.84 帧/秒**回涨。于是:
|
| 474 |
+
|
| 475 |
+
- **段首队列是空的**:头一两秒只有 1~2 帧余量,一次停顿就直接落进画面(25 起全在
|
| 476 |
+
1.47s 之内)。
|
| 477 |
+
- **队列越深越能垫**:满仓 30 帧 = 1s 余量。后期最大的读侧停顿是
|
| 478 |
+
`ep-018 row291 = 257.8ms`(开录后 9.9s),而那时队列只积了 ~8 帧(0.27s)——
|
| 479 |
+
**刚好够**;写侧停顿(最长 `ep-014 row275 = 798.5ms`)根本不丢内容,队列涨一下
|
| 480 |
+
就吸收了。
|
| 481 |
+
- 代价是 2.7 节那条恒定 ~1s 滞后 —— 队列深度换的就是抗顿挫能力。
|
| 482 |
+
|
| 483 |
+
这是**推测**(每一环都有数,但没有一条日志能直接证明「那一刻队列里有几帧」)。真机
|
| 484 |
+
确认靠 4.6 的四层仪表:`readfail_max_ms ≈ gap_max_ms` 且 `reconnect_count ≥ 1` ⇒
|
| 485 |
+
相机/服务侧停摆;`readfail ≈ 0` 而 `overwrite_count` 大 ⇒ emit 侧没取走。
|
| 486 |
+
|
| 487 |
+
### 4.6 本次做了什么(只装仪表 + 留档)
|
| 488 |
+
|
| 489 |
+
用户拍板:**本次只让下次复现时日志直接指认是哪一层,不改录制通路行为**。
|
| 490 |
+
(明确不做:录制通路与显示解耦、相机侧自愈、外部队列 `maxsize` 改小。)
|
| 491 |
+
|
| 492 |
+
| 层 | 指标(parquet `drop_stats` 的键) | 实时告警 |
|
| 493 |
+
|---|---|---|
|
| 494 |
+
| 落盘侧 | `<slot>_gap_ms` / `_gap_max_ms` / `_gap_count` | `[录制] RGB 帧空洞 …ms(槽 …,开录后 …s 起)` |
|
| 495 |
+
| 采集侧 | `<slot>_readfail_ms` / `_readfail_max_ms` / `_readfail_stall_count` / `_reconnect_count` | `[夹爪-RGB告警] RGB 采集停摆 …s` / `…已恢复`(进入一次 / 30s 限频 / 恢复一次) |
|
| 496 |
+
| emit 与派发 | `<slot>_overwrite_count` / `_emit_lag_max_ms` / `_dispatch_lag_max_ms` | 录制结束汇总行(值 >0 才打) |
|
| 497 |
+
| camera-service | `logs/camera_service/<时刻>_<tag>_camera-service.log`(留最近 20 份)+ 告警摘录进 `logs/main.log` | 摘录只在有告警时打 |
|
| 498 |
+
|
| 499 |
+
键的约定(`core/pipeline.is_frame_drop_key`):**新键全带 `_ms`/`_count` 后缀**,
|
| 500 |
+
不计进「丢帧统计」的帧数里(`[录制] 丢帧统计` 与「换编码器」提示一个字没改)。
|
| 501 |
+
后缀是硬约束,不是风格:采集侧读数里有几个键(停摆次数曾叫 `readfail_episodes`)
|
| 502 |
+
不在后缀表里,会**原样被当成帧数加进「丢帧统计」**——正是本次要消灭的那类混淆。
|
| 503 |
+
现在 `test_gripper_bridge` 逐个键走一遍 `rgb_quality_snapshot()`,`test_drop_stats`
|
| 504 |
+
的真值表覆盖全部 10 个会落盘的诊断键。
|
| 505 |
+
留档与摘录失败一律只记一行日志,绝不打断清理流程;**不含体积上限**(每 5 秒一行
|
| 506 |
+
stats,量本就极小),与 `fays_single.py` 的 slam_native 留档逐字同构。
|
| 507 |
+
|
| 508 |
+
### 4.7 回归与验收
|
| 509 |
+
|
| 510 |
+
```bash
|
| 511 |
+
# 离线自检(都不需要硬件;rc=0 且要看得到 PASS 行)
|
| 512 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python tools/tests/test_frame_gap.py
|
| 513 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python tools/tests/test_rgb_quality.py
|
| 514 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python tools/tests/test_ext_frame_gap.py
|
| 515 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python tools/tests/test_camera_log_archive.py
|
| 516 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python tools/tests/test_audit_frame_gaps.py
|
| 517 |
+
# 全库审计(只读)
|
| 518 |
+
venv/bin/python tools/audit_frame_gaps.py
|
| 519 |
+
```
|
| 520 |
+
|
| 521 |
+
真机验收(录音 30s+ 后看):① `[夹爪-RGB告警]` 与恢复行;② `[录制] RGB 帧空洞 …ms`;
|
| 522 |
+
③ `logs/main.log` 里的 `[UVC] camera-service 告警摘录` + 留档路径;
|
| 523 |
+
④ `logs/camera_service/` 下有 `<时刻>_bus*-port*_camera-service.log`;
|
| 524 |
+
⑤ parquet 的 `drop_stats` 含 `*_gap_*`,且 `[录制] 丢帧统计` 的帧数里**没有**它们。
|
| 525 |
+
|
| 526 |
+
**遗留**:2.7 节那条「外部队列 maxsize 30 → ~4」的建议**仍未实施**(滞后 1s → 0.13s,
|
| 527 |
+
但抗顿挫变浅);本次不动录制时序,留给后续按真机证据决策。
|
|
@@ -2,16 +2,17 @@
|
|
| 2 |
|
| 3 |
## 定位
|
| 4 |
|
| 5 |
-
`scripts/` 提供
|
| 6 |
|
| 7 |
-
主程序不调用这些脚本(全库检索 `scripts/` 除 `scripts/` 自身外无任何引用)。`process_hands.py` 反向依赖 `core/`(`core.hand_tracking` 与 `core.helpers`);`pack_wheels.py` 零 core 依赖。
|
| 8 |
|
| 9 |
## 文件清单
|
| 10 |
|
| 11 |
| 文件 | 一句话作用 | 运行方式 |
|
| 12 |
|---|---|---|
|
| 13 |
| `scripts/process_hands.py` | 手部关键点提取(2D+可选 3D)、手势自动标注、可视化渲染,子命令 `kpts/label/all/show/render` | `python scripts/process_hands.py kpts <session> --mode bare` |
|
| 14 |
-
| `scripts/pack_wheels.py` | 生成 Windows 3.12 离线部署包(`wheels/`:依赖轮子 + Python 安装包),供客户无外网一键安装 | `python scripts/pack_wheels.py [--extras|--torch|--out]` |
|
|
|
|
| 15 |
|
| 16 |
## 各文件详解
|
| 17 |
|
|
@@ -58,8 +59,32 @@
|
|
| 58 |
| `main` | 参数解析 | — | — |
|
| 59 |
|
| 60 |
**关键数据**:
|
| 61 |
-
- 参数:`--extras`(+ mediapipe
|
| 62 |
- 镜像链:阿里云 → 清华 → 官方源(与 start.bat 安装顺序一致)
|
| 63 |
-
- 产物:`<out>/*.whl`(Windows 3.12 依赖闭包)+ `<out>/python-3.12.10-amd64.exe`
|
|
|
|
| 64 |
|
| 65 |
-
**调用关系**:不 import 仓库任何模块(纯标准库);产物被 `start.bat`/`start.sh` 的离线安装逻辑消费。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
## 定位
|
| 4 |
|
| 5 |
+
`scripts/` 提供三类离线 CLI:对已录制会话的离线批处理(手部关键点提取与手势标注、可视化渲染导出)、Windows 离线部署包打包,以及随包分发的手套工具包裁剪。`process_hands.py` 在开头把仓库根目录插入 `sys.path`,从任意位置以 `python scripts/xxx.py ...` 运行即可(`pack_wheels.py` 与 `pack_toolkit.py` 只依赖标准库,无此 shim)。
|
| 6 |
|
| 7 |
+
主程序不调用这些脚本(全库检索 `scripts/` 除 `scripts/` 自身外无任何引用)。`process_hands.py` 反向依赖 `core/`(`core.hand_tracking` 与 `core.helpers`);`pack_wheels.py`、`pack_toolkit.py` 零 core 依赖(后者用子进程/独立解释器校验解算链)。
|
| 8 |
|
| 9 |
## 文件清单
|
| 10 |
|
| 11 |
| 文件 | 一句话作用 | 运行方式 |
|
| 12 |
|---|---|---|
|
| 13 |
| `scripts/process_hands.py` | 手部关键点提取(2D+可选 3D)、手势自动标注、可视化渲染,子命令 `kpts/label/all/show/render` | `python scripts/process_hands.py kpts <session> --mode bare` |
|
| 14 |
+
| `scripts/pack_wheels.py` | 生成 Windows 3.12 离线部署包(`wheels/`:依赖轮子 + Python 安装包 + 手套工具包 zip),供客户无外网一键安装 | `python scripts/pack_wheels.py [--extras|--torch|--lite|--no-toolkit|--out]` |
|
| 15 |
+
| `scripts/pack_toolkit.py` | 裁剪手套工具包(`stouch_glove_toolkit*`)成随包分发的小压缩包,使普通版一键部署自带骨架解算 | `python scripts/pack_toolkit.py [--src|--out|--keep|--no-verify|--no-zip]` |
|
| 16 |
|
| 17 |
## 各文件详解
|
| 18 |
|
|
|
|
| 59 |
| `main` | 参数解析 | — | — |
|
| 60 |
|
| 61 |
**关键数据**:
|
| 62 |
+
- 参数:`--extras`(+ mediapipe)、`--torch`(+ CPU 版 torch,走阿里云/官方 CPU 索引)、`--lite`(仅 `requirements-lite.txt`,**不裁工具包**)、`--no-toolkit`(只打依赖轮子)、`--out <dir>`(默认 `wheels/`)、`--no-python-installer`
|
| 63 |
- 镜像链:阿里云 → 清华 → 官方源(与 start.bat 安装顺序一致)
|
| 64 |
+
- 产物:`<out>/*.whl`(Windows 3.12 依赖闭包)+ `<out>/python-3.12.10-amd64.exe` + `<out>/toolkit/glove_toolkit.zip`(默认调用 `pack_toolkit.py` 裁出;`--lite` / `--no-toolkit` 时跳过,失败只告警)
|
| 65 |
+
- 注意:工具包 zip 必须放在 `wheels/` 的**子目录**里,放根下会被 `pip install --find-links wheels` 当源码包解析
|
| 66 |
|
| 67 |
+
**调用关系**:不 import 仓库任何模块(纯标准库);默认以子进程调用 `scripts/pack_toolkit.py`(`--lite`/`--no-toolkit` 除外);产物被 `start.bat`/`start.sh` 的离线安装逻辑(含 `[4/7]` 展开工具包)消费。
|
| 68 |
+
|
| 69 |
+
### `scripts/pack_toolkit.py`
|
| 70 |
+
|
| 71 |
+
**作用**:把项目根同级的手套工具包(`stouch_glove_toolkit*`,本地参考副本约 2.1GB)按白名单裁成约 6.0MB 的 `wheels/toolkit/glove_toolkit.zip`,使普通版一键部署自带实时骨架解算(解算链由 `core/glove_keypoint_solver.py` 的 `find_toolkit_dir()` 按目录名在项目根查找,故解压后须落在项目根同级)。
|
| 72 |
+
|
| 73 |
+
**类/函数**:
|
| 74 |
+
|
| 75 |
+
| 名称 | 签名要点 | 作用 | 返回/副作用 |
|
| 76 |
+
|---|---|---|---|
|
| 77 |
+
| `find_toolkit_dir` | `(src)` | 定位源工具包(默认扫项目根,`stouch_glove_toolkit*` 前缀;多个时取第一个并告警) | `Path` |
|
| 78 |
+
| `copy_trimmed` | `(src, dst)` | 按白名单拷进 `dst`(清空重建):`glove_sdk` / `glove_core` / `assets/hand_geometry` / `assets/hand`(`.npz`,排除 `models/`)+ 少量根文件;`calibration/` **只留** `*_default.json` | — |
|
| 79 |
+
| `verify` | `(toolkit)` | 在裁剪产物上**实跑**解算链:导入 → 构造 `HandSolver` → 喂单位四元数到 warmup 完成 → 断言关键点 `(21,3)` 且有限、手尺寸合理(左右手各一遍);用 `venv/bin/python`(或当前解释器)、`PYTHONDONTWRITEBYTECODE=1` 避免写 `__pycache__` | `bool` |
|
| 80 |
+
| `make_zip` | `(toolkit, zip_path)` | 打成 zip(含工具包目录名一层,解压即落在项目根),过滤 `__pycache__` / `.pyc` | 写 `<out>/toolkit/glove_toolkit.zip` |
|
| 81 |
+
| `main` | 参数解析 | — | — |
|
| 82 |
+
|
| 83 |
+
**关键数据**:
|
| 84 |
+
- 参数:`--src <dir>`(源工具包)、`--out <dir>`(默认 `wheels/`)、`--keep <dir>`(另留一份展开副本,可直接拷到项目根)、`--no-verify`(跳过实跑校验)、`--no-zip`(只出展开目录)
|
| 85 |
+
- 保留(解算运行时闭包):`glove_sdk`、`glove_core`、`assets/hand_geometry`、`assets/hand` 的 `.npz`、`calibration/imu_calibration_{left,right}_default.json`
|
| 86 |
+
- 剔除及原因(`DROP_NOTE`):`.venv`(2.1G,依赖由本仓库 `requirements.txt` 装)、`apps`(GUI/标定界面,解算链不导入)、`firmware`、`glove_io`、`glove_runtime`、`tools`、`assets/hand/models`(MANO `.pkl`,`HandNumpy` 只读 `.npz`)、`imu_log.csv`、文档等
|
| 87 |
+
- 刻意**不**带开发机上那只手套的带时间戳标定:`core/glove_keypoint_solver.py:pick_calibration()` 按 `generated_at` 取最新,带过去会被优先选中(骨架解成别人的手)
|
| 88 |
+
- 客户机项目根若已有 `stouch_glove_toolkit*/`,`start.bat`/`start.sh` 的 `[4/7]` 原样复用、不覆盖
|
| 89 |
+
|
| 90 |
+
**调用关系**:被 `scripts/pack_wheels.py` 默认以子进程调用;也可独立运行。产物由 `start.bat`/`start.sh` 的 `[4/7]` 步骤展开到项目根。
|
|
@@ -13,6 +13,7 @@
|
|
| 13 |
| `tools/diag_color.py` | S80M 子进程 pipe 输出一帧的颜色通道诊断(需 `FAYSSENSE_SDK_DIR`) |
|
| 14 |
| `tools/diag_frame_layout.py` | ctypes 直连 FaysSense SDK 打印标定/帧布局/双目相关性(需 `FAYSSENSE_SDK_DIR`) |
|
| 15 |
| `tools/diag_frame_trace.py` | 陈旧帧取证:判「只戳错(H1)」还是「旧帧被重投递(H2)」(离线读取证目录,不需相机) |
|
|
|
|
| 16 |
| `tools/hand_3d_d435/` | D435 RGB-D 单目 3D 手部关键点独立模块(实时 demo + 离线批处理 + 验收探针) |
|
| 17 |
| `tools/hand_3d_d435/probes/` | 6 个离线验收探针(对齐/一致性/完整性/标签/传播/骨长) |
|
| 18 |
| `tools/hand_3d_d435/tools/` | 3 个配套小工具(parquet 渲染、交付版 demo 导出、标定提取) |
|
|
@@ -307,7 +308,7 @@ YOLO-World 检测 + RTMPose 姿态的自包含工具箱(11 个 .py),专为
|
|
| 307 |
|
| 308 |
## 诊断工具
|
| 309 |
|
| 310 |
-
|
| 311 |
|
| 312 |
#### `diag_color.py`
|
| 313 |
|
|
@@ -371,9 +372,57 @@ mad 与正常帧间差分不开 —— 第一版判据(比 mad 与全场基线
|
|
| 371 |
比对窗、常量与 `fays_raw_client.py` 逐字一致、残尾/多分片/缺 `capture.json`、
|
| 372 |
恒定相位偏移、零下陷时的结论行。
|
| 373 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
## tests/ 测试
|
| 375 |
|
| 376 |
-
|
| 377 |
|
| 378 |
| 文件 | 类型 | 一句话 |
|
| 379 |
| --- | --- | --- |
|
|
@@ -393,3 +442,8 @@ mad 与正常帧间差分不开 —— 第一版判据(比 mad 与全场基线
|
|
| 393 |
| `d435_gui_smoke_test.py` | 真机 | D435 GUI 冒烟 |
|
| 394 |
| `d435_playback_test.py` | 真机 | D435 回放 |
|
| 395 |
| `mono_regression.py` | 真机 | 单目回归 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
| `tools/diag_color.py` | S80M 子进程 pipe 输出一帧的颜色通道诊断(需 `FAYSSENSE_SDK_DIR`) |
|
| 14 |
| `tools/diag_frame_layout.py` | ctypes 直连 FaysSense SDK 打印标定/帧布局/双目相关性(需 `FAYSSENSE_SDK_DIR`) |
|
| 15 |
| `tools/diag_frame_trace.py` | 陈旧帧取证:判「只戳错(H1)」还是「旧帧被重投递(H2)」(离线读取证目录,不需相机) |
|
| 16 |
+
| `tools/audit_frame_gaps.py` | 帧空洞全库审计:画面复核判「真丢/画面连续/判不了」+ 双钟定性(只读,见「诊断工具」节) |
|
| 17 |
| `tools/hand_3d_d435/` | D435 RGB-D 单目 3D 手部关键点独立模块(实时 demo + 离线批处理 + 验收探针) |
|
| 18 |
| `tools/hand_3d_d435/probes/` | 6 个离线验收探针(对齐/一致性/完整性/标签/传播/骨长) |
|
| 19 |
| `tools/hand_3d_d435/tools/` | 3 个配套小工具(parquet 渲染、交付版 demo 导出、标定提取) |
|
|
|
|
| 308 |
|
| 309 |
## 诊断工具
|
| 310 |
|
| 311 |
+
三个离线取证脚本(都不需要相机/硬件;前两个需 `FAYSSENSE_SDK_DIR`,第三个只读录制产物)。
|
| 312 |
|
| 313 |
#### `diag_color.py`
|
| 314 |
|
|
|
|
| 372 |
比对窗、常量与 `fays_raw_client.py` 逐字一致、残尾/多分片/缺 `capture.json`、
|
| 373 |
恒定相位偏移、零下陷时的结论行。
|
| 374 |
|
| 375 |
+
#### `audit_frame_gaps.py`
|
| 376 |
+
|
| 377 |
+
**作用**:把「录下来的视频到底丢了多少」一次数清楚(**只读**,不写任何东西;
|
| 378 |
+
背景与全库基线见 [postmortem](postmortem_trajectory_and_rgb.md) 第四节)。
|
| 379 |
+
|
| 380 |
+
```bash
|
| 381 |
+
venv/bin/python tools/audit_frame_gaps.py [任务目录] [选项] # 默认 data/recordings/UMIGripper_Action_AI
|
| 382 |
+
```
|
| 383 |
+
|
| 384 |
+
选项:`--min-gap-ms 100`(相邻帧间隔 ≥ 该值才算异常)、`--clock-tol-ms 100`
|
| 385 |
+
(双钟互证容差)、`--merge-rows 15`(相隔 ≤N 行的异常并成一次事件)、
|
| 386 |
+
`--no-video-check`(跳过画面复核,只剩钟口径)、`--all`、`--json`、
|
| 387 |
+
`--camera-logs DIR`(关联 `logs/camera_service/` 的留档日志,秒级粗相关,默认关)。
|
| 388 |
+
|
| 389 |
+
**三层判据**(由强到弱):
|
| 390 |
+
|
| 391 |
+
| 层 | 判据 | 结论 |
|
| 392 |
+
|---|---|---|
|
| 393 |
+
| 1 画面复核 | 事件处两帧差 ÷ 同窗邻帧差中位 ≤2.0 | 画面连续 ⇒ **没丢**(帧到得晚/写得晚) |
|
| 394 |
+
| | ≥3.0 或 ≥0.7×远端饱和差 | 画面跳变 ⇒ **丢了** |
|
| 395 |
+
| | 其余(含整窗静止 <噪声地板 1.5) | 判不了 ⇒ 回落第 2/3 层,进「待复核」 |
|
| 396 |
+
| 2 双钟 | Δhw ≈ Δwall ≥ 阈值 | 两侧都这么说(无画面时按疑似计) |
|
| 397 |
+
| 3 单钟 | 只有墙钟跳 | **写侧打嗝**(帧按 33ms 到了、只是写晚) |
|
| 398 |
+
| | 只有戳跳 | **读侧停顿**(帧晚到,写侧靠队列垫住) |
|
| 399 |
+
|
| 400 |
+
**两个戳分别是谁盖的**(不认识这个会得出错结论):`hardware_ns` 由**采集线程**
|
| 401 |
+
在相机 `read()` 返回处盖(量「取到帧的时刻」,宿主单调钟;≤078 段是被截成**有符号
|
| 402 |
+
32 位**的同一个钟,每 4.295s 锯齿一次,必须先按 2^32 解卷);`wall_time` 由**写入
|
| 403 |
+
线程**在建行落盘处盖(量「写下来的时刻」,宿主墙钟)。因此 **Δwall − Δhw = 队列
|
| 404 |
+
滞留的变化量**:阶跃为正 = 写侧积压、为负 = 读侧空窗把积压排空 —— 这是区分「哪一
|
| 405 |
+
侧停了」的判据。
|
| 406 |
+
|
| 407 |
+
**归账四桶**(互斥,只第 1 桶算「证实丢了」):
|
| 408 |
+
|
| 409 |
+
```
|
| 410 |
+
画面跳变 → gap_ms(丢了) 只有墙钟跳 → wall_ms(写侧打嗝)
|
| 411 |
+
画面连续 → stamp_ms(没丢) 其余 → pending_ms(待复核,绝不计入损失)
|
| 412 |
+
```
|
| 413 |
+
|
| 414 |
+
**退出码**:有画面证实丢帧、或有待复核 → 1(「不上报等于把未知当没事」);否则 0。
|
| 415 |
+
2026-09-18 全库结果:95 段 / **画面证实丢了 25 段 37412.6ms**(23 段早年段 + 098/099,
|
| 416 |
+
**全部落在开录后 0.13~1.47s**)/ 钟跳但画面连续 72 段 20076.2ms / 写侧打嗝 43 段
|
| 417 |
+
9944.8ms / 待复核 0。
|
| 418 |
+
|
| 419 |
+
离线自检:`QT_QPA_PLATFORM=offscreen venv/bin/python tools/tests/test_audit_frame_gaps.py`
|
| 420 |
+
(10 组、全合成 fixture,不依赖真机数据;含「渐变条」画面模型使一帧运动量与 30 帧
|
| 421 |
+
运动量在数值上分得开,以及「静止场景不许判成没丢」的反向用例)。
|
| 422 |
+
|
| 423 |
## tests/ 测试
|
| 424 |
|
| 425 |
+
测试脚本见 `tools/tests/`(当前 56 份;离线测试加 `QT_QPA_PLATFORM=offscreen` 无需任何硬件,真机测试需对应设备在线)。完整运行命令见 `README.md` 测试节;下表是早期 16 份,末尾补上帧空洞相关的 5 份。
|
| 426 |
|
| 427 |
| 文件 | 类型 | 一句话 |
|
| 428 |
| --- | --- | --- |
|
|
|
|
| 442 |
| `d435_gui_smoke_test.py` | 真机 | D435 GUI 冒烟 |
|
| 443 |
| `d435_playback_test.py` | 真机 | D435 回放 |
|
| 444 |
| `mono_regression.py` | 真机 | 单目回归 |
|
| 445 |
+
| `test_frame_gap.py` | 离线 | 帧空洞看门狗纯类(口径、混源不造假空洞、负值戳) |
|
| 446 |
+
| `test_rgb_quality.py` | 离线 | 采集侧停摆告警去抖 + 覆盖/滞后峰值仪表 |
|
| 447 |
+
| `test_ext_frame_gap.py` | 离线 | 落盘侧空洞端到端(含 parquet `*_gap_*` 注入) |
|
| 448 |
+
| `test_camera_log_archive.py` | 离线 | camera-service 日志留档 + 告警摘录(健康会话零命中) |
|
| 449 |
+
| `test_audit_frame_gaps.py` | 离线 | 审计脚本三层判据/四桶/退出码(全合成 fixture) |
|
|
@@ -24,6 +24,14 @@ try:
|
|
| 24 |
except ImportError:
|
| 25 |
pass
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
from PyQt5.QtWidgets import QApplication, QDesktopWidget
|
| 28 |
from PyQt5.QtCore import Qt
|
| 29 |
from PyQt5.QtGui import QFontDatabase # noqa: F401 — qt-material 需要
|
|
|
|
| 24 |
except ImportError:
|
| 25 |
pass
|
| 26 |
|
| 27 |
+
# ── 运行环境守卫(在 PyQt5 之前、torch 之后: 顺序不能动)──────────
|
| 28 |
+
# 用错解释器(没激活 venv / 激活了 conda 或别的 venv)时,真正的报错是
|
| 29 |
+
# "No module named 'PyQt5'" 这种看不出该怎么办的信息。这里提前判断关键
|
| 30 |
+
# 依赖是否真的缺,缺了就直接给出可照抄的启动命令(细节见模块注释)。
|
| 31 |
+
from core.startup_guard import enforce as _enforce_env
|
| 32 |
+
|
| 33 |
+
_enforce_env(_base, "main")
|
| 34 |
+
|
| 35 |
from PyQt5.QtWidgets import QApplication, QDesktopWidget
|
| 36 |
from PyQt5.QtCore import Qt
|
| 37 |
from PyQt5.QtGui import QFontDatabase # noqa: F401 — qt-material 需要
|
|
@@ -15,6 +15,14 @@ import os
|
|
| 15 |
_base = os.path.dirname(os.path.abspath(__file__))
|
| 16 |
sys.path.insert(0, _base)
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
from PyQt5.QtWidgets import QApplication, QDesktopWidget
|
| 19 |
from PyQt5.QtCore import Qt
|
| 20 |
|
|
|
|
| 15 |
_base = os.path.dirname(os.path.abspath(__file__))
|
| 16 |
sys.path.insert(0, _base)
|
| 17 |
|
| 18 |
+
# ── 运行环境守卫(必须在 PyQt5 import 之前)────────────────────────
|
| 19 |
+
# 用错解释器(没激活 venv_lite / 激活了 conda 或别的 venv)时,真正的报错是
|
| 20 |
+
# "No module named 'PyQt5'" 这种看不出该怎么办的信息。这里提前判断关键依赖
|
| 21 |
+
# 是否真的缺,缺了就直接给出可照抄的启动命令(细节见模块注释)。
|
| 22 |
+
from core.startup_guard import enforce as _enforce_env
|
| 23 |
+
|
| 24 |
+
_enforce_env(_base, "lite")
|
| 25 |
+
|
| 26 |
from PyQt5.QtWidgets import QApplication, QDesktopWidget
|
| 27 |
from PyQt5.QtCore import Qt
|
| 28 |
|
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# 极简采集版依赖白名单(start_lite.bat / start_lite.sh 使用)
|
| 2 |
# 只保留: 连接设备 → 采集(parquet+MP4) → 上传。
|
| 3 |
-
# 不含回放/登录/任务页/骨架解算(toolkit/scipy/loguru/pydantic)/pyvista 等重型依赖。
|
| 4 |
# 注意: imageio-ffmpeg(约 77MB) 提供静态 ffmpeg 二进制(含 x264),
|
| 5 |
# 客户机无 PATH ffmpeg 时录制链必需;装有系统 ffmpeg 的机器可删掉本行。
|
| 6 |
# UVC 摄像头零新增依赖: Linux 走 sysfs 枚举;Windows 无 pygrabber 时
|
|
|
|
| 1 |
# 极简采集版依赖白名单(start_lite.bat / start_lite.sh 使用)
|
| 2 |
# 只保留: 连接设备 → 采集(parquet+MP4) → 上传。
|
| 3 |
+
# 不含回放/登录/任务页/骨架解算(toolkit/scipy/loguru/pydantic/polars)/pyvista 等重型依赖。
|
| 4 |
# 注意: imageio-ffmpeg(约 77MB) 提供静态 ffmpeg 二进制(含 x264),
|
| 5 |
# 客户机无 PATH ffmpeg 时录制链必需;装有系统 ffmpeg 的机器可删掉本行。
|
| 6 |
# UVC 摄像头零新增依赖: Linux 走 sysfs 枚举;Windows 无 pygrabber 时
|
|
@@ -13,9 +13,19 @@ comtypes>=1.4 # pygrabber 依赖
|
|
| 13 |
pyvista>=0.42
|
| 14 |
pyvistaqt>=0.11
|
| 15 |
pyserial>=3.5 # USB (Type-C) STM32 手套 CDC 串口
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
# ── 可选依赖(代码内惰性导入,缺失时对应功能不可用)──
|
| 18 |
# 一键安装: start.bat extras / start.bat extras-torch
|
| 19 |
-
# pyrealsense2 # Intel D435/D405 深度相机
|
| 20 |
# mediapipe # 裸手 3D 关键点(bare 模式)
|
| 21 |
# torch # 手部关键点 RTMPose 后端(CPU 版安装见 `start.bat extras-torch`)
|
|
|
|
| 13 |
pyvista>=0.42
|
| 14 |
pyvistaqt>=0.11
|
| 15 |
pyserial>=3.5 # USB (Type-C) STM32 手套 CDC 串口
|
| 16 |
+
pyrealsense2 # Intel D435/D405 深度相机(core/d435_camera.py 惰性导入,
|
| 17 |
+
# 缺则设备面板不识别 RealSense;深度走它自带的 librealsense)
|
| 18 |
+
|
| 19 |
+
# ── 手套实时骨架解算(普通版默认包含;start.sh 的 [4/7] 会校验这条链)──
|
| 20 |
+
# 解算本身走随包的手套工具包(stouch_glove_toolkit*,由 scripts/pack_toolkit.py
|
| 21 |
+
# 裁剪后经 wheels/toolkit/ 分发),但工具包要这几个包才能导入 —— 少任何一个
|
| 22 |
+
# 都会让骨架**静默不可用**(连上手套才在日志里报错,录制不受影响)。
|
| 23 |
+
scipy>=1.11 # glove_core.algorithm.solver 顶层 import(空间旋转)
|
| 24 |
+
pydantic>=2.9 # glove_core.protected.modules.datamodels
|
| 25 |
+
polars>=1.0 # glove_fk.fitting —— 经 glove_fk/__init__.py 间接导入
|
| 26 |
+
loguru>=0.7 # 工具包全链日志
|
| 27 |
|
| 28 |
# ── 可选依赖(代码内惰性导入,缺失时对应功能不可用)──
|
| 29 |
# 一键安装: start.bat extras / start.bat extras-torch
|
|
|
|
| 30 |
# mediapipe # 裸手 3D 关键点(bare 模式)
|
| 31 |
# torch # 手部关键点 RTMPose 后端(CPU 版安装见 `start.bat extras-torch`)
|
|
@@ -156,6 +156,15 @@ MODULE_FILES = {
|
|
| 156 |
"gripper_codec.py",
|
| 157 |
# core/gripper/bridge.py:39 顶层 import 它的双目丢帧窗口常量
|
| 158 |
"s80m_manager.py",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
],
|
| 160 |
}
|
| 161 |
|
|
@@ -322,9 +331,9 @@ def _verify_payload(out_dir: str, target: str) -> None:
|
|
| 322 |
if not os.path.isfile(os.path.join(out_dir, "core",
|
| 323 |
"gripper_codec.py")):
|
| 324 |
absent.append("core/gripper_codec.py")
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
if absent:
|
| 329 |
print(f"[失败] Windows 包缺夹爪代码(两个包都收 .py): {absent}")
|
| 330 |
sys.exit(1)
|
|
|
|
| 156 |
"gripper_codec.py",
|
| 157 |
# core/gripper/bridge.py:39 顶层 import 它的双目丢帧窗口常量
|
| 158 |
"s80m_manager.py",
|
| 159 |
+
# core/pipeline.py:19 顶层 import 的帧空洞看门狗(录制侧与
|
| 160 |
+
# tools/audit_frame_gaps.py 审计脚本共用同一份口径)
|
| 161 |
+
"frame_gap.py",
|
| 162 |
+
# core/pipeline.py / core/egodata_writer.py 顶层 import 的收尾
|
| 163 |
+
# 分段计时(v1.3.11 L0-1;漏了它 lite 一 import 就 ModuleNotFoundError)
|
| 164 |
+
"timing.py",
|
| 165 |
+
# main_lite.py 顶层 import 的启动环境守卫(用错解释器时给出启动
|
| 166 |
+
# 指引再退出;零第三方依赖,必须在包里)
|
| 167 |
+
"startup_guard.py",
|
| 168 |
],
|
| 169 |
}
|
| 170 |
|
|
|
|
| 331 |
if not os.path.isfile(os.path.join(out_dir, "core",
|
| 332 |
"gripper_codec.py")):
|
| 333 |
absent.append("core/gripper_codec.py")
|
| 334 |
+
for name in ("s80m_manager.py", "frame_gap.py"):
|
| 335 |
+
if not os.path.isfile(os.path.join(out_dir, "core", name)):
|
| 336 |
+
absent.append(f"core/{name}")
|
| 337 |
if absent:
|
| 338 |
print(f"[失败] Windows 包缺夹爪代码(两个包都收 .py): {absent}")
|
| 339 |
sys.exit(1)
|
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""裁剪手套工具包(stouch_glove_toolkit*)供随包分发,使普通版一键部署自带骨架解算。
|
| 3 |
+
|
| 4 |
+
背景: 骨架解算依赖第三方手套工具包(项目根同级的 stouch_glove_toolkit*,
|
| 5 |
+
core/glove_keypoint_solver.py 的 find_toolkit_dir() 按目录名找)。本地参考副本
|
| 6 |
+
2.1G,其中 2.1G 是 .venv/、7.3M 是 MANO 模型的 .pkl —— 解算路径两者都不需要,
|
| 7 |
+
真正的运行时闭包约 6M。
|
| 8 |
+
|
| 9 |
+
本脚本按白名单裁一份,并在裁剪产物上**实跑一遍解算链**(导入 → 构造 HandSolver
|
| 10 |
+
→ 喂帧到 warmup 完成 → 校验 (21,3) 关键点),确认裁掉的东西确实用不上。
|
| 11 |
+
|
| 12 |
+
用法:
|
| 13 |
+
python scripts/pack_toolkit.py # 裁一份 → wheels/toolkit/glove_toolkit.zip
|
| 14 |
+
python scripts/pack_toolkit.py --no-verify # 跳过实跑校验(没装依赖时)
|
| 15 |
+
python scripts/pack_toolkit.py --src DIR # 指定源工具包目录
|
| 16 |
+
python scripts/pack_toolkit.py --keep DIR # 同时留一份展开的目录
|
| 17 |
+
python scripts/pack_toolkit.py --out DIR # 自定义输出目录
|
| 18 |
+
|
| 19 |
+
产物:
|
| 20 |
+
<out>/toolkit/glove_toolkit.zip 解压后即为项目根同级的 stouch_glove_toolkit*/
|
| 21 |
+
<out>/toolkit/<工具包名>/ --keep 时的展开副本(可直接拷到项目根)
|
| 22 |
+
|
| 23 |
+
注意: zip 必须放在 wheels/ 的**子目录**里 —— 放在 wheels/ 根会让
|
| 24 |
+
start.bat 的 `pip install --find-links wheels` 把它当成源码包尝试解析。
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
import json
|
| 31 |
+
import os
|
| 32 |
+
import shutil
|
| 33 |
+
import subprocess
|
| 34 |
+
import sys
|
| 35 |
+
import tempfile
|
| 36 |
+
import zipfile
|
| 37 |
+
from pathlib import Path
|
| 38 |
+
|
| 39 |
+
ROOT = Path(__file__).resolve().parent.parent
|
| 40 |
+
TOOLKIT_PREFIX = "stouch_glove_toolkit"
|
| 41 |
+
|
| 42 |
+
# 解算路径的运行时闭包(白名单)。目录整体拷贝,单文件按名拷贝。
|
| 43 |
+
KEEP_DIRS = [
|
| 44 |
+
"glove_sdk", # HandSolver / RawImuFrame 等公开接口
|
| 45 |
+
"glove_core", # 算法与受保护运行时(含 glove_lite 手模型)
|
| 46 |
+
"assets/hand_geometry", # hand_measured_runtime_v1.json(几何)
|
| 47 |
+
"assets/hand", # HAND_LEFT/RIGHT_PINKY_PLUS_2MM.npz(手模型)
|
| 48 |
+
]
|
| 49 |
+
KEEP_FILES = [
|
| 50 |
+
"99-stm32-glove.rules", # Linux 免 root 访问 USB CDC 的 udev 规则
|
| 51 |
+
"glove_devices.json", # 设备配置(采集侧同款)
|
| 52 |
+
"config.json", # 工具包自带标定配置(param_inst_calib)
|
| 53 |
+
"config_left.json",
|
| 54 |
+
"bimanual_display_config.json",
|
| 55 |
+
"requirements.txt",
|
| 56 |
+
"README-SDK.md",
|
| 57 |
+
"QUICKSTART.md",
|
| 58 |
+
]
|
| 59 |
+
# 明确不要的(白名单之外的重物,注释写明原因,避免以后有人"顺手加回来")
|
| 60 |
+
DROP_NOTE = {
|
| 61 |
+
".venv": "工具包自带的虚拟环境 2.1G;依赖由本仓库 requirements.txt 统一装",
|
| 62 |
+
"apps": "GUI/标定界面,解算链不导入(已实测)",
|
| 63 |
+
"firmware": "固件源码,上位机不需要",
|
| 64 |
+
"glove_io": "独立 IO 程序",
|
| 65 |
+
"glove_runtime": "独立运行时壳",
|
| 66 |
+
"tools": "工具包自带小工具",
|
| 67 |
+
"assets/hand/models": "MANO_*.pkl 7.3M;HandNumpy 只读 .npz(已实测)",
|
| 68 |
+
"calibration": "只留两个 *_default.json —— 其它是开发机上这只手套的标定,"
|
| 69 |
+
"带过去会被 pick_calibration 按时间戳优先选中(见下)",
|
| 70 |
+
"imu_log.csv": "1.4M 实测日志",
|
| 71 |
+
"hand_kinematics_guide.html": "文档",
|
| 72 |
+
"pyarmor.bug.log": "打包日志",
|
| 73 |
+
"ENCRYPTION.md": "加密说明(本地明文版用不到)",
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def find_toolkit_dir(src: Path | None) -> Path:
|
| 78 |
+
"""定位源工具包目录(默认扫项目根,与 find_toolkit_dir() 同口径)。"""
|
| 79 |
+
if src is not None:
|
| 80 |
+
if not src.is_dir():
|
| 81 |
+
sys.exit(f"[错误] --src 不是目录: {src}")
|
| 82 |
+
return src
|
| 83 |
+
cands = sorted(p for p in ROOT.iterdir()
|
| 84 |
+
if p.is_dir() and p.name.lower().startswith(TOOLKIT_PREFIX))
|
| 85 |
+
if not cands:
|
| 86 |
+
sys.exit(f"[错误] 项目根未找到 {TOOLKIT_PREFIX}* 目录(用 --src 指定)")
|
| 87 |
+
if len(cands) > 1:
|
| 88 |
+
print(f"[警告] 找到多个工具包目录,取第一个: {cands[0].name}")
|
| 89 |
+
print(f" 全部: {', '.join(p.name for p in cands)}")
|
| 90 |
+
return cands[0]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def copy_trimmed(src: Path, dst: Path) -> None:
|
| 94 |
+
"""按白名单把 src 裁进 dst(dst 会被清空重建)。"""
|
| 95 |
+
if dst.exists():
|
| 96 |
+
shutil.rmtree(dst)
|
| 97 |
+
# models/ 是 assets/hand/models/MANO_*.pkl(7.3M),HandNumpy 只读 .npz,
|
| 98 |
+
# 拷贝时就排除,省得先拷后删
|
| 99 |
+
ignore = shutil.ignore_patterns("__pycache__", "*.pyc", "*.pyo", "models")
|
| 100 |
+
for rel in KEEP_DIRS:
|
| 101 |
+
s = src / rel
|
| 102 |
+
if not s.is_dir():
|
| 103 |
+
sys.exit(f"[错误] 源工具包缺少必需目录: {rel}")
|
| 104 |
+
shutil.copytree(s, dst / rel, ignore=ignore)
|
| 105 |
+
for name in KEEP_FILES:
|
| 106 |
+
s = src / name
|
| 107 |
+
if s.is_file():
|
| 108 |
+
shutil.copy2(s, dst / name)
|
| 109 |
+
# 标定:只留随包默认标定。带时间戳的标定属于开发��上那只手套,
|
| 110 |
+
# 一旦被带到客户机,core/glove_keypoint_solver.py 的 pick_calibration
|
| 111 |
+
# 会按 generated_at 优先选中它 —— 骨架会解成别人的手。
|
| 112 |
+
cal_src, cal_dst = src / "calibration", dst / "calibration"
|
| 113 |
+
cal_dst.mkdir(parents=True, exist_ok=True)
|
| 114 |
+
kept = []
|
| 115 |
+
for f in sorted(cal_src.glob("*_default.json")):
|
| 116 |
+
shutil.copy2(f, cal_dst / f.name)
|
| 117 |
+
kept.append(f.name)
|
| 118 |
+
if not kept:
|
| 119 |
+
sys.exit("[错误] 源工具包 calibration/ 下没有 *_default.json")
|
| 120 |
+
print(f" calibration/: 保留 {len(kept)} 个默认标定 → {', '.join(kept)}")
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _python() -> str:
|
| 124 |
+
"""校验用的解释器:优先本仓库 venv(依赖齐全)。"""
|
| 125 |
+
for rel in ("venv/bin/python", "venv/Scripts/python.exe"):
|
| 126 |
+
p = ROOT / rel
|
| 127 |
+
if p.exists():
|
| 128 |
+
return str(p)
|
| 129 |
+
return sys.executable
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
VERIFY_SNIPPET = r'''
|
| 133 |
+
import os, sys, time
|
| 134 |
+
import numpy as np
|
| 135 |
+
TK = sys.argv[1]
|
| 136 |
+
sys.path.insert(0, TK)
|
| 137 |
+
from glove_sdk.interfaces.solver import HandSolver
|
| 138 |
+
from glove_sdk.types import RawImuFrame
|
| 139 |
+
|
| 140 |
+
for side in ("left", "right"):
|
| 141 |
+
calib = os.path.join(TK, "calibration", f"imu_calibration_{side}_default.json")
|
| 142 |
+
geom = os.path.join(TK, "assets", "hand_geometry", "hand_measured_runtime_v1.json")
|
| 143 |
+
s = HandSolver(side, calib, geom)
|
| 144 |
+
q = np.zeros((16, 4)); q[:, 3] = 1.0 # 16×单位四元数(静止姿)
|
| 145 |
+
warm = None
|
| 146 |
+
for i in range(1, 601):
|
| 147 |
+
kf = s.process(RawImuFrame(
|
| 148 |
+
sequence=i, device_timestamp_us=i * 10000,
|
| 149 |
+
host_timestamp_us=time.time_ns() // 1000,
|
| 150 |
+
quaternions_xyzw=q,
|
| 151 |
+
present_mask=np.ones(16, bool), valid_mask=np.ones(16, bool)))
|
| 152 |
+
if warm is None and getattr(getattr(kf, "status", None),
|
| 153 |
+
"details", {}).get("warmup_completed"):
|
| 154 |
+
warm = i
|
| 155 |
+
if warm and i == warm + 3:
|
| 156 |
+
j = np.asarray(kf.joints_m, np.float64)
|
| 157 |
+
assert j.shape == (21, 3), f"{side}: 关键点形状 {j.shape} != (21,3)"
|
| 158 |
+
assert np.isfinite(j).all(), f"{side}: 关键点含 NaN/Inf"
|
| 159 |
+
span = j.max(0) - j.min(0)
|
| 160 |
+
assert 0.02 < float(span.max()) < 0.5, f"{side}: 手尺寸异常 {span}"
|
| 161 |
+
print(f" {side}: warmup {warm} 帧, 关键点 (21,3), "
|
| 162 |
+
f"包围盒 {np.round(span, 3)} m")
|
| 163 |
+
break
|
| 164 |
+
else:
|
| 165 |
+
raise SystemExit(f"{side}: 600 帧内未完成 warmup")
|
| 166 |
+
'''
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def verify(toolkit: Path) -> bool:
|
| 170 |
+
"""在裁剪产物上实跑解算链(左右手各一遍)。返回是否通过。"""
|
| 171 |
+
py = _python()
|
| 172 |
+
print(f" 校验解释器: {py}")
|
| 173 |
+
# 校验会 import 整条链,默认会往产物里写 __pycache__/*.pyc —— 那是构建垃圾,
|
| 174 |
+
# 别让它进交付物(客户机 Python 小版本不同还会被判为陈旧而重编)
|
| 175 |
+
env = {**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}
|
| 176 |
+
proc = subprocess.run([py, "-c", VERIFY_SNIPPET, str(toolkit)],
|
| 177 |
+
capture_output=True, text=True, env=env)
|
| 178 |
+
ok = proc.returncode == 0
|
| 179 |
+
for line in (proc.stdout or "").splitlines():
|
| 180 |
+
if line.strip():
|
| 181 |
+
print(f" {line}" if line.startswith(" ") else f" {line}")
|
| 182 |
+
if not ok:
|
| 183 |
+
print(" [失败] 裁剪产物跑不了解算链,stderr 末 20 行:")
|
| 184 |
+
for line in (proc.stderr or "").strip().splitlines()[-20:]:
|
| 185 |
+
print(f" {line}")
|
| 186 |
+
return ok
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def make_zip(toolkit: Path, zip_path: Path) -> None:
|
| 190 |
+
"""打包成 zip(含工具包目录名一层,解压即落在项目根)。"""
|
| 191 |
+
zip_path.parent.mkdir(parents=True, exist_ok=True)
|
| 192 |
+
n = 0
|
| 193 |
+
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as z:
|
| 194 |
+
for p in sorted(toolkit.rglob("*")):
|
| 195 |
+
# 防御性过滤:任何路径下都不收字节码缓存
|
| 196 |
+
if not p.is_file() or p.suffix in (".pyc", ".pyo"):
|
| 197 |
+
continue
|
| 198 |
+
if "__pycache__" in p.parts:
|
| 199 |
+
continue
|
| 200 |
+
z.write(p, Path(toolkit.name) / p.relative_to(toolkit))
|
| 201 |
+
n += 1
|
| 202 |
+
print(f" 已打包: {zip_path} ({n} 个文件, "
|
| 203 |
+
f"{zip_path.stat().st_size / 1e6:.1f} MB)")
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def dir_size(p: Path) -> tuple[int, int]:
|
| 207 |
+
files = [f for f in p.rglob("*") if f.is_file()]
|
| 208 |
+
return len(files), sum(f.stat().st_size for f in files)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def main() -> None:
|
| 212 |
+
ap = argparse.ArgumentParser(
|
| 213 |
+
description="裁剪手套工具包供随包分发(普通版一键部署自带骨架解算)")
|
| 214 |
+
ap.add_argument("--src", type=Path, help="源工具包目录(默认扫项目根)")
|
| 215 |
+
ap.add_argument("--out", type=Path, default=ROOT / "wheels",
|
| 216 |
+
help="输出目录(默认 wheels/,与离线包同处便于一起拷给客户)")
|
| 217 |
+
ap.add_argument("--keep", type=Path, metavar="DIR",
|
| 218 |
+
help="同时留一份展开的目录(可直接拷到项目根)")
|
| 219 |
+
ap.add_argument("--no-verify", action="store_true", help="跳过实跑校验")
|
| 220 |
+
ap.add_argument("--no-zip", action="store_true", help="只产出展开目录,不打包")
|
| 221 |
+
args = ap.parse_args()
|
| 222 |
+
|
| 223 |
+
src = find_toolkit_dir(args.src)
|
| 224 |
+
n0, s0 = dir_size(src)
|
| 225 |
+
print(f"源工具包: {src.name} ({n0} 个文件, {s0 / 1e6:.0f} MB)")
|
| 226 |
+
|
| 227 |
+
with tempfile.TemporaryDirectory(prefix="pack_toolkit_") as tmp:
|
| 228 |
+
staged = Path(tmp) / src.name
|
| 229 |
+
print("按白名单裁剪 ...")
|
| 230 |
+
copy_trimmed(src, staged)
|
| 231 |
+
n1, s1 = dir_size(staged)
|
| 232 |
+
print(f"裁剪后: {n1} 个文件, {s1 / 1e6:.1f} MB "
|
| 233 |
+
f"(省 {(1 - s1 / max(s0, 1)) * 100:.1f}%)")
|
| 234 |
+
print("未随包的部分及原因:")
|
| 235 |
+
for name, why in DROP_NOTE.items():
|
| 236 |
+
print(f" - {name}: {why}")
|
| 237 |
+
|
| 238 |
+
if not args.no_verify:
|
| 239 |
+
print("实跑解算链校验 ...")
|
| 240 |
+
if not verify(staged):
|
| 241 |
+
sys.exit("[错误] 校验未通过 —— 白名单漏了东西,请补 KEEP_DIRS/KEEP_FILES")
|
| 242 |
+
|
| 243 |
+
if args.keep:
|
| 244 |
+
dst = args.keep / src.name
|
| 245 |
+
if dst.exists():
|
| 246 |
+
shutil.rmtree(dst)
|
| 247 |
+
shutil.copytree(staged, dst)
|
| 248 |
+
print(f" 展开副本: {dst}")
|
| 249 |
+
|
| 250 |
+
if not args.no_zip:
|
| 251 |
+
make_zip(staged, args.out / "toolkit" / "glove_toolkit.zip")
|
| 252 |
+
|
| 253 |
+
print()
|
| 254 |
+
print("完成。随包分发: 把整个 wheels/ 拷到客户机项目根目录,"
|
| 255 |
+
"start.bat / start.sh 会自动把工具包展开到项目根。")
|
| 256 |
+
print("客户机若已有 stouch_glove_toolkit*/ 目录则原样不动。")
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
if __name__ == "__main__":
|
| 260 |
+
main()
|
|
@@ -10,15 +10,17 @@ start.bat / start.sh 检测到 wheels\\*.whl 后自动改走纯离线安装。
|
|
| 10 |
pip download(此时建议直接在一台 Windows 机器上运行本脚本)。
|
| 11 |
|
| 12 |
用法:
|
| 13 |
-
python scripts/pack_wheels.py #
|
| 14 |
-
python scripts/pack_wheels.py --lite # 仅极简采集版依赖(requirements-lite.txt)
|
| 15 |
-
python scripts/pack_wheels.py --extras # + mediapipe
|
| 16 |
python scripts/pack_wheels.py --torch # + CPU 版 torch(较大)
|
|
|
|
| 17 |
python scripts/pack_wheels.py --out /tmp/wheels # 自定义输出目录
|
| 18 |
|
| 19 |
产物:
|
| 20 |
<out>/*.whl Windows 3.12 依赖轮子(含依赖闭包)
|
| 21 |
<out>/python-3.12.10-amd64.exe Python 安装包(客户机器无 Python 时用)
|
|
|
|
| 22 |
"""
|
| 23 |
|
| 24 |
from __future__ import annotations
|
|
@@ -41,7 +43,8 @@ ALIYUN = "https://mirrors.aliyun.com/pypi/simple/"
|
|
| 41 |
TUNA = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
| 42 |
PYPI = "https://pypi.org/simple"
|
| 43 |
MIRRORS = [ALIYUN, TUNA, PYPI]
|
| 44 |
-
|
|
|
|
| 45 |
TORCH_INDEXES = [
|
| 46 |
("https://mirrors.aliyun.com/pytorch-wheels/cpu/", ALIYUN),
|
| 47 |
("https://download.pytorch.org/whl/cpu", PYPI),
|
|
@@ -127,7 +130,7 @@ def main() -> int:
|
|
| 127 |
parser.add_argument("--lite", action="store_true",
|
| 128 |
help="仅打包极简采集版依赖(requirements-lite.txt)")
|
| 129 |
parser.add_argument("--extras", action="store_true",
|
| 130 |
-
help="额外打包 mediapipe
|
| 131 |
parser.add_argument("--torch", action="store_true",
|
| 132 |
help="额外打包 CPU 版 torch(体积较大)")
|
| 133 |
parser.add_argument("--out", type=Path,
|
|
@@ -135,6 +138,8 @@ def main() -> int:
|
|
| 135 |
help="输出目录(默认仓库根目录 wheels/)")
|
| 136 |
parser.add_argument("--no-python-installer", action="store_true",
|
| 137 |
help="跳过 Python 安装包下载")
|
|
|
|
|
|
|
| 138 |
args = parser.parse_args()
|
| 139 |
|
| 140 |
if args.lite and (args.extras or args.torch):
|
|
@@ -152,7 +157,7 @@ def main() -> int:
|
|
| 152 |
if args.extras:
|
| 153 |
specs = specs + EXTRAS
|
| 154 |
|
| 155 |
-
print(f"[1/
|
| 156 |
if UV is None:
|
| 157 |
print(" [提示] 未检测到 uv,回退纯 pip 解析(建议在一台 Windows 机器上运行,"
|
| 158 |
"或 pip install uv 后重试)")
|
|
@@ -174,7 +179,7 @@ def main() -> int:
|
|
| 174 |
return 1
|
| 175 |
|
| 176 |
if args.torch:
|
| 177 |
-
print("[2/
|
| 178 |
torch_done = False
|
| 179 |
for index, extra in TORCH_INDEXES:
|
| 180 |
try:
|
|
@@ -188,27 +193,45 @@ def main() -> int:
|
|
| 188 |
if not torch_done:
|
| 189 |
print(f"[错误] torch 下载失败: {last_err}", file=sys.stderr)
|
| 190 |
return 1
|
| 191 |
-
print("[2/
|
| 192 |
else:
|
| 193 |
-
print("[2/
|
| 194 |
|
| 195 |
if not args.no_python_installer:
|
| 196 |
-
print("[3/
|
| 197 |
try:
|
| 198 |
download_python_installer(out)
|
| 199 |
except RuntimeError as e:
|
| 200 |
print(f"[警告] {e};不影响 wheels 使用,手动放入同名文件即可",
|
| 201 |
file=sys.stderr)
|
| 202 |
else:
|
| 203 |
-
print("[3/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
whls = sorted(out.glob("*.whl"))
|
| 206 |
total = sum(w.stat().st_size for w in whls) / 1e6
|
| 207 |
print()
|
| 208 |
print("=" * 60)
|
| 209 |
print(f"打包完成: {len(whls)} 个 wheel,共 {total:.0f} MB -> {out}/")
|
|
|
|
|
|
|
| 210 |
print("交付方式: 把整个 wheels/ 目录拷到客户项目根目录,")
|
| 211 |
-
print(" start.bat / start.sh 会自动改走纯离线安装
|
|
|
|
| 212 |
print("=" * 60)
|
| 213 |
return 0
|
| 214 |
|
|
|
|
| 10 |
pip download(此时建议直接在一台 Windows 机器上运行本脚本)。
|
| 11 |
|
| 12 |
用法:
|
| 13 |
+
python scripts/pack_wheels.py # 主程序必需依赖 + 手套工具包
|
| 14 |
+
python scripts/pack_wheels.py --lite # 仅极简采集版依赖(requirements-lite.txt,不带工具包)
|
| 15 |
+
python scripts/pack_wheels.py --extras # + mediapipe
|
| 16 |
python scripts/pack_wheels.py --torch # + CPU 版 torch(较大)
|
| 17 |
+
python scripts/pack_wheels.py --no-toolkit # 只打依赖轮子,不裁手套工具包
|
| 18 |
python scripts/pack_wheels.py --out /tmp/wheels # 自定义输出目录
|
| 19 |
|
| 20 |
产物:
|
| 21 |
<out>/*.whl Windows 3.12 依赖轮子(含依赖闭包)
|
| 22 |
<out>/python-3.12.10-amd64.exe Python 安装包(客户机器无 Python 时用)
|
| 23 |
+
<out>/toolkit/glove_toolkit.zip 手套工具包裁剪版(骨架解算用;见 pack_toolkit.py)
|
| 24 |
"""
|
| 25 |
|
| 26 |
from __future__ import annotations
|
|
|
|
| 43 |
TUNA = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
| 44 |
PYPI = "https://pypi.org/simple"
|
| 45 |
MIRRORS = [ALIYUN, TUNA, PYPI]
|
| 46 |
+
# pyrealsense2(D435/D405)已提升为 requirements.txt 的默认依赖,不再属于可选包
|
| 47 |
+
EXTRAS = ["mediapipe"]
|
| 48 |
TORCH_INDEXES = [
|
| 49 |
("https://mirrors.aliyun.com/pytorch-wheels/cpu/", ALIYUN),
|
| 50 |
("https://download.pytorch.org/whl/cpu", PYPI),
|
|
|
|
| 130 |
parser.add_argument("--lite", action="store_true",
|
| 131 |
help="仅打包极简采集版依赖(requirements-lite.txt)")
|
| 132 |
parser.add_argument("--extras", action="store_true",
|
| 133 |
+
help="额外打包 mediapipe")
|
| 134 |
parser.add_argument("--torch", action="store_true",
|
| 135 |
help="额外打包 CPU 版 torch(体积较大)")
|
| 136 |
parser.add_argument("--out", type=Path,
|
|
|
|
| 138 |
help="输出目录(默认仓库根目录 wheels/)")
|
| 139 |
parser.add_argument("--no-python-installer", action="store_true",
|
| 140 |
help="跳过 Python 安装包下载")
|
| 141 |
+
parser.add_argument("--no-toolkit", action="store_true",
|
| 142 |
+
help="不裁手套工具包(骨架解算随包,仅 --lite 时才可省)")
|
| 143 |
args = parser.parse_args()
|
| 144 |
|
| 145 |
if args.lite and (args.extras or args.torch):
|
|
|
|
| 157 |
if args.extras:
|
| 158 |
specs = specs + EXTRAS
|
| 159 |
|
| 160 |
+
print(f"[1/4] 解析 {len(specs)} 个包的 Windows {PY_VERSION} 依赖闭包 -> {out}/ ...")
|
| 161 |
if UV is None:
|
| 162 |
print(" [提示] 未检测到 uv,回退纯 pip 解析(建议在一台 Windows 机器上运行,"
|
| 163 |
"或 pip install uv 后重试)")
|
|
|
|
| 179 |
return 1
|
| 180 |
|
| 181 |
if args.torch:
|
| 182 |
+
print("[2/4] 解析 CPU 版 torch(Windows)...")
|
| 183 |
torch_done = False
|
| 184 |
for index, extra in TORCH_INDEXES:
|
| 185 |
try:
|
|
|
|
| 193 |
if not torch_done:
|
| 194 |
print(f"[错误] torch 下载失败: {last_err}", file=sys.stderr)
|
| 195 |
return 1
|
| 196 |
+
print("[2/4] torch 完成")
|
| 197 |
else:
|
| 198 |
+
print("[2/4] 跳过 torch(--torch 可打包 CPU 版)")
|
| 199 |
|
| 200 |
if not args.no_python_installer:
|
| 201 |
+
print("[3/4] 拉取 Python 安装包(客户机器无 Python 时 start.bat 会用)...")
|
| 202 |
try:
|
| 203 |
download_python_installer(out)
|
| 204 |
except RuntimeError as e:
|
| 205 |
print(f"[警告] {e};不影响 wheels 使用,手动放入同名文件即可",
|
| 206 |
file=sys.stderr)
|
| 207 |
else:
|
| 208 |
+
print("[3/4] 跳过 Python 安装包(--no-python-installer)")
|
| 209 |
+
|
| 210 |
+
# 手套工具包(骨架解算)——普通版随包,极简版不需要
|
| 211 |
+
if args.lite or args.no_toolkit:
|
| 212 |
+
print("[4/4] 跳过手套工具包"
|
| 213 |
+
+ ("(--lite 极简版不含骨架解算)" if args.lite else "(--no-toolkit)"))
|
| 214 |
+
else:
|
| 215 |
+
print("[4/4] 裁剪手套工具包(骨架解算随包)...")
|
| 216 |
+
rc = subprocess.run(
|
| 217 |
+
[sys.executable, str(repo_root / "scripts" / "pack_toolkit.py"),
|
| 218 |
+
"--out", str(out)]).returncode
|
| 219 |
+
if rc != 0:
|
| 220 |
+
# 不阻断 wheel 打包:工具包缺失只影响骨架,主程序照常
|
| 221 |
+
print("[警告] 工具包裁剪失败(骨架解算将不可用)。"
|
| 222 |
+
"单独重试: python scripts/pack_toolkit.py --out "
|
| 223 |
+
f"{out}", file=sys.stderr)
|
| 224 |
|
| 225 |
whls = sorted(out.glob("*.whl"))
|
| 226 |
total = sum(w.stat().st_size for w in whls) / 1e6
|
| 227 |
print()
|
| 228 |
print("=" * 60)
|
| 229 |
print(f"打包完成: {len(whls)} 个 wheel,共 {total:.0f} MB -> {out}/")
|
| 230 |
+
if not (args.lite or args.no_toolkit):
|
| 231 |
+
print(f" 手套工具包 -> {out}/toolkit/glove_toolkit.zip")
|
| 232 |
print("交付方式: 把整个 wheels/ 目录拷到客户项目根目录,")
|
| 233 |
+
print(" start.bat / start.sh 会自动改走纯离线安装,")
|
| 234 |
+
print(" 并把工具包展开到项目根(骨架解算开箱可用)。")
|
| 235 |
print("=" * 60)
|
| 236 |
return 0
|
| 237 |
|
|
@@ -10,16 +10,35 @@ rem
|
|
| 10 |
rem �÷�:
|
| 11 |
rem start.bat ����(����) + ����������
|
| 12 |
rem start.bat reinstall ɾ�� venv ǿ����װ����������ѡ��
|
| 13 |
-
rem start.bat extras �Ӱ�װ mediapipe
|
| 14 |
rem start.bat extras-torch �Ӱ�װ CPU �� torch
|
| 15 |
rem start.bat help �� ʹ��˵��.md
|
| 16 |
rem
|
|
|
|
| 17 |
rem ������װ˳��: ���� wheels\ �� �� �����ƾ��� �� �廪���� �� �ٷ�Դ
|
| 18 |
rem ������ A-G ��Ӧ ʹ��˵��.md�������쳣�����������½�
|
|
|
|
|
|
|
|
|
|
| 19 |
rem ============================================================
|
| 20 |
setlocal enabledelayedexpansion
|
| 21 |
cd /d "%~dp0"
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
set "MODE=run"
|
| 24 |
set "FORCE=0"
|
| 25 |
set "MAIN_ARGS="
|
|
@@ -53,7 +72,7 @@ if not exist "main.py" goto :errG
|
|
| 53 |
if not exist "requirements.txt" goto :errG
|
| 54 |
|
| 55 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 56 |
-
rem [1/
|
| 57 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 58 |
set "PY="
|
| 59 |
set "VPY=venv\Scripts\python.exe"
|
|
@@ -62,7 +81,7 @@ set "PY=%VPY%"
|
|
| 62 |
goto :have_python
|
| 63 |
|
| 64 |
:find_py
|
| 65 |
-
echo [1/
|
| 66 |
call :try_py py -3.12
|
| 67 |
if defined PY goto :have_python
|
| 68 |
call :try_py py -3
|
|
@@ -71,7 +90,7 @@ call :try_py python
|
|
| 71 |
if defined PY goto :have_python
|
| 72 |
|
| 73 |
rem ���� δ�� �� �Զ����ز���Ĭ��װ Python 3.12 ����
|
| 74 |
-
echo [1/
|
| 75 |
set "PY_VER=3.12.10"
|
| 76 |
set "PY_EXE=%TEMP%\python-%PY_VER%-amd64.exe"
|
| 77 |
set "PY_URL=https://mirrors.aliyun.com/python-release/windows/python-%PY_VER%-amd64.exe"
|
|
@@ -86,10 +105,10 @@ curl -L -o "%PY_EXE%" "%PY_URL3%" --connect-timeout 20 --retry 2 --silent --show
|
|
| 86 |
if exist "%PY_EXE%" goto :py_run_installer
|
| 87 |
goto :errA
|
| 88 |
:py_copy_local
|
| 89 |
-
echo [1/
|
| 90 |
copy /y "wheels\python-%PY_VER%-amd64.exe" "%PY_EXE%" >nul
|
| 91 |
:py_run_installer
|
| 92 |
-
echo [1/
|
| 93 |
"%PY_EXE%" /quiet InstallAllUsers=0 PrependPath=1 Include_pip=1 Include_test=0 Include_launcher=1
|
| 94 |
del "%PY_EXE%" >nul 2>&1
|
| 95 |
call :try_py py -3.12
|
|
@@ -97,24 +116,46 @@ if defined PY goto :have_python
|
|
| 97 |
goto :errA
|
| 98 |
|
| 99 |
:have_python
|
| 100 |
-
echo [1/
|
| 101 |
|
| 102 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 103 |
-
rem [2/
|
| 104 |
rem ������������������������������������������������������������������������������������������������������������������������
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
if not exist "%VPY%" goto :make_venv
|
| 106 |
-
if
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
rmdir /s /q "venv" 2>nul
|
| 109 |
if exist "%VPY%" goto :errC2
|
| 110 |
:make_venv
|
| 111 |
-
echo [2/
|
| 112 |
rem ע��: PY �����py -3.12 / python�������ܼ�����
|
| 113 |
%PY% -m venv "venv"
|
| 114 |
if not exist "%VPY%" goto :errC
|
| 115 |
|
| 116 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 117 |
-
rem [3/
|
| 118 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 119 |
:deps_check
|
| 120 |
rem �� requirements.txt �� ��ʱ��|��С ��ǩ�������ݱ��˲���װ��
|
|
@@ -122,26 +163,97 @@ for %%I in (requirements.txt) do set "SIG=%%~tI;%%~zI"
|
|
| 122 |
if "%FORCE%"=="1" goto :install_deps
|
| 123 |
if not exist "venv\.deps-ok" goto :install_deps
|
| 124 |
set /p STAMP=<"venv\.deps-ok"
|
| 125 |
-
if "%STAMP%"=="%SIG%" goto :
|
| 126 |
|
| 127 |
:install_deps
|
| 128 |
-
echo [3/
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
call :pip_install_req
|
| 131 |
if errorlevel 1 goto :errD
|
|
|
|
| 132 |
> "venv\.deps-ok" echo %SIG%
|
| 133 |
|
| 134 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 135 |
-
rem [4/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 137 |
:after_deps
|
| 138 |
-
echo [
|
| 139 |
"%VPY%" -c "import main" >nul 2>&1
|
| 140 |
if errorlevel 1 goto :errE
|
| 141 |
-
echo [
|
| 142 |
|
| 143 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 144 |
-
rem [
|
| 145 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 146 |
if "%MODE%"=="extras" goto :install_extras
|
| 147 |
if "%MODE%"=="extras-torch" goto :install_torch
|
|
@@ -149,33 +261,32 @@ goto :launch
|
|
| 149 |
|
| 150 |
:install_extras
|
| 151 |
if exist "venv\.extras-ok" goto :extras_done
|
| 152 |
-
|
|
|
|
| 153 |
call :pip_pkg "mediapipe"
|
| 154 |
if errorlevel 1 echo [����] mediapipe ��װʧ�ܣ���������Ӱ�죬���ʹ��˵��.md��
|
| 155 |
-
call :pip_pkg "pyrealsense2"
|
| 156 |
-
if errorlevel 1 echo [����] pyrealsense2 ��װʧ�ܣ���������Ӱ�죬���ʹ��˵��.md��
|
| 157 |
> "venv\.extras-ok" echo done
|
| 158 |
:extras_done
|
| 159 |
-
echo [
|
| 160 |
pause
|
| 161 |
exit /b 0
|
| 162 |
|
| 163 |
:install_torch
|
| 164 |
if exist "venv\.torch-ok" goto :torch_done
|
| 165 |
-
echo [
|
| 166 |
call :pip_torch
|
| 167 |
if errorlevel 1 echo [����] torch ��װʧ�ܣ���������Ӱ�죬GPU �氲װ��ʹ��˵��.md��
|
| 168 |
> "venv\.torch-ok" echo done
|
| 169 |
:torch_done
|
| 170 |
-
echo [
|
| 171 |
pause
|
| 172 |
exit /b 0
|
| 173 |
|
| 174 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 175 |
-
rem [
|
| 176 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 177 |
:launch
|
| 178 |
-
echo [
|
| 179 |
echo.
|
| 180 |
echo ������ָ����
|
| 181 |
echo �� �豸���: ��������Լ 2 ���Զ����֣��������Ԥ��
|
|
@@ -204,6 +315,17 @@ if errorlevel 1 exit /b 1
|
|
| 204 |
set "PY=%*"
|
| 205 |
exit /b 0
|
| 206 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
rem ���� wheels\ Ŀ¼���Ƿ��� .whl �ļ� ����
|
| 208 |
:wheels_exists
|
| 209 |
dir /b "wheels\*.whl" >nul 2>&1
|
|
@@ -213,10 +335,10 @@ rem
|
|
| 213 |
:pip_install_req
|
| 214 |
call :wheels_exists
|
| 215 |
if errorlevel 1 goto :req_online
|
| 216 |
-
echo [3/
|
| 217 |
"%VPY%" -m pip install --no-index --find-links "wheels" -r requirements.txt
|
| 218 |
if not errorlevel 1 exit /b 0
|
| 219 |
-
echo [3/
|
| 220 |
:req_online
|
| 221 |
"%VPY%" -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
|
| 222 |
if not errorlevel 1 exit /b 0
|
|
@@ -231,7 +353,7 @@ call :wheels_exists
|
|
| 231 |
if errorlevel 1 goto :pkg_online
|
| 232 |
"%VPY%" -m pip install --no-index --find-links "wheels" "%~1"
|
| 233 |
if not errorlevel 1 exit /b 0
|
| 234 |
-
echo [
|
| 235 |
:pkg_online
|
| 236 |
"%VPY%" -m pip install "%~1" -i https://mirrors.aliyun.com/pypi/simple/
|
| 237 |
if not errorlevel 1 exit /b 0
|
|
@@ -246,7 +368,7 @@ call :wheels_exists
|
|
| 246 |
if errorlevel 1 goto :torch_online
|
| 247 |
"%VPY%" -m pip install --no-index --find-links "wheels" torch
|
| 248 |
if not errorlevel 1 exit /b 0
|
| 249 |
-
echo [
|
| 250 |
:torch_online
|
| 251 |
"%VPY%" -m pip install torch --index-url https://mirrors.aliyun.com/pytorch-wheels/cpu/
|
| 252 |
if not errorlevel 1 exit /b 0
|
|
@@ -316,11 +438,19 @@ exit /b 1
|
|
| 316 |
echo.
|
| 317 |
echo [���� D] ��������/��װʧ��
|
| 318 |
echo ------------------------------------------------------------
|
| 319 |
-
echo
|
| 320 |
-
echo
|
| 321 |
-
echo
|
| 322 |
-
echo
|
| 323 |
-
echo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
echo.
|
| 325 |
pause
|
| 326 |
exit /b 1
|
|
|
|
| 10 |
rem �÷�:
|
| 11 |
rem start.bat ����(����) + ����������
|
| 12 |
rem start.bat reinstall ɾ�� venv ǿ����װ����������ѡ��
|
| 13 |
+
rem start.bat extras �Ӱ�װ mediapipe������ 3D �ؼ��㣩
|
| 14 |
rem start.bat extras-torch �Ӱ�װ CPU �� torch
|
| 15 |
rem start.bat help �� ʹ��˵��.md
|
| 16 |
rem
|
| 17 |
+
rem ���ű��Դ� venv�������Ѽ��� conda / ���� venv �Ĵ�����ֱ�����У�����Ӱ�죩
|
| 18 |
rem ������װ˳��: ���� wheels\ �� �� �����ƾ��� �� �廪���� �� �ٷ�Դ
|
| 19 |
rem ������ A-G ��Ӧ ʹ��˵��.md�������쳣�����������½�
|
| 20 |
+
rem
|
| 21 |
+
rem Ĭ���Ѱ���: D435/D405 ��������pyrealsense2��������ʵʱ�Ǽܽ���
|
| 22 |
+
rem ��scipy/pydantic/polars + ������߰����� [4/7]��
|
| 23 |
rem ============================================================
|
| 24 |
setlocal enabledelayedexpansion
|
| 25 |
cd /d "%~dp0"
|
| 26 |
|
| 27 |
+
rem ���� ��������: �����κ� Python ֮ǰ��������ᡸ��ζ�����ⲿ���� ����
|
| 28 |
+
rem ���ű�һ������Ŀ�Դ� venv�����û��������� conda / ��һ�� venv ��˫���ģ�
|
| 29 |
+
rem ���Լ���� PYTHONHOME����Щ�����ᴩ�����ǵ� venv���ѽ�����ָ����
|
| 30 |
+
rem ��֢״: ��������װ��ȴ import ʧ�� / DLL load failed / pip װ���˱�Ļ�������
|
| 31 |
+
rem ֱ����ղ���ʾ�������û�ȥ�£�ֻ��ʾ������ϡ�
|
| 32 |
+
if defined VIRTUAL_ENV echo [��ʾ] ���Ѽ��������� "%VIRTUAL_ENV%"�����ű���ʹ������������Ŀ�Դ� venv��
|
| 33 |
+
if defined CONDA_PREFIX echo [��ʾ] ���Ѽ���� conda ���� "%CONDA_PREFIX%"�����ű���ʹ������������Ŀ�Դ� venv��
|
| 34 |
+
if defined PYTHONHOME echo [��ʾ] �Ѻ����ⲿ���� PYTHONHOME="%PYTHONHOME%"
|
| 35 |
+
if defined PYTHONPATH echo [��ʾ] �Ѻ����ⲿ���� PYTHONPATH="%PYTHONPATH%"
|
| 36 |
+
set "PYTHONHOME="
|
| 37 |
+
set "PYTHONPATH="
|
| 38 |
+
set "PYTHONSTARTUP="
|
| 39 |
+
rem �����û��� site-packages��%APPDATA%\Python �µİ������� venv ��ȫ�Ը�����
|
| 40 |
+
set "PYTHONNOUSERSITE=1"
|
| 41 |
+
|
| 42 |
set "MODE=run"
|
| 43 |
set "FORCE=0"
|
| 44 |
set "MAIN_ARGS="
|
|
|
|
| 72 |
if not exist "requirements.txt" goto :errG
|
| 73 |
|
| 74 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 75 |
+
rem [1/7] ��λ Python���汾�� >= 3.10���Ƽ� 3.12��
|
| 76 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 77 |
set "PY="
|
| 78 |
set "VPY=venv\Scripts\python.exe"
|
|
|
|
| 81 |
goto :have_python
|
| 82 |
|
| 83 |
:find_py
|
| 84 |
+
echo [1/7] ��� Python ���� ...
|
| 85 |
call :try_py py -3.12
|
| 86 |
if defined PY goto :have_python
|
| 87 |
call :try_py py -3
|
|
|
|
| 90 |
if defined PY goto :have_python
|
| 91 |
|
| 92 |
rem ���� δ�� �� �Զ����ز���Ĭ��װ Python 3.12 ����
|
| 93 |
+
echo [1/7] δ�� Python���Զ����ذ�װ Python 3.12��Լ 25MB��...
|
| 94 |
set "PY_VER=3.12.10"
|
| 95 |
set "PY_EXE=%TEMP%\python-%PY_VER%-amd64.exe"
|
| 96 |
set "PY_URL=https://mirrors.aliyun.com/python-release/windows/python-%PY_VER%-amd64.exe"
|
|
|
|
| 105 |
if exist "%PY_EXE%" goto :py_run_installer
|
| 106 |
goto :errA
|
| 107 |
:py_copy_local
|
| 108 |
+
echo [1/7] ʹ�� wheels\ Ŀ¼�ڵ� Python ��װ�� ...
|
| 109 |
copy /y "wheels\python-%PY_VER%-amd64.exe" "%PY_EXE%" >nul
|
| 110 |
:py_run_installer
|
| 111 |
+
echo [1/7] ��Ĭ��װ Python �У�����رմ��ڣ�Լ 1 ���ӣ�...
|
| 112 |
"%PY_EXE%" /quiet InstallAllUsers=0 PrependPath=1 Include_pip=1 Include_test=0 Include_launcher=1
|
| 113 |
del "%PY_EXE%" >nul 2>&1
|
| 114 |
call :try_py py -3.12
|
|
|
|
| 116 |
goto :errA
|
| 117 |
|
| 118 |
:have_python
|
| 119 |
+
echo [1/7] ʹ�� Python: %PY%
|
| 120 |
|
| 121 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 122 |
+
rem [2/7] ����� venv
|
| 123 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 124 |
+
rem Ϊʲô���: venv Ŀ¼�� �� venv ���á�
|
| 125 |
+
rem �� �ӱ�Ļ��������� venv: python.exe �ڣ�������Ӳ���������̨������
|
| 126 |
+
rem Python ·�� �� һ�ܾ͡�No Python at ...����
|
| 127 |
+
rem �� pip ���� / ɱ�� / �ϵ���: pip ��ɾ��һ�루Ŀ¼���ڡ�ģ��û�ˣ���
|
| 128 |
+
rem ���� pip ����� ModuleNotFoundError: pip._internal.cli��
|
| 129 |
+
rem ������������û�ȥ��: һ���������ޣ�ensurepip �� Python �Դ��������
|
| 130 |
+
rem ��������Ŀ¼�ؽ���ͬ������������
|
| 131 |
if not exist "%VPY%" goto :make_venv
|
| 132 |
+
if "%FORCE%"=="1" goto :reinstall_venv
|
| 133 |
+
rem ��� ��: �����������ܲ����ܡ��汾�������������� venv ���������Σ�
|
| 134 |
+
"%VPY%" -c "import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)" >nul 2>&1
|
| 135 |
+
if errorlevel 1 goto :venv_broken
|
| 136 |
+
rem ��� ��: pip �Ƿ���������װ pip ���������Σ�
|
| 137 |
+
"%VPY%" -m pip --version >nul 2>&1
|
| 138 |
+
if not errorlevel 1 goto :deps_check
|
| 139 |
+
echo [2/7] �� venv �� pip ������������������ ...
|
| 140 |
+
"%VPY%" -m ensurepip --upgrade >nul 2>&1
|
| 141 |
+
"%VPY%" -m pip --version >nul 2>&1
|
| 142 |
+
if not errorlevel 1 goto :deps_check
|
| 143 |
+
:venv_broken
|
| 144 |
+
echo [2/7] venv �����ã�pip ȱʧ��������쳣�����Զ��ؽ�������Ҫ������Լ 1 ���ӣ�...
|
| 145 |
+
goto :reinstall_venv_do
|
| 146 |
+
:reinstall_venv
|
| 147 |
+
echo [2/7] reinstall: ɾ���� venv ...
|
| 148 |
+
:reinstall_venv_do
|
| 149 |
rmdir /s /q "venv" 2>nul
|
| 150 |
if exist "%VPY%" goto :errC2
|
| 151 |
:make_venv
|
| 152 |
+
echo [2/7] ��������� venv���״�Լ 1 ���ӣ�...
|
| 153 |
rem ע��: PY �����py -3.12 / python�������ܼ�����
|
| 154 |
%PY% -m venv "venv"
|
| 155 |
if not exist "%VPY%" goto :errC
|
| 156 |
|
| 157 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 158 |
+
rem [3/7] ��װ������requirements.txt �б仯���״�����ʱ��
|
| 159 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 160 |
:deps_check
|
| 161 |
rem �� requirements.txt �� ��ʱ��|��С ��ǩ�������ݱ��˲���װ��
|
|
|
|
| 163 |
if "%FORCE%"=="1" goto :install_deps
|
| 164 |
if not exist "venv\.deps-ok" goto :install_deps
|
| 165 |
set /p STAMP=<"venv\.deps-ok"
|
| 166 |
+
if "%STAMP%"=="%SIG%" goto :toolkit_check
|
| 167 |
|
| 168 |
:install_deps
|
| 169 |
+
echo [3/7] ��װ�������״�Լ 3-10 ���ӣ�֮�������뿪��...
|
| 170 |
+
rem ������������������������������������������������������������������������������������������������������������������������
|
| 171 |
+
rem ������ǰ��һ�侲Ĭ�� pip install --upgrade pip�����Ƴ� ���� ���ǡ���װ pip��
|
| 172 |
+
rem ��Ψһ��Դ: pip �����ǡ���ɾ�ɡ��ٽ��¡�����;����ϣ��ش��� / ���� /
|
| 173 |
+
rem ɱ�� / �ϵ磩��ֻʣһ���տǣ�֮��ÿ����������
|
| 174 |
+
rem ModuleNotFoundError: pip._internal.cli�����û��������ǡ���������ʧ�ܡ�
|
| 175 |
+
rem ������ D������ ������ȫ��ƫ���������Զ��ٴζ�һ����
|
| 176 |
+
rem Python 3.10+ �Դ��� pip �㹻װ����Ŀ��ȫ���������ʲ����Զ�������
|
| 177 |
+
rem ȷ����Ҫ���� cmd ���ֶ�ִ�У����˵� pip �´������ᱻ [2/7] ����ã�:
|
| 178 |
+
rem venv\Scripts\python.exe -m pip install --upgrade pip
|
| 179 |
+
rem ������������������������������������������������������������������������������������������������������������������������
|
| 180 |
+
call :pip_install_req
|
| 181 |
+
if not errorlevel 1 goto :deps_write_ok
|
| 182 |
+
rem ��װʧ��: ��ȷ�� pip �������ڲ��ڣ�����װ / ��ɱ��ɾ�dz����ֳ���
|
| 183 |
+
"%VPY%" -m pip --version >nul 2>&1
|
| 184 |
+
if not errorlevel 1 goto :errD
|
| 185 |
+
call :repair_pip
|
| 186 |
+
if errorlevel 1 goto :errD
|
| 187 |
+
echo [3/7] pip ����������װ ...
|
| 188 |
call :pip_install_req
|
| 189 |
if errorlevel 1 goto :errD
|
| 190 |
+
:deps_write_ok
|
| 191 |
> "venv\.deps-ok" echo %SIG%
|
| 192 |
|
| 193 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 194 |
+
rem [4/7] �����߰����ֲ��Ǽܽ��㣩
|
| 195 |
+
rem ʵʱ�Ǽܽ���������Ŀ��ͬ���� stouch_glove_toolkit*��core\glove_keypoint_solver.py
|
| 196 |
+
rem �� find_toolkit_dir() ��Ŀ¼���ң����ü����� wheels\ �ַ����״β���������չ����
|
| 197 |
+
rem **ȱʧֻ���桢������** ���� ����/IMU/���¼�ƶ�����Ӱ�졣
|
| 198 |
+
rem ������������������������������������������������������������������������������������������������������������������������
|
| 199 |
+
:toolkit_check
|
| 200 |
+
set "TOOLKIT="
|
| 201 |
+
rem ע��: for /d �ļ��ϼ����Żᵱ����������ͨ�����չ�� ���� ���ܼ�����
|
| 202 |
+
for /d %%D in (stouch_glove_toolkit*) do if not defined TOOLKIT set "TOOLKIT=%%~fD"
|
| 203 |
+
if defined TOOLKIT goto :toolkit_verify
|
| 204 |
+
if not exist "wheels\toolkit\glove_toolkit.zip" goto :toolkit_missing
|
| 205 |
+
|
| 206 |
+
echo [4/7] չ������������߰����Ǽܽ��㣩...
|
| 207 |
+
"%VPY%" -c "import sys,zipfile; zipfile.ZipFile(sys.argv[1]).extractall('.')" "wheels\toolkit\glove_toolkit.zip"
|
| 208 |
+
rem ע��: for /d �ļ��ϼ����Żᵱ����������ͨ�����չ�� ���� ���ܼ�����
|
| 209 |
+
for /d %%D in (stouch_glove_toolkit*) do if not defined TOOLKIT set "TOOLKIT=%%~fD"
|
| 210 |
+
if not defined TOOLKIT goto :toolkit_missing
|
| 211 |
+
|
| 212 |
+
:toolkit_verify
|
| 213 |
+
rem ���߰��� != ����: ��������Ҫ scipy/pydantic/polars �������������Ƕ��Ƕ���
|
| 214 |
+
rem ���� ���� �����ð���Լ�(import main)�鲻�������ﰴ�����߰� + ����ǩ����������ۡ�
|
| 215 |
+
set "TK_SIG=%TOOLKIT%;%SIG%"
|
| 216 |
+
if not exist "venv\.toolkit-ok" goto :toolkit_probe
|
| 217 |
+
set /p TK_STAMP=<"venv\.toolkit-ok"
|
| 218 |
+
if "%TK_STAMP%"=="%TK_SIG%" goto :toolkit_ok
|
| 219 |
+
|
| 220 |
+
:toolkit_probe
|
| 221 |
+
echo [4/7] У��Ǽܽ����� ...
|
| 222 |
+
"%VPY%" -c "import sys; sys.path.insert(0,sys.argv[1]); from glove_sdk.interfaces.solver import HandSolver" "%TOOLKIT%" 2>"%TEMP%\daq_toolkit_err.txt"
|
| 223 |
+
if not errorlevel 1 goto :toolkit_pass
|
| 224 |
+
set "TK_ERR="
|
| 225 |
+
for /f "usebackq delims=" %%L in ("%TEMP%\daq_toolkit_err.txt") do set "TK_ERR=%%L"
|
| 226 |
+
del "%TEMP%\daq_toolkit_err.txt" >nul 2>&1
|
| 227 |
+
echo [4/7] [����] ���߰��ڣ�������������ʧ�ܣ����������ûװȫ����
|
| 228 |
+
echo ԭ��: !TK_ERR!
|
| 229 |
+
echo ��װ����: start.bat reinstall
|
| 230 |
+
echo �������ճ�������ֻ��û���ֲ��Ǽܡ�
|
| 231 |
+
goto :after_deps
|
| 232 |
+
|
| 233 |
+
:toolkit_pass
|
| 234 |
+
del "%TEMP%\daq_toolkit_err.txt" >nul 2>&1
|
| 235 |
+
> "venv\.toolkit-ok" echo %TK_SIG%
|
| 236 |
+
:toolkit_ok
|
| 237 |
+
echo [4/7] �����߰�������ʵʱ�ֲ��Ǽܽ����Ѿ߱�
|
| 238 |
+
goto :after_deps
|
| 239 |
+
|
| 240 |
+
:toolkit_missing
|
| 241 |
+
echo [4/7] [����] δ�ҵ������߰� ���� �������ճ���������û��ʵʱ�ֲ��Ǽܽ��㡣
|
| 242 |
+
echo ��װ: �ڿ�����ִ�� python scripts\pack_toolkit.py��
|
| 243 |
+
echo �����ɵ� wheels\ ����������Ŀ¼������ start.bat
|
| 244 |
+
goto :after_deps
|
| 245 |
+
|
| 246 |
+
rem ������������������������������������������������������������������������������������������������������������������������
|
| 247 |
+
rem [5/7] ����ð���Լ죨������������������
|
| 248 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 249 |
:after_deps
|
| 250 |
+
echo [5/7] �����Լ� ...
|
| 251 |
"%VPY%" -c "import main" >nul 2>&1
|
| 252 |
if errorlevel 1 goto :errE
|
| 253 |
+
echo [5/7] �����Լ�ͨ��
|
| 254 |
|
| 255 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 256 |
+
rem [6/7] ��ѡ���ܣ�extras / extras-torch �����
|
| 257 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 258 |
if "%MODE%"=="extras" goto :install_extras
|
| 259 |
if "%MODE%"=="extras-torch" goto :install_torch
|
|
|
|
| 261 |
|
| 262 |
:install_extras
|
| 263 |
if exist "venv\.extras-ok" goto :extras_done
|
| 264 |
+
rem pyrealsense2��D435/D405���Ա������� requirements.txt Ĭ�ϰ�װ���������ڿ�ѡ��
|
| 265 |
+
echo [6/7] ��װ��ѡ����: mediapipe(����3D�ؼ���) ...
|
| 266 |
call :pip_pkg "mediapipe"
|
| 267 |
if errorlevel 1 echo [����] mediapipe ��װʧ�ܣ���������Ӱ�죬���ʹ��˵��.md��
|
|
|
|
|
|
|
| 268 |
> "venv\.extras-ok" echo done
|
| 269 |
:extras_done
|
| 270 |
+
echo [6/7] ��ѡ���ܰ�װ��ɡ�˫�� start.bat ����������
|
| 271 |
pause
|
| 272 |
exit /b 0
|
| 273 |
|
| 274 |
:install_torch
|
| 275 |
if exist "venv\.torch-ok" goto :torch_done
|
| 276 |
+
echo [6/7] ��װ��ѡ����: torch CPU �棨�ֲ��ؼ��� RTMPose �ã�...
|
| 277 |
call :pip_torch
|
| 278 |
if errorlevel 1 echo [����] torch ��װʧ�ܣ���������Ӱ�죬GPU �氲װ��ʹ��˵��.md��
|
| 279 |
> "venv\.torch-ok" echo done
|
| 280 |
:torch_done
|
| 281 |
+
echo [6/7] ��ѡ���ܰ�װ��ɡ�˫�� start.bat ����������
|
| 282 |
pause
|
| 283 |
exit /b 0
|
| 284 |
|
| 285 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 286 |
+
rem [7/7] ����������
|
| 287 |
rem ������������������������������������������������������������������������������������������������������������������������
|
| 288 |
:launch
|
| 289 |
+
echo [7/7] ���������� ...
|
| 290 |
echo.
|
| 291 |
echo ������ָ����
|
| 292 |
echo �� �豸���: ��������Լ 2 ���Զ����֣��������Ԥ��
|
|
|
|
| 315 |
set "PY=%*"
|
| 316 |
exit /b 0
|
| 317 |
|
| 318 |
+
rem ������������������������������������������������������������������������������������������������������������������������
|
| 319 |
+
rem �ӳ���: pip ��װʱ�������Ծ�
|
| 320 |
+
rem ensurepip �� Python �Դ������װ pip�������������÷��ط��㣬
|
| 321 |
+
rem �ɵ��÷�����������װ����ֱ�ӱ������ٲ��о�ֻ���ؽ� venv����
|
| 322 |
+
rem ������������������������������������������������������������������������������������������������������������������������
|
| 323 |
+
:repair_pip
|
| 324 |
+
echo [3/7] pip �쳣������������ ...
|
| 325 |
+
"%VPY%" -m ensurepip --upgrade >nul 2>&1
|
| 326 |
+
"%VPY%" -m pip --version >nul 2>&1
|
| 327 |
+
exit /b %errorlevel%
|
| 328 |
+
|
| 329 |
rem ���� wheels\ Ŀ¼���Ƿ��� .whl �ļ� ����
|
| 330 |
:wheels_exists
|
| 331 |
dir /b "wheels\*.whl" >nul 2>&1
|
|
|
|
| 335 |
:pip_install_req
|
| 336 |
call :wheels_exists
|
| 337 |
if errorlevel 1 goto :req_online
|
| 338 |
+
echo [3/7] �� wheels\ ���߰����������߰�װ ...
|
| 339 |
"%VPY%" -m pip install --no-index --find-links "wheels" -r requirements.txt
|
| 340 |
if not errorlevel 1 exit /b 0
|
| 341 |
+
echo [3/7] ���߰���װʧ�ܣ�ת���߰�װ ...
|
| 342 |
:req_online
|
| 343 |
"%VPY%" -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
|
| 344 |
if not errorlevel 1 exit /b 0
|
|
|
|
| 353 |
if errorlevel 1 goto :pkg_online
|
| 354 |
"%VPY%" -m pip install --no-index --find-links "wheels" "%~1"
|
| 355 |
if not errorlevel 1 exit /b 0
|
| 356 |
+
echo [6/7] ���߰�ȱʧ��ʧ�ܣ�ת���߰�װ ...
|
| 357 |
:pkg_online
|
| 358 |
"%VPY%" -m pip install "%~1" -i https://mirrors.aliyun.com/pypi/simple/
|
| 359 |
if not errorlevel 1 exit /b 0
|
|
|
|
| 368 |
if errorlevel 1 goto :torch_online
|
| 369 |
"%VPY%" -m pip install --no-index --find-links "wheels" torch
|
| 370 |
if not errorlevel 1 exit /b 0
|
| 371 |
+
echo [6/7] ���߰�ȱʧ��ʧ�ܣ�ת���߰�װ ...
|
| 372 |
:torch_online
|
| 373 |
"%VPY%" -m pip install torch --index-url https://mirrors.aliyun.com/pytorch-wheels/cpu/
|
| 374 |
if not errorlevel 1 exit /b 0
|
|
|
|
| 438 |
echo.
|
| 439 |
echo [���� D] ��������/��װʧ��
|
| 440 |
echo ------------------------------------------------------------
|
| 441 |
+
echo �ȿ���һ���ı������ٶ�֢����:
|
| 442 |
+
echo.
|
| 443 |
+
echo �� �� ModuleNotFoundError: pip._internal.cli / No module named 'pip'
|
| 444 |
+
echo �� venv ��� pip ���ˣ���������� / ɱ��ɾ���ļ����������������⡣
|
| 445 |
+
echo ֱ��˫�� start.bat reinstall �ؽ� venv��Լ 1 ���ӣ�����Ҫ��������
|
| 446 |
+
echo �� �� No Python at ... / �Ҳ��� Python
|
| 447 |
+
echo �� venv �Ǵӱ�Ļ��������ģ�˫�� start.bat reinstall �ؽ����ɡ�
|
| 448 |
+
echo �� �� Could not find a version / connection / timeout / ֤�����
|
| 449 |
+
echo �� ���������Ȩ������:
|
| 450 |
+
echo 1. ��������: ������������˫�� start.bat�������ز��ֻỺ�棬���ظ����أ�
|
| 451 |
+
echo 2. ��˾��������/����: �����Ա���� pypi ����������߰�����
|
| 452 |
+
echo ������Ա���� scripts\pack_wheels.py ���� wheels\����ʹ��˵��.md��
|
| 453 |
+
echo 3. ɱ������/����ǽ���� pip: ���������������
|
| 454 |
echo.
|
| 455 |
pause
|
| 456 |
exit /b 1
|
|
@@ -5,15 +5,41 @@
|
|
| 5 |
# 用法:
|
| 6 |
# ./start.sh 部署(按需) + 启动主程序
|
| 7 |
# ./start.sh reinstall 删除 venv 强制重装(出问题首选)
|
| 8 |
-
# ./start.sh extras 追加安装 mediapipe
|
| 9 |
# ./start.sh extras-torch 追加安装 CPU 版 torch
|
| 10 |
# ./start.sh help 打开 使用说明.md
|
| 11 |
#
|
| 12 |
# 依赖安装顺序: 离线 wheels/ 包 → 阿里云镜像 → 清华镜像 → 官方源
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
# ============================================================
|
| 14 |
set -euo pipefail
|
| 15 |
cd "$(dirname "$0")"
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
MODE=run
|
| 18 |
FORCE=0
|
| 19 |
case "${1:-}" in
|
|
@@ -37,7 +63,7 @@ if [ ! -f main.py ] || [ ! -f requirements.txt ]; then
|
|
| 37 |
exit 1
|
| 38 |
fi
|
| 39 |
|
| 40 |
-
# ── [1/
|
| 41 |
PY=""
|
| 42 |
find_python() {
|
| 43 |
for c in python3.12 python3.11 python3.10 python3; do
|
|
@@ -57,20 +83,47 @@ elif ! find_python; then
|
|
| 57 |
echo " conda: conda create -n daq python=3.12"
|
| 58 |
exit 1
|
| 59 |
fi
|
| 60 |
-
echo "[1/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
|
| 63 |
-
if [ -x
|
| 64 |
-
echo "[2/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
rm -rf venv
|
| 66 |
-
fi
|
| 67 |
-
if [ ! -x venv/bin/python ]; then
|
| 68 |
-
echo "[2/6] 创建虚拟环境 venv(首次约 1 分钟)..."
|
| 69 |
"$PY" -m venv venv
|
| 70 |
fi
|
| 71 |
-
VPY
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
# ── [3/
|
| 74 |
HASH="$(md5sum requirements.txt | cut -d' ' -f1)"
|
| 75 |
NEED_INSTALL=0
|
| 76 |
if [ "$FORCE" = 1 ]; then
|
|
@@ -82,36 +135,112 @@ fi
|
|
| 82 |
install_req() {
|
| 83 |
local req="$1"
|
| 84 |
if [ -d wheels ] && ls wheels/*.whl >/dev/null 2>&1; then
|
| 85 |
-
echo "[3/
|
| 86 |
"$VPY" -m pip install --no-index --find-links wheels -r "$req" && return 0
|
| 87 |
-
echo "[3/
|
| 88 |
fi
|
| 89 |
"$VPY" -m pip install -r "$req" -i https://mirrors.aliyun.com/pypi/simple/ && return 0
|
| 90 |
"$VPY" -m pip install -r "$req" -i https://pypi.tuna.tsinghua.edu.cn/simple && return 0
|
| 91 |
"$VPY" -m pip install -r "$req"
|
| 92 |
}
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
if [ "$NEED_INSTALL" = 1 ]; then
|
| 95 |
-
echo "[3/
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
if ! install_req requirements.txt; then
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
fi
|
| 101 |
echo "$HASH" > venv/.deps-ok
|
| 102 |
fi
|
| 103 |
|
| 104 |
-
# ── [4/
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
if ! "$VPY" -c "import main" >/dev/null 2>&1; then
|
| 107 |
echo "[错误 E] 依赖自检失败。查看具体原因:"
|
| 108 |
echo " venv/bin/python -c \"import main\""
|
| 109 |
echo "重装: ./start.sh reinstall"
|
| 110 |
exit 1
|
| 111 |
fi
|
| 112 |
-
echo "[
|
| 113 |
|
| 114 |
-
# ── [
|
| 115 |
install_pkg() {
|
| 116 |
if [ -d wheels ] && ls wheels/*.whl >/dev/null 2>&1; then
|
| 117 |
"$VPY" -m pip install --no-index --find-links wheels "$1" && return 0
|
|
@@ -124,16 +253,16 @@ install_pkg() {
|
|
| 124 |
case "$MODE" in
|
| 125 |
extras)
|
| 126 |
[ -f venv/.extras-ok ] || {
|
| 127 |
-
|
|
|
|
| 128 |
install_pkg mediapipe || echo " [警告] mediapipe 安装失败(主程序不受影响)"
|
| 129 |
-
install_pkg pyrealsense2 || echo " [警告] pyrealsense2 安装失败(主程序不受影响)"
|
| 130 |
echo done > venv/.extras-ok
|
| 131 |
}
|
| 132 |
-
echo "[
|
| 133 |
exit 0 ;;
|
| 134 |
extras-torch)
|
| 135 |
[ -f venv/.torch-ok ] || {
|
| 136 |
-
echo "[
|
| 137 |
install_torch() {
|
| 138 |
if [ -d wheels ] && ls wheels/*.whl >/dev/null 2>&1; then
|
| 139 |
"$VPY" -m pip install --no-index --find-links wheels torch && return 0
|
|
@@ -144,12 +273,12 @@ case "$MODE" in
|
|
| 144 |
install_torch || echo " [警告] torch 安装失败(主程序不受影响)"
|
| 145 |
echo done > venv/.torch-ok
|
| 146 |
}
|
| 147 |
-
echo "[
|
| 148 |
exit 0 ;;
|
| 149 |
esac
|
| 150 |
|
| 151 |
-
# ── [
|
| 152 |
-
echo "[
|
| 153 |
echo
|
| 154 |
echo "【操作指引】"
|
| 155 |
echo " · 设备面板: 相机插入后约 2 秒自动出现,点击即可预览"
|
|
|
|
| 5 |
# 用法:
|
| 6 |
# ./start.sh 部署(按需) + 启动主程序
|
| 7 |
# ./start.sh reinstall 删除 venv 强制重装(出问题首选)
|
| 8 |
+
# ./start.sh extras 追加安装 mediapipe(裸手 3D 关键点)
|
| 9 |
# ./start.sh extras-torch 追加安装 CPU 版 torch
|
| 10 |
# ./start.sh help 打开 使用说明.md
|
| 11 |
#
|
| 12 |
# 依赖安装顺序: 离线 wheels/ 包 → 阿里云镜像 → 清华镜像 → 官方源
|
| 13 |
+
#
|
| 14 |
+
# 本脚本自带 venv,可在已激活 conda / 其它 venv 的终端里直接运行(互不影响)
|
| 15 |
+
#
|
| 16 |
+
# 默认已包含: D435/D405 深度相机(pyrealsense2)与手套实时骨架解算
|
| 17 |
+
# (scipy/pydantic/polars + 随包工具包,见 [4/7])
|
| 18 |
# ============================================================
|
| 19 |
set -euo pipefail
|
| 20 |
cd "$(dirname "$0")"
|
| 21 |
|
| 22 |
+
# ── 环境隔离: 调用任何 Python 之前,先清掉会「串味」的外部变量 ──
|
| 23 |
+
# 本脚本一律用项目自带 venv,但用户可能是在 conda / 另一个 venv 里跑的,
|
| 24 |
+
# 或自己设过 PYTHONHOME。这些变量会穿透进我们的 venv,把解释器指到别处
|
| 25 |
+
# (症状: 依赖明明装了却 import 失败 / pip 装到了别的环境)。
|
| 26 |
+
# 直接清空并提示,不让用户去猜;只提示,不打断。
|
| 27 |
+
if [ -n "${VIRTUAL_ENV:-}" ]; then
|
| 28 |
+
echo "[提示] 检测到已激活的虚拟环境 $VIRTUAL_ENV,本脚本不使用它(仍用项目自带 venv)"
|
| 29 |
+
fi
|
| 30 |
+
if [ -n "${CONDA_PREFIX:-}" ]; then
|
| 31 |
+
echo "[提示] 检测到已激活的 conda 环境 $CONDA_PREFIX,本脚本不使用它(仍用项目自带 venv)"
|
| 32 |
+
fi
|
| 33 |
+
if [ -n "${PYTHONHOME:-}" ]; then
|
| 34 |
+
echo "[提示] 已忽略外部变量 PYTHONHOME=$PYTHONHOME"
|
| 35 |
+
fi
|
| 36 |
+
if [ -n "${PYTHONPATH:-}" ]; then
|
| 37 |
+
echo "[提示] 已忽略外部变量 PYTHONPATH=$PYTHONPATH"
|
| 38 |
+
fi
|
| 39 |
+
unset PYTHONHOME PYTHONPATH PYTHONSTARTUP
|
| 40 |
+
# 屏蔽用户级 site-packages(~/.local/lib/pythonX.Y/...),让 venv 完全自给自足
|
| 41 |
+
export PYTHONNOUSERSITE=1
|
| 42 |
+
|
| 43 |
MODE=run
|
| 44 |
FORCE=0
|
| 45 |
case "${1:-}" in
|
|
|
|
| 63 |
exit 1
|
| 64 |
fi
|
| 65 |
|
| 66 |
+
# ── [1/7] 定位 Python(>= 3.10,推荐 3.12)──
|
| 67 |
PY=""
|
| 68 |
find_python() {
|
| 69 |
for c in python3.12 python3.11 python3.10 python3; do
|
|
|
|
| 83 |
echo " conda: conda create -n daq python=3.12"
|
| 84 |
exit 1
|
| 85 |
fi
|
| 86 |
+
echo "[1/7] 使用 Python: $PY"
|
| 87 |
+
|
| 88 |
+
# ── [2/7] venv(完整性体检 + 自愈)──
|
| 89 |
+
# 为什么体检: venv 目录在 ≠ venv 可用。
|
| 90 |
+
# ① 从别的机器拷来的 venv: python 在,但 pyvenv.cfg 指向那台机器的解释器
|
| 91 |
+
# → 一跑就报找不到 Python;
|
| 92 |
+
# ② pip 升级 / 断电 / 杀软打断: pip 被删到一半(目录还在、模块没了)→
|
| 93 |
+
# 所有 pip 命令都报 ModuleNotFoundError: pip._internal.cli。
|
| 94 |
+
# 这两类都不该让用户去猜: 先离线修(ensurepip 用 Python 自带组件),
|
| 95 |
+
# 修不动就整目录重建(同样不联网)。
|
| 96 |
+
venv_healthy() {
|
| 97 |
+
"$VPY" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)' \
|
| 98 |
+
>/dev/null 2>&1 || return 1
|
| 99 |
+
"$VPY" -m pip --version >/dev/null 2>&1 && return 0
|
| 100 |
+
echo "[2/7] 检测到 venv 的 pip 不完整,正在离线修复 ..."
|
| 101 |
+
"$VPY" -m ensurepip --upgrade >/dev/null 2>&1 || true
|
| 102 |
+
"$VPY" -m pip --version >/dev/null 2>&1
|
| 103 |
+
}
|
| 104 |
|
| 105 |
+
VPY="venv/bin/python"
|
| 106 |
+
if [ ! -x "$VPY" ]; then
|
| 107 |
+
echo "[2/7] 创建虚拟环境 venv(首次约 1 分钟)..."
|
| 108 |
+
"$PY" -m venv venv
|
| 109 |
+
elif [ "$FORCE" = 1 ]; then
|
| 110 |
+
echo "[2/7] reinstall: 删除旧 venv ..."
|
| 111 |
+
rm -rf venv
|
| 112 |
+
echo "[2/7] 创建虚拟环境 venv(首次约 1 分钟)..."
|
| 113 |
+
"$PY" -m venv venv
|
| 114 |
+
elif ! venv_healthy; then
|
| 115 |
+
echo "[2/7] venv 不可用(pip 缺失或解释器异常),自动重建(不需要联网,约 1 分钟)..."
|
| 116 |
rm -rf venv
|
|
|
|
|
|
|
|
|
|
| 117 |
"$PY" -m venv venv
|
| 118 |
fi
|
| 119 |
+
if [ ! -x "$VPY" ]; then
|
| 120 |
+
echo "[错误 C] 虚拟环境创建失败:"
|
| 121 |
+
echo " ① Ubuntu/Debian 先装: sudo apt install python3.12-venv"
|
| 122 |
+
echo " ② 磁盘空间不足(需约 2GB);③ 目录写权限;④ 路径含特殊字符"
|
| 123 |
+
exit 1
|
| 124 |
+
fi
|
| 125 |
|
| 126 |
+
# ── [3/7] 依赖 ──
|
| 127 |
HASH="$(md5sum requirements.txt | cut -d' ' -f1)"
|
| 128 |
NEED_INSTALL=0
|
| 129 |
if [ "$FORCE" = 1 ]; then
|
|
|
|
| 135 |
install_req() {
|
| 136 |
local req="$1"
|
| 137 |
if [ -d wheels ] && ls wheels/*.whl >/dev/null 2>&1; then
|
| 138 |
+
echo "[3/7] 检测到 wheels/ 离线包,优先离线安装 ..."
|
| 139 |
"$VPY" -m pip install --no-index --find-links wheels -r "$req" && return 0
|
| 140 |
+
echo "[3/7] 离线包安装失败,转在线安装 ..."
|
| 141 |
fi
|
| 142 |
"$VPY" -m pip install -r "$req" -i https://mirrors.aliyun.com/pypi/simple/ && return 0
|
| 143 |
"$VPY" -m pip install -r "$req" -i https://pypi.tuna.tsinghua.edu.cn/simple && return 0
|
| 144 |
"$VPY" -m pip install -r "$req"
|
| 145 |
}
|
| 146 |
|
| 147 |
+
err_d() {
|
| 148 |
+
echo "[错误 D] 依赖下载/安装失败"
|
| 149 |
+
echo " 先看上一屏的报错再对症处理:"
|
| 150 |
+
echo " · 报 ModuleNotFoundError: pip._internal.cli / No module named 'pip'"
|
| 151 |
+
echo " → venv 里的 pip 坏了(升级被打断 / 被杀软删了文件),不是网络问题。"
|
| 152 |
+
echo " 执行 ./start.sh reinstall 重建 venv(约 1 分钟,不需要联网)。"
|
| 153 |
+
echo " · 报 Could not find a version / connection / timeout / 证书错误"
|
| 154 |
+
echo " → 才是网络问题: 检查网络;内网环境请用 scripts/pack_wheels.py 生成 wheels/ 离线包。"
|
| 155 |
+
exit 1
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
if [ "$NEED_INSTALL" = 1 ]; then
|
| 159 |
+
echo "[3/7] 安装依赖(首次约 3-10 分钟,之后启动秒开)..."
|
| 160 |
+
# 这里以前有一句静默的 `pip install --upgrade pip`,已移除 —— 它是「半装
|
| 161 |
+
# pip」的唯一来源: pip 升级是「先删旧、再解新」,中途被打断(关窗口 /
|
| 162 |
+
# 断网 / 被杀软删)就只剩一个空壳,之后每次启动都报
|
| 163 |
+
# ModuleNotFoundError: pip._internal.cli,而用户看到的是「依赖安装失败」
|
| 164 |
+
# (错误 D)—— 方向完全跑偏,而且重试多少次都一样。
|
| 165 |
+
# Python 3.10+ 自带的 pip 足够安装本项目的全部依赖,故不再自动升级;
|
| 166 |
+
# 确有需要时手动执行(坏了的 pip 下次启动会被 [2/7] 体检修好):
|
| 167 |
+
# venv/bin/python -m pip install --upgrade pip
|
| 168 |
if ! install_req requirements.txt; then
|
| 169 |
+
# 安装失败: 先确认 pip 本身还在不在(被半装 / 被杀软删是常见现场)
|
| 170 |
+
if "$VPY" -m pip --version >/dev/null 2>&1; then
|
| 171 |
+
err_d
|
| 172 |
+
fi
|
| 173 |
+
echo "[3/7] pip 异常,尝试离线修复 ..."
|
| 174 |
+
"$VPY" -m ensurepip --upgrade >/dev/null 2>&1 || true
|
| 175 |
+
"$VPY" -m pip --version >/dev/null 2>&1 || err_d
|
| 176 |
+
echo "[3/7] pip 已修复,重试安装 ..."
|
| 177 |
+
install_req requirements.txt || err_d
|
| 178 |
fi
|
| 179 |
echo "$HASH" > venv/.deps-ok
|
| 180 |
fi
|
| 181 |
|
| 182 |
+
# ── [4/7] 手套工具包(手部骨架解算)──
|
| 183 |
+
# 实时骨架解算依赖第三方手套工具包,位于项目根同级(core/glove_keypoint_solver.py
|
| 184 |
+
# 的 find_toolkit_dir() 按目录名 stouch_glove_toolkit* 找)。裁剪版随 wheels/ 分发,
|
| 185 |
+
# 首次部署在这里展开到项目根。**缺失只警告、不拦截** —— 触觉/IMU/相机录制都不受影响。
|
| 186 |
+
TOOLKIT=""
|
| 187 |
+
find_toolkit() {
|
| 188 |
+
TOOLKIT=""
|
| 189 |
+
for d in stouch_glove_toolkit*/; do
|
| 190 |
+
if [ -d "$d" ]; then TOOLKIT="${d%/}"; return 0; fi
|
| 191 |
+
done
|
| 192 |
+
return 1
|
| 193 |
+
}
|
| 194 |
+
find_toolkit || true
|
| 195 |
+
|
| 196 |
+
if [ -z "$TOOLKIT" ] && [ -f wheels/toolkit/glove_toolkit.zip ]; then
|
| 197 |
+
echo "[4/7] 展开随包的手套工具包(骨架解算)..."
|
| 198 |
+
"$VPY" -c 'import sys, zipfile; zipfile.ZipFile(sys.argv[1]).extractall(".")' \
|
| 199 |
+
wheels/toolkit/glove_toolkit.zip
|
| 200 |
+
find_toolkit || true
|
| 201 |
+
fi
|
| 202 |
+
|
| 203 |
+
if [ -z "$TOOLKIT" ]; then
|
| 204 |
+
echo "[4/7] [警告] 未找到手套工具包 —— 主程序照常启动,但没有实时手部骨架解算。"
|
| 205 |
+
echo " 补装: 在开发机执行 python scripts/pack_toolkit.py,"
|
| 206 |
+
echo " 把生成的 wheels/ 整个拷到本目录后重跑 ./start.sh"
|
| 207 |
+
else
|
| 208 |
+
# 工具包在 ≠ 能用:解算链还要 scipy/pydantic/polars 等依赖。冒烟自检
|
| 209 |
+
# (import main) 查不到这些 —— 它们都是惰性导入,缺了要到连手套时才报错。
|
| 210 |
+
# 这里按「工具包 + 依赖清单版本」缓存结论,命中缓存就不重复跑(省 ~1s)。
|
| 211 |
+
TK_MARK="venv/.toolkit-ok"
|
| 212 |
+
TK_SIG="$TOOLKIT:$HASH"
|
| 213 |
+
if [ -f "$TK_MARK" ] && [ "$(cat "$TK_MARK" 2>/dev/null)" = "$TK_SIG" ]; then
|
| 214 |
+
echo "[4/7] 手套工具包就绪:$TOOLKIT"
|
| 215 |
+
else
|
| 216 |
+
echo "[4/7] 校验骨架解算链($TOOLKIT)..."
|
| 217 |
+
if TK_OUT="$("$VPY" -c '
|
| 218 |
+
import sys
|
| 219 |
+
sys.path.insert(0, sys.argv[1])
|
| 220 |
+
from glove_sdk.interfaces.solver import HandSolver
|
| 221 |
+
' "$TOOLKIT" 2>&1)"; then
|
| 222 |
+
echo "$TK_SIG" > "$TK_MARK"
|
| 223 |
+
echo "[4/7] 手套工具包就绪:实时手部骨架解算已具备"
|
| 224 |
+
else
|
| 225 |
+
echo "[4/7] [警告] 工具包在,但解算链导入失败(多半是依赖没装全)。"
|
| 226 |
+
echo " 原因: $(printf '%s\n' "$TK_OUT" | tail -n 1)"
|
| 227 |
+
echo " 重装依赖: ./start.sh reinstall"
|
| 228 |
+
echo " 主程序���常启动,只是没有手部骨架。"
|
| 229 |
+
fi
|
| 230 |
+
fi
|
| 231 |
+
fi
|
| 232 |
+
|
| 233 |
+
# ── [5/7] 冒烟自检 ──
|
| 234 |
+
echo "[5/7] 依赖自检 ..."
|
| 235 |
if ! "$VPY" -c "import main" >/dev/null 2>&1; then
|
| 236 |
echo "[错误 E] 依赖自检失败。查看具体原因:"
|
| 237 |
echo " venv/bin/python -c \"import main\""
|
| 238 |
echo "重装: ./start.sh reinstall"
|
| 239 |
exit 1
|
| 240 |
fi
|
| 241 |
+
echo "[5/7] 依赖自检通过"
|
| 242 |
|
| 243 |
+
# ── [6/7] 可选功能 ──
|
| 244 |
install_pkg() {
|
| 245 |
if [ -d wheels ] && ls wheels/*.whl >/dev/null 2>&1; then
|
| 246 |
"$VPY" -m pip install --no-index --find-links wheels "$1" && return 0
|
|
|
|
| 253 |
case "$MODE" in
|
| 254 |
extras)
|
| 255 |
[ -f venv/.extras-ok ] || {
|
| 256 |
+
# pyrealsense2(D435/D405)自本次起随 requirements.txt 默认安装,不再属于可选包
|
| 257 |
+
echo "[6/7] 安装可选功能: mediapipe ..."
|
| 258 |
install_pkg mediapipe || echo " [警告] mediapipe 安装失败(主程序不受影响)"
|
|
|
|
| 259 |
echo done > venv/.extras-ok
|
| 260 |
}
|
| 261 |
+
echo "[6/7] 可选功能安装完成。运行 ./start.sh 启动主程序。"
|
| 262 |
exit 0 ;;
|
| 263 |
extras-torch)
|
| 264 |
[ -f venv/.torch-ok ] || {
|
| 265 |
+
echo "[6/7] 安装可选功能: torch CPU 版 ..."
|
| 266 |
install_torch() {
|
| 267 |
if [ -d wheels ] && ls wheels/*.whl >/dev/null 2>&1; then
|
| 268 |
"$VPY" -m pip install --no-index --find-links wheels torch && return 0
|
|
|
|
| 273 |
install_torch || echo " [警告] torch 安装失败(主程序不受影响)"
|
| 274 |
echo done > venv/.torch-ok
|
| 275 |
}
|
| 276 |
+
echo "[6/7] 可选功能安装完成。运行 ./start.sh 启动主程序。"
|
| 277 |
exit 0 ;;
|
| 278 |
esac
|
| 279 |
|
| 280 |
+
# ── [7/7] 启动 ──
|
| 281 |
+
echo "[7/7] 启动主程序 ..."
|
| 282 |
echo
|
| 283 |
echo "【操作指引】"
|
| 284 |
echo " · 设备面板: 相机插入后约 2 秒自动出现,点击即可预览"
|
|
@@ -14,6 +14,7 @@ rem start_lite.bat help
|
|
| 14 |
rem
|
| 15 |
rem ֻ��װ requirements-lite.txt ���������������� venv_lite/��
|
| 16 |
rem �������� venv/ ����Ӱ�죩��wheels/ �� data/ ���汾���á�
|
|
|
|
| 17 |
rem ������װ˳��: wheels\ ���߰� �� �����ƾ��� �� �廪���� �� �ٷ�Դ
|
| 18 |
rem ������ A-G ��Ӧ ʹ��˵��_lite.md���쳣�����½ڣ�
|
| 19 |
rem
|
|
@@ -29,6 +30,22 @@ rem ============================================================
|
|
| 29 |
setlocal enabledelayedexpansion
|
| 30 |
cd /d "%~dp0"
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
set "FORCE=0"
|
| 33 |
if /i "%~1"=="reinstall" set "FORCE=1"
|
| 34 |
if /i "%~1"=="help" goto :show_help
|
|
@@ -83,12 +100,34 @@ goto :errA
|
|
| 83 |
echo [1/6] ʹ�� Python: %PY%
|
| 84 |
|
| 85 |
rem ���� [2/6] ����� venv_lite ����
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
echo [2/6] ��������� venv_lite���״�Լ 1 ���ӣ�...
|
| 93 |
rem ע��: PY �����Ǵ��ո�����py -3.12 / python�������ܼ�����
|
| 94 |
%PY% -m venv "venv_lite"
|
|
@@ -105,9 +144,27 @@ if "%STAMP%"=="%SIG%" goto :after_deps
|
|
| 105 |
|
| 106 |
:install_deps
|
| 107 |
echo [3/6] ��װ�������״�Լ 3-8 ���ӣ�֮�������뿪��...
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
call :pip_install_req
|
| 110 |
if errorlevel 1 goto :errD
|
|
|
|
| 111 |
> "venv_lite\.deps-lite-ok" echo %SIG%
|
| 112 |
|
| 113 |
rem ���� [4/6] ����ð���Լ죨�� import ��ͨ��������
|
|
@@ -141,6 +198,17 @@ if errorlevel 1 exit /b 1
|
|
| 141 |
set "PY=%*"
|
| 142 |
exit /b 0
|
| 143 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
rem ���� ��� wheels\ Ŀ¼���Ƿ��� .whl �ļ� ����
|
| 145 |
:wheels_exists
|
| 146 |
dir /b "wheels\*.whl" >nul 2>&1
|
|
@@ -220,11 +288,19 @@ exit /b 1
|
|
| 220 |
echo.
|
| 221 |
echo [���� D] ��������/��װʧ��
|
| 222 |
echo ------------------------------------------------------------
|
| 223 |
-
echo
|
| 224 |
-
echo
|
| 225 |
-
echo
|
| 226 |
-
echo
|
| 227 |
-
echo
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
echo.
|
| 229 |
pause
|
| 230 |
exit /b 1
|
|
|
|
| 14 |
rem
|
| 15 |
rem ֻ��װ requirements-lite.txt ���������������� venv_lite/��
|
| 16 |
rem �������� venv/ ����Ӱ�죩��wheels/ �� data/ ���汾���á�
|
| 17 |
+
rem ���ű��Դ� venv�������Ѽ��� conda / ���� venv �Ĵ�����ֱ�����У�����Ӱ�죩
|
| 18 |
rem ������װ˳��: wheels\ ���߰� �� �����ƾ��� �� �廪���� �� �ٷ�Դ
|
| 19 |
rem ������ A-G ��Ӧ ʹ��˵��_lite.md���쳣�����½ڣ�
|
| 20 |
rem
|
|
|
|
| 30 |
setlocal enabledelayedexpansion
|
| 31 |
cd /d "%~dp0"
|
| 32 |
|
| 33 |
+
rem ���� ��������: �����κ� Python ֮ǰ��������ᡸ��ζ�����ⲿ���� ����
|
| 34 |
+
rem ���ű�һ������Ŀ�Դ� venv�����û��������� conda / ��һ�� venv ��˫���ģ�
|
| 35 |
+
rem ���Լ���� PYTHONHOME����Щ�����ᴩ�����ǵ� venv���ѽ�����ָ����
|
| 36 |
+
rem ��֢״: ��������װ��ȴ import ʧ�� / DLL load failed / pip װ���˱�Ļ�������
|
| 37 |
+
rem ֱ����ղ���ʾ�������û�ȥ�£�ֻ��ʾ������ϡ�
|
| 38 |
+
if defined VIRTUAL_ENV echo [��ʾ] ���Ѽ��������� "%VIRTUAL_ENV%"�����ű���ʹ������������Ŀ�Դ� venv��
|
| 39 |
+
if defined CONDA_PREFIX echo [��ʾ] ���Ѽ���� conda ���� "%CONDA_PREFIX%"�����ű���ʹ������������Ŀ�Դ� venv��
|
| 40 |
+
if defined PYTHONHOME echo [��ʾ] �Ѻ����ⲿ���� PYTHONHOME="%PYTHONHOME%"
|
| 41 |
+
if defined PYTHONPATH echo [��ʾ] �Ѻ����ⲿ���� PYTHONPATH="%PYTHONPATH%"
|
| 42 |
+
set "PYTHONHOME="
|
| 43 |
+
set "PYTHONPATH="
|
| 44 |
+
set "PYTHONSTARTUP="
|
| 45 |
+
rem �����û��� site-packages��%APPDATA%\Python �µİ������� venv ��ȫ�Ը�����
|
| 46 |
+
set "PYTHONNOUSERSITE=1"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
set "FORCE=0"
|
| 50 |
if /i "%~1"=="reinstall" set "FORCE=1"
|
| 51 |
if /i "%~1"=="help" goto :show_help
|
|
|
|
| 100 |
echo [1/6] ʹ�� Python: %PY%
|
| 101 |
|
| 102 |
rem ���� [2/6] ����� venv_lite ����
|
| 103 |
+
rem Ϊʲô���: venv Ŀ¼�� �� venv ���á�
|
| 104 |
+
rem �� �ӱ�Ļ��������� venv: python.exe �ڣ�������Ӳ���������̨������
|
| 105 |
+
rem Python ·�� �� һ�ܾ͡�No Python at ...����
|
| 106 |
+
rem �� pip ���� / ɱ�� / �ϵ���: pip ��ɾ��һ�루Ŀ¼���ڡ�ģ��û�ˣ���
|
| 107 |
+
rem ���� pip ����� ModuleNotFoundError: pip._internal.cli��
|
| 108 |
+
rem ������������û�ȥ��: һ���������ޣ�ensurepip �� Python �Դ��������
|
| 109 |
+
rem ��������Ŀ¼�ؽ���ͬ������������
|
| 110 |
+
if not exist "%VPY%" goto :make_venv
|
| 111 |
+
if "%FORCE%"=="1" goto :reinstall_venv
|
| 112 |
+
rem ��� ��: �����������ܲ����ܡ��汾�������������� venv ���������Σ�
|
| 113 |
+
"%VPY%" -c "import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)" >nul 2>&1
|
| 114 |
+
if errorlevel 1 goto :venv_broken
|
| 115 |
+
rem ��� ��: pip �Ƿ���������װ pip ���������Σ�
|
| 116 |
+
"%VPY%" -m pip --version >nul 2>&1
|
| 117 |
+
if not errorlevel 1 goto :deps_check
|
| 118 |
+
echo [2/6] �� venv_lite �� pip ������������������ ...
|
| 119 |
+
"%VPY%" -m ensurepip --upgrade >nul 2>&1
|
| 120 |
+
"%VPY%" -m pip --version >nul 2>&1
|
| 121 |
+
if not errorlevel 1 goto :deps_check
|
| 122 |
+
:venv_broken
|
| 123 |
+
echo [2/6] venv_lite �����ã�pip ȱʧ��������쳣�����Զ��ؽ�������Ҫ������Լ 1 ���ӣ�...
|
| 124 |
+
goto :reinstall_venv_do
|
| 125 |
+
:reinstall_venv
|
| 126 |
+
echo [2/6] reinstall: ɾ���� venv_lite ...
|
| 127 |
+
:reinstall_venv_do
|
| 128 |
+
rmdir /s /q "venv_lite" 2>nul
|
| 129 |
+
if exist "%VPY%" goto :errC2
|
| 130 |
+
:make_venv
|
| 131 |
echo [2/6] ��������� venv_lite���״�Լ 1 ���ӣ�...
|
| 132 |
rem ע��: PY �����Ǵ��ո�����py -3.12 / python�������ܼ�����
|
| 133 |
%PY% -m venv "venv_lite"
|
|
|
|
| 144 |
|
| 145 |
:install_deps
|
| 146 |
echo [3/6] ��װ�������״�Լ 3-8 ���ӣ�֮�������뿪��...
|
| 147 |
+
rem ������������������������������������������������������������������������������������������������������������������������
|
| 148 |
+
rem ������ǰ��һ�侲Ĭ�� pip install --upgrade pip�����Ƴ� ���� ���ǡ���װ pip��
|
| 149 |
+
rem ��Ψһ��Դ: pip �����ǡ���ɾ�ɡ��ٽ��¡�����;����ϣ��ش��� / ���� /
|
| 150 |
+
rem ɱ�� / �ϵ磩��ֻʣһ���տǣ�֮��ÿ����������
|
| 151 |
+
rem ModuleNotFoundError: pip._internal.cli�����û��������ǡ���������ʧ�ܡ�
|
| 152 |
+
rem ������ D������ ������ȫ��ƫ���������Զ��ٴζ�һ����
|
| 153 |
+
rem Python 3.10+ �Դ��� pip �㹻װ����Ŀ��ȫ���������ʲ����Զ�������
|
| 154 |
+
rem ȷ����Ҫ���� cmd ���ֶ�ִ�У����˵� pip �´������ᱻ [2/6] ����ã�:
|
| 155 |
+
rem venv_lite\Scripts\python.exe -m pip install --upgrade pip
|
| 156 |
+
rem ������������������������������������������������������������������������������������������������������������������������
|
| 157 |
+
call :pip_install_req
|
| 158 |
+
if not errorlevel 1 goto :deps_write_ok
|
| 159 |
+
rem ��װʧ��: ��ȷ�� pip �������ڲ��ڣ�����װ / ��ɱ��ɾ�dz����ֳ���
|
| 160 |
+
"%VPY%" -m pip --version >nul 2>&1
|
| 161 |
+
if not errorlevel 1 goto :errD
|
| 162 |
+
call :repair_pip
|
| 163 |
+
if errorlevel 1 goto :errD
|
| 164 |
+
echo [3/6] pip ����������װ ...
|
| 165 |
call :pip_install_req
|
| 166 |
if errorlevel 1 goto :errD
|
| 167 |
+
:deps_write_ok
|
| 168 |
> "venv_lite\.deps-lite-ok" echo %SIG%
|
| 169 |
|
| 170 |
rem ���� [4/6] ����ð���Լ죨�� import ��ͨ��������
|
|
|
|
| 198 |
set "PY=%*"
|
| 199 |
exit /b 0
|
| 200 |
|
| 201 |
+
rem ������������������������������������������������������������������������������������������������������������������������
|
| 202 |
+
rem �ӳ���: pip ��װʱ�������Ծ�
|
| 203 |
+
rem ensurepip �� Python �Դ������װ pip�������������÷��ط��㣬
|
| 204 |
+
rem �ɵ��÷�����������װ����ֱ�ӱ������ٲ��о�ֻ���ؽ� venv����
|
| 205 |
+
rem ������������������������������������������������������������������������������������������������������������������������
|
| 206 |
+
:repair_pip
|
| 207 |
+
echo [3/6] pip �쳣������������ ...
|
| 208 |
+
"%VPY%" -m ensurepip --upgrade >nul 2>&1
|
| 209 |
+
"%VPY%" -m pip --version >nul 2>&1
|
| 210 |
+
exit /b %errorlevel%
|
| 211 |
+
|
| 212 |
rem ���� ��� wheels\ Ŀ¼���Ƿ��� .whl �ļ� ����
|
| 213 |
:wheels_exists
|
| 214 |
dir /b "wheels\*.whl" >nul 2>&1
|
|
|
|
| 288 |
echo.
|
| 289 |
echo [���� D] ��������/��װʧ��
|
| 290 |
echo ------------------------------------------------------------
|
| 291 |
+
echo �ȿ���һ���ı������ٶ�֢����:
|
| 292 |
+
echo.
|
| 293 |
+
echo �� �� ModuleNotFoundError: pip._internal.cli / No module named 'pip'
|
| 294 |
+
echo �� venv ��� pip ���ˣ���������� / ɱ��ɾ���ļ����������������⡣
|
| 295 |
+
echo ֱ��˫�� start_lite.bat reinstall �ؽ� venv��Լ 1 ���ӣ�����Ҫ��������
|
| 296 |
+
echo �� �� No Python at ... / �Ҳ��� Python
|
| 297 |
+
echo �� venv �Ǵӱ�Ļ��������ģ�˫�� start_lite.bat reinstall �ؽ����ɡ�
|
| 298 |
+
echo �� �� Could not find a version / connection / timeout / ֤�����
|
| 299 |
+
echo �� ���������Ȩ������:
|
| 300 |
+
echo 1. �������: �Ժ�˫�� start_lite.bat ���ԣ������ز��ֻỺ�棩
|
| 301 |
+
echo 2. ��˾����/����ǽ: ����ϵ����Ա��ͨ pypi ����ʹ�����߰�
|
| 302 |
+
echo ����Ա�� scripts\pack_wheels.py --lite ���� wheels\ Ŀ¼
|
| 303 |
+
echo 3. ɱ������/����ǽ���� pip: ���������������
|
| 304 |
echo.
|
| 305 |
pause
|
| 306 |
exit /b 1
|
|
@@ -11,12 +11,35 @@
|
|
| 11 |
# 与主程序 venv/ 互不影响);wheels/ 与 data/ 两版本共用。
|
| 12 |
# 依赖安装顺序: 离线 wheels/ 包 → 阿里云镜像 → 清华镜像 → 官方源
|
| 13 |
#
|
|
|
|
|
|
|
| 14 |
# 夹爪(UMI/Fays S80M): 原生资源 core/gripper/native(约 460MB)随本包
|
| 15 |
# 下发,[B] 会逐项校验,缺失报 [错误 B] 并拒启;Windows 包不带该资源。
|
| 16 |
# ============================================================
|
| 17 |
set -euo pipefail
|
| 18 |
cd "$(dirname "$0")"
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
FORCE=0
|
| 21 |
case "${1:-}" in
|
| 22 |
reinstall) FORCE=1 ;;
|
|
@@ -99,16 +122,43 @@ elif ! find_python; then
|
|
| 99 |
fi
|
| 100 |
echo "[1/6] 使用 Python: $PY"
|
| 101 |
|
| 102 |
-
# ── [2/6] venv_lite ──
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
echo "[2/6] reinstall: 删除旧 venv_lite ..."
|
| 105 |
rm -rf venv_lite
|
| 106 |
-
fi
|
| 107 |
-
if [ ! -x venv_lite/bin/python ]; then
|
| 108 |
echo "[2/6] 创建虚拟环境 venv_lite(首次约 1 分钟)..."
|
| 109 |
"$PY" -m venv venv_lite
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
fi
|
| 111 |
-
VPY="venv_lite/bin/python"
|
| 112 |
|
| 113 |
# ── [3/6] 依赖(requirements-lite.txt 的 mtime+size 签名驱动)──
|
| 114 |
HASH="$(md5sum requirements-lite.txt | cut -d' ' -f1)"
|
|
@@ -131,12 +181,37 @@ install_req() {
|
|
| 131 |
"$VPY" -m pip install -r "$req"
|
| 132 |
}
|
| 133 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
if [ "$NEED_INSTALL" = 1 ]; then
|
| 135 |
echo "[3/6] 安装依赖(首次约 3-8 分钟,之后启动秒开)..."
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
if ! install_req requirements-lite.txt; then
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
fi
|
| 141 |
echo "$HASH" > venv_lite/.deps-lite-ok
|
| 142 |
fi
|
|
|
|
| 11 |
# 与主程序 venv/ 互不影响);wheels/ 与 data/ 两版本共用。
|
| 12 |
# 依赖安装顺序: 离线 wheels/ 包 → 阿里云镜像 → 清华镜像 → 官方源
|
| 13 |
#
|
| 14 |
+
# 本脚本自带 venv_lite,可在已激活 conda / 其它 venv 的终端里直接运行(互不影响)
|
| 15 |
+
#
|
| 16 |
# 夹爪(UMI/Fays S80M): 原生资源 core/gripper/native(约 460MB)随本包
|
| 17 |
# 下发,[B] 会逐项校验,缺失报 [错误 B] 并拒启;Windows 包不带该资源。
|
| 18 |
# ============================================================
|
| 19 |
set -euo pipefail
|
| 20 |
cd "$(dirname "$0")"
|
| 21 |
|
| 22 |
+
# ── 环境隔离: 调用任何 Python 之前,先清掉会「串味」的外部变量 ──
|
| 23 |
+
# 本脚本一律用项目自带 venv_lite,但用户可能是在 conda / 另一个 venv 里跑的,
|
| 24 |
+
# 或自己设过 PYTHONHOME。这些变量会穿透进我们的 venv,把解释器指到别处
|
| 25 |
+
# (症状: 依赖明明装了却 import 失败 / pip 装到了别的环境)。
|
| 26 |
+
# 直接清空并提示,不让用户去猜;只提示,不打断。
|
| 27 |
+
if [ -n "${VIRTUAL_ENV:-}" ]; then
|
| 28 |
+
echo "[提示] 检测到已激活的虚拟环境 $VIRTUAL_ENV,本脚本不使用它(仍用项目自带 venv_lite)"
|
| 29 |
+
fi
|
| 30 |
+
if [ -n "${CONDA_PREFIX:-}" ]; then
|
| 31 |
+
echo "[提示] 检测到已激活的 conda 环境 $CONDA_PREFIX,本脚本不使用它(仍用项目自带 venv_lite)"
|
| 32 |
+
fi
|
| 33 |
+
if [ -n "${PYTHONHOME:-}" ]; then
|
| 34 |
+
echo "[提示] 已忽略外部变量 PYTHONHOME=$PYTHONHOME"
|
| 35 |
+
fi
|
| 36 |
+
if [ -n "${PYTHONPATH:-}" ]; then
|
| 37 |
+
echo "[提示] 已忽略外部变量 PYTHONPATH=$PYTHONPATH"
|
| 38 |
+
fi
|
| 39 |
+
unset PYTHONHOME PYTHONPATH PYTHONSTARTUP
|
| 40 |
+
# 屏蔽用户级 site-packages(~/.local/lib/pythonX.Y/...),让 venv 完全自给自足
|
| 41 |
+
export PYTHONNOUSERSITE=1
|
| 42 |
+
|
| 43 |
FORCE=0
|
| 44 |
case "${1:-}" in
|
| 45 |
reinstall) FORCE=1 ;;
|
|
|
|
| 122 |
fi
|
| 123 |
echo "[1/6] 使用 Python: $PY"
|
| 124 |
|
| 125 |
+
# ── [2/6] venv_lite(完整性体检 + 自愈)──
|
| 126 |
+
# 为什么体检: venv 目录在 ≠ venv 可用。
|
| 127 |
+
# ① 从别的机器拷来的 venv: python 在,但 pyvenv.cfg 指向那台机器的解释器
|
| 128 |
+
# → 一跑就报找不到 Python;
|
| 129 |
+
# ② pip 升级 / 断电 / 杀软打断: pip 被删到一半(目录还在、模块没了)→
|
| 130 |
+
# 所有 pip 命令都报 ModuleNotFoundError: pip._internal.cli。
|
| 131 |
+
# 这两类都不该让用户去猜: 先离线修(ensurepip 用 Python 自带组件),
|
| 132 |
+
# 修不动就整目录重建(同样不联网)。
|
| 133 |
+
venv_healthy() {
|
| 134 |
+
"$VPY" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 10) else 1)' \
|
| 135 |
+
>/dev/null 2>&1 || return 1
|
| 136 |
+
"$VPY" -m pip --version >/dev/null 2>&1 && return 0
|
| 137 |
+
echo "[2/6] 检测到 venv_lite 的 pip 不完整,正在离线修复 ..."
|
| 138 |
+
"$VPY" -m ensurepip --upgrade >/dev/null 2>&1 || true
|
| 139 |
+
"$VPY" -m pip --version >/dev/null 2>&1
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
VPY="venv_lite/bin/python"
|
| 143 |
+
if [ ! -x "$VPY" ]; then
|
| 144 |
+
echo "[2/6] 创建虚拟环境 venv_lite(首次约 1 分钟)..."
|
| 145 |
+
"$PY" -m venv venv_lite
|
| 146 |
+
elif [ "$FORCE" = 1 ]; then
|
| 147 |
echo "[2/6] reinstall: 删除旧 venv_lite ..."
|
| 148 |
rm -rf venv_lite
|
|
|
|
|
|
|
| 149 |
echo "[2/6] 创建虚拟环境 venv_lite(首次约 1 分钟)..."
|
| 150 |
"$PY" -m venv venv_lite
|
| 151 |
+
elif ! venv_healthy; then
|
| 152 |
+
echo "[2/6] venv_lite 不可用(pip 缺失或解释器异常),自动重建(不需要联网,约 1 分钟)..."
|
| 153 |
+
rm -rf venv_lite
|
| 154 |
+
"$PY" -m venv venv_lite
|
| 155 |
+
fi
|
| 156 |
+
if [ ! -x "$VPY" ]; then
|
| 157 |
+
echo "[错误 C] 虚拟环境创建失败:"
|
| 158 |
+
echo " ① Ubuntu/Debian 先装: sudo apt install python3.12-venv"
|
| 159 |
+
echo " ② 磁盘空间不足(需约 2GB);③ 目录写权限;④ 路径含特殊字符"
|
| 160 |
+
exit 1
|
| 161 |
fi
|
|
|
|
| 162 |
|
| 163 |
# ── [3/6] 依赖(requirements-lite.txt 的 mtime+size 签名驱动)──
|
| 164 |
HASH="$(md5sum requirements-lite.txt | cut -d' ' -f1)"
|
|
|
|
| 181 |
"$VPY" -m pip install -r "$req"
|
| 182 |
}
|
| 183 |
|
| 184 |
+
err_d() {
|
| 185 |
+
echo "[错误 D] 依赖下载/安装失败"
|
| 186 |
+
echo " 先看上一屏的报错再对症处理:"
|
| 187 |
+
echo " · 报 ModuleNotFoundError: pip._internal.cli / No module named 'pip'"
|
| 188 |
+
echo " → venv_lite 里的 pip 坏了(升级被打断 / 被杀软删了文件),不是网络问题。"
|
| 189 |
+
echo " 执行 ./start_lite.sh reinstall 重建(约 1 分钟,不需要联网)。"
|
| 190 |
+
echo " · 报 Could not find a version / connection / timeout / 证书错误"
|
| 191 |
+
echo " → 才是网络问题: 检查网络;内网环境请用 scripts/pack_wheels.py --lite 生成 wheels/ 离线包。"
|
| 192 |
+
exit 1
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
if [ "$NEED_INSTALL" = 1 ]; then
|
| 196 |
echo "[3/6] 安装依赖(首次约 3-8 分钟,之后启动秒开)..."
|
| 197 |
+
# 这里以前有一句静默的 `pip install --upgrade pip`,已移除 —— 它是「半装
|
| 198 |
+
# pip」的唯一来源: pip 升级是「先删旧、再解新」,中途被打断(��窗口 /
|
| 199 |
+
# 断网 / 被杀软删)就只剩一个空壳,之后每次启动都报
|
| 200 |
+
# ModuleNotFoundError: pip._internal.cli,而用户看到的是「依赖安装失败」
|
| 201 |
+
# (错误 D)—— 方向完全跑偏,而且重试多少次都一样。
|
| 202 |
+
# Python 3.10+ 自带的 pip 足够安装本项目的全部依赖,故不再自动升级;
|
| 203 |
+
# 确有需要时手动执行(坏了的 pip 下次启动会被 [2/6] 体检修好):
|
| 204 |
+
# venv_lite/bin/python -m pip install --upgrade pip
|
| 205 |
if ! install_req requirements-lite.txt; then
|
| 206 |
+
# 安装失败: 先确认 pip 本身还在不在(被半装 / 被杀软删是常见现场)
|
| 207 |
+
if "$VPY" -m pip --version >/dev/null 2>&1; then
|
| 208 |
+
err_d
|
| 209 |
+
fi
|
| 210 |
+
echo "[3/6] pip 异常,尝试离线修复 ..."
|
| 211 |
+
"$VPY" -m ensurepip --upgrade >/dev/null 2>&1 || true
|
| 212 |
+
"$VPY" -m pip --version >/dev/null 2>&1 || err_d
|
| 213 |
+
echo "[3/6] pip 已修复,重试安装 ..."
|
| 214 |
+
install_req requirements-lite.txt || err_d
|
| 215 |
fi
|
| 216 |
echo "$HASH" > venv_lite/.deps-lite-ok
|
| 217 |
fi
|
|
@@ -0,0 +1,641 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""帧空洞全库审计:录制里「视频静止后跳变」的所有段落(只读)。
|
| 3 |
+
|
| 4 |
+
背景:episode-099 报「前 40 帧静止不动」,实测开头 45 帧是真帧、真正的缺陷是
|
| 5 |
+
row44→45 之间少了 4.68 秒(hardware_ns 与 wall_time 同步跳)。一次录制丢一段,
|
| 6 |
+
事后在视频里表现为「静止 → 跳变」。本脚本把**全库**这种段落一次数清楚,作为
|
| 7 |
+
后续修复的基线与回归对照。
|
| 8 |
+
|
| 9 |
+
用法:
|
| 10 |
+
venv/bin/python tools/audit_frame_gaps.py [任务目录] [选项]
|
| 11 |
+
默认 data/recordings/UMIGripper_Action_AI(相对**仓库根**,可从任意 cwd 运行)
|
| 12 |
+
|
| 13 |
+
选项:
|
| 14 |
+
--min-gap-ms 100 相邻两帧间隔 ≥ 该值才算一次异常(正常帧距 29.9~37.5ms)
|
| 15 |
+
--clock-tol-ms 100 双钟一致阈值:|Δhw − Δwall| ≤ 该值才算「两个钟都这么说」
|
| 16 |
+
--merge-rows 15 相隔 ≤ 这么多行的异常合并成**一次**事件(≤15 行内两侧都
|
| 17 |
+
停 = 整机被抢同一件事,取大不加总;**相隔更远**的一墙一戳
|
| 18 |
+
是两次独立停顿,见下「两类时钟」)
|
| 19 |
+
--no-video-check 跳过**画面复核**与 mp4 帧数校验(快,但只剩钟口径)
|
| 20 |
+
--all 连零异常的段也列出来
|
| 21 |
+
--camera-logs DIR 关联 logs/camera_service/ 的留档日志(秒级粗相关,默认关)
|
| 22 |
+
--json 输出机器可读结果
|
| 23 |
+
|
| 24 |
+
三层判据(由强到弱)
|
| 25 |
+
--------------------
|
| 26 |
+
1. **画面复核(主判据)**:把整段视频降采样成灰度,比较事件前后两帧的画面差
|
| 27 |
+
(mad)与同一段视频的「邻域逐帧差中位」和「远端饱和差中位」:
|
| 28 |
+
|
| 29 |
+
============ ========================== ==============================
|
| 30 |
+
画面连续 边界差 ≈ 邻域逐帧差(≤2×) **没丢**:画面是连的(帧到得晚,
|
| 31 |
+
不是画面上少了一截)
|
| 32 |
+
画面跳变 边界差 ≥ 3× 邻域或 ≥ 0.7×饱和 **丢了**:画面真断了一截
|
| 33 |
+
不定 介于两者之间 回落第 2/3 层判
|
| 34 |
+
============ ========================== ==============================
|
| 35 |
+
|
| 36 |
+
2026-09-18 标定:真丢的两处 ep-099 row45 = 18.6×、ep-098 row40 = 91.6×(对
|
| 37 |
+
饱和 0.75/1.62×);而 15 个「双钟都跳 ~250ms」的事件全是 0.16~1.60×,即边界
|
| 38 |
+
差**正好是一帧的运动量**(钟却说过了 8 帧)——它们不是丢帧,是画面本来就接得上。
|
| 39 |
+
2. **双钟(次判据)**:Δhw ≈ Δwall ≥ 阈值 ⇒ 两侧都这么说(无画面时按疑似计)。
|
| 40 |
+
3. **单钟(定「哪一侧停了」)**:只有墙钟跳 ⇒ **写侧打嗝**(帧按 33ms 到了、
|
| 41 |
+
只是写晚);只有戳跳 ⇒ **读侧停顿**(帧晚到,写侧靠队列垫住)。两者都只是
|
| 42 |
+
停顿,**是不是丢帧仍然由第 1 层说了算**。
|
| 43 |
+
|
| 44 |
+
两类时钟(不认识这个会得出错结论)
|
| 45 |
+
----------------------------------
|
| 46 |
+
两个戳都取自**宿主钟**,但取的地方不同 —— 这是本脚本最要紧的一条:
|
| 47 |
+
|
| 48 |
+
* ``hardware_ns`` 由采集线程在**相机 read() 返回处**盖(bridge._rgb_run 的
|
| 49 |
+
time.monotonic_ns())⇒ 它量的是**取到帧的时刻**:读侧停顿、帧晚到都记在这里。
|
| 50 |
+
- ``hw64`` ≥079 段:完整宿主单调钟,值域远超 2^32,单调递增,可信。
|
| 51 |
+
- ``trunc32`` ≤078 段:同一个钟被截成**有符号 32 位**纳秒(±2^31,每 4.295 秒
|
| 52 |
+
锯齿一次)⇒ 判空洞前必须先按 2^32 解卷,否则每次过零都是一次天文数字级的
|
| 53 |
+
假空洞。
|
| 54 |
+
- ``none`` hardware_ns 全 0(无时间戳槽位,如 lite 路径)⇒ 判不了,只报数。
|
| 55 |
+
* ``wall_time`` 由**写入线程**在**建行落盘处**盖(egodata_writer.py 的
|
| 56 |
+
time.time())⇒ 它量的是**写下来的时刻**(墙钟,会被 NTP 校时)。
|
| 57 |
+
|
| 58 |
+
于是 **Δwall − Δhw 就是「队列滞留」的变化量**(两个钟的固定偏移在差里抵消)。
|
| 59 |
+
2026-09-18 全库验过:ep-011 row162 偏移 +138.7ms、row180 −131.3ms ⇒ 先写侧积压
|
| 60 |
+
139ms、随后读侧一段空窗把积压排空;ep-014/018/007 是同一种形状。**两侧各停
|
| 61 |
+
一次、是两件事**,不是同一个洞的两半——据此删掉了早期的「配对」层(它会把
|
| 62 |
+
两次停顿捏成一次、把账记到错的桶里)。墙钟单独跳也可能是 NTP 校时,但本库的
|
| 63 |
+
墙钟事件都成对出现且互相抵消,不是校时。
|
| 64 |
+
|
| 65 |
+
口径:空洞 = 相邻两帧间隔 − 标称间隔(33.3ms),与录制侧同一个类
|
| 66 |
+
(core/frame_gap.GapWatch)——实时告警「[录制] RGB 帧空洞 …ms」与 parquet 里的
|
| 67 |
+
``*_gap_ms`` 报的就是这个数(日志里是**空洞**不是间隔,差一个标称间隔)。
|
| 68 |
+
|
| 69 |
+
退出码:发现画面复核判定为真丢的段 → 1;否则 0(与 tools/check_segment_seam.py 同)。
|
| 70 |
+
"""
|
| 71 |
+
import argparse
|
| 72 |
+
import datetime
|
| 73 |
+
import glob
|
| 74 |
+
import json
|
| 75 |
+
import os
|
| 76 |
+
import re
|
| 77 |
+
import statistics
|
| 78 |
+
import sys
|
| 79 |
+
|
| 80 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 81 |
+
sys.path.insert(0, ROOT)
|
| 82 |
+
|
| 83 |
+
from core.frame_gap import GapWatch # noqa: E402
|
| 84 |
+
|
| 85 |
+
DEFAULT_TASK_DIR = os.path.join(ROOT, "data", "recordings",
|
| 86 |
+
"UMIGripper_Action_AI")
|
| 87 |
+
COLUMNS = ("frame_index", "hardware_ns", "wall_time")
|
| 88 |
+
GRAY_SIZE = (160, 120) # 画面复核用的降采样尺寸(实测够分辨 33ms 的运动)
|
| 89 |
+
EVIDENCE_WINDOW = 15 # 邻域取多少帧算「逐帧运动水平」
|
| 90 |
+
SAT_STRIDE = 60 # 远端饱和差:隔这么多帧取一对
|
| 91 |
+
SAT_STEP = 37 # 取样步长(质数,避开周期性画面)
|
| 92 |
+
CONTINUOUS_RATIO = 2.0 # 边界差 / 邻域逐帧差 ≤ 此值 ⇒ 画面连续
|
| 93 |
+
JUMP_RATIO = 3.0 # ≥ 此值(或达饱和 0.7)⇒ 画面跳变
|
| 94 |
+
SAT_LEVEL = 0.7
|
| 95 |
+
STATIC_FLOOR = 1.5 # 8 位灰度 mad 的噪声地板(静止场景实测 0.45)
|
| 96 |
+
# 留档日志名:%Y%m%d_%H%M%S_<tag>_camera-service.log(见 uvc_camera_service.py)
|
| 97 |
+
_ARCHIVE_RE = re.compile(r"^(\d{8}_\d{6})_.*camera-service\.log$")
|
| 98 |
+
_ARCHIVE_WINDOW_S = 600.0 # 留档发生在会话结束时,故只往后找
|
| 99 |
+
_ARCHIVE_BACK_S = 5.0
|
| 100 |
+
|
| 101 |
+
_KIND_LABEL = {"both": "两侧同停", "wall": "写侧打嗝", "hw": "读侧停顿",
|
| 102 |
+
"mismatch": "两侧不齐"}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# ── 时钟与解卷 ──────────────────────────────────────────────
|
| 106 |
+
def clock_class(hw):
|
| 107 |
+
"""判本段 hardware_ns 是哪一种钟(见模块 docstring)。"""
|
| 108 |
+
if not any(hw):
|
| 109 |
+
return "none"
|
| 110 |
+
low, high = min(hw), max(hw)
|
| 111 |
+
if low >= -2 ** 31 and high < 2 ** 31 and (low < 0 or high - low > 2 ** 31):
|
| 112 |
+
return "trunc32"
|
| 113 |
+
return "hw64"
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _unwrap(delta):
|
| 117 |
+
"""把有符号 32 位截断钟的差解卷回 [-2^31, 2^31)。"""
|
| 118 |
+
return ((delta + 2 ** 31) % 2 ** 32) - 2 ** 31
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def deltas(hw, cls):
|
| 122 |
+
"""本段逐行 hw 间隔(trunc32 解卷;其余原样)。"""
|
| 123 |
+
out = [0] * len(hw)
|
| 124 |
+
for index in range(1, len(hw)):
|
| 125 |
+
delta = hw[index] - hw[index - 1]
|
| 126 |
+
out[index] = _unwrap(delta) if cls == "trunc32" else delta
|
| 127 |
+
return out
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# ── 取数 ────────────────────────────────────────────────────
|
| 131 |
+
def episode_stem(name):
|
| 132 |
+
"""'episode-099.parquet' / '…/episode-099.mp4' → '099'。"""
|
| 133 |
+
return re.sub(r"^episode-|\.(parquet|mp4)$", "", os.path.basename(name))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _episode_paths(task_dir):
|
| 137 |
+
"""(段号, parquet, mp4) 列表,按段号排序;两边存在性各自独立。
|
| 138 |
+
|
| 139 |
+
键必须归一到**段号**:parquet 与 mp4 的文件名后缀不同,直接拿 basename
|
| 140 |
+
当键会让同一段分裂成两条(一条只有 parquet、一条只有 mp4),全库统计
|
| 141 |
+
随之翻倍且两边都缺一半证据。
|
| 142 |
+
"""
|
| 143 |
+
parquets = {}
|
| 144 |
+
for path in glob.glob(os.path.join(
|
| 145 |
+
task_dir, "data", "chunk-*", "episode-*.parquet")):
|
| 146 |
+
parquets[episode_stem(path)] = path
|
| 147 |
+
videos = {}
|
| 148 |
+
for path in glob.glob(os.path.join(
|
| 149 |
+
task_dir, "videos", "chunk-*", "*", "episode-*.mp4")):
|
| 150 |
+
videos.setdefault(episode_stem(path), []).append(path)
|
| 151 |
+
for key, paths in videos.items():
|
| 152 |
+
# 同一段号可能有多个视频槽位(stereo_left / gripper_rgb)。本工具审计的
|
| 153 |
+
# 是夹爪 RGB,优先取槽位名带 rgb 的那个;并列时按路径排序保证稳定。
|
| 154 |
+
videos[key] = sorted(paths, key=lambda item: ("rgb" not in item, item))[0]
|
| 155 |
+
names = sorted(set(parquets) | set(videos))
|
| 156 |
+
return [(name, parquets.get(name), videos.get(name)) for name in names]
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _load_rows(parquet_path):
|
| 160 |
+
"""读三列 → [fi, hw, wall];缺列/读不动时返回 (None, 原因)。"""
|
| 161 |
+
import pyarrow.parquet as pq
|
| 162 |
+
try:
|
| 163 |
+
table = pq.ParquetFile(parquet_path).read(columns=list(COLUMNS))
|
| 164 |
+
except Exception as exc: # noqa: BLE001 - 只读取证工具
|
| 165 |
+
return None, f"读取失败: {exc}"
|
| 166 |
+
# 用 Table.schema.names;ParquetFile.schema.names 是扁平化的另一套名字
|
| 167 |
+
names = table.schema.names
|
| 168 |
+
missing = [name for name in COLUMNS if name not in names]
|
| 169 |
+
if missing:
|
| 170 |
+
return None, f"缺列 {missing}"
|
| 171 |
+
return [[table.column(name).to_pylist() for name in COLUMNS], None]
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# ── 画面复核 ────────────────────────────────────────────────
|
| 175 |
+
def probe_frames(video_path):
|
| 176 |
+
"""mp4 帧数(CAP_PROP,不解码)。读不了返回 None。"""
|
| 177 |
+
if video_path is None or not os.path.isfile(video_path):
|
| 178 |
+
return None
|
| 179 |
+
import cv2
|
| 180 |
+
cap = cv2.VideoCapture(video_path)
|
| 181 |
+
if not cap.isOpened():
|
| 182 |
+
return None
|
| 183 |
+
count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 184 |
+
cap.release()
|
| 185 |
+
return count if count > 0 else None
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def load_video_gray(video_path):
|
| 189 |
+
"""整段视频降采样灰度缓存;读不了时返回 None(调用方回落钟口径)。"""
|
| 190 |
+
if video_path is None or not os.path.isfile(video_path):
|
| 191 |
+
return None
|
| 192 |
+
import cv2
|
| 193 |
+
cap = cv2.VideoCapture(video_path)
|
| 194 |
+
if not cap.isOpened():
|
| 195 |
+
return None
|
| 196 |
+
frames = []
|
| 197 |
+
try:
|
| 198 |
+
while True:
|
| 199 |
+
ok, frame = cap.read()
|
| 200 |
+
if not ok:
|
| 201 |
+
break
|
| 202 |
+
frames.append(cv2.cvtColor(cv2.resize(frame, GRAY_SIZE),
|
| 203 |
+
cv2.COLOR_BGR2GRAY).astype("int16"))
|
| 204 |
+
finally:
|
| 205 |
+
cap.release()
|
| 206 |
+
return frames or None
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def _mad(first, second):
|
| 210 |
+
import numpy as np
|
| 211 |
+
return float(np.mean(np.abs(first - second)))
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def screen_hit(frames, row):
|
| 215 |
+
"""画面复核一个事件:返回 (evidence, 边界差, 邻域逐帧差, 饱和差)。
|
| 216 |
+
|
| 217 |
+
evidence: "continuous"(画面连续 ⇒ 没丢)/ "jump"(画面跳了 ⇒ 丢了)/
|
| 218 |
+
"unknown"(读不到画面、落在两端、或**整窗静止** ⇒ 回落钟口径)
|
| 219 |
+
"""
|
| 220 |
+
if frames is None or row < 1 or row >= len(frames):
|
| 221 |
+
return "unknown", None, None, None
|
| 222 |
+
count = len(frames)
|
| 223 |
+
near = [j for j in range(max(1, row - EVIDENCE_WINDOW), row)
|
| 224 |
+
if j < count]
|
| 225 |
+
near += [j for j in range(row + 1, min(count, row + 1 + EVIDENCE_WINDOW))]
|
| 226 |
+
base = statistics.median([_mad(frames[j - 1], frames[j]) for j in near]) \
|
| 227 |
+
if near else 0.0
|
| 228 |
+
sat = [_mad(frames[j], frames[j + SAT_STRIDE])
|
| 229 |
+
for j in range(0, count - SAT_STRIDE, SAT_STEP)]
|
| 230 |
+
saturation = statistics.median(sat) if sat else 0.0
|
| 231 |
+
boundary = _mad(frames[row - 1], frames[row])
|
| 232 |
+
# 整窗静止(邻域与边界都在传感器噪声地板以下):画面本身就无信息,事件处
|
| 233 |
+
# 少了 8 帧静止画面也看不出来——此时**不能**判「没丢」,回落钟口径
|
| 234 |
+
if base < STATIC_FLOOR and boundary < STATIC_FLOOR:
|
| 235 |
+
return "unknown", round(boundary, 2), round(base, 2), \
|
| 236 |
+
round(saturation, 2)
|
| 237 |
+
ratio = boundary / max(base, 0.05)
|
| 238 |
+
if ratio <= CONTINUOUS_RATIO:
|
| 239 |
+
evidence = "continuous"
|
| 240 |
+
elif ratio >= JUMP_RATIO or boundary >= SAT_LEVEL * saturation:
|
| 241 |
+
evidence = "jump"
|
| 242 |
+
else:
|
| 243 |
+
evidence = "unknown"
|
| 244 |
+
return evidence, round(boundary, 2), round(base, 2), round(saturation, 2)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
# ── 事件合并与定性 ──────────────────────────────────────────
|
| 248 |
+
def _classify(raw_events, min_ns, tol_ns, merge_rows):
|
| 249 |
+
"""把逐行异常合并成事件并定性(只按两个钟,画面复核在此之后)。
|
| 250 |
+
|
| 251 |
+
raw_events: [(row, d_hw, d_wall)],均为 ns,已按行号升序。
|
| 252 |
+
返回事件列表,每个 {"row","rows","d_hw","d_wall","kind"}(ns,未减标称)。
|
| 253 |
+
"""
|
| 254 |
+
events = []
|
| 255 |
+
for row, d_hw, d_wall in raw_events:
|
| 256 |
+
if events and row - events[-1]["rows"][-1] <= merge_rows:
|
| 257 |
+
# 同一件事的两侧(≤15 行内两侧都停 = 整机被抢):各自取最大,不做
|
| 258 |
+
# 加法(加法会把同一个洞数两遍)
|
| 259 |
+
events[-1]["rows"].append(row)
|
| 260 |
+
events[-1]["d_hw"] = max(events[-1]["d_hw"], d_hw)
|
| 261 |
+
events[-1]["d_wall"] = max(events[-1]["d_wall"], d_wall)
|
| 262 |
+
continue
|
| 263 |
+
events.append({"rows": [row], "d_hw": d_hw, "d_wall": d_wall})
|
| 264 |
+
for event in events:
|
| 265 |
+
d_hw, d_wall = event["d_hw"], event["d_wall"]
|
| 266 |
+
hw_big = d_hw >= min_ns
|
| 267 |
+
wall_big = d_wall >= min_ns
|
| 268 |
+
if hw_big and wall_big:
|
| 269 |
+
kind = "both" if abs(d_hw - d_wall) <= tol_ns else "mismatch"
|
| 270 |
+
elif wall_big:
|
| 271 |
+
kind = "wall"
|
| 272 |
+
elif hw_big:
|
| 273 |
+
kind = "hw"
|
| 274 |
+
else:
|
| 275 |
+
kind = "mismatch" # 合并后反而都不过阈值(异常被吸收)
|
| 276 |
+
event["kind"] = kind
|
| 277 |
+
event["row"] = event["rows"][0]
|
| 278 |
+
return events
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _account(result):
|
| 282 |
+
"""按事件定性归账(四桶,互斥;顺序即优先级)。
|
| 283 |
+
|
| 284 |
+
1. 画面复核说跳变 → gap_ms **丢了**(>任何钟口径,画面是硬证据)
|
| 285 |
+
2. 只有墙钟跳 → wall_ms 写侧打嗝(帧没少、只是写晚)
|
| 286 |
+
3. 画面复核说连续 → stamp_ms 没丢:有停顿、画面接得上(帧到得晚/写得晚)
|
| 287 |
+
4. 其余 → pending_ms 判不了/未复核(钟互证的疑似落这里)
|
| 288 |
+
|
| 289 |
+
只有第 1 桶算「证实丢了」;第 4 桶单列,绝不计入损失——「钟说跳了」不等于
|
| 290 |
+
「画面少了帧」,本库 15 个双钟跳 ~250ms 的事件画面全是连续的(见模块 docstring)。
|
| 291 |
+
桶名 stamp_ms 说的是「钟上的洞、画面上的连续」,不是「戳错了」。
|
| 292 |
+
"""
|
| 293 |
+
sums = {"gap_ms": 0.0, "stamp_ms": 0.0, "pending_ms": 0.0, "wall_ms": 0.0}
|
| 294 |
+
for event in result["events"]:
|
| 295 |
+
kind, evidence = event["kind"], event["evidence"]
|
| 296 |
+
if evidence == "jump":
|
| 297 |
+
sums["gap_ms"] += event["gap_ms"]
|
| 298 |
+
elif kind == "wall":
|
| 299 |
+
sums["wall_ms"] += event["gap_ms"]
|
| 300 |
+
elif evidence == "continuous":
|
| 301 |
+
sums["stamp_ms"] += event["gap_ms"]
|
| 302 |
+
else:
|
| 303 |
+
sums["pending_ms"] += event["gap_ms"]
|
| 304 |
+
for key, value in sums.items():
|
| 305 |
+
result[key] = round(value, 1)
|
| 306 |
+
return result
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def audit_episode(parquet_path, video_path, nominal_ns, min_gap_ms,
|
| 310 |
+
clock_tol_ms, merge_rows, video_check=True):
|
| 311 |
+
"""单段审计 → dict(字段即 --json 的展开)。"""
|
| 312 |
+
episode = episode_stem(parquet_path or video_path or "episode-?")
|
| 313 |
+
result = {"episode": episode, "rows": 0, "status": "ok", "note": "",
|
| 314 |
+
"clock": "", "gap_ms": 0, "stamp_ms": 0, "pending_ms": 0,
|
| 315 |
+
"wall_ms": 0, "resyncs": 0, "video_frames": None, "video_ok": None,
|
| 316 |
+
"screened": False,
|
| 317 |
+
"events": []}
|
| 318 |
+
if parquet_path is None:
|
| 319 |
+
result.update(status="skip", note="只有视频没有 parquet")
|
| 320 |
+
return result
|
| 321 |
+
rows, err = _load_rows(parquet_path)
|
| 322 |
+
if rows is None:
|
| 323 |
+
result.update(status="skip", note=err)
|
| 324 |
+
return result
|
| 325 |
+
frame_index, hw, wall = rows
|
| 326 |
+
result["rows"] = len(frame_index)
|
| 327 |
+
# 单流判定:帧序号无重复且严格 0..N-1。多槽 episode 的行按槽各自从 0 编号,
|
| 328 |
+
# 无法唯一拆出「哪几行属于这个 mp4」——宁可拒答也不给个靠位置猜出来的数
|
| 329 |
+
if sorted(frame_index) != list(range(len(frame_index))):
|
| 330 |
+
result.update(status="skip", note="多槽 episode,无法唯一拆分")
|
| 331 |
+
return result
|
| 332 |
+
cls = clock_class(hw)
|
| 333 |
+
result["clock"] = cls
|
| 334 |
+
if cls == "none":
|
| 335 |
+
result.update(status="skip", note="hardware_ns 全 0(无时间戳)")
|
| 336 |
+
return result
|
| 337 |
+
|
| 338 |
+
# 逐行异常 → 合并 → 定性。门槛用 max(Δhw, Δwall):只看一个钟会漏掉
|
| 339 |
+
# 「写侧打嗝」(戳不动)与「戳单独跳」(墙钟不动)这两种签名
|
| 340 |
+
min_ns = min_gap_ms * 1_000_000
|
| 341 |
+
dh = deltas(hw, cls)
|
| 342 |
+
raw = []
|
| 343 |
+
for index in range(1, len(hw)):
|
| 344 |
+
d_wall = int(round((wall[index] - wall[index - 1]) * 1e9))
|
| 345 |
+
if dh[index] < min_ns and d_wall < min_ns:
|
| 346 |
+
continue
|
| 347 |
+
raw.append((index, dh[index], d_wall))
|
| 348 |
+
tol_ns = clock_tol_ms * 1_000_000
|
| 349 |
+
events = _classify(raw, min_ns, tol_ns, merge_rows)
|
| 350 |
+
|
| 351 |
+
# hw 口径的空洞统计交给录制侧同一个类:解卷后的戳喂进去,口径逐字一致
|
| 352 |
+
watch = GapWatch(nominal_ns, min_ns)
|
| 353 |
+
base = hw[0]
|
| 354 |
+
for index in range(1, len(hw)):
|
| 355 |
+
base += dh[index]
|
| 356 |
+
watch.note(base, "hw")
|
| 357 |
+
result["resyncs"] = watch.snapshot()["resyncs"]
|
| 358 |
+
|
| 359 |
+
# 帧数校验一律做(只读 CAP_PROP,不解码):行与帧必须一一对应,画面复核才
|
| 360 |
+
# 成立;等于顺手把「mp4 帧数 = 行数」这条完整性也一并核了。有事件时才真解
|
| 361 |
+
# 码(解一段 30s 视频是秒级开销,只为没有事件的段解纯属浪费)。
|
| 362 |
+
frames = None
|
| 363 |
+
if video_check and probe_frames(video_path) is not None:
|
| 364 |
+
count = probe_frames(video_path)
|
| 365 |
+
result["video_frames"] = count
|
| 366 |
+
result["video_ok"] = count == len(frame_index)
|
| 367 |
+
if not result["video_ok"]:
|
| 368 |
+
result.update(status="warn",
|
| 369 |
+
note=f"mp4 帧数 {count} ≠ 行数 {len(frame_index)},"
|
| 370 |
+
f"画面复核不可用")
|
| 371 |
+
elif events:
|
| 372 |
+
frames = load_video_gray(video_path)
|
| 373 |
+
if frames is None or len(frames) != len(frame_index):
|
| 374 |
+
result["video_ok"] = False
|
| 375 |
+
frames = None
|
| 376 |
+
result.update(status="warn",
|
| 377 |
+
note="mp4 解码帧数与行数不符,画面复核不可用")
|
| 378 |
+
else:
|
| 379 |
+
result["screened"] = True
|
| 380 |
+
|
| 381 |
+
for event in events:
|
| 382 |
+
size_ns = max(event["d_hw"], event["d_wall"])
|
| 383 |
+
row = event["row"]
|
| 384 |
+
evidence, boundary, near, saturation = screen_hit(frames, row)
|
| 385 |
+
result["events"].append({
|
| 386 |
+
"row": row,
|
| 387 |
+
"rows": event["rows"],
|
| 388 |
+
"rel_s": round(wall[row - 1] - wall[0], 3),
|
| 389 |
+
"wall_abs": round(wall[row - 1], 3),
|
| 390 |
+
"kind": event["kind"],
|
| 391 |
+
"evidence": evidence,
|
| 392 |
+
"boundary": boundary,
|
| 393 |
+
"near": near,
|
| 394 |
+
"saturation": saturation,
|
| 395 |
+
"d_hw_ms": round(event["d_hw"] / 1e6, 1),
|
| 396 |
+
"d_wall_ms": round(event["d_wall"] / 1e6, 1),
|
| 397 |
+
"gap_ms": round((size_ns - nominal_ns) / 1e6, 1),
|
| 398 |
+
"interval_ms": round(size_ns / 1e6, 1),
|
| 399 |
+
})
|
| 400 |
+
# 画面复核优先:判定为「连续」的事件不必再看钟口径
|
| 401 |
+
for event in result["events"]:
|
| 402 |
+
if event["evidence"] == "jump":
|
| 403 |
+
event["verdict"] = "丢了"
|
| 404 |
+
elif event["evidence"] == "continuous":
|
| 405 |
+
event["verdict"] = "没丢(画面连续)"
|
| 406 |
+
else:
|
| 407 |
+
event["verdict"] = _KIND_LABEL[event["kind"]]
|
| 408 |
+
return _account(result)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
# ���─ camera-service 留档相关 ─────────────────────────────────
|
| 412 |
+
def _archive_entries(directory):
|
| 413 |
+
entries = []
|
| 414 |
+
for name in sorted(os.listdir(directory)):
|
| 415 |
+
match = _ARCHIVE_RE.match(name)
|
| 416 |
+
if not match:
|
| 417 |
+
continue
|
| 418 |
+
try:
|
| 419 |
+
stamp = datetime.datetime.strptime(
|
| 420 |
+
match.group(1), "%Y%m%d_%H%M%S").timestamp()
|
| 421 |
+
except ValueError:
|
| 422 |
+
continue
|
| 423 |
+
entries.append((stamp, os.path.join(directory, name)))
|
| 424 |
+
return entries
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def correlate_camera_logs(directory, results):
|
| 428 |
+
"""给每个事件挂上候选留档日志(秒级粗相关)。
|
| 429 |
+
|
| 430 |
+
留档发生在**会话结束时**,所以只往后找:事件墙钟时刻 ≤ 留档时刻 ≤ +10min。
|
| 431 |
+
只给候选——判读要看文件内容([UVC] camera-service 告警摘录已在 main.log)。
|
| 432 |
+
"""
|
| 433 |
+
entries = _archive_entries(directory)
|
| 434 |
+
for row in results:
|
| 435 |
+
for event in row["events"]:
|
| 436 |
+
event["camera_logs"] = [
|
| 437 |
+
{"file": os.path.basename(path),
|
| 438 |
+
"delta_s": round(stamp - event["wall_abs"], 1)}
|
| 439 |
+
for stamp, path in entries
|
| 440 |
+
if -_ARCHIVE_BACK_S <= stamp - event["wall_abs"]
|
| 441 |
+
<= _ARCHIVE_WINDOW_S]
|
| 442 |
+
return len(entries)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def main(argv=None):
|
| 446 |
+
parser = argparse.ArgumentParser(
|
| 447 |
+
description="帧空洞全库审计(只读)",
|
| 448 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 449 |
+
parser.add_argument("task_dir", nargs="?", default=DEFAULT_TASK_DIR,
|
| 450 |
+
help="录制任务目录(默认 data/recordings/"
|
| 451 |
+
"UMIGripper_Action_AI;相对仓库根解析)")
|
| 452 |
+
parser.add_argument("--min-gap-ms", type=float, default=100.0,
|
| 453 |
+
help="计入异常的间隔下限(默认 100)")
|
| 454 |
+
parser.add_argument("--clock-tol-ms", type=float, default=100.0,
|
| 455 |
+
help="双钟一致阈值(默认 100;0 = 只认严格相等)")
|
| 456 |
+
parser.add_argument("--merge-rows", type=int, default=15,
|
| 457 |
+
help="相隔 ≤ 这么多行的异常合并成一次事件(默认 15)")
|
| 458 |
+
parser.add_argument("--no-video-check", action="store_true",
|
| 459 |
+
help="跳过画面复核(快,但只剩钟口径;结论会标「未复核」)")
|
| 460 |
+
parser.add_argument("--all", action="store_true", help="连零异常的段也列出")
|
| 461 |
+
parser.add_argument("--camera-logs", default=None,
|
| 462 |
+
help="logs/camera_service 目录(关联留档日志)")
|
| 463 |
+
parser.add_argument("--json", action="store_true", help="输出 JSON")
|
| 464 |
+
args = parser.parse_args(argv)
|
| 465 |
+
|
| 466 |
+
task_dir = args.task_dir
|
| 467 |
+
if not os.path.isdir(task_dir):
|
| 468 |
+
print(f"任务目录不存在: {task_dir}")
|
| 469 |
+
print(f"(相对路径按仓库根 {ROOT} 解析;也可显式传入任务目录)")
|
| 470 |
+
return 2
|
| 471 |
+
if not os.path.isdir(os.path.join(task_dir, "data")):
|
| 472 |
+
print(f"不是任务目录(缺 data/): {task_dir}")
|
| 473 |
+
return 2
|
| 474 |
+
|
| 475 |
+
nominal_ns = int(1e9 / 30.0)
|
| 476 |
+
nom_ms = nominal_ns / 1e6
|
| 477 |
+
episodes = _episode_paths(task_dir)
|
| 478 |
+
results = []
|
| 479 |
+
for name, parquet, video in episodes:
|
| 480 |
+
results.append(audit_episode(
|
| 481 |
+
parquet, video, nominal_ns, args.min_gap_ms, args.clock_tol_ms,
|
| 482 |
+
args.merge_rows, video_check=not args.no_video_check))
|
| 483 |
+
|
| 484 |
+
if args.camera_logs:
|
| 485 |
+
if not os.path.isdir(args.camera_logs):
|
| 486 |
+
print(f"留档目录不存在: {args.camera_logs}")
|
| 487 |
+
return 2
|
| 488 |
+
correlate_camera_logs(args.camera_logs, results)
|
| 489 |
+
|
| 490 |
+
hit = [r for r in results if r["gap_ms"] > 0]
|
| 491 |
+
stamps = [r for r in results if r["stamp_ms"] > 0]
|
| 492 |
+
pending = [r for r in results if r["pending_ms"] > 0]
|
| 493 |
+
hiccups = [r for r in results if r["wall_ms"] > 0]
|
| 494 |
+
skipped = [r for r in results if r["status"] == "skip"]
|
| 495 |
+
warned = [r for r in results if r["status"] == "warn"]
|
| 496 |
+
total_ms = round(sum(r["gap_ms"] for r in hit), 1)
|
| 497 |
+
stamp_ms = round(sum(r["stamp_ms"] for r in stamps), 1)
|
| 498 |
+
pending_ms = round(sum(r["pending_ms"] for r in pending), 1)
|
| 499 |
+
wall_ms = round(sum(r["wall_ms"] for r in hiccups), 1)
|
| 500 |
+
worst = max(hit, key=lambda r: r["gap_ms"], default=None)
|
| 501 |
+
clocks = {}
|
| 502 |
+
for row in results:
|
| 503 |
+
clocks[row["clock"]] = clocks.get(row["clock"], 0) + 1
|
| 504 |
+
|
| 505 |
+
if args.json:
|
| 506 |
+
print(json.dumps({
|
| 507 |
+
"task_dir": task_dir,
|
| 508 |
+
"nominal_ms": round(nom_ms, 2),
|
| 509 |
+
"min_gap_ms": args.min_gap_ms,
|
| 510 |
+
"clock_tol_ms": args.clock_tol_ms,
|
| 511 |
+
"merge_rows": args.merge_rows,
|
| 512 |
+
"video_checked": not args.no_video_check,
|
| 513 |
+
"episodes": results,
|
| 514 |
+
"totals": {
|
| 515 |
+
"episodes": len(results),
|
| 516 |
+
"lost_episodes": len(hit), "lost_ms": total_ms,
|
| 517 |
+
"lost_max_ms": worst["gap_ms"] if worst else 0.0,
|
| 518 |
+
"lost_max_episode": worst["episode"] if worst else "",
|
| 519 |
+
"stamp_only_ms": stamp_ms, "stamp_only_episodes": len(stamps),
|
| 520 |
+
"pending_ms": pending_ms, "pending_episodes": len(pending),
|
| 521 |
+
"writer_hiccup_ms": wall_ms, "writer_hiccup_episodes": len(hiccups),
|
| 522 |
+
"clocks": clocks,
|
| 523 |
+
},
|
| 524 |
+
}, ensure_ascii=False, indent=2))
|
| 525 |
+
return 1 if (hit or pending) else 0
|
| 526 |
+
|
| 527 |
+
print(f"任务目录: {task_dir}")
|
| 528 |
+
print(f"口径: 空洞 = 相邻两帧间隔 − 标称 {nom_ms:.1f}ms(core/frame_gap."
|
| 529 |
+
f"GapWatch,与录制侧「[录制] RGB 帧空洞 …ms」同一个数)")
|
| 530 |
+
print(f" 间隔 ≥ {args.min_gap_ms:.0f}ms 才算异常;双钟 |Δhw − Δwall| ≤ "
|
| 531 |
+
f"{args.clock_tol_ms:.0f}ms 才算互证;≤{args.merge_rows} 行的异常"
|
| 532 |
+
f"合并成一次事件")
|
| 533 |
+
print(f" 主判据: " + ("画面复核(跳变=丢了 / 连续=没丢)"
|
| 534 |
+
if not args.no_video_check else
|
| 535 |
+
"关(--no-video-check,只剩钟口径)"))
|
| 536 |
+
print(f" 时钟: " + "、".join(
|
| 537 |
+
f"{key} {value} 段" for key, value in sorted(clocks.items())))
|
| 538 |
+
verified = [r for r in results if r["video_ok"]]
|
| 539 |
+
no_video = [r for r in results if r["status"] != "skip"
|
| 540 |
+
and r["video_frames"] is None]
|
| 541 |
+
screened = [r for r in results if r["screened"]]
|
| 542 |
+
print(f" 画面: mp4 帧数与行数一致 {len(verified)} 段"
|
| 543 |
+
+ (f";**不符 {len(warned)} 段**(画面复核不可用)" if warned else "")
|
| 544 |
+
+ (f";无 mp4 {len(no_video)} 段(画面未复核)" if no_video else "")
|
| 545 |
+
+ f";内容复核实际覆盖 {len(screened)} 段(有事件的段)")
|
| 546 |
+
if skipped:
|
| 547 |
+
print(f" 跳过 {len(skipped)} 段(另计,不进下表):"
|
| 548 |
+
+ ";".join(f"{r['episode']}({r['note']})" for r in skipped[:4])
|
| 549 |
+
+ ("…" if len(skipped) > 4 else ""))
|
| 550 |
+
print()
|
| 551 |
+
print(f" {'段':>4}{'行数':>6}{'钟':>9}{'证实丢了':>9}{'钟跳没丢':>8}"
|
| 552 |
+
f"{'事件':>5}{'打嗝':>8}{'待复核':>8} 判定")
|
| 553 |
+
for row in results:
|
| 554 |
+
if not (row["events"] or args.all):
|
| 555 |
+
continue
|
| 556 |
+
if row["gap_ms"] > 0:
|
| 557 |
+
verdict = "实际丢了"
|
| 558 |
+
elif row["status"] == "skip":
|
| 559 |
+
verdict = row["note"]
|
| 560 |
+
elif row["events"]:
|
| 561 |
+
labels = []
|
| 562 |
+
for event in row["events"]:
|
| 563 |
+
if event["verdict"] not in labels:
|
| 564 |
+
labels.append(event["verdict"])
|
| 565 |
+
verdict = "、".join(labels)
|
| 566 |
+
else:
|
| 567 |
+
verdict = "OK"
|
| 568 |
+
print(f" {row['episode']:>4}{row['rows']:>6}{row['clock']:>9}"
|
| 569 |
+
f"{row['gap_ms']:>9.1f}{row['stamp_ms']:>8.1f}"
|
| 570 |
+
f"{len(row['events']):>5}{row['wall_ms']:>8.1f}"
|
| 571 |
+
f"{row['pending_ms']:>8.1f} {verdict}")
|
| 572 |
+
|
| 573 |
+
print()
|
| 574 |
+
print(f"合计 {len(results)} 段:**画面证实丢了 {len(hit)} 段 / "
|
| 575 |
+
f"{total_ms:.1f}ms**"
|
| 576 |
+
+ (f"(最大 {worst['gap_ms']:.1f}ms @ 段{worst['episode']})"
|
| 577 |
+
if worst else ""))
|
| 578 |
+
lost_at = sorted(event["rel_s"] for row in hit for event in row["events"]
|
| 579 |
+
if event["evidence"] == "jump")
|
| 580 |
+
if lost_at:
|
| 581 |
+
print(f" · **全部 {len(lost_at)} 起都落在开录后 {lost_at[0]:.2f}~"
|
| 582 |
+
f"{lost_at[-1]:.2f}s**(启动窗口)—— 推测是这段还没排队、一次停顿"
|
| 583 |
+
"就直接在画面里留下空洞(后期同样的停顿都被队列垫住了)"
|
| 584 |
+
";这是排查方向,不是随机掉帧")
|
| 585 |
+
if stamps:
|
| 586 |
+
print(f" · 钟跳但画面连续(**没丢**):{len(stamps)} 段 / {stamp_ms:.1f}ms"
|
| 587 |
+
" —— 有停顿、画面接得上:帧到得晚(读侧停顿)或写得晚(写侧打嗝),"
|
| 588 |
+
"队列把它垫住了;这些点上的「间隔」是钟的、不是画面的")
|
| 589 |
+
if hiccups:
|
| 590 |
+
print(f" · 写侧打嗝(墙钟洞而戳只走一帧 ⇒ 帧数没少、只是写晚):"
|
| 591 |
+
f"{len(hiccups)} 段 / {wall_ms:.1f}ms")
|
| 592 |
+
if pending:
|
| 593 |
+
print(f" · 待复核(画面判不了或未复核,**不计入**上面的数):"
|
| 594 |
+
f"{len(pending)} 段 / {pending_ms:.1f}ms —— "
|
| 595 |
+
+ ("本次 --no-video-check,全部事件都在这一桶;"
|
| 596 |
+
if args.no_video_check else
|
| 597 |
+
"画面灰区/读不了视频;")
|
| 598 |
+
+ "真机日志才能定性")
|
| 599 |
+
if warned:
|
| 600 |
+
print(f" · 视频帧数校验不通过 {len(warned)} 段:"
|
| 601 |
+
+ ";".join(f"{r['episode']}({r['note']})" for r in warned[:5]))
|
| 602 |
+
|
| 603 |
+
print()
|
| 604 |
+
print("逐事件明细(画面复核:boundary=事件处两帧差,near=邻域逐帧差中位,"
|
| 605 |
+
"sat=远端饱和差中位)")
|
| 606 |
+
print(f" {'段':>4}{'行':>6}{'开录后':>9}{'判定':<11}{'间隔ms':>9}"
|
| 607 |
+
f"{'Δhw':>9}{'Δwall':>8}{'空洞ms':>9}{'boundary':>9}{'near':>7}"
|
| 608 |
+
f"{'sat':>7} camera-service")
|
| 609 |
+
for row in results:
|
| 610 |
+
for event in row["events"]:
|
| 611 |
+
logs = ""
|
| 612 |
+
if "camera_logs" in event:
|
| 613 |
+
logs = ("、".join(f"{item['file']}(+{item['delta_s']}s)"
|
| 614 |
+
for item in event["camera_logs"])
|
| 615 |
+
or "无同期留档")
|
| 616 |
+
|
| 617 |
+
def _fmt(value):
|
| 618 |
+
return "-" if value is None else f"{value:.1f}"
|
| 619 |
+
|
| 620 |
+
print(f" {row['episode']:>4}{event['row']:>6}"
|
| 621 |
+
f"{event['rel_s']:>8.2f}s{event['verdict']:<11}"
|
| 622 |
+
f"{event['interval_ms']:>9.1f}{event['d_hw_ms']:>9.1f}"
|
| 623 |
+
f"{event['d_wall_ms']:>8.1f}{event['gap_ms']:>9.1f}"
|
| 624 |
+
f"{_fmt(event['boundary']):>9}{_fmt(event['near']):>7}"
|
| 625 |
+
f"{_fmt(event['saturation']):>7} {logs}")
|
| 626 |
+
print()
|
| 627 |
+
if hit:
|
| 628 |
+
print(f"FAIL: {len(hit)} 段画面真丢了时间(上表「证实丢了」列)"
|
| 629 |
+
+ (f";另有 {len(pending)} 段钟口径疑似待复核" if pending else "")
|
| 630 |
+
+ ",详见 docs/postmortem_trajectory_and_rgb.md")
|
| 631 |
+
return 1
|
| 632 |
+
if pending:
|
| 633 |
+
print(f"FAIL: 无画面证实的丢帧,但 {len(pending)} 段 / {pending_ms:.1f}ms "
|
| 634 |
+
f"钟口径疑似(画面判不了或未复核)——不上报等于把未知当没事")
|
| 635 |
+
return 1
|
| 636 |
+
print("PASS: 未发现画面复核判定为真丢帧的段落")
|
| 637 |
+
return 0
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
if __name__ == "__main__":
|
| 641 |
+
sys.exit(main())
|
|
@@ -0,0 +1,754 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""SLAM 位姿发散审计:每次「轨迹冻住 + rebase 刷屏」是哪一次停止引起的(只读)。
|
| 3 |
+
|
| 4 |
+
背景:2026-09-18 用户报「SLAM 解算崩溃了…轨迹停止…日志大量崩溃信息」。查实**进程
|
| 5 |
+
一次没死**(当天 18 个原生会话 returncode 全 0、无 FATAL_SIGNAL dump)——真相是位姿
|
| 6 |
+
解算**发散**:native 的 rebase 把参考位姿重锚成 ``Twc_out ≡ P_prev``,每帧都触发时
|
| 7 |
+
发布位姿被**钉死**(轨迹冻住,不是乱飞),步长按恒定加速度线性上涨(IMU 双重积分的
|
| 8 |
+
形状)。它发生在**录制收尾窗口**:收尾那几秒我们的进程抢占了 SLAM 分区的 SMT 兄弟
|
| 9 |
+
核(同一秒 ``image=32.3 imu=203.1 post_ms=101.16``),跟踪 LOST → 重定位进错误地图
|
| 10 |
+
→ 31m 跳 → rebase 自锁。本脚本把这件事**全量数清楚**,作为修复前的基线与回归对照。
|
| 11 |
+
|
| 12 |
+
用法:
|
| 13 |
+
venv/bin/python tools/audit_slam_divergence.py [选项]
|
| 14 |
+
默认读 logs/slam_native/ 与 logs/main.log(相对**仓库根**,可从任意 cwd 运行)
|
| 15 |
+
|
| 16 |
+
选项:
|
| 17 |
+
--date YYYY-MM-DD 只看这一天(停止事件 + 会话 + 洪水)
|
| 18 |
+
--since YYYY-MM-DD 只看该日及以后
|
| 19 |
+
--window-s 1.0 密度判据的滑窗宽度
|
| 20 |
+
--min-lines 15 滑窗内至少这么多条 rebase(步长 ≥ --min-step-m)才算洪水
|
| 21 |
+
--min-step-m 1.0 单条 rebase 计入门槛(米)
|
| 22 |
+
--gap-s 2.0 相邻命中相隔 ≤ 该值合并成同一场洪水
|
| 23 |
+
--all 连没有 rebase 的会话也列出
|
| 24 |
+
--json 输出机器可读结果
|
| 25 |
+
|
| 26 |
+
判据(为什么不是「数行数」)
|
| 27 |
+
--------------------------
|
| 28 |
+
发散与「正常重定位」在**总行数**上分不开(良性会话 162342 也有 46 行 rebase、163131
|
| 29 |
+
有 13 行),把它们分开的是两条**形状**证据——都是发散独有、良性不会有的:
|
| 30 |
+
|
| 31 |
+
============ ================================ ===========================
|
| 32 |
+
判据 阈值/读数 2026-09-18 实测
|
| 33 |
+
============ ================================ ===========================
|
| 34 |
+
密度(主) 任一 1 秒滑窗内 step≥1m 的条数 灾害 **34/45** 条 vs 良性最大
|
| 35 |
+
**3**(两侧余量 4.5×/11×)
|
| 36 |
+
增长(判线性)8 等分桶内 step/dt 的中位数, 灾害 **R²=1.00**(137→986 m/s
|
| 37 |
+
对时间拟合的 R² 与 53→173 m/s,直线),良性
|
| 38 |
+
零散重定位不起涨也不成线
|
| 39 |
+
============ ================================ ===========================
|
| 40 |
+
|
| 41 |
+
「步长」本身没有单调性(每触发一次 rebase 参考位姿就被重锚,步长回落再涨:
|
| 42 |
+
31.4→17.8→18.1→16.6m 锯齿),所以看的是 **step/dt = 内部估计的漂移速度**——IMU
|
| 43 |
+
双重积分的发散里它线性上涨。桶内取**中位**是为了压掉起步那次重定位大跳
|
| 44 |
+
(165036 有一条 27079m、165700 有一条 31.4m)。
|
| 45 |
+
|
| 46 |
+
用秒窗而不是「连续 N 行」:原生 stdout 是**多线程无锁**写的,行会被撕裂(实测
|
| 47 |
+
2654 行 rebase 里 7 行,甚至有 ``tid=[POSE_REBASE] reason=translation_jump3720726
|
| 48 |
+
dt_s=0.020000 cpus= translation_step_m=9`` 这种两个消息**逐字交错**的),丢一两行
|
| 49 |
+
不该把计数打断。所以解析一律走**松散正则**:``translation_step_m=`` 出现在行内任意
|
| 50 |
+
位置即可,数值只取最长的合法数字前缀;取不到步长的 rebase 行单独计数、只算行数。
|
| 51 |
+
|
| 52 |
+
两个坑
|
| 53 |
+
------
|
| 54 |
+
1. ``logs/main.log`` 是**多天追加、无日期分隔**的(行首只有 ``[HH:MM:SS]``)⇒ 行号
|
| 55 |
+
跨天不是时间序,不能直接按行读。这里先重建时间线:用日志内**带绝对日期的 SLAM
|
| 56 |
+
转发行**(``[SLAM] ⚠ 2026-09-08 18:46:28.935 …``)当锚点,锚点之间用「时刻倒退
|
| 57 |
+
>12 小时即跨天」递推,遇到锚点重新对齐;锚点之前的历史行日期未知,一律不配对。
|
| 58 |
+
2. ``logs/slam_native/*_stdout.log`` 是**每会话一份**的 JSON 行(``{"time":…,
|
| 59 |
+
"line":…}``)⇒ 按文件读就自带绝对时间,**不要**把它们合并成文本再 grep。
|
| 60 |
+
|
| 61 |
+
2026-09-18 全天基线(改前,用来对照修复效果;这一天的数由本脚本产生)
|
| 62 |
+
------------------------------------------------------------------
|
| 63 |
+
完成 55 / 中止 11 / 断链 59 / 重连 59 / 原生会话 20 / **发散 2 次**
|
| 64 |
+
断链落在「完成」收尾窗口 [−3,+1]s 内 **54/55**(中位 −2.0s);带断链的完成 52/55
|
| 65 |
+
断链落在「中止」±3s 内 **0/11** ← 中止不做 parquet,只 flush,一次都不触发
|
| 66 |
+
(历史对照:09-10 是 94/94 完成带断链、中止 2/14;09-08 只有 4/15 —— 断链率
|
| 67 |
+
本身在变,所以基线要按天看,别跨天比)
|
| 68 |
+
发散 16:49:16.975(165036 会话,完成 −4.0s 起):54.7s / 1474 行 / 3 段 /
|
| 69 |
+
最大步长 2530.9m,速率 137→986 m/s(R²=1.00)
|
| 70 |
+
发散 16:56:32.917(165700 会话,完成 −7.9s 起):25.6s / 763 行 / 1 段 /
|
| 71 |
+
最大步长 11.0m,速率 53→173 m/s(R²=1.00)
|
| 72 |
+
两次都在「完成」之后数秒、且都在断链+重连的黑洞之后 ⇒ 与「收尾抢占 → 跟踪
|
| 73 |
+
LOST → 重定位 → rebase 自锁」这条链一致(详见 docs 里那次的排查记录)。
|
| 74 |
+
|
| 75 |
+
口径说明(同名数字与历史记录对不上的原因)
|
| 76 |
+
----------------------------------------
|
| 77 |
+
「最长连跑」= 相邻 rebase 行里 **step≥1m** 的最长连跑(本脚本口径);早期排查时
|
| 78 |
+
数的是**全部** rebase 行的连跑(165036 1105 / 165700 822),所以两者不同源;
|
| 79 |
+
判据用的是「1 秒窗峰值」,与两者都不同源。
|
| 80 |
+
|
| 81 |
+
退出码:发现发散 → 1;否则 0(与 tools/audit_frame_gaps.py 同)。
|
| 82 |
+
"""
|
| 83 |
+
import argparse
|
| 84 |
+
import datetime
|
| 85 |
+
import glob
|
| 86 |
+
import json
|
| 87 |
+
import os
|
| 88 |
+
import re
|
| 89 |
+
import statistics
|
| 90 |
+
import sys
|
| 91 |
+
import time
|
| 92 |
+
|
| 93 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 94 |
+
DEFAULT_NATIVE_DIR = os.path.join(ROOT, "logs", "slam_native")
|
| 95 |
+
DEFAULT_MAIN_LOG = os.path.join(ROOT, "logs", "main.log")
|
| 96 |
+
|
| 97 |
+
# 松散解析:撕裂行里 ``translation_step_m=`` 可能被别的消息插在中间,
|
| 98 |
+
# 数值后面也可能紧跟别的 token(``=9verified=yes``)⇒ 只取最长数字前缀
|
| 99 |
+
RE_STEP = re.compile(r"translation_step_m=([0-9]+(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?)")
|
| 100 |
+
RE_DT = re.compile(r"dt_s=([0-9]+(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?)")
|
| 101 |
+
RE_REASON = re.compile(r"reason=(?:translation_jump|tracking_recovery)")
|
| 102 |
+
RE_REBASE_MARK = re.compile(r"\[POSE_REBASE\]")
|
| 103 |
+
# 会话日志名:%Y%m%d_%H%M%S_<serial>_slam_stdout.log(见 process_controller)
|
| 104 |
+
RE_NATIVE_NAME = re.compile(r"^(\d{8})_(\d{6})_(\d+)_slam_stdout\.log$")
|
| 105 |
+
# main.log 行首时刻;带绝对日期的转发行(SLAM stderr 转发)当时间线锚点
|
| 106 |
+
RE_MAIN_TS = re.compile(r"^\[(\d\d):(\d\d):(\d\d)\]")
|
| 107 |
+
RE_EMBED_DATE = re.compile(r"(20\d\d)-(\d\d)-(\d\d)[ T](\d\d):(\d\d):(\d\d)")
|
| 108 |
+
_ANCHOR_TOL_S = 300.0 # 锚点行:行首时刻与内嵌时刻相差超过它就不当锚点
|
| 109 |
+
_DAY_JUMP_S = 12 * 3600 # 时刻倒退超过这么多 ⇒ 判为跨天
|
| 110 |
+
|
| 111 |
+
# 停止事件的配对窗口(秒;负 = 事件早于停止)
|
| 112 |
+
COMPLETED_WINDOW = (-3.0, 1.0) # 完成:收尾窗口(实测断链中位 −2s)
|
| 113 |
+
ABORT_WINDOW = (-3.0, 3.0) # 中止:中止不写 parquet,理论上不该有断链
|
| 114 |
+
NEAR_S = 60.0 # 「这次洪水挨着谁」的搜索半径
|
| 115 |
+
|
| 116 |
+
_KIND_LABEL = {"completed": "完成", "aborted": "中止", "started": "开录",
|
| 117 |
+
"disconnect": "断链", "reconnect": "重连"}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# ── native 侧:会话与 rebase 事件 ────────────────────────────
|
| 121 |
+
def load_session(path):
|
| 122 |
+
"""读一份原生会话日志 → rebase 事件表(容错撕裂行与截断)。"""
|
| 123 |
+
name = os.path.basename(path)
|
| 124 |
+
m = RE_NATIVE_NAME.match(name)
|
| 125 |
+
started = None
|
| 126 |
+
if m:
|
| 127 |
+
started = time.mktime(time.strptime(m.group(1) + m.group(2),
|
| 128 |
+
"%Y%m%d%H%M%S"))
|
| 129 |
+
events = []
|
| 130 |
+
first_t = last_t = None
|
| 131 |
+
unparsed = 0
|
| 132 |
+
t = None
|
| 133 |
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
| 134 |
+
for raw in fh:
|
| 135 |
+
raw = raw.strip()
|
| 136 |
+
if not raw:
|
| 137 |
+
continue
|
| 138 |
+
try:
|
| 139 |
+
obj = json.loads(raw)
|
| 140 |
+
except ValueError:
|
| 141 |
+
continue # 包装侧带锁写,理论不会坏;坏了就跳过
|
| 142 |
+
if "time" in obj:
|
| 143 |
+
try:
|
| 144 |
+
t = float(obj["time"])
|
| 145 |
+
except (TypeError, ValueError):
|
| 146 |
+
pass
|
| 147 |
+
if t is None:
|
| 148 |
+
continue
|
| 149 |
+
if first_t is None:
|
| 150 |
+
first_t = t
|
| 151 |
+
last_t = t
|
| 152 |
+
line = obj.get("line")
|
| 153 |
+
if not isinstance(line, str) or not line:
|
| 154 |
+
continue
|
| 155 |
+
steps = RE_STEP.findall(line)
|
| 156 |
+
if steps:
|
| 157 |
+
dts = RE_DT.findall(line)
|
| 158 |
+
for i, s in enumerate(steps):
|
| 159 |
+
try:
|
| 160 |
+
step = float(s)
|
| 161 |
+
except ValueError:
|
| 162 |
+
step = None
|
| 163 |
+
unparsed += 1
|
| 164 |
+
dt = None
|
| 165 |
+
if i < len(dts):
|
| 166 |
+
try:
|
| 167 |
+
dt = float(dts[i])
|
| 168 |
+
except ValueError:
|
| 169 |
+
dt = None
|
| 170 |
+
events.append({"t": t, "step": step, "dt": dt})
|
| 171 |
+
elif RE_REASON.search(line) or RE_REBASE_MARK.search(line):
|
| 172 |
+
# 步长被撕裂吃掉了:仍是一次 rebase,只丢数值
|
| 173 |
+
events.append({"t": t, "step": None, "dt": None})
|
| 174 |
+
unparsed += 1
|
| 175 |
+
events.sort(key=lambda e: e["t"])
|
| 176 |
+
return {
|
| 177 |
+
"name": name,
|
| 178 |
+
"path": path,
|
| 179 |
+
"serial": m.group(3) if m else "",
|
| 180 |
+
"started": started,
|
| 181 |
+
"first_t": first_t,
|
| 182 |
+
"last_t": last_t,
|
| 183 |
+
"events": events,
|
| 184 |
+
"unparsed": unparsed,
|
| 185 |
+
"rebase": len(events),
|
| 186 |
+
"max_step": max((e["step"] for e in events if e["step"] is not None),
|
| 187 |
+
default=0.0),
|
| 188 |
+
"max_run": _max_run(events),
|
| 189 |
+
"max_window": _max_window(events, 1.0, 1.0),
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _max_run(events):
|
| 194 |
+
"""相邻 rebase 行里步长 ≥1m 的最长连跑(不设窗;老口径,便于与历史对照)。"""
|
| 195 |
+
run = best = 0
|
| 196 |
+
for e in events:
|
| 197 |
+
if e["step"] is not None and e["step"] >= 1.0:
|
| 198 |
+
run += 1
|
| 199 |
+
best = max(best, run)
|
| 200 |
+
else:
|
| 201 |
+
run = 0
|
| 202 |
+
return best
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _max_window(events, window_s, min_step):
|
| 206 |
+
"""任一滑窗内 step≥min_step 的条数最大值(密度判据的读数)。"""
|
| 207 |
+
q = [e["t"] for e in events
|
| 208 |
+
if e["step"] is not None and e["step"] >= min_step]
|
| 209 |
+
best = 0
|
| 210 |
+
j = 0
|
| 211 |
+
for i in range(len(q)):
|
| 212 |
+
if j < i:
|
| 213 |
+
j = i
|
| 214 |
+
while j + 1 < len(q) and q[j + 1] - q[i] <= window_s:
|
| 215 |
+
j += 1
|
| 216 |
+
best = max(best, j - i + 1)
|
| 217 |
+
return best
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _slope(pts):
|
| 221 |
+
"""最小二乘斜率(y 对 x)。点少于 3 个或 x 无展布返回 None。"""
|
| 222 |
+
n = len(pts)
|
| 223 |
+
if n < 3:
|
| 224 |
+
return None
|
| 225 |
+
mx = sum(p[0] for p in pts) / n
|
| 226 |
+
my = sum(p[1] for p in pts) / n
|
| 227 |
+
den = sum((p[0] - mx) ** 2 for p in pts)
|
| 228 |
+
if den <= 0:
|
| 229 |
+
return None
|
| 230 |
+
return sum((p[0] - mx) * (p[1] - my) for p in pts) / den
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def _median(xs):
|
| 234 |
+
xs = sorted(xs)
|
| 235 |
+
n = len(xs)
|
| 236 |
+
if not n:
|
| 237 |
+
return None
|
| 238 |
+
return xs[n // 2] if n % 2 else 0.5 * (xs[n // 2 - 1] + xs[n // 2])
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def _growth_stats(events, buckets=8):
|
| 242 |
+
"""发散的**增长**读数:把事件按时间等分成若干桶,取每桶 step/dt 的中位数。
|
| 243 |
+
|
| 244 |
+
为什么看**速率**(step/dt)而不是步长:每触发一次 rebase 参考位姿就被重锚,
|
| 245 |
+
步长随之回落再涨(实测 31.4→17.8→18.1→16.6m 锯齿)⇒ 单条步长没有单调性;
|
| 246 |
+
而 step/dt 是**内部估计的漂移速度**,发散时它随时间**线性上涨**(IMU 双重
|
| 247 |
+
积分:速度线性、位置二次)。取桶内中位是为了压掉那次重定位大跳(165036 有
|
| 248 |
+
一条 27079m、165700 有 31.4m 的起步跳)。
|
| 249 |
+
|
| 250 |
+
**线性度(R²)才是判据**:良性会话的 rebase 是零散重定位,速率既不起涨也
|
| 251 |
+
不成线;发散是「每秒都在 rebase 且越来越快」。2026-09-18 实测两条灾害会话的
|
| 252 |
+
桶速率 R² = 0.98/0.99(165036: 122→964 m/s,约 +16 m/s²;
|
| 253 |
+
165700: 34→170 m/s,约 +5 m/s²),且都是从**静止/慢速**起涨。
|
| 254 |
+
"""
|
| 255 |
+
pts = sorted((e["t"], e["step"], e["step"] / e["dt"]) for e in events
|
| 256 |
+
if e["step"] is not None and e["dt"] and e["dt"] > 0)
|
| 257 |
+
if len(pts) < 3 * buckets:
|
| 258 |
+
return None
|
| 259 |
+
size = max(1, len(pts) // buckets)
|
| 260 |
+
series = []
|
| 261 |
+
for i in range(0, len(pts), size):
|
| 262 |
+
chunk = pts[i:i + size]
|
| 263 |
+
if len(chunk) < 3:
|
| 264 |
+
continue
|
| 265 |
+
series.append({
|
| 266 |
+
"t": sum(p[0] for p in chunk) / len(chunk),
|
| 267 |
+
"n": len(chunk),
|
| 268 |
+
"step": _median([p[1] for p in chunk]),
|
| 269 |
+
"speed": _median([p[2] for p in chunk]),
|
| 270 |
+
})
|
| 271 |
+
if len(series) < 3:
|
| 272 |
+
return None
|
| 273 |
+
t0 = series[0]["t"]
|
| 274 |
+
xs = [s["t"] - t0 for s in series]
|
| 275 |
+
ys = [s["speed"] for s in series]
|
| 276 |
+
slope = _slope(list(zip(xs, ys)))
|
| 277 |
+
r2 = None
|
| 278 |
+
if slope is not None:
|
| 279 |
+
my = sum(ys) / len(ys)
|
| 280 |
+
ss_tot = sum((y - my) ** 2 for y in ys)
|
| 281 |
+
mx = sum(xs) / len(xs)
|
| 282 |
+
a = my - slope * mx
|
| 283 |
+
ss_res = sum((y - (a + slope * x)) ** 2 for x, y in zip(xs, ys))
|
| 284 |
+
r2 = (1.0 - ss_res / ss_tot) if ss_tot > 0 else None
|
| 285 |
+
return {
|
| 286 |
+
"speed_head": series[0]["speed"],
|
| 287 |
+
"speed_tail": series[-1]["speed"],
|
| 288 |
+
"speed_slope": slope,
|
| 289 |
+
"r2": r2,
|
| 290 |
+
"step_head": series[0]["step"],
|
| 291 |
+
"step_tail": series[-1]["step"],
|
| 292 |
+
"series": series,
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def find_floods(events, window_s, min_step, min_lines, gap_s):
|
| 297 |
+
"""滑窗密度 ≥ min_lines 的 rebase 串 → 洪水段(相邻段相隔 ≤gap_s 合并)。"""
|
| 298 |
+
q = [e for e in events if e["step"] is not None and e["step"] >= min_step]
|
| 299 |
+
hot = [False] * len(q)
|
| 300 |
+
j = 0
|
| 301 |
+
for i in range(len(q)):
|
| 302 |
+
if j < i:
|
| 303 |
+
j = i
|
| 304 |
+
while j + 1 < len(q) and q[j + 1]["t"] - q[i]["t"] <= window_s:
|
| 305 |
+
j += 1
|
| 306 |
+
if j - i + 1 >= min_lines:
|
| 307 |
+
for k in range(i, j + 1):
|
| 308 |
+
hot[k] = True
|
| 309 |
+
segs = []
|
| 310 |
+
for k, e in enumerate(q):
|
| 311 |
+
if not hot[k]:
|
| 312 |
+
continue
|
| 313 |
+
if segs and e["t"] - segs[-1][-1]["t"] <= gap_s:
|
| 314 |
+
segs[-1].append(e)
|
| 315 |
+
else:
|
| 316 |
+
segs.append([e])
|
| 317 |
+
floods = []
|
| 318 |
+
for seg in segs:
|
| 319 |
+
t0 = seg[0]["t"]
|
| 320 |
+
t1 = seg[-1]["t"]
|
| 321 |
+
inside = [e for e in events if t0 <= e["t"] <= t1]
|
| 322 |
+
floods.append({
|
| 323 |
+
"t0": t0,
|
| 324 |
+
"t1": t1,
|
| 325 |
+
"duration_s": t1 - t0,
|
| 326 |
+
"lines": len(inside),
|
| 327 |
+
"peak_window": _max_window(inside, window_s, min_step),
|
| 328 |
+
"max_run": _max_run(inside),
|
| 329 |
+
"max_step": max((e["step"] for e in inside
|
| 330 |
+
if e["step"] is not None), default=0.0),
|
| 331 |
+
"events": inside,
|
| 332 |
+
})
|
| 333 |
+
return floods
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def merge_episodes(floods, gap_s, sessions=None):
|
| 337 |
+
"""把同一会话里相隔 ≤gap_s 的洪水段并成**一次发散**。
|
| 338 |
+
|
| 339 |
+
发散一旦开始就自锁(每帧 rebase),直到重开夹爪才结束——中途 rebase 密度会
|
| 340 |
+
随跟踪状态起伏掉到阈值以下(165036 就被切成 3 段:37.3s / 10.7s / 0.1s),
|
| 341 |
+
那是**同一次发散**,不该按三次计。合并后 onset 取第一段的起点。
|
| 342 |
+
|
| 343 |
+
``sessions`` 传进来时,行数按 [t0,t1] 区间里的**全部** rebase 行重算(含阈值
|
| 344 |
+
以下那几段垫底),这样「1474 行」读起来就是「这次发散期间刷了多少行」。
|
| 345 |
+
"""
|
| 346 |
+
episodes = []
|
| 347 |
+
for f in sorted(floods, key=lambda x: x["t0"]):
|
| 348 |
+
if (episodes and episodes[-1]["session"] == f["session"] and
|
| 349 |
+
f["t0"] - episodes[-1]["t1"] <= gap_s):
|
| 350 |
+
ep = episodes[-1]
|
| 351 |
+
ep["segments"] += 1
|
| 352 |
+
ep["t1"] = max(ep["t1"], f["t1"])
|
| 353 |
+
ep["lines"] += f["lines"]
|
| 354 |
+
ep["peak_window"] = max(ep["peak_window"], f["peak_window"])
|
| 355 |
+
ep["max_run"] = max(ep["max_run"], f["max_run"])
|
| 356 |
+
ep["max_step"] = max(ep["max_step"], f["max_step"])
|
| 357 |
+
ep["events"] = ep["events"] + f["events"]
|
| 358 |
+
ep["duration_s"] = ep["t1"] - ep["t0"]
|
| 359 |
+
else:
|
| 360 |
+
ep = dict(f)
|
| 361 |
+
ep["events"] = list(f["events"])
|
| 362 |
+
ep["segments"] = 1
|
| 363 |
+
episodes.append(ep)
|
| 364 |
+
by_name = {s["name"]: s["events"] for s in (sessions or [])}
|
| 365 |
+
for ep in episodes:
|
| 366 |
+
ep.update(_growth_stats(ep["events"]) or {
|
| 367 |
+
"speed_head": None, "speed_tail": None, "speed_slope": None,
|
| 368 |
+
"r2": None, "step_head": None, "step_tail": None, "series": []})
|
| 369 |
+
if ep["session"] in by_name:
|
| 370 |
+
ep["lines"] = len([e for e in by_name[ep["session"]]
|
| 371 |
+
if ep["t0"] <= e["t"] <= ep["t1"]])
|
| 372 |
+
return episodes
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
# ── main.log 侧:时间线重建与停止事件 ───────────────────────
|
| 376 |
+
def _midnight(date_str):
|
| 377 |
+
"""'YYYY-MM-DD' → 该日本地零点 epoch(走 mktime,时区/夏令时交给 libc)。"""
|
| 378 |
+
d = datetime.datetime.strptime(date_str, "%Y-%m-%d")
|
| 379 |
+
return time.mktime(d.timetuple())
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def load_main_log(path):
|
| 383 |
+
"""读 main.log → 行表(含重建出的 epoch;日期未知的行 epoch=None)。
|
| 384 |
+
|
| 385 |
+
行表元素:[tod, date_or_None, text, epoch_or_None]
|
| 386 |
+
"""
|
| 387 |
+
rows = []
|
| 388 |
+
with open(path, encoding="utf-8", errors="replace") as fh:
|
| 389 |
+
for raw in fh:
|
| 390 |
+
raw = raw.rstrip("\n")
|
| 391 |
+
ts = RE_MAIN_TS.match(raw)
|
| 392 |
+
tod = None
|
| 393 |
+
date = None
|
| 394 |
+
if ts:
|
| 395 |
+
tod = int(ts.group(1)) * 3600 + int(ts.group(2)) * 60 + \
|
| 396 |
+
int(ts.group(3))
|
| 397 |
+
emb = RE_EMBED_DATE.search(raw)
|
| 398 |
+
if emb and tod is not None:
|
| 399 |
+
etod = (int(emb.group(4)) * 3600 + int(emb.group(5)) * 60 +
|
| 400 |
+
int(emb.group(6)))
|
| 401 |
+
if abs(etod - tod) <= _ANCHOR_TOL_S:
|
| 402 |
+
date = "-".join(emb.group(1, 2, 3))
|
| 403 |
+
rows.append([tod, date, raw, None])
|
| 404 |
+
|
| 405 |
+
day = None
|
| 406 |
+
last_tod = None
|
| 407 |
+
last_epoch = None
|
| 408 |
+
known = 0
|
| 409 |
+
for row in rows:
|
| 410 |
+
tod, date = row[0], row[1]
|
| 411 |
+
if tod is None:
|
| 412 |
+
row[3] = last_epoch # 续行(多行堆栈等)与上一行同一时刻
|
| 413 |
+
continue
|
| 414 |
+
if day is not None and last_tod is not None:
|
| 415 |
+
delta = tod - last_tod
|
| 416 |
+
if delta < -_DAY_JUMP_S:
|
| 417 |
+
day += 86400.0 # 跨天
|
| 418 |
+
elif delta > _DAY_JUMP_S:
|
| 419 |
+
day -= 86400.0 # 时钟回拨/日志重排(防御)
|
| 420 |
+
if date is not None:
|
| 421 |
+
day = _midnight(date) # 锚点:重新对齐
|
| 422 |
+
row[3] = (day + tod) if day is not None else None
|
| 423 |
+
if row[3] is not None:
|
| 424 |
+
known += 1
|
| 425 |
+
last_tod = tod
|
| 426 |
+
last_epoch = row[3]
|
| 427 |
+
return rows, known
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def extract_stops(rows):
|
| 431 |
+
"""从行表里摘出录制/链路事件(epoch 未知的行跳过)。"""
|
| 432 |
+
stops = []
|
| 433 |
+
for idx, row in enumerate(rows):
|
| 434 |
+
epoch, text = row[3], row[2]
|
| 435 |
+
if epoch is None:
|
| 436 |
+
continue
|
| 437 |
+
if "■ Recording completed" in text:
|
| 438 |
+
kind = "completed"
|
| 439 |
+
elif "⛔ Recording aborted" in text:
|
| 440 |
+
kind = "aborted"
|
| 441 |
+
elif "▶ Recording started" in text:
|
| 442 |
+
kind = "started"
|
| 443 |
+
elif "原始流连接中断" in text:
|
| 444 |
+
kind = "disconnect"
|
| 445 |
+
elif "原始流���重连" in text:
|
| 446 |
+
kind = "reconnect"
|
| 447 |
+
else:
|
| 448 |
+
continue
|
| 449 |
+
stops.append({"kind": kind, "epoch": epoch, "idx": idx,
|
| 450 |
+
"text": text[:100]})
|
| 451 |
+
return stops
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
# ── 配对与统计 ──────────────────────────────────────────────
|
| 455 |
+
def attribute(flood, stops, lookback_s):
|
| 456 |
+
"""这次发散 ← 哪一次停止:**往前**找最近的完成/中止(默认 30s 内)。
|
| 457 |
+
|
| 458 |
+
不能取「时间上最近的事件」:发散自锁后会一直持续,中途的断链/重连/开录都
|
| 459 |
+
比起因更近,会把账记到错的事件上。所以只认**之前的停止**,取最近的;找不
|
| 460 |
+
到就报「无邻近停止」并把附近事件列出来供人工判断。
|
| 461 |
+
"""
|
| 462 |
+
cand = [s for s in stops
|
| 463 |
+
if s["kind"] in ("completed", "aborted") and
|
| 464 |
+
0.0 <= flood["t0"] - s["epoch"] <= lookback_s]
|
| 465 |
+
first = max(cand, key=lambda x: x["epoch"]) if cand else None
|
| 466 |
+
label = ("{}({:+.1f}s)".format(_KIND_LABEL[first["kind"]],
|
| 467 |
+
first["epoch"] - flood["t0"])
|
| 468 |
+
if first else "无邻近停止")
|
| 469 |
+
near = [s for s in stops if abs(s["epoch"] - flood["t0"]) <= NEAR_S]
|
| 470 |
+
near.sort(key=lambda s: abs(s["epoch"] - flood["t0"]))
|
| 471 |
+
return label, first, near
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def _match(targets, others, window):
|
| 475 |
+
"""把 others 按窗口配到 targets 上 → (窗口内条数, 命中过的 target 数, 偏移表)。"""
|
| 476 |
+
hits = 0
|
| 477 |
+
matched = 0
|
| 478 |
+
offsets = []
|
| 479 |
+
for tgt in targets:
|
| 480 |
+
got = [o for o in others
|
| 481 |
+
if window[0] <= o["epoch"] - tgt["epoch"] <= window[1]]
|
| 482 |
+
if got:
|
| 483 |
+
matched += 1
|
| 484 |
+
nearest = min(got, key=lambda o: abs(o["epoch"] - tgt["epoch"]))
|
| 485 |
+
offsets.append(nearest["epoch"] - tgt["epoch"])
|
| 486 |
+
hits += len(got)
|
| 487 |
+
return hits, matched, offsets
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def day_stats(day, stops, sessions, floods, window_s, min_lines):
|
| 491 |
+
of_day = [s for s in stops
|
| 492 |
+
if datetime.date.fromtimestamp(s["epoch"]).isoformat() == day]
|
| 493 |
+
kinds = {}
|
| 494 |
+
for s in of_day:
|
| 495 |
+
kinds[s["kind"]] = kinds.get(s["kind"], 0) + 1
|
| 496 |
+
completed = [s for s in of_day if s["kind"] == "completed"]
|
| 497 |
+
aborted = [s for s in of_day if s["kind"] == "aborted"]
|
| 498 |
+
disconnect = [s for s in of_day if s["kind"] == "disconnect"]
|
| 499 |
+
hits, matched, offsets = _match(completed, disconnect, COMPLETED_WINDOW)
|
| 500 |
+
a_hits, a_matched, a_offsets = _match(aborted, disconnect, ABORT_WINDOW)
|
| 501 |
+
day_floods = [f for f in floods
|
| 502 |
+
if datetime.date.fromtimestamp(f["t0"]).isoformat() == day]
|
| 503 |
+
return {
|
| 504 |
+
"date": day,
|
| 505 |
+
"started": kinds.get("started", 0),
|
| 506 |
+
"completed": len(completed),
|
| 507 |
+
"aborted": len(aborted),
|
| 508 |
+
"disconnect": len(disconnect),
|
| 509 |
+
"reconnect": kinds.get("reconnect", 0),
|
| 510 |
+
"sessions": len([s for s in sessions if s["first_t"] and
|
| 511 |
+
datetime.date.fromtimestamp(s["first_t"]).isoformat()
|
| 512 |
+
== day]),
|
| 513 |
+
"floods": day_floods,
|
| 514 |
+
"disc_in_completed_window": hits,
|
| 515 |
+
"completed_with_disc": matched,
|
| 516 |
+
"disc_in_completed_offsets": offsets,
|
| 517 |
+
"disc_in_abort_window": a_hits,
|
| 518 |
+
"aborted_with_disc": a_matched,
|
| 519 |
+
"disc_in_abort_offsets": a_offsets,
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
# ── 打印 ────────────────────────────────────────────────────
|
| 524 |
+
def _hms(epoch, ms=False):
|
| 525 |
+
if epoch is None:
|
| 526 |
+
return "—"
|
| 527 |
+
out = datetime.datetime.fromtimestamp(epoch).strftime("%H:%M:%S")
|
| 528 |
+
if ms:
|
| 529 |
+
out += ".{:03d}".format(int(round((epoch % 1) * 1000)) % 1000)
|
| 530 |
+
return out
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def _dur(sec):
|
| 534 |
+
if sec is None:
|
| 535 |
+
return "—"
|
| 536 |
+
if sec < 60:
|
| 537 |
+
return "{:.1f}s".format(sec)
|
| 538 |
+
return "{:.0f}m{:02.0f}s".format(sec // 60, sec % 60)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def _session_of(epoch):
|
| 542 |
+
return next((s for s in _SESSION_CACHE
|
| 543 |
+
if s["first_t"] is not None and
|
| 544 |
+
s["first_t"] <= epoch <= (s["last_t"] or s["first_t"])), None)
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def print_sessions(sessions, episodes, show_all):
|
| 548 |
+
print("── 逐会话:位姿 rebase ─────────────────────────────────────"
|
| 549 |
+
"──────────")
|
| 550 |
+
print(" {:<10}{:>10}{:>8}{:>8}{:>9}{:>10}{:>10} {}".format(
|
| 551 |
+
"会话起点", "日志 id", "时长", "rebase", "最长连跑", "1秒窗峰值",
|
| 552 |
+
"最大步长", "发散"))
|
| 553 |
+
by_id = {}
|
| 554 |
+
for ep in episodes:
|
| 555 |
+
by_id.setdefault(ep["session"], []).append(ep)
|
| 556 |
+
for s in sessions:
|
| 557 |
+
mine = by_id.get(s["name"], [])
|
| 558 |
+
if not show_all and not s["rebase"] and not mine:
|
| 559 |
+
continue
|
| 560 |
+
start = s["first_t"]
|
| 561 |
+
dur = (s["last_t"] - start) if (start and s["last_t"]) else None
|
| 562 |
+
tag = " ".join("★{} {}行".format(_dur(ep["duration_s"]), ep["lines"])
|
| 563 |
+
for ep in mine)
|
| 564 |
+
print(" {:<10}{:>10}{:>8}{:>8}{:>9}{:>10}{:>9.2f}m {}".format(
|
| 565 |
+
_hms(start), s["name"].split("_")[1] if "_" in s["name"] else "",
|
| 566 |
+
_dur(dur), s["rebase"], s["max_run"], s["max_window"],
|
| 567 |
+
s["max_step"], tag or "—"))
|
| 568 |
+
if any(s["unparsed"] for s in sessions):
|
| 569 |
+
print(" (撕裂/截断导致取不到步长的 rebase 行:{} 条,只计行数)".format(
|
| 570 |
+
sum(s["unparsed"] for s in sessions)))
|
| 571 |
+
print(" 注:文件名里的时刻是包装侧建文件的时间,比会话真正的首行晚 1~3 分钟,"
|
| 572 |
+
"所以「会话起点」取首行时刻。")
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def print_episodes(episodes, stops, lookback_s):
|
| 576 |
+
print()
|
| 577 |
+
print("── 每次发散 ← 哪一次停止 ───────────────────────────────────"
|
| 578 |
+
"──────────")
|
| 579 |
+
if not episodes:
|
| 580 |
+
print(" 无(阈值内没有会话发生 rebase 洪水)")
|
| 581 |
+
return
|
| 582 |
+
print(" {:<9}{:>13}{:>8}{:>4}{:>7}{:>10}{:>17}{:>8} {}".format(
|
| 583 |
+
"会话起点", "发散起点", "时长", "段", "行数", "最大步长",
|
| 584 |
+
"漂移速率 首→末", "线性度", "归属"))
|
| 585 |
+
for ep in sorted(episodes, key=lambda x: x["t0"]):
|
| 586 |
+
sid = _session_of(ep["t0"])
|
| 587 |
+
speed = ("{:.0f}→{:.0f} m/s".format(ep["speed_head"], ep["speed_tail"])
|
| 588 |
+
if ep["speed_head"] is not None else "—")
|
| 589 |
+
r2 = "{:.2f}".format(ep["r2"]) if ep["r2"] is not None else "—"
|
| 590 |
+
label, first, near = attribute(ep, stops, lookback_s)
|
| 591 |
+
print(" {:<9}{:>13}{:>8}{:>4}{:>7}{:>9.1f}m{:>17}{:>8} {}".format(
|
| 592 |
+
_hms(sid["first_t"]) if sid else "—", _hms(ep["t0"], ms=True),
|
| 593 |
+
_dur(ep["duration_s"]), ep["segments"], ep["lines"],
|
| 594 |
+
ep["max_step"], speed, r2, label))
|
| 595 |
+
for s in near[:4]:
|
| 596 |
+
print(" {:<6}{:>10} {:+.1f}s {}".format(
|
| 597 |
+
_KIND_LABEL.get(s["kind"], s["kind"]), _hms(s["epoch"]),
|
| 598 |
+
s["epoch"] - ep["t0"], s["text"][:76]))
|
| 599 |
+
if first is not None:
|
| 600 |
+
print(" ↳ 起因而这次停止:{} {}(发散起点在它之后 {:+.1f}s)"
|
| 601 |
+
.format(_KIND_LABEL[first["kind"]], _hms(first["epoch"]),
|
| 602 |
+
ep["t0"] - first["epoch"]))
|
| 603 |
+
print(" 判据:漂移速率 = rebase 步长/dt(内部估计速度),按时间等分 8 桶取中位;")
|
| 604 |
+
print(" 线性度 = 桶速率对时间拟合的 R²(发散=线性上涨;良性零散重定位"
|
| 605 |
+
"既不起涨也不成线)。")
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
_SESSION_CACHE = []
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
def print_baseline(days):
|
| 612 |
+
print()
|
| 613 |
+
print("── 逐日基线 ───────────────────────────────────────────────"
|
| 614 |
+
"──────────")
|
| 615 |
+
print(" {:<12}{:>6}{:>6}{:>9}{:>6}{:>9}{:>7}{:>7}{:>9}".format(
|
| 616 |
+
"日期", "会话", "完成", "收尾断链", "中止", "中止断链", "断链", "重连",
|
| 617 |
+
"发散"))
|
| 618 |
+
for d in days:
|
| 619 |
+
offs = d["disc_in_completed_offsets"]
|
| 620 |
+
med = ("{:.1f}s".format(statistics.median(offs)) if offs else "—")
|
| 621 |
+
print(" {:<12}{:>6}{:>6}{:>9}{:>6}{:>9}{:>7}{:>7}{:>9}".format(
|
| 622 |
+
d["date"], d["sessions"], d["completed"],
|
| 623 |
+
"{}/{}".format(d["disc_in_completed_window"], d["completed"]),
|
| 624 |
+
d["aborted"],
|
| 625 |
+
"{}/{}".format(d["disc_in_abort_window"], d["aborted"]),
|
| 626 |
+
d["disconnect"], d["reconnect"], len(d["floods"])))
|
| 627 |
+
if d["completed"]:
|
| 628 |
+
print(" 「完成」收尾窗口 {}s 内命中断链 {} 条;"
|
| 629 |
+
"带断链的完成 {}/{};最近偏移中位 {}(正=断链更晚)".format(
|
| 630 |
+
"{:g}~{:g}".format(*COMPLETED_WINDOW),
|
| 631 |
+
d["disc_in_completed_window"], d["completed_with_disc"],
|
| 632 |
+
d["completed"], med))
|
| 633 |
+
if d["aborted"]:
|
| 634 |
+
print(" 「中止」窗口 {}s 内命中断链 {} 条;带断链的中止 {}/{}"
|
| 635 |
+
"(中止不做 parquet 确认,只 flush ⇒ 与「完成」的对比是"
|
| 636 |
+
"「断链主因是不是 parquet」的判据)".format(
|
| 637 |
+
"{:g}~{:g}".format(*ABORT_WINDOW),
|
| 638 |
+
d["disc_in_abort_window"], d["aborted_with_disc"],
|
| 639 |
+
d["aborted"]))
|
| 640 |
+
for ep in d["floods"]:
|
| 641 |
+
print(" 发散 {} → {}({} 行 / {} 段,最大步长 {:.1f}m)".format(
|
| 642 |
+
_hms(ep["t0"], ms=True), _hms(ep["t1"]),
|
| 643 |
+
ep["lines"], ep["segments"], ep["max_step"]))
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
# ── main ────────────────────────────────────────────────────
|
| 647 |
+
def main(argv=None):
|
| 648 |
+
parser = argparse.ArgumentParser(
|
| 649 |
+
description="SLAM 位姿发散审计(只读)",
|
| 650 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 651 |
+
parser.add_argument("--native-dir", default=DEFAULT_NATIVE_DIR,
|
| 652 |
+
help="原生会话日志目录(默认 logs/slam_native)")
|
| 653 |
+
parser.add_argument("--main-log", default=DEFAULT_MAIN_LOG,
|
| 654 |
+
help="主程序日志(默认 logs/main.log)")
|
| 655 |
+
parser.add_argument("--date", default=None, help="只看这一天 YYYY-MM-DD")
|
| 656 |
+
parser.add_argument("--since", default=None,
|
| 657 |
+
help="只看该日及以后 YYYY-MM-DD")
|
| 658 |
+
parser.add_argument("--window-s", type=float, default=1.0,
|
| 659 |
+
help="密度判据的滑窗宽度(默认 1.0)")
|
| 660 |
+
parser.add_argument("--min-lines", type=int, default=15,
|
| 661 |
+
help="滑窗内至少这么多条 rebase 才算洪水(默认 15)")
|
| 662 |
+
parser.add_argument("--min-step-m", type=float, default=1.0,
|
| 663 |
+
help="单条 rebase 计入门槛,米(默认 1.0)")
|
| 664 |
+
parser.add_argument("--gap-s", type=float, default=2.0,
|
| 665 |
+
help="相邻命中相隔 ≤ 该值合并成同一段洪水(默认 2.0)")
|
| 666 |
+
parser.add_argument("--episode-gap-s", type=float, default=30.0,
|
| 667 |
+
help="同一会话里两段洪水相隔 ≤ 该值视为同一次发散"
|
| 668 |
+
"(默认 30;发散自锁后会持续,中途密度会掉下去)")
|
| 669 |
+
parser.add_argument("--lookback-s", type=float, default=30.0,
|
| 670 |
+
help="往前找起因果的停止事件的最大回溯(默认 30)")
|
| 671 |
+
parser.add_argument("--all", action="store_true",
|
| 672 |
+
help="连没有 rebase 的会话也列出")
|
| 673 |
+
parser.add_argument("--json", action="store_true", help="输出 JSON")
|
| 674 |
+
args = parser.parse_args(argv)
|
| 675 |
+
|
| 676 |
+
if not os.path.isdir(args.native_dir):
|
| 677 |
+
print(f"原生日志目录不存在: {args.native_dir}")
|
| 678 |
+
return 2
|
| 679 |
+
if not os.path.isfile(args.main_log):
|
| 680 |
+
print(f"主程序日志不存在: {args.main_log}")
|
| 681 |
+
return 2
|
| 682 |
+
|
| 683 |
+
sessions = [load_session(p) for p in
|
| 684 |
+
sorted(glob.glob(os.path.join(args.native_dir,
|
| 685 |
+
"*_stdout.log")))]
|
| 686 |
+
sessions.sort(key=lambda s: s["first_t"] or 0)
|
| 687 |
+
global _SESSION_CACHE
|
| 688 |
+
_SESSION_CACHE = sessions
|
| 689 |
+
|
| 690 |
+
floods = []
|
| 691 |
+
for s in sessions:
|
| 692 |
+
for f in find_floods(s["events"], args.window_s, args.min_step_m,
|
| 693 |
+
args.min_lines, args.gap_s):
|
| 694 |
+
f["session"] = s["name"]
|
| 695 |
+
floods.append(f)
|
| 696 |
+
# 会话之间不合并:不同会话的洪水必然是两次(换过进程/重开过夹爪)
|
| 697 |
+
episodes = merge_episodes(floods, args.episode_gap_s, sessions)
|
| 698 |
+
|
| 699 |
+
rows, known = load_main_log(args.main_log)
|
| 700 |
+
stops = extract_stops(rows)
|
| 701 |
+
|
| 702 |
+
if args.date or args.since:
|
| 703 |
+
lo = args.date or args.since
|
| 704 |
+
hi = args.date
|
| 705 |
+
def keep(ep):
|
| 706 |
+
d = datetime.date.fromtimestamp(ep).isoformat()
|
| 707 |
+
if hi:
|
| 708 |
+
return d == hi
|
| 709 |
+
return d >= lo
|
| 710 |
+
stops = [s for s in stops if keep(s["epoch"])]
|
| 711 |
+
sessions = [s for s in sessions
|
| 712 |
+
if s["first_t"] and keep(s["first_t"])]
|
| 713 |
+
episodes = [ep for ep in episodes if keep(ep["t0"])]
|
| 714 |
+
floods = [f for f in floods if keep(f["t0"])]
|
| 715 |
+
|
| 716 |
+
dates = sorted({datetime.date.fromtimestamp(s["epoch"]).isoformat()
|
| 717 |
+
for s in stops} |
|
| 718 |
+
{datetime.date.fromtimestamp(s["first_t"]).isoformat()
|
| 719 |
+
for s in sessions if s["first_t"]})
|
| 720 |
+
days = [day_stats(d, stops, sessions, episodes, args.window_s,
|
| 721 |
+
args.min_lines) for d in dates]
|
| 722 |
+
|
| 723 |
+
if args.json:
|
| 724 |
+
print(json.dumps({
|
| 725 |
+
"main_log_lines": len(rows),
|
| 726 |
+
"dated_lines": known,
|
| 727 |
+
"sessions": [{k: v for k, v in s.items()
|
| 728 |
+
if k not in ("events", "path")} for s in sessions],
|
| 729 |
+
"episodes": [{k: v for k, v in ep.items() if k != "events"}
|
| 730 |
+
for ep in episodes],
|
| 731 |
+
"days": [{k: v for k, v in d.items() if k != "floods"} | {
|
| 732 |
+
"divergences": len(d["floods"])} for d in days],
|
| 733 |
+
"criteria": {"window_s": args.window_s,
|
| 734 |
+
"min_lines": args.min_lines,
|
| 735 |
+
"min_step_m": args.min_step_m,
|
| 736 |
+
"gap_s": args.gap_s,
|
| 737 |
+
"episode_gap_s": args.episode_gap_s,
|
| 738 |
+
"lookback_s": args.lookback_s},
|
| 739 |
+
}, ensure_ascii=False, indent=2, default=str))
|
| 740 |
+
else:
|
| 741 |
+
print("原生会话日志: {} 份({})".format(
|
| 742 |
+
len(sessions), os.path.relpath(args.native_dir, ROOT)))
|
| 743 |
+
print("主程序日志: {} 行,其中 {} 行解出日期(锚点之前的行不参与配对)"
|
| 744 |
+
.format(len(rows), known))
|
| 745 |
+
print()
|
| 746 |
+
print_sessions(sessions, episodes, args.all)
|
| 747 |
+
print_episodes(episodes, stops, args.lookback_s)
|
| 748 |
+
print_baseline(days)
|
| 749 |
+
|
| 750 |
+
return 1 if episodes else 0
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
if __name__ == "__main__":
|
| 754 |
+
sys.exit(main())
|
|
@@ -1,10 +1,19 @@
|
|
| 1 |
# Pooled Viewer Demo —— 池化录制查看器
|
| 2 |
|
| 3 |
-
单文件自包含的查看器 demo
|
| 4 |
-
D435 相机视频
|
| 5 |
-
手套 IMU
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
## 用法
|
| 10 |
|
|
@@ -25,14 +34,21 @@ venv/bin/python tools/demos/pooled_viewer_demo/pooled_viewer_demo.py [episode-NN
|
|
| 25 |
<task>/videos/chunk-NNN/<image_key>/episode-FFF.mp4 # 每路视频一个文件
|
| 26 |
```
|
| 27 |
|
| 28 |
-
- 触觉列:`observation.<sensor>` fixed_size_list\<float32,256\>(16×16 摊平)
|
| 29 |
-
传感器名
|
|
|
|
|
|
|
|
|
|
| 30 |
- IMU 列:`observation.<sensor>_imu_quat`(16×4 XYZW 摊平为 64)+
|
| 31 |
-
`observation.<sensor>_imu_valid`(16 个掩码)
|
|
|
|
|
|
|
|
|
|
| 32 |
- 帧对齐:视频与传感器行按写入帧号一一对应;播放时视频顺序读、
|
| 33 |
跳帧 seek,视频帧数不足保持最后一帧
|
| 34 |
-
- 深度流(`*_depth` / `.mkv`,12-bit 灰度 HEVC
|
| 35 |
-
|
|
|
|
| 36 |
|
| 37 |
## 依赖
|
| 38 |
|
|
|
|
| 1 |
# Pooled Viewer Demo —— 池化录制查看器
|
| 2 |
|
| 3 |
+
单文件自包含的查看器 demo(只依赖 numpy/pyarrow/opencv/PyQt5,不 import 主程序
|
| 4 |
+
任何模块):选中主程序池化录制的 `episode-NNN.parquet` 即可播放 D435 相机视频
|
| 5 |
+
与深度伪彩 + 手套触觉矩阵 + 手部骨架 + 手套 IMU 姿态。
|
| 6 |
+
|
| 7 |
+
各可视化组件的出处(都是**源码级移植**,不是运行时调用):
|
| 8 |
+
|
| 9 |
+
| 面板 | 本文件里的实现 | 血缘 |
|
| 10 |
+
|---|---|---|
|
| 11 |
+
| 触觉矩阵 | `render_tactile_grid` | 厂商 Glove-test V1.4 `glove_qt_visualizer.py` 的 `PressureMatrixCanvas`(QPainter → OpenCV,全仓唯一移植处) |
|
| 12 |
+
| 手部骨架 | `render_skeleton` | 主程序 `core/render_engine.py:render_skeleton` ← 工具包 `apps/rendering/replay.py`(主程序实时手套面板用的就是同一血缘那份) |
|
| 13 |
+
| 手套 IMU | `render_imu_panel` | 本文件自写 |
|
| 14 |
+
|
| 15 |
+
注意主程序的触觉可视化**不是**这个矩阵网格:它是 `core/render_engine.py:render_hand`
|
| 16 |
+
的仿生手掌(实时面板 + 回放默认模式),`render_grid` 简单网格只是五个可选模式之一。
|
| 17 |
|
| 18 |
## 用法
|
| 19 |
|
|
|
|
| 34 |
<task>/videos/chunk-NNN/<image_key>/episode-FFF.mp4 # 每路视频一个文件
|
| 35 |
```
|
| 36 |
|
| 37 |
+
- 触觉列:`observation.<sensor>` fixed_size_list\<float32,256\>(16×16 摊平)。
|
| 38 |
+
**左右手各一个面板并排、左手在左**,顶栏标传感器名(`left_glove` /
|
| 39 |
+
`right_glove`);传感器名含 left 时网格行序翻转(左手行序与右手镜像,
|
| 40 |
+
2026-09-04 与实机数据逐格核对)。列是稀疏的 —— 哪只手有数据才有哪列,
|
| 41 |
+
只有单手数据时就只显示那一个面板
|
| 42 |
- IMU 列:`observation.<sensor>_imu_quat`(16×4 XYZW 摊平为 64)+
|
| 43 |
+
`observation.<sensor>_imu_valid`(16 个掩码)。每传感器一个面板左右并排,
|
| 44 |
+
标题带传感器名;有骨架数据时默认隐藏,勾选"显示 IMU 四元数"切出
|
| 45 |
+
- 骨架列:`observation.<side>_hand_pose` fixed_size_list\<float32,63\>(21×3),
|
| 46 |
+
恒写列、全零 = 无数据(会被过滤掉)。左右各一个面板并排
|
| 47 |
- 帧对齐:视频与传感器行按写入帧号一一对应;播放时视频顺序读、
|
| 48 |
跳帧 seek,视频帧数不足保持最后一帧
|
| 49 |
+
- 深度流(`*_depth` / `.mkv`,12-bit 灰度 HEVC / FFV1 gray16le)反量化成
|
| 50 |
+
毫米后画 JET 伪彩,与主程序显示口径一致;解码要 ffmpeg(打包版已随包
|
| 51 |
+
带 imageio-ffmpeg,源码运行时装 `pip install imageio-ffmpeg` 即可)
|
| 52 |
|
| 53 |
## 依赖
|
| 54 |
|
|
@@ -19,10 +19,10 @@
|
|
| 19 |
无深度流时 RGB 占满整行)
|
| 20 |
2) 手套触觉面板(厂商 Glove-test V1.4 glove_qt_visualizer.py 的
|
| 21 |
PressureMatrixCanvas 的 OpenCV 移植:只留 16x16 分区网格,
|
| 22 |
-
手形热图 PressureHandCanvas 移植已按用户要求移除;
|
| 23 |
-
|
| 24 |
-
(每传感器中位基线,
|
| 25 |
-
(触觉左、骨架右))
|
| 26 |
3) 手部骨架面板(工具包 apps/rendering/replay.py 的 MANO 21 关键点
|
| 27 |
骨骼渲染,observation.{left,right}_hand_pose,左 | 右;
|
| 28 |
视角 = 标定预览初始视角(calibration_pose_preview 的
|
|
@@ -31,7 +31,8 @@
|
|
| 31 |
在画面左侧);相机距离与居中点按整段数据一次计算,播放中
|
| 32 |
相机完全不动)
|
| 33 |
4) 手套 IMU 面板(16 个 BNO055 的四元数姿态,每格画旋转后的 XYZ 轴;
|
| 34 |
-
有骨架数据时默认隐藏,
|
|
|
|
| 35 |
|
| 36 |
parquet 稀疏列约定(与 core/egodata_writer 一致):
|
| 37 |
observation.<sensor> fixed_size_list<float32,256> 16x16 触觉
|
|
@@ -562,6 +563,10 @@ class PooledSession:
|
|
| 562 |
# (右手传感列 [10,9,8,6,4] / 左手 [10,9,8,6]),列 0-2 为空。
|
| 563 |
# 面板内拇指统一朝左:网格 x 轴 = 矩阵行,左手翻转、右手不翻
|
| 564 |
# (与厂商网格恰好对调,因左手行序与厂商 README 假定相反)。
|
|
|
|
|
|
|
|
|
|
|
|
|
| 565 |
|
| 566 |
_TACTILE_FINGER_NAMES = ("Thumb", "Index", "Middle", "Ring", "Pinky")
|
| 567 |
# 手指区分区框颜色(厂商 _FINGER_COLORS,BGR)
|
|
@@ -670,8 +675,10 @@ def render_tactile_grid(matrix, side="right", baseline=None,
|
|
| 670 |
|
| 671 |
finger_height = 4.0 * cell
|
| 672 |
for group in range(5):
|
| 673 |
-
|
| 674 |
-
|
|
|
|
|
|
|
| 675 |
x0 = int(grid_left + display_start_x * cell)
|
| 676 |
y0 = int(grid_top)
|
| 677 |
cv2.rectangle(img, (x0 + 2, y0 + 2),
|
|
@@ -699,7 +706,8 @@ def render_tactile_grid(matrix, side="right", baseline=None,
|
|
| 699 |
cv2.rectangle(img, (legend_left, top),
|
| 700 |
(legend_left + 15, top + 15),
|
| 701 |
_TACTILE_FINGER_BGR[group], -1)
|
| 702 |
-
|
|
|
|
| 703 |
(legend_left + 23, top + 13),
|
| 704 |
cv2.FONT_HERSHEY_SIMPLEX, 0.4, _TACTILE_TEXT, 1, cv2.LINE_AA)
|
| 705 |
cv2.putText(img, "Spare col: x=0, y=3..15",
|
|
@@ -785,19 +793,22 @@ def _arrow(img, p0, p1, color, thick=2):
|
|
| 785 |
], np.int32), color, cv2.LINE_AA)
|
| 786 |
|
| 787 |
|
| 788 |
-
def render_imu_panel(quats, valid, w=880, h=240):
|
| 789 |
"""手套 IMU 姿态面板:16 个 BNO055 各画一格,格内为旋转后的 XYZ 轴。
|
| 790 |
|
| 791 |
Args:
|
| 792 |
quats: (16,4) float XYZW
|
| 793 |
valid: (16,) bool
|
|
|
|
| 794 |
Returns:
|
| 795 |
BGR 画布
|
| 796 |
"""
|
| 797 |
canvas = np.full((h, w, 3), 18, np.uint8)
|
| 798 |
n_valid = int(np.count_nonzero(valid))
|
| 799 |
-
|
| 800 |
-
|
|
|
|
|
|
|
| 801 |
(8, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.55,
|
| 802 |
(220, 220, 220), 1, cv2.LINE_AA)
|
| 803 |
|
|
@@ -1171,13 +1182,11 @@ class DemoWindow(QMainWindow):
|
|
| 1171 |
self.has_depth = self.data.has_depth()
|
| 1172 |
self.has_imu = self.data.has_imu()
|
| 1173 |
self.has_kpts = self.data.has_keypoints()
|
| 1174 |
-
# 触觉面板
|
| 1175 |
-
#
|
| 1176 |
-
|
| 1177 |
-
|
| 1178 |
-
|
| 1179 |
-
if glove_side_of(s) == "right"]
|
| 1180 |
-
self.tactile_sensors = lefts or rights
|
| 1181 |
self._update_panel_visibility()
|
| 1182 |
# 骨架相机:距离照工具包 replay.py 按整段数据空间尺度一次拟合、
|
| 1183 |
# 居中点按整段数据各帧包围盒中心的中位数一次计算,播放中全部
|
|
@@ -1205,10 +1214,9 @@ class DemoWindow(QMainWindow):
|
|
| 1205 |
"触觉列存在但全为零\n"
|
| 1206 |
"(手套触觉传感器无数据,检查硬件/连接后重新录制)")
|
| 1207 |
elif self.tactile_sensors:
|
| 1208 |
-
|
| 1209 |
-
|
| 1210 |
-
self.lbl_hand.setText(
|
| 1211 |
-
f"Glove Tactile Matrix Panel ({side.upper()})")
|
| 1212 |
else:
|
| 1213 |
self.lbl_hand.setText("Glove Tactile Matrix Panel")
|
| 1214 |
self.chk_imu.setVisible(self.has_imu and self.has_kpts)
|
|
@@ -1236,13 +1244,7 @@ class DemoWindow(QMainWindow):
|
|
| 1236 |
f"深度 {len(self.data.depth_videos)} 路"]
|
| 1237 |
if self.data.skipped_depth:
|
| 1238 |
bits.append(f"深度流无法解码: {', '.join(self.data.skipped_depth)}")
|
| 1239 |
-
|
| 1240 |
-
if self.tactile_sensors and glove_side_of(
|
| 1241 |
-
self.tactile_sensors[0]) == "right":
|
| 1242 |
-
tbit += "(无左手数据,显示右手)"
|
| 1243 |
-
elif len(self.data.tactile) > len(self.tactile_sensors):
|
| 1244 |
-
tbit += "(暂只显示左手)"
|
| 1245 |
-
bits.append(tbit)
|
| 1246 |
bits.append(f"骨架 {', '.join(self.data.keypoints) or '无'}"
|
| 1247 |
if self.has_kpts else "骨架 无")
|
| 1248 |
bits.append(f"IMU {', '.join(self.data.imu_quats) or '无'}")
|
|
@@ -1251,7 +1253,7 @@ class DemoWindow(QMainWindow):
|
|
| 1251 |
def _update_panel_visibility(self):
|
| 1252 |
"""骨架/IMU 面板可见性:有骨架时骨架优先,IMU 降为勾选兜底。
|
| 1253 |
|
| 1254 |
-
触觉面板显示 self.tactile_sensors(
|
| 1255 |
"""
|
| 1256 |
self.lbl_depth.setVisible(self.has_depth)
|
| 1257 |
# 有触觉列就保留面板(正常渲染网格;全零时显示说明占位),
|
|
@@ -1426,8 +1428,8 @@ class DemoWindow(QMainWindow):
|
|
| 1426 |
self._show_image(self.lbl_depth, top)
|
| 1427 |
|
| 1428 |
# 2) 手套触觉面板(厂商 Glove-test 移植:只留分区网格,手形热图
|
| 1429 |
-
# 已按用户要求移除;
|
| 1430 |
-
#
|
| 1431 |
sensors = self.tactile_sensors
|
| 1432 |
if self.has_tactile and sensors:
|
| 1433 |
h = max(self.lbl_hand.height() or 560, 240)
|
|
@@ -1447,9 +1449,15 @@ class DemoWindow(QMainWindow):
|
|
| 1447 |
bhv = panels[0]
|
| 1448 |
for p in panels[1:]:
|
| 1449 |
bhv = np.hstack([bhv, pad24, p])
|
| 1450 |
-
|
| 1451 |
-
|
| 1452 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1453 |
|
| 1454 |
# 3) 手部骨架面板(MANO 21 关键点,每侧一个面板横排;视角 =
|
| 1455 |
# 标定预览初始视角 yaw=186.8°/elev=-44.3°/roll=1.5° + 每侧
|
|
@@ -1477,24 +1485,28 @@ class DemoWindow(QMainWindow):
|
|
| 1477 |
out = panels[0]
|
| 1478 |
self._show_image(self.lbl_skel, out)
|
| 1479 |
|
| 1480 |
-
# 4) IMU 姿态面板(每传感器一个面板,
|
|
|
|
|
|
|
| 1481 |
imu_sensors = sorted(self.data.imu_quats)
|
| 1482 |
if self.has_imu and imu_sensors and self.lbl_imu.isVisible():
|
|
|
|
| 1483 |
w = self.lbl_imu.width() or 880
|
| 1484 |
-
|
|
|
|
| 1485 |
panels = []
|
| 1486 |
for sn in imu_sensors:
|
| 1487 |
quats, valid = self.data.imu_frame(sn, idx)
|
| 1488 |
-
panels.append(render_imu_panel(
|
| 1489 |
-
|
| 1490 |
if len(panels) > 1:
|
| 1491 |
-
pad = np.full((
|
| 1492 |
out = panels[0]
|
| 1493 |
for p in panels[1:]:
|
| 1494 |
-
out = np.
|
| 1495 |
-
self._show_image(self.lbl_imu, out)
|
| 1496 |
else:
|
| 1497 |
-
|
|
|
|
| 1498 |
|
| 1499 |
@staticmethod
|
| 1500 |
def _show_image(label, bgr):
|
|
|
|
| 19 |
无深度流时 RGB 占满整行)
|
| 20 |
2) 手套触觉面板(厂商 Glove-test V1.4 glove_qt_visualizer.py 的
|
| 21 |
PressureMatrixCanvas 的 OpenCV 移植:只留 16x16 分区网格,
|
| 22 |
+
手形热图 PressureHandCanvas 移植已按用户要求移除;左右手各一个
|
| 23 |
+
面板并排、左手在左,面板角上标传感器名;会话只有单手数据时
|
| 24 |
+
就只剩那一个面板;可选"触觉基线校正"(每传感器中位基线,
|
| 25 |
+
默认开)。与骨架面板在同一行左右并排(触觉左、骨架右))
|
| 26 |
3) 手部骨架面板(工具包 apps/rendering/replay.py 的 MANO 21 关键点
|
| 27 |
骨骼渲染,observation.{left,right}_hand_pose,左 | 右;
|
| 28 |
视角 = 标定预览初始视角(calibration_pose_preview 的
|
|
|
|
| 31 |
在画面左侧);相机距离与居中点按整段数据一次计算,播放中
|
| 32 |
相机完全不动)
|
| 33 |
4) 手套 IMU 面板(16 个 BNO055 的四元数姿态,每格画旋转后的 XYZ 轴;
|
| 34 |
+
每传感器一个面板左右并排、标题带传感器名;有骨架数据时默认隐藏,
|
| 35 |
+
"显示 IMU 四元数"勾选可切出)
|
| 36 |
|
| 37 |
parquet 稀疏列约定(与 core/egodata_writer 一致):
|
| 38 |
observation.<sensor> fixed_size_list<float32,256> 16x16 触觉
|
|
|
|
| 563 |
# (右手传感列 [10,9,8,6,4] / 左手 [10,9,8,6]),列 0-2 为空。
|
| 564 |
# 面板内拇指统一朝左:网格 x 轴 = 矩阵行,左手翻转、右手不翻
|
| 565 |
# (与厂商网格恰好对调,因左手行序与厂商 README 假定相反)。
|
| 566 |
+
# 手指分区框与图例里的 x 区间也按各手的行序给(左手 拇指 x=13..15、
|
| 567 |
+
# 小指 x=1..3),所以两只手的拇指框都落在画面左侧 —— 2026-09-20 修正:
|
| 568 |
+
# 旧写法按「两只手拇指都在行 1-3」摆框,左手的五个框整体对调了
|
| 569 |
+
# (分区框/图例与 Spare 框、掌心框口径不一致)。
|
| 570 |
|
| 571 |
_TACTILE_FINGER_NAMES = ("Thumb", "Index", "Middle", "Ring", "Pinky")
|
| 572 |
# 手指区分区框颜色(厂商 _FINGER_COLORS,BGR)
|
|
|
|
| 675 |
|
| 676 |
finger_height = 4.0 * cell
|
| 677 |
for group in range(5):
|
| 678 |
+
# 框要扣在该手指的行落点上:右手行序 1..15(拇指 1-3),左手镜像
|
| 679 |
+
# (拇指 15-13)→ 翻转后第 g 组落在显示列 3g..3g+2,拇指仍在画面
|
| 680 |
+
# 左侧。与下面 Spare 框(行 0)、掌心框(行 1..15)同一口径。
|
| 681 |
+
display_start_x = 3 * group if flip else 1 + group * 3
|
| 682 |
x0 = int(grid_left + display_start_x * cell)
|
| 683 |
y0 = int(grid_top)
|
| 684 |
cv2.rectangle(img, (x0 + 2, y0 + 2),
|
|
|
|
| 706 |
cv2.rectangle(img, (legend_left, top),
|
| 707 |
(legend_left + 15, top + 15),
|
| 708 |
_TACTILE_FINGER_BGR[group], -1)
|
| 709 |
+
row_lo = 13 - 3 * group if flip else 1 + 3 * group
|
| 710 |
+
cv2.putText(img, f"{_TACTILE_FINGER_NAMES[group]}: x={row_lo}..{row_lo+2}",
|
| 711 |
(legend_left + 23, top + 13),
|
| 712 |
cv2.FONT_HERSHEY_SIMPLEX, 0.4, _TACTILE_TEXT, 1, cv2.LINE_AA)
|
| 713 |
cv2.putText(img, "Spare col: x=0, y=3..15",
|
|
|
|
| 793 |
], np.int32), color, cv2.LINE_AA)
|
| 794 |
|
| 795 |
|
| 796 |
+
def render_imu_panel(quats, valid, w=880, h=240, label=""):
|
| 797 |
"""手套 IMU 姿态面板:16 个 BNO055 各画一格,格内为旋转后的 XYZ 轴。
|
| 798 |
|
| 799 |
Args:
|
| 800 |
quats: (16,4) float XYZW
|
| 801 |
valid: (16,) bool
|
| 802 |
+
label: 传感器名(左右手各一个面板时用于区分,空则不显示)
|
| 803 |
Returns:
|
| 804 |
BGR 画布
|
| 805 |
"""
|
| 806 |
canvas = np.full((h, w, 3), 18, np.uint8)
|
| 807 |
n_valid = int(np.count_nonzero(valid))
|
| 808 |
+
title = "Glove IMU 四元数姿态"
|
| 809 |
+
if label:
|
| 810 |
+
title += f" [{label}]"
|
| 811 |
+
cv2.putText(canvas, f"{title} ({n_valid}/16 sensors)",
|
| 812 |
(8, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.55,
|
| 813 |
(220, 220, 220), 1, cv2.LINE_AA)
|
| 814 |
|
|
|
|
| 1182 |
self.has_depth = self.data.has_depth()
|
| 1183 |
self.has_imu = self.data.has_imu()
|
| 1184 |
self.has_kpts = self.data.has_keypoints()
|
| 1185 |
+
# 触觉面板:左手套 + 右手套各一个并排(左手在左,与骨架面板
|
| 1186 |
+
# 同序);会话只有单手数据时就只剩那一个面板
|
| 1187 |
+
self.tactile_sensors = sorted(
|
| 1188 |
+
self.data.tactile,
|
| 1189 |
+
key=lambda s: (0 if glove_side_of(s) == "left" else 1, s))
|
|
|
|
|
|
|
| 1190 |
self._update_panel_visibility()
|
| 1191 |
# 骨架相机:距离照工具包 replay.py 按整段数据空间尺度一次拟合、
|
| 1192 |
# 居中点按整段数据各帧包围盒中心的中位数一次计算,播放中全部
|
|
|
|
| 1214 |
"触觉列存在但全为零\n"
|
| 1215 |
"(手套触觉传感器无数据,检查硬件/连接后重新录制)")
|
| 1216 |
elif self.tactile_sensors:
|
| 1217 |
+
sides = "+".join(glove_side_of(s).upper()
|
| 1218 |
+
for s in self.tactile_sensors)
|
| 1219 |
+
self.lbl_hand.setText(f"Glove Tactile Matrix Panel ({sides})")
|
|
|
|
| 1220 |
else:
|
| 1221 |
self.lbl_hand.setText("Glove Tactile Matrix Panel")
|
| 1222 |
self.chk_imu.setVisible(self.has_imu and self.has_kpts)
|
|
|
|
| 1244 |
f"深度 {len(self.data.depth_videos)} 路"]
|
| 1245 |
if self.data.skipped_depth:
|
| 1246 |
bits.append(f"深度流无法解码: {', '.join(self.data.skipped_depth)}")
|
| 1247 |
+
bits.append(f"触觉 {', '.join(self.data.tactile) or '无'}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1248 |
bits.append(f"骨架 {', '.join(self.data.keypoints) or '无'}"
|
| 1249 |
if self.has_kpts else "骨架 无")
|
| 1250 |
bits.append(f"IMU {', '.join(self.data.imu_quats) or '无'}")
|
|
|
|
| 1253 |
def _update_panel_visibility(self):
|
| 1254 |
"""骨架/IMU 面板可见性:有骨架时骨架优先,IMU 降为勾选兜底。
|
| 1255 |
|
| 1256 |
+
触觉面板显示 self.tactile_sensors(左右手各一个,左手在左)。
|
| 1257 |
"""
|
| 1258 |
self.lbl_depth.setVisible(self.has_depth)
|
| 1259 |
# 有触觉列就保留面板(正常渲染网格;全零时显示说明占位),
|
|
|
|
| 1428 |
self._show_image(self.lbl_depth, top)
|
| 1429 |
|
| 1430 |
# 2) 手套触觉面板(厂商 Glove-test 移植:只留分区网格,手形热图
|
| 1431 |
+
# 已按用户要求移除;左右手各一个面板并排(左手在左),面板角
|
| 1432 |
+
# 上标传感器名;全零数据时不渲染、保留 load 里的占位说明文字)
|
| 1433 |
sensors = self.tactile_sensors
|
| 1434 |
if self.has_tactile and sensors:
|
| 1435 |
h = max(self.lbl_hand.height() or 560, 240)
|
|
|
|
| 1449 |
bhv = panels[0]
|
| 1450 |
for p in panels[1:]:
|
| 1451 |
bhv = np.hstack([bhv, pad24, p])
|
| 1452 |
+
# 传感器名另起一条顶栏:两个网格左右手单看分不出是谁的,
|
| 1453 |
+
# 但网格本身画得满(左上角压着坐标数字、中上是 "X -> …"),
|
| 1454 |
+
# 名字写进面板里必然盖掉东西 —— 往上加带子,标签区还有余量
|
| 1455 |
+
head = np.full((26, bhv.shape[1], 3), 15, np.uint8)
|
| 1456 |
+
for k, sn in enumerate(sensors):
|
| 1457 |
+
cv2.putText(head, sn, (k * (int(per_w) + 24) + 10, 19),
|
| 1458 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255),
|
| 1459 |
+
1, cv2.LINE_AA)
|
| 1460 |
+
self._show_image(self.lbl_hand, np.vstack([head, bhv]))
|
| 1461 |
|
| 1462 |
# 3) 手部骨架面板(MANO 21 关键点,每侧一个面板横排;视角 =
|
| 1463 |
# 标定预览初始视角 yaw=186.8°/elev=-44.3°/roll=1.5° + 每侧
|
|
|
|
| 1485 |
out = panels[0]
|
| 1486 |
self._show_image(self.lbl_skel, out)
|
| 1487 |
|
| 1488 |
+
# 4) IMU 姿态面板(每传感器一个面板,左右并排,标题带传感器名;
|
| 1489 |
+
# 有骨架时默认隐藏。IMU 面板是宽扁的,两个竖排会被面板高度
|
| 1490 |
+
# 压到看不清,横排刚好铺满)
|
| 1491 |
imu_sensors = sorted(self.data.imu_quats)
|
| 1492 |
if self.has_imu and imu_sensors and self.lbl_imu.isVisible():
|
| 1493 |
+
h = max(self.lbl_imu.height() or 240, 200)
|
| 1494 |
w = self.lbl_imu.width() or 880
|
| 1495 |
+
per_w = max((w - 4 * (len(imu_sensors) - 1)) // len(imu_sensors),
|
| 1496 |
+
480)
|
| 1497 |
panels = []
|
| 1498 |
for sn in imu_sensors:
|
| 1499 |
quats, valid = self.data.imu_frame(sn, idx)
|
| 1500 |
+
panels.append(render_imu_panel(quats, valid, w=int(per_w),
|
| 1501 |
+
h=h, label=sn))
|
| 1502 |
if len(panels) > 1:
|
| 1503 |
+
pad = np.full((h, 4, 3), 10, np.uint8)
|
| 1504 |
out = panels[0]
|
| 1505 |
for p in panels[1:]:
|
| 1506 |
+
out = np.hstack([out, pad, p])
|
|
|
|
| 1507 |
else:
|
| 1508 |
+
out = panels[0]
|
| 1509 |
+
self._show_image(self.lbl_imu, out)
|
| 1510 |
|
| 1511 |
@staticmethod
|
| 1512 |
def _show_image(label, bgr):
|
|
@@ -0,0 +1,471 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""tools/audit_frame_gaps.py 回归自检(**不依赖真机数据**,全部现场造)。
|
| 4 |
+
|
| 5 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python tools/tests/test_audit_frame_gaps.py
|
| 6 |
+
|
| 7 |
+
为什么值得单测:这个脚本的结论会被当成「视频到底丢了多少」的权威数字写进
|
| 8 |
+
文档,而它的三层判据(画面 / 双钟 / 单钟)每一层都有一种**看起来很对但结论
|
| 9 |
+
相反**的坑:
|
| 10 |
+
|
| 11 |
+
① 画面复核是主判据。把「钟跳了但画面是连的」当成丢帧(本库 72 段 / 20.1s
|
| 12 |
+
的 ~250ms 事件全是这一类),或把「钟跳了且画面真跳」当成没事,都会得到
|
| 13 |
+
一个自洽但错误的结论——所以两种情形都要有正反用例钉住。
|
| 14 |
+
② 早年段的 hardware_ns 是**有符号 32 位**的截断计数器:不解卷 ⇒ 每次过零都
|
| 15 |
+
是一次天文数字级的假空洞;解卷过头(对 64 位戳也解卷)⇒ 把真实的大空洞
|
| 16 |
+
折叠成小数字(ep-099 的 4.68s 会变成 0.39s)。
|
| 17 |
+
③ 静止场景里「画面连续」和「画面跳变」长得一样(都≈噪声地板)⇒ 必须回落
|
| 18 |
+
到「判不了」,不许判成「没丢」。
|
| 19 |
+
|
| 20 |
+
用例里的画面是**线性渐变条**:整体平移 δ 像素 ⇒ mad ≡ 255δ/宽,与位移严格
|
| 21 |
+
成正比。于是「一帧的运动量」和「30 帧的运动量」在数值上就分得开(6.4 vs 191),
|
| 22 |
+
阈值判据才有可判定的正反例。
|
| 23 |
+
|
| 24 |
+
覆盖:
|
| 25 |
+
1 纯函数契约:时钟分类 / 解卷 / 段号归一 / 事件定性
|
| 26 |
+
2 健康段:零事件零账
|
| 27 |
+
3 画面复核三态:真丢(跳变)/ 钟跳(连续)/ 静止(判不了,不许说没丢)
|
| 28 |
+
4 归账四桶互斥:丢了 / 钟跳没丢 / 打嗝 / 待复核,且同一形状只进一桶
|
| 29 |
+
5 trunc32 解卷:跨符号边界仍恰好 1 起事件、大小正确(防回绕假空洞)
|
| 30 |
+
6 63 位戳不解卷:>2.1s 的真空洞必须原样保留(防折叠)
|
| 31 |
+
7 合并:15 行内的两次异常 → 1 起事件、取 max 不求和(防同一个洞数两遍)
|
| 32 |
+
8 拒答:多槽 episode / 无时间戳 / mp4 帧数不符行数
|
| 33 |
+
9 CLI:退出码、--json 结构、--no-video-check(未复核不许算「没丢」)、
|
| 34 |
+
--clock-tol-ms 0 时必须变红、--camera-logs 时间窗
|
| 35 |
+
退出码 0 = 全部通过。
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
from __future__ import annotations
|
| 39 |
+
|
| 40 |
+
import contextlib
|
| 41 |
+
import datetime
|
| 42 |
+
import io
|
| 43 |
+
import json
|
| 44 |
+
import os
|
| 45 |
+
import shutil
|
| 46 |
+
import sys
|
| 47 |
+
import tempfile
|
| 48 |
+
|
| 49 |
+
import numpy as np
|
| 50 |
+
|
| 51 |
+
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
|
| 52 |
+
os.path.abspath(__file__))))
|
| 53 |
+
sys.path.insert(0, REPO_ROOT)
|
| 54 |
+
|
| 55 |
+
from tools import audit_frame_gaps as audit # noqa: E402
|
| 56 |
+
|
| 57 |
+
FAILS = []
|
| 58 |
+
NOMINAL = int(1e9 / 30.0)
|
| 59 |
+
MS = 1_000_000
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def check(cond, msg):
|
| 63 |
+
if cond:
|
| 64 |
+
print(f" PASS: {msg}")
|
| 65 |
+
else:
|
| 66 |
+
print(f" FAIL: {msg}")
|
| 67 |
+
FAILS.append(msg)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# ── 造数据 ──────────────────────────────────────────────────
|
| 71 |
+
def _gradient(offset, width=160, height=120):
|
| 72 |
+
"""线性渐变条(整体平移 offset 像素,环绕)。平移 δ ⇒ mad ≈ 255δ/width。"""
|
| 73 |
+
xs = (np.arange(width) - int(offset)) % width
|
| 74 |
+
row = (xs * 255 // width).astype("uint8")
|
| 75 |
+
gray = np.tile(row, (height, 1))
|
| 76 |
+
return np.dstack([gray] * 3)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _write_video(path, count, step_px=4, jump_at=None, jump_px=120,
|
| 80 |
+
static=False):
|
| 81 |
+
"""count 帧;第 jump_at 帧前额外多平移 jump_px 像素(= 画面跳变)。"""
|
| 82 |
+
import cv2
|
| 83 |
+
writer = cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*"mp4v"), 30.0,
|
| 84 |
+
(160, 120), isColor=True)
|
| 85 |
+
if not writer.isOpened():
|
| 86 |
+
raise RuntimeError("VideoWriter 打不开,测试无法取证")
|
| 87 |
+
offset = 0
|
| 88 |
+
for index in range(count):
|
| 89 |
+
if jump_at is not None and index == jump_at:
|
| 90 |
+
offset += jump_px
|
| 91 |
+
writer.write(_gradient(offset))
|
| 92 |
+
if not static:
|
| 93 |
+
offset += step_px
|
| 94 |
+
writer.release()
|
| 95 |
+
return _video_count(path)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _video_count(path):
|
| 99 |
+
import cv2
|
| 100 |
+
cap = cv2.VideoCapture(path)
|
| 101 |
+
count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) if cap.isOpened() else -1
|
| 102 |
+
cap.release()
|
| 103 |
+
return count
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _write_parquet(path, frame_index, hw, wall):
|
| 107 |
+
import pyarrow as pa
|
| 108 |
+
import pyarrow.parquet as pq
|
| 109 |
+
pq.write_table(pa.table({
|
| 110 |
+
"frame_index": pa.array(frame_index, pa.int64()),
|
| 111 |
+
"hardware_ns": pa.array(hw, pa.int64()),
|
| 112 |
+
"wall_time": pa.array(wall, pa.float64()),
|
| 113 |
+
}), path)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _series(count, hw_step=NOMINAL, wall_step_ns=NOMINAL, hw0=3_600_000_000_000,
|
| 117 |
+
wall0=1_789_000_000.0, hw_jump_at=None, hw_jump_ns=0,
|
| 118 |
+
wall_jump_at=None, wall_jump_ns=0, wrap32=False):
|
| 119 |
+
"""造两条时间轴;jump_at 处的**间隔**额外加 jump_ns(洞就在那两行之间)。"""
|
| 120 |
+
hw, wall = [hw0], [wall0]
|
| 121 |
+
for index in range(1, count):
|
| 122 |
+
hw.append(hw[-1] + hw_step + (hw_jump_ns if index == hw_jump_at else 0))
|
| 123 |
+
wall.append(wall[-1] + (wall_step_ns
|
| 124 |
+
+ (wall_jump_ns if index == wall_jump_at else 0))
|
| 125 |
+
/ 1e9)
|
| 126 |
+
if wrap32: # 折进有符号 32 位:值域 [−2^31, 2^31)
|
| 127 |
+
hw = [((value + 2 ** 31) % 2 ** 32) - 2 ** 31 for value in hw]
|
| 128 |
+
return hw, wall
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class _Sandbox:
|
| 132 |
+
"""一个临时任务目录;add() 造一段(parquet + mp4)。"""
|
| 133 |
+
|
| 134 |
+
def __init__(self):
|
| 135 |
+
self.root = tempfile.mkdtemp(prefix="ksq-audit-test-")
|
| 136 |
+
os.makedirs(os.path.join(self.root, "data", "chunk-000"))
|
| 137 |
+
os.makedirs(os.path.join(self.root, "videos", "chunk-000",
|
| 138 |
+
"gripper_rgb"))
|
| 139 |
+
|
| 140 |
+
def paths(self, ep):
|
| 141 |
+
return (os.path.join(self.root, "data", "chunk-000",
|
| 142 |
+
f"episode-{ep}.parquet"),
|
| 143 |
+
os.path.join(self.root, "videos", "chunk-000", "gripper_rgb",
|
| 144 |
+
f"episode-{ep}.mp4"))
|
| 145 |
+
|
| 146 |
+
def add(self, ep, count=60, video_count=None, **kw):
|
| 147 |
+
"""kw 分两路:video_* 给 _write_video,其余给 _series。"""
|
| 148 |
+
video_kw = {key[6:]: kw.pop(key) for key in list(kw)
|
| 149 |
+
if key.startswith("video_")}
|
| 150 |
+
hw, wall = _series(count, **kw)
|
| 151 |
+
parquet, video = self.paths(ep)
|
| 152 |
+
_write_parquet(parquet, list(range(count)), hw, wall)
|
| 153 |
+
frames = _write_video(video, count if video_count is None
|
| 154 |
+
else video_count, **video_kw)
|
| 155 |
+
return parquet, video, frames
|
| 156 |
+
|
| 157 |
+
def close(self):
|
| 158 |
+
shutil.rmtree(self.root, ignore_errors=True)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def audit_one(parquet, video, **kw):
|
| 162 |
+
kw.setdefault("video_check", True)
|
| 163 |
+
return audit.audit_episode(parquet, video, NOMINAL, 100.0, 100.0, 15, **kw)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def events_of(result):
|
| 167 |
+
return result["events"]
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
# ── 1 纯函数 ────────────────────────────────────────────────
|
| 171 |
+
def check_pure_functions():
|
| 172 |
+
print("\n[1] 纯函数契约")
|
| 173 |
+
check(audit.clock_class([0, 0, 0]) == "none", "全 0 ⇒ none(无时间戳)")
|
| 174 |
+
check(audit.clock_class([100, 200, 300]) == "hw64", "小正数 ⇒ hw64")
|
| 175 |
+
check(audit.clock_class([10 ** 14, 10 ** 14 + 33 * MS]) == "hw64",
|
| 176 |
+
"宿主单调钟量级 ⇒ hw64")
|
| 177 |
+
check(audit.clock_class([1_004_913_502, -1_774_230_385]) == "trunc32",
|
| 178 |
+
"出现负值 ⇒ trunc32(有符号 32 位)")
|
| 179 |
+
check(audit.clock_class([2 ** 31 - 10, 2 ** 31 - 5]) == "hw64",
|
| 180 |
+
"值域上界 <2^31 且全正、跨度小 ⇒ hw64(不能一见 <2^31 就喊 trunc32)")
|
| 181 |
+
check(audit._unwrap(-2_779_143_887) == 1_515_823_409,
|
| 182 |
+
"解卷:−2779.1ms 的回绕读作 +1515.8ms")
|
| 183 |
+
check(audit._unwrap(33 * MS) == 33 * MS, "解卷:正常间隔原样返回")
|
| 184 |
+
check(audit.episode_stem("/x/episode-099.parquet") == "099"
|
| 185 |
+
and audit.episode_stem("episode-051.mp4") == "051",
|
| 186 |
+
"parquet 与 mp4 归一到同一个段号(否则一段被数成两条)")
|
| 187 |
+
merged = audit._classify([(10, 30 * MS, 220 * MS), (12, 210 * MS, 33 * MS)],
|
| 188 |
+
100 * MS, 100 * MS, 15)
|
| 189 |
+
check(len(merged) == 1 and merged[0]["kind"] == "both",
|
| 190 |
+
"15 行内两侧都停合并成一件事(同一件事不许数两遍)")
|
| 191 |
+
check(merged[0]["d_hw"] == 210 * MS and merged[0]["d_wall"] == 220 * MS,
|
| 192 |
+
"合并取 max 而不是求和(求和会把 250ms 的洞报成 500ms)")
|
| 193 |
+
check(audit._classify([(10, 30 * MS, 220 * MS)], 100 * MS, 100 * MS,
|
| 194 |
+
15)[0]["kind"] == "wall",
|
| 195 |
+
"只有墙钟跳 ⇒ wall(写侧打嗝)")
|
| 196 |
+
check(audit._classify([(10, 220 * MS, 33 * MS)], 100 * MS, 100 * MS,
|
| 197 |
+
15)[0]["kind"] == "hw",
|
| 198 |
+
"只有戳跳(读数取帧处的大间隔)⇒ hw(读侧停顿)")
|
| 199 |
+
check(audit._classify([(10, 220 * MS, 400 * MS)], 100 * MS, 100 * MS,
|
| 200 |
+
15)[0]["kind"] == "mismatch",
|
| 201 |
+
"双钟都跳但差 180ms > 容差 ⇒ mismatch(两侧不齐,不当成互证)")
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# ── 2/3/4 画面复核与归账 ────────────────────────────────────
|
| 205 |
+
def check_healthy(box):
|
| 206 |
+
print("\n[2] 健康段:零事件、零账")
|
| 207 |
+
parquet, video, frames = box.add("001")
|
| 208 |
+
check(frames == 60, f"造出的 mp4 帧数与行数一致({frames})")
|
| 209 |
+
result = audit_one(parquet, video)
|
| 210 |
+
check(result["clock"] == "hw64", "时钟判定 hw64")
|
| 211 |
+
check(events_of(result) == [], "零事件")
|
| 212 |
+
check(result["gap_ms"] == 0 and result["pending_ms"] == 0
|
| 213 |
+
and result["stamp_ms"] == 0 and result["wall_ms"] == 0,
|
| 214 |
+
"四桶全 0")
|
| 215 |
+
check(result["video_ok"] is True, "mp4 帧数校验通过(画面复核真的跑了)")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def check_real_loss(box):
|
| 219 |
+
print("\n[3a] 真丢帧:双钟跳 + 画面跳 ⇒ 计入「丢了」")
|
| 220 |
+
parquet, video, _ = box.add("002", count=80, hw_jump_at=10,
|
| 221 |
+
hw_jump_ns=1000 * MS, wall_jump_at=10,
|
| 222 |
+
wall_jump_ns=1000 * MS,
|
| 223 |
+
video_jump_at=10, video_jump_px=120)
|
| 224 |
+
result = audit_one(parquet, video)
|
| 225 |
+
event = events_of(result)[0]
|
| 226 |
+
check(len(events_of(result)) == 1, "恰好 1 起事件")
|
| 227 |
+
check(event["evidence"] == "jump",
|
| 228 |
+
f"画面复核判跳变(boundary={event['boundary']} vs "
|
| 229 |
+
f"near={event['near']})")
|
| 230 |
+
check(event["verdict"] == "丢了", "结论「丢了」")
|
| 231 |
+
check(abs(result["gap_ms"] - 1000.0) < 2,
|
| 232 |
+
f"空洞 {result['gap_ms']}ms ≈ 1000ms(间隔 1033ms − 标称 33ms)")
|
| 233 |
+
check(result["stamp_ms"] == 0 and result["pending_ms"] == 0,
|
| 234 |
+
"不进「戳跳」也不进「待复核」桶(四桶互斥)")
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def check_stamp_only(box):
|
| 238 |
+
print("\n[3b] 钟跳但画面连续 ⇒ **不算丢**(本库 72 段 20.1s 的形态)")
|
| 239 |
+
parquet, video, _ = box.add("003", count=80, hw_jump_at=10,
|
| 240 |
+
hw_jump_ns=1000 * MS, wall_jump_at=10,
|
| 241 |
+
wall_jump_ns=1000 * MS)
|
| 242 |
+
result = audit_one(parquet, video)
|
| 243 |
+
event = events_of(result)[0]
|
| 244 |
+
check(event["evidence"] == "continuous",
|
| 245 |
+
f"画面复核判连续(boundary={event['boundary']} ≈ "
|
| 246 |
+
f"near={event['near']})")
|
| 247 |
+
check(event["verdict"] == "没丢(画面连续)", "结论「没丢(画面连续)」")
|
| 248 |
+
check(result["gap_ms"] == 0, "**不计入损失**(这正是本次审计的关键结论)")
|
| 249 |
+
check(result["stamp_ms"] > 900,
|
| 250 |
+
f"进「钟跳没丢」桶({result['stamp_ms']}ms)")
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def check_static_scene(box):
|
| 254 |
+
print("\n[3c] 静止场景里的钟跳 ⇒ 判不了(不许判「没丢」)")
|
| 255 |
+
parquet, video, _ = box.add("004", count=80, hw_jump_at=10,
|
| 256 |
+
hw_jump_ns=1000 * MS, wall_jump_at=10,
|
| 257 |
+
wall_jump_ns=1000 * MS, video_static=True)
|
| 258 |
+
result = audit_one(parquet, video)
|
| 259 |
+
event = events_of(result)[0]
|
| 260 |
+
check(event["evidence"] == "unknown",
|
| 261 |
+
"画面整窗静止 ⇒ 不定(少了静止画面也看不出来,不能反着判)")
|
| 262 |
+
check(result["gap_ms"] == 0 and result["pending_ms"] > 900,
|
| 263 |
+
f"只进「待复核」桶({result['pending_ms']}ms),不计入损失也不说没事")
|
| 264 |
+
check(event["verdict"] == "两侧同停",
|
| 265 |
+
"结论按双钟口径标出「哪一侧停了」(不是「没丢」)")
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def check_writer_hiccup(box):
|
| 269 |
+
print("\n[4] 写侧打嗝:只有墙钟跳 ⇒ 帧没少、只是写晚")
|
| 270 |
+
parquet, video, _ = box.add("005", count=80, wall_jump_at=10,
|
| 271 |
+
wall_jump_ns=300 * MS)
|
| 272 |
+
result = audit_one(parquet, video)
|
| 273 |
+
check(result["wall_ms"] > 250 and result["gap_ms"] == 0,
|
| 274 |
+
f"进「打嗝」桶({result['wall_ms']}ms)且不计入损失")
|
| 275 |
+
check(events_of(result)[0]["kind"] == "wall", "事件定性 wall")
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
# ── 5/6 时钟与解卷 ──────────────────────────────────────────
|
| 279 |
+
def check_trunc32(box):
|
| 280 |
+
print("\n[5] 早年段(有符号 32 位戳):跨符号边界仍恰好 1 起事件")
|
| 281 |
+
parquet, video, _ = box.add("006", count=200, hw_jump_at=100,
|
| 282 |
+
hw_jump_ns=800 * MS, wall_jump_at=100,
|
| 283 |
+
wall_jump_ns=800 * MS, wrap32=True,
|
| 284 |
+
video_jump_at=100, video_jump_px=120)
|
| 285 |
+
result = audit_one(parquet, video)
|
| 286 |
+
check(result["clock"] == "trunc32", "时钟判定 trunc32")
|
| 287 |
+
check(len(events_of(result)) == 1,
|
| 288 |
+
f"200 行里 6 次过零,只报 1 起事件(回绕不该造出假空洞):"
|
| 289 |
+
f"{len(events_of(result))} 起")
|
| 290 |
+
check(abs(result["gap_ms"] - 800.0) < 2,
|
| 291 |
+
f"空洞 {result['gap_ms']}ms ≈ 800ms(解卷正确)")
|
| 292 |
+
check(result["resyncs"] == 0, "解卷后没有「时间倒退」")
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def check_hw64_no_unwrap(box):
|
| 296 |
+
print("\n[6] 64 位戳不解卷:>2.1s 的真空洞必须原样保留")
|
| 297 |
+
parquet, video, _ = box.add("007", count=80, hw_jump_at=10,
|
| 298 |
+
hw_jump_ns=4680 * MS, wall_jump_at=10,
|
| 299 |
+
wall_jump_ns=4680 * MS,
|
| 300 |
+
video_jump_at=10, video_jump_px=120)
|
| 301 |
+
result = audit_one(parquet, video)
|
| 302 |
+
check(result["clock"] == "hw64", "时钟判定 hw64(不按 trunc32 处理)")
|
| 303 |
+
check(abs(result["gap_ms"] - 4680.0) < 2,
|
| 304 |
+
f"空洞 {result['gap_ms']}ms ≈ 4680ms —— 若误按回绕解卷会变成 418ms")
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
# ── 8 拒答 ─────────────────────────────────────────────────
|
| 308 |
+
def check_refusals(box):
|
| 309 |
+
print("\n[8] 宁可拒答也不猜")
|
| 310 |
+
# 多槽 episode:帧序号按槽各自从 0 编号
|
| 311 |
+
parquet, video = box.paths("008")
|
| 312 |
+
_write_parquet(parquet, [0, 1, 0, 1, 0, 1],
|
| 313 |
+
[3_600_000_000_000 + i * NOMINAL for i in range(6)],
|
| 314 |
+
[1_789_000_000.0 + i / 30 for i in range(6)])
|
| 315 |
+
_write_video(video, 6)
|
| 316 |
+
result = audit_one(parquet, video)
|
| 317 |
+
check(result["status"] == "skip" and "多槽" in result["note"],
|
| 318 |
+
f"多槽 episode 跳过({result['note']})")
|
| 319 |
+
|
| 320 |
+
# hardware_ns 全 0(lite 那种无时间戳槽位)
|
| 321 |
+
parquet, video, _ = box.add("009", count=40)
|
| 322 |
+
_write_parquet(parquet, list(range(40)), [0] * 40, [0.0] * 40)
|
| 323 |
+
result = audit_one(parquet, video)
|
| 324 |
+
check(result["status"] == "skip" and "时间戳" in result["note"],
|
| 325 |
+
f"无时间戳跳过({result['note']})")
|
| 326 |
+
|
| 327 |
+
# mp4 帧数 ≠ 行数:画面复核的序号对不上,结论不可用
|
| 328 |
+
parquet, video, _ = box.add("010", count=80, hw_jump_at=10,
|
| 329 |
+
hw_jump_ns=1000 * MS, wall_jump_at=10,
|
| 330 |
+
wall_jump_ns=1000 * MS, video_count=70)
|
| 331 |
+
result = audit_one(parquet, video)
|
| 332 |
+
check(result["status"] == "warn" and result["video_frames"] == 70,
|
| 333 |
+
f"帧数不符 ⇒ warn({result['note']})")
|
| 334 |
+
check(events_of(result)[0]["evidence"] == "unknown"
|
| 335 |
+
and result["gap_ms"] == 0 and result["pending_ms"] > 900,
|
| 336 |
+
"画面对不上号 ⇒ 不判跳变也不判连续,落「待复核」")
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
# ── 9 CLI ──────────────────────────────────────────────────
|
| 340 |
+
def _run(argv):
|
| 341 |
+
buffer = io.StringIO()
|
| 342 |
+
with contextlib.redirect_stdout(buffer):
|
| 343 |
+
code = audit.main(argv)
|
| 344 |
+
return code, buffer.getvalue()
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def check_cli(box):
|
| 348 |
+
print("\n[9] CLI:退出码 / JSON / 未复核口径 / 双钟阈值 / 留档关联")
|
| 349 |
+
task_dir = os.path.join(box.root, "cli")
|
| 350 |
+
shutil.copytree(os.path.join(box.root, "data"),
|
| 351 |
+
os.path.join(task_dir, "data"), dirs_exist_ok=True)
|
| 352 |
+
shutil.copytree(os.path.join(box.root, "videos"),
|
| 353 |
+
os.path.join(task_dir, "videos"), dirs_exist_ok=True)
|
| 354 |
+
# 只留 003(戳跳、画面连续)与 005(写侧打嗝):两者都不该判「丢了」
|
| 355 |
+
for name in os.listdir(os.path.join(task_dir, "data", "chunk-000")):
|
| 356 |
+
if not name.startswith(("episode-003", "episode-005")):
|
| 357 |
+
os.unlink(os.path.join(task_dir, "data", "chunk-000", name))
|
| 358 |
+
for name in os.listdir(os.path.join(task_dir, "videos", "chunk-000",
|
| 359 |
+
"gripper_rgb")):
|
| 360 |
+
if not name.startswith(("episode-003", "episode-005")):
|
| 361 |
+
os.unlink(os.path.join(task_dir, "videos", "chunk-000",
|
| 362 |
+
"gripper_rgb", name))
|
| 363 |
+
|
| 364 |
+
code, out = _run([task_dir])
|
| 365 |
+
check(code == 0, f"画面证实零丢帧 ⇒ 退出码 0(rc={code})")
|
| 366 |
+
check("画面证实丢了 0 段" in out, "合计行说 0 段(不许把钟跳算成丢)")
|
| 367 |
+
check("钟跳但画面连续" in out and "写侧打嗝" in out, "两个非损失桶都列出来")
|
| 368 |
+
|
| 369 |
+
# 加一个真丢帧的段 ⇒ 必须变红
|
| 370 |
+
parquet, video, _ = box.add("011", count=80, hw_jump_at=10,
|
| 371 |
+
hw_jump_ns=1000 * MS, wall_jump_at=10,
|
| 372 |
+
wall_jump_ns=1000 * MS, video_jump_at=10)
|
| 373 |
+
for kind, src in (("data", parquet), ("videos", video)):
|
| 374 |
+
dst = os.path.join(task_dir, kind, "chunk-000",
|
| 375 |
+
"gripper_rgb" if kind == "videos" else "",
|
| 376 |
+
os.path.basename(src))
|
| 377 |
+
shutil.copyfile(src, dst)
|
| 378 |
+
code, out = _run([task_dir])
|
| 379 |
+
check(code == 1, f"有真丢帧 ⇒ 退出码 1(rc={code})")
|
| 380 |
+
check("画面证实丢了 1 段" in out, "合计行数到 1 段")
|
| 381 |
+
check("开录后 0." in out and "启动窗口" in out,
|
| 382 |
+
"报出丢帧落在开录后哪一段(启动窗口是排查方向)")
|
| 383 |
+
|
| 384 |
+
code, out = _run([task_dir, "--json"])
|
| 385 |
+
payload = json.loads(out)
|
| 386 |
+
totals = payload["totals"]
|
| 387 |
+
check(code == 1 and totals["lost_episodes"] == 1, "JSON 里 lost_episodes=1")
|
| 388 |
+
check(totals["lost_max_ms"] > 900 and totals["lost_max_episode"] == "011",
|
| 389 |
+
f"最大空洞归属正确({totals['lost_max_ms']}ms @ {totals['lost_max_episode']})")
|
| 390 |
+
check(totals["stamp_only_ms"] > 900 and totals["writer_hiccup_ms"] > 250,
|
| 391 |
+
"JSON 也分桶报(钟跳没丢 / 打嗝)")
|
| 392 |
+
check(payload["episodes"][0]["events"][0]["evidence"] in
|
| 393 |
+
("jump", "continuous", "unknown"), "JSON 带逐事件画面证据")
|
| 394 |
+
|
| 395 |
+
# --no-video-check:未复核 ⇒ 一律进「待复核」,且仍变红(未知不等于没事)
|
| 396 |
+
code, out = _run([task_dir, "--no-video-check"])
|
| 397 |
+
check(code == 1, f"未复核也返回 1(rc={code})——不把未知当没事")
|
| 398 |
+
check("画面证实丢了 0 段" in out and "全部事件都在这一桶" in out,
|
| 399 |
+
"明确标注未复核,不进「证实丢了」")
|
| 400 |
+
|
| 401 |
+
# 双钟阈值设 0:差 14ms 的「互证」必须散伙(本库 ep-099 是 4680.8 vs 4666.4)
|
| 402 |
+
parquet, video, _ = box.add("012", count=80, hw_jump_at=10,
|
| 403 |
+
hw_jump_ns=1000 * MS, wall_jump_at=10,
|
| 404 |
+
wall_jump_ns=986 * MS, video_static=True)
|
| 405 |
+
result = audit.audit_episode(parquet, video, NOMINAL, 100.0, 0.0001, 15)
|
| 406 |
+
check(events_of(result)[0]["kind"] == "mismatch",
|
| 407 |
+
"容差压到 0 时,差 14ms 的两条不算互证(阈值真的在起作用)")
|
| 408 |
+
result = audit_one(parquet, video)
|
| 409 |
+
check(events_of(result)[0]["kind"] == "both",
|
| 410 |
+
"默认 100ms 容差下同样两条算互证(对照组)")
|
| 411 |
+
|
| 412 |
+
# --camera-logs:留档发生在会话结束时,只往后关联;窗外的不挂
|
| 413 |
+
logs = os.path.join(box.root, "camera_service")
|
| 414 |
+
os.makedirs(logs, exist_ok=True)
|
| 415 |
+
wall_abs = events_of(audit_one(parquet, video))[0]["wall_abs"]
|
| 416 |
+
names = {}
|
| 417 |
+
for offset, key in ((120, "in"), (99_999, "out")):
|
| 418 |
+
when = datetime.datetime.fromtimestamp(wall_abs + offset)
|
| 419 |
+
name = (f"{when.strftime('%Y%m%d_%H%M%S')}"
|
| 420 |
+
f"_bus1-port2_camera-service.log")
|
| 421 |
+
with open(os.path.join(logs, name), "w", encoding="utf-8") as handle:
|
| 422 |
+
handle.write(key)
|
| 423 |
+
names[key] = name
|
| 424 |
+
code, out = _run([task_dir, "--camera-logs", logs])
|
| 425 |
+
check(code == 1 and names["in"] in out,
|
| 426 |
+
f"留档按时刻关联到事件行({names['in']})")
|
| 427 |
+
check(names["out"] not in out, "10 万秒后的留档不挂(时间窗真的在起作用)")
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def check_missing_dir(box):
|
| 431 |
+
print("\n[10] 参数与失败路径")
|
| 432 |
+
code, out = _run([os.path.join(box.root, "nope")])
|
| 433 |
+
check(code == 2 and "任务目录不存在" in out, "目录不存在 ⇒ 2 且说清原因")
|
| 434 |
+
empty = tempfile.mkdtemp(prefix="ksq-audit-empty-", dir=box.root)
|
| 435 |
+
code, out = _run([empty])
|
| 436 |
+
check(code == 2 and "不是任务目录" in out, "缺 data/ ⇒ 2")
|
| 437 |
+
code, out = _run([box.root, "--camera-logs",
|
| 438 |
+
os.path.join(box.root, "no-logs")])
|
| 439 |
+
check(code == 2 and "留档目录不存在" in out, "留档目录不存在 ⇒ 2")
|
| 440 |
+
shutil.rmtree(empty, ignore_errors=True)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def main():
|
| 444 |
+
box = _Sandbox()
|
| 445 |
+
try:
|
| 446 |
+
check_pure_functions()
|
| 447 |
+
check_healthy(box)
|
| 448 |
+
check_real_loss(box)
|
| 449 |
+
check_stamp_only(box)
|
| 450 |
+
check_static_scene(box)
|
| 451 |
+
check_writer_hiccup(box)
|
| 452 |
+
check_trunc32(box)
|
| 453 |
+
check_hw64_no_unwrap(box)
|
| 454 |
+
check_refusals(box)
|
| 455 |
+
check_cli(box)
|
| 456 |
+
check_missing_dir(box)
|
| 457 |
+
finally:
|
| 458 |
+
box.close()
|
| 459 |
+
|
| 460 |
+
print()
|
| 461 |
+
if FAILS:
|
| 462 |
+
print(f"FAIL: {len(FAILS)} 项未通过")
|
| 463 |
+
for msg in FAILS:
|
| 464 |
+
print(f" - {msg}")
|
| 465 |
+
return 1
|
| 466 |
+
print("PASS: 帧空洞审计回归通过")
|
| 467 |
+
return 0
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
if __name__ == "__main__":
|
| 471 |
+
sys.exit(main())
|
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""tools/audit_slam_divergence.py 的单测(v1.3.11 L0-3)。
|
| 2 |
+
|
| 3 |
+
这个脚本是「发散 ← 哪次停止」的**基线工具**,它自己的两处推断最容易悄悄错:
|
| 4 |
+
① main.log 的**多天时间线重建**(日志无日期分隔,错了就把账记到别的天上);
|
| 5 |
+
② 撕裂行里 rebase 步长的**松散解析**(错了要么漏数、要么把良性会话判成灾害)。
|
| 6 |
+
所以用合成 fixture 把这两条钉死,另加密度判据、发散合并、速率线性度的行为断言。
|
| 7 |
+
|
| 8 |
+
真实数据的端到端基线在脚本 docstring 里(2026-09-18:55 完成 / 54 收尾断链 /
|
| 9 |
+
11 中止且 0 断链 / 2 次发散,两次都在「完成」之后)。
|
| 10 |
+
|
| 11 |
+
用法:
|
| 12 |
+
venv/bin/python tools/tests/test_audit_slam_divergence.py
|
| 13 |
+
"""
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
import tempfile
|
| 18 |
+
|
| 19 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 20 |
+
sys.path.insert(0, ROOT)
|
| 21 |
+
sys.path.insert(0, os.path.join(ROOT, "tools"))
|
| 22 |
+
|
| 23 |
+
import audit_slam_divergence as aud # noqa: E402
|
| 24 |
+
|
| 25 |
+
FAILS = []
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def check(cond, msg):
|
| 29 |
+
if cond:
|
| 30 |
+
print(f" PASS: {msg}")
|
| 31 |
+
else:
|
| 32 |
+
print(f" FAIL: {msg}")
|
| 33 |
+
FAILS.append(msg)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def write_native(lines, name="20260918_120000_3500000000000001_slam_stdout.log"):
|
| 37 |
+
"""把 (epoch, text) 写成原生会话日志(JSON 行)。"""
|
| 38 |
+
fd, path = tempfile.mkstemp(suffix="_slam_stdout.log")
|
| 39 |
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
| 40 |
+
for t, text in lines:
|
| 41 |
+
fh.write(json.dumps({"time": t, "arrival_monotonic": t,
|
| 42 |
+
"line": text}) + "\n")
|
| 43 |
+
os.rename(path, os.path.join(os.path.dirname(path), name))
|
| 44 |
+
return os.path.join(os.path.dirname(path), name)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def rebase(t, step, dt=0.02, reason="translation_jump"):
|
| 48 |
+
return ('[POSE_REBASE] reason={} dt_s={:.6f} translation_step_m={:.6f} '
|
| 49 |
+
'translation_limit_m=0.35'.format(reason, dt, step))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def parse_events(lines):
|
| 53 |
+
"""写一份临时会话日志 → 走真实解析路径取回事件表(测完删)。"""
|
| 54 |
+
path = write_native(lines)
|
| 55 |
+
try:
|
| 56 |
+
return aud.load_session(path)["events"]
|
| 57 |
+
finally:
|
| 58 |
+
os.unlink(path)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ── ① 撕裂行:步长仍要解析出来 ───────────────────────────────
|
| 62 |
+
def test_torn_lines():
|
| 63 |
+
t0 = 1_700_000_000.0
|
| 64 |
+
path = write_native([
|
| 65 |
+
(t0, "[FAYS-CALIB] WARN SetStereoFPS(50) failed"),
|
| 66 |
+
# 两个消息逐字交错(真实样本):步长被撕成 ``=9verified=yes``
|
| 67 |
+
(t0 + 1, "[FAYS-AFFINITY] background stage: tid=[POSE_REBASE] reason="
|
| 68 |
+
"translation_jump3720726 dt_s=0.020000 cpus= "
|
| 69 |
+
"translation_step_m=9 verified=yes"),
|
| 70 |
+
# 标签被上一个消息吃掉,行首直接是字段
|
| 71 |
+
(t0 + 2, "translation_jump dt_s=0.060000 translation_step_m=58.003757 "
|
| 72 |
+
"translation_limit_m=0.230000"),
|
| 73 |
+
# 只有标签、步长被吃掉
|
| 74 |
+
(t0 + 3, "[POSE_REBASE] reason=tracking_recovery dt_s=1.22"),
|
| 75 |
+
])
|
| 76 |
+
s = aud.load_session(path)
|
| 77 |
+
steps = [e["step"] for e in s["events"]]
|
| 78 |
+
check(len(s["events"]) == 3, f"三条 rebase 全记账(实际 {len(s['events'])})")
|
| 79 |
+
check(steps[0] == 9.0, f"交错行里的步长解析出来={steps[0]}")
|
| 80 |
+
check(steps[1] == 58.003757, f"无标签行同样解析={steps[1]}")
|
| 81 |
+
check(steps[2] is None, "步长被吃掉的那条记 None 不计数值")
|
| 82 |
+
check(s["unparsed"] == 1, f"只算 1 条无法解析(实际 {s['unparsed']})")
|
| 83 |
+
check(abs(s["events"][1]["dt"] - 0.06) < 1e-9,
|
| 84 |
+
f"dt_s 一并解析({s['events'][1]['dt']})")
|
| 85 |
+
os.unlink(path)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ── ② 密度判据:良性不报、灾害报 ─────────────────────────────
|
| 89 |
+
def test_density():
|
| 90 |
+
t0 = 1_700_000_000.0
|
| 91 |
+
# 良性:零散重定位,1 秒窗内最多 3 条(真实基线)
|
| 92 |
+
benign = parse_events([(t0 + i * 2.0, rebase(t0 + i * 2.0, 2.0, dt=0.5))
|
| 93 |
+
for i in range(20)])
|
| 94 |
+
check(aud.find_floods(benign, 1.0, 1.0, 15, 2.0) == [],
|
| 95 |
+
"良性零散 rebase(2s 一条)不判为发散")
|
| 96 |
+
# 灾害:每秒 30 条、步长都 ≥1m
|
| 97 |
+
hot = parse_events([(t0 + i * 0.033, rebase(t0 + i * 0.033, 5.0))
|
| 98 |
+
for i in range(90)])
|
| 99 |
+
floods = aud.find_floods(hot, 1.0, 1.0, 15, 2.0)
|
| 100 |
+
check(len(floods) == 1, f"灾害串判出 1 段(实际 {len(floods)})")
|
| 101 |
+
check(floods and floods[0]["peak_window"] >= 15,
|
| 102 |
+
f"1 秒窗峰值 ≥15(实际 {floods[0]['peak_window'] if floods else 0})")
|
| 103 |
+
# 步长 <1m 的高频 rebase 不算(重定位小幅抖动的形状)
|
| 104 |
+
small = parse_events([(t0 + i * 0.02, rebase(t0 + i * 0.02, 0.05))
|
| 105 |
+
for i in range(200)])
|
| 106 |
+
check(aud.find_floods(small, 1.0, 1.0, 15, 2.0) == [],
|
| 107 |
+
"每秒 50 条但步长 0.05m 的不判为发散")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# ── ③ 同一次发散被密度低谷切成多段 → 合并 ──��────────────────
|
| 111 |
+
def test_episode_merge():
|
| 112 |
+
t0 = 1_700_000_000.0
|
| 113 |
+
ev = []
|
| 114 |
+
for i in range(60): # 第 1 段
|
| 115 |
+
ev.append({"t": t0 + i * 0.033, "step": 5.0, "dt": 0.02})
|
| 116 |
+
for i in range(8): # 中间掉到阈值以下(5s)
|
| 117 |
+
ev.append({"t": t0 + 2.1 + i * 0.6, "step": 5.0, "dt": 0.02})
|
| 118 |
+
for i in range(60): # 第 2 段
|
| 119 |
+
ev.append({"t": t0 + 8.3 + i * 0.033, "step": 9.0, "dt": 0.02})
|
| 120 |
+
floods = aud.find_floods(ev, 1.0, 1.0, 15, 2.0)
|
| 121 |
+
check(len(floods) == 2, f"原始切成 2 段(实际 {len(floods)})")
|
| 122 |
+
for f in floods:
|
| 123 |
+
f["session"] = "s1"
|
| 124 |
+
ev = sorted(ev, key=lambda e: e["t"])
|
| 125 |
+
eps = aud.merge_episodes(floods, 30.0, [{"name": "s1", "events": ev}])
|
| 126 |
+
check(len(eps) == 1, f"相隔 30s 内并成 1 次发散(实际 {len(eps)})")
|
| 127 |
+
check(eps and eps[0]["segments"] == 2, "合并后段数=2")
|
| 128 |
+
check(eps and eps[0]["lines"] == len(ev),
|
| 129 |
+
f"行数按 [t0,t1] 全区间重算={len(ev)}(实际 {eps[0]['lines'] if eps else 0})")
|
| 130 |
+
check(eps and eps[0]["duration_s"] > 8.0, "跨越两段 → 时长按首尾算")
|
| 131 |
+
# 会话不同绝不合并(换进程/重开夹爪必然是两次)
|
| 132 |
+
floods[0]["session"], floods[1]["session"] = "a", "b"
|
| 133 |
+
check(len(aud.merge_episodes(floods, 30.0)) == 2, "不同会话不合并")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# ── ④ 速率线性度:真发散 R²≈1,零散不起涨 ────────────────────
|
| 137 |
+
def test_growth():
|
| 138 |
+
t0 = 1_700_000_000.0
|
| 139 |
+
ramp = []
|
| 140 |
+
for i in range(400): # 速率 10 → 110 m/s 匀速涨
|
| 141 |
+
t = t0 + i * 0.033
|
| 142 |
+
ramp.append({"t": t, "step": (10 + 0.25 * i) * 0.02, "dt": 0.02})
|
| 143 |
+
g = aud._growth_stats(ramp)
|
| 144 |
+
check(g is not None and g["r2"] is not None and g["r2"] > 0.99,
|
| 145 |
+
f"线性上涨的速率 R²≈1(实际 {None if not g else round(g['r2'], 4)})")
|
| 146 |
+
check(g and abs(g["speed_slope"] - 7.5) < 1.0,
|
| 147 |
+
f"斜率≈+7.5 m/s²(实际 {None if not g else round(g['speed_slope'], 2)})")
|
| 148 |
+
flat = [{"t": t0 + i * 0.033, "step": 0.5, "dt": 0.02} for i in range(400)]
|
| 149 |
+
gf = aud._growth_stats(flat)
|
| 150 |
+
check(gf is None or gf["r2"] is None or gf["r2"] < 0.5,
|
| 151 |
+
"速率不涨的串 R² 很低(不成线)")
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
# ── ⑤ main.log 时间线:跨天递推 + 日期锚点 + 锚点前不配对 ────
|
| 155 |
+
def test_timeline():
|
| 156 |
+
lines = [
|
| 157 |
+
"[23:59:00] DAQ Video Pipeline started.", # 锚点前:日期未知
|
| 158 |
+
"[23:59:30] [SLAM] ⚠ 2026-09-17 23:59:30.100 [ ERROR] StereoOnlineCapture()",
|
| 159 |
+
"[23:59:50] [gripper_stereo_left] ▶ Recording started — codec: HEVC",
|
| 160 |
+
"[00:00:20] [gripper_stereo_left] ■ Recording completed: /tmp/x",
|
| 161 |
+
"[00:00:21] [Gripper-Raw] 原始流连接中断:Fays raw stream closed unexpectedly",
|
| 162 |
+
"[00:01:00] [SLAM] ⚠ 2026-09-18 00:01:00.200 [ ERROR] ImuOnlineCapture()",
|
| 163 |
+
"[00:01:10] [gripper_stereo_left] ■ Recording completed: /tmp/y",
|
| 164 |
+
]
|
| 165 |
+
fd, path = tempfile.mkstemp(suffix=".log")
|
| 166 |
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
| 167 |
+
fh.write("\n".join(lines) + "\n")
|
| 168 |
+
rows, known = aud.load_main_log(path)
|
| 169 |
+
check(known == len(rows) - 1,
|
| 170 |
+
f"只有锚点前那一行日期未知(解出 {known}/{len(rows)})")
|
| 171 |
+
check(rows[0][3] is None, "锚点之前的行 epoch=None(不参与配对)")
|
| 172 |
+
import datetime
|
| 173 |
+
days = [datetime.date.fromtimestamp(r[3]).isoformat() if r[3] else None
|
| 174 |
+
for r in rows]
|
| 175 |
+
check(days[1] == "2026-09-17", f"锚点行归 09-17({days[1]})")
|
| 176 |
+
check(days[2] == "2026-09-17" and days[3] == "2026-09-18",
|
| 177 |
+
f"23:59→00:00 的倒退 >12h ⇒ 判跨天({days[2]} → {days[3]})")
|
| 178 |
+
check(days[5] == "2026-09-18", "第二个锚点把日期重新对齐")
|
| 179 |
+
stops = aud.extract_stops(rows)
|
| 180 |
+
kinds = [s["kind"] for s in stops]
|
| 181 |
+
check(kinds == ["started", "completed", "disconnect", "completed"],
|
| 182 |
+
f"事件摘取正确({kinds})")
|
| 183 |
+
check(len(stops) == 4, "锚点前的 started 不参与(无 epoch)")
|
| 184 |
+
os.unlink(path)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# ── ⑥ 配对:只认**之前**的停止,且窗口一视同仁 ───────────────
|
| 188 |
+
def test_attribute():
|
| 189 |
+
t0 = 1_700_000_000.0
|
| 190 |
+
stops = [
|
| 191 |
+
{"kind": "completed", "epoch": t0 - 4.0, "idx": 1, "text": "c"},
|
| 192 |
+
{"kind": "disconnect", "epoch": t0 - 6.0, "idx": 2, "text": "d"},
|
| 193 |
+
{"kind": "completed", "epoch": t0 + 3.0, "idx": 3, "text": "c2"},
|
| 194 |
+
]
|
| 195 |
+
ep = {"t0": t0, "t1": t0 + 10}
|
| 196 |
+
label, first, near = aud.attribute(ep, stops, 30.0)
|
| 197 |
+
check("完成" in label and "-4.0s" in label,
|
| 198 |
+
f"归属=之前 4 秒那次完成({label})")
|
| 199 |
+
check(first is not None and first["epoch"] == t0 - 4.0,
|
| 200 |
+
"返回的起因是那次完成,不是更近的断链")
|
| 201 |
+
label2, first2, _ = aud.attribute({"t0": t0, "t1": t0 + 10}, stops, 2.0)
|
| 202 |
+
check(first2 is None and label2 == "无��近停止",
|
| 203 |
+
f"回溯窗口收窄到 2s 就找不到起因({label2})")
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# ── ⑦ 日中基线:完成/中止两路的断链率 ────────────────────────
|
| 207 |
+
def test_day_stats():
|
| 208 |
+
import datetime
|
| 209 |
+
day = "2026-09-18"
|
| 210 |
+
base = datetime.datetime(2026, 9, 18, 12, 0).timestamp()
|
| 211 |
+
stops = []
|
| 212 |
+
for i in range(4): # 4 次完成,3 次带收尾断链
|
| 213 |
+
t = base + i * 60
|
| 214 |
+
stops.append({"kind": "completed", "epoch": t, "idx": i, "text": "c"})
|
| 215 |
+
if i < 3:
|
| 216 |
+
stops.append({"kind": "disconnect", "epoch": t - 2.0,
|
| 217 |
+
"idx": 100 + i, "text": "d"})
|
| 218 |
+
for i in range(3): # 3 次中止,0 次带断链
|
| 219 |
+
stops.append({"kind": "aborted", "epoch": base + 300 + i * 60,
|
| 220 |
+
"idx": 200 + i, "text": "a"})
|
| 221 |
+
d = aud.day_stats(day, stops, [], [], 1.0, 15)
|
| 222 |
+
check(d["completed"] == 4 and d["aborted"] == 3, "完成/中止计数")
|
| 223 |
+
check(d["disc_in_completed_window"] == 3 and d["completed_with_disc"] == 3,
|
| 224 |
+
f"收尾窗口命中 3/4(实际 {d['disc_in_completed_window']},"
|
| 225 |
+
f"带断链 {d['completed_with_disc']})")
|
| 226 |
+
check(d["disc_in_abort_window"] == 0 and d["aborted_with_disc"] == 0,
|
| 227 |
+
"中止路径一条都不命中(判「断链主因是 parquet」的依据)")
|
| 228 |
+
check(d["disc_in_completed_offsets"] == [-2.0] * 3,
|
| 229 |
+
f"偏移记录为 −2.0s({d['disc_in_completed_offsets']})")
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def main():
|
| 233 |
+
for fn in (test_torn_lines, test_density, test_episode_merge, test_growth,
|
| 234 |
+
test_timeline, test_attribute, test_day_stats):
|
| 235 |
+
print(f"── {fn.__name__} " + "─" * max(0, 50 - len(fn.__name__)))
|
| 236 |
+
fn()
|
| 237 |
+
print()
|
| 238 |
+
if FAILS:
|
| 239 |
+
print(f"FAIL: {len(FAILS)} 项未通过")
|
| 240 |
+
for f in FAILS:
|
| 241 |
+
print(" -", f)
|
| 242 |
+
return 1
|
| 243 |
+
print("PASS: audit_slam_divergence 单测全部通过")
|
| 244 |
+
return 0
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
if __name__ == "__main__":
|
| 248 |
+
sys.exit(main())
|
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""camera-service 原生日志留档 + 告警摘录自检。
|
| 4 |
+
|
| 5 |
+
venv/bin/python tools/tests/test_camera_log_archive.py
|
| 6 |
+
|
| 7 |
+
背景:2026-09-18 排查 episode-099 那 4.68 秒视频空洞时,客户端侧能看到的
|
| 8 |
+
只有「read() 失败」;相机侧的停摆 / 降档 / USB 复位**只**写 camera-service
|
| 9 |
+
自己的日志,而它活在 runtime_dir 里、随 _stop_entry_locked 的 rmtree 一起
|
| 10 |
+
消失——一次干净退出的会话(正是最该留证据的那种)日志等于没写过。
|
| 11 |
+
|
| 12 |
+
覆盖:
|
| 13 |
+
1. _archive_camera_log 逐字节留档、源文件不动、文件名带 tag 与时刻
|
| 14 |
+
2. 没有 camera-service.log 时静默返回 None,不抛异常
|
| 15 |
+
3. 留档目录不可用时只记一行日志,绝不打断清理
|
| 16 |
+
4. _prune_camera_log_archive 只留最近 20 份(按文件名时间序)
|
| 17 |
+
5. 摘录只认告警行;**健康的 5 秒 stats 行与退出汇总行不得命中**
|
| 18 |
+
6. 摘录取末尾(一次会话里最要紧的是结束前发生了什么)并限量
|
| 19 |
+
7. _stop_entry_locked 端到端:先留档再 rmtree、摘录与路径按序进日志、
|
| 20 |
+
健康会话不占 main.log
|
| 21 |
+
8. _service_tag 身份拼接与降级;恶意 tag 不能逃出留档目录
|
| 22 |
+
退出码 0 = 全部通过。
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import os
|
| 28 |
+
import shutil
|
| 29 |
+
import sys
|
| 30 |
+
import tempfile
|
| 31 |
+
from types import SimpleNamespace
|
| 32 |
+
|
| 33 |
+
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
|
| 34 |
+
os.path.abspath(__file__))))
|
| 35 |
+
sys.path.insert(0, REPO_ROOT)
|
| 36 |
+
|
| 37 |
+
from core.gripper.devices import uvc_camera_service as uvc # noqa: E402
|
| 38 |
+
|
| 39 |
+
FAILS = []
|
| 40 |
+
|
| 41 |
+
# 一次**健康**会话的完整日志(取自 camera_service.c 里的实际格式):
|
| 42 |
+
# 每 5 秒一行的 stats、开流协商行、libuvc 的档位权威行、IPC 行、退出汇总行
|
| 43 |
+
HEALTHY_LOG = "\n".join([
|
| 44 |
+
"[unit_1_left] IPC socket=/tmp/x/unit_1_left.sock format=MJPEG "
|
| 45 |
+
"size=640x480 fps=30",
|
| 46 |
+
"[unit_1_left] vidpid=0c45:636f bus=1 port=2.2 interface=1 alt=3 "
|
| 47 |
+
"payload=800 format=MJPEG size=640x480 fps=30 socket=/tmp/x.sock "
|
| 48 |
+
"negotiated_payload=800",
|
| 49 |
+
"[LIBUVC-QUIRK] VID:PID 0c45:636f alt=3 payload=800 endpoint=800 "
|
| 50 |
+
"frame=640x480 interval=333333 xfers=4 xfer_bytes=3200",
|
| 51 |
+
"[unit_1_left] fps_in=30.00 fps_out=29.98 received=1500 output=1490 "
|
| 52 |
+
"dropped=10 (+0) bad_jpeg=0 (+0) bad_replaced=0 write_errors=0 queue=2",
|
| 53 |
+
"[unit_1_left] fps_in=30.00 fps_out=30.00 received=1800 output=1795 "
|
| 54 |
+
"dropped=10 (+0) bad_jpeg=0 (+0) bad_replaced=0 write_errors=0 queue=1",
|
| 55 |
+
"[unit_1_left] received=1800 output=1795 dropped=10 bad_jpeg=0 "
|
| 56 |
+
"bad_replaced=0 write_errors=0 retries=0 stalls=0 usb_resets=0",
|
| 57 |
+
]) + "\n"
|
| 58 |
+
|
| 59 |
+
# 行号即「出事」的顺序,断言按原文引用,免得改文案时测试跟着漂
|
| 60 |
+
EVIDENCE_LINES = [
|
| 61 |
+
"[unit_1_left] stream stalled: no frame for 3.0s (received=900); "
|
| 62 |
+
"restarting UVC stream",
|
| 63 |
+
"[unit_1_left] 2 stalls at alt=7; dropping to alt=6 payload=944",
|
| 64 |
+
"[unit_1_left] remembered altsetting=6 payload=944 for this "
|
| 65 |
+
"camera/controller in /home/u/.ksq/x.mode",
|
| 66 |
+
"[unit_1_left] usb reset: rc=0 (Success)",
|
| 67 |
+
"[unit_1_left] device 1bcf:2d4f bus=1 port=2.3 unavailable: "
|
| 68 |
+
"LIBUSB_ERROR_NO_DEVICE",
|
| 69 |
+
"[LIBUVC-QUIRK] VID:PID 1bcf:2d4f alt=6 payload=944 unavailable "
|
| 70 |
+
"endpoint=512",
|
| 71 |
+
"[unit_1_left] dropped incomplete MJPEG sequence=42 bytes=1234 bad=1",
|
| 72 |
+
"[unit_1_left] uvc_start_streaming failed: LIBUSB_ERROR_BUSY",
|
| 73 |
+
]
|
| 74 |
+
TROUBLE_LOG = HEALTHY_LOG + "\n".join(EVIDENCE_LINES) + "\n"
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def check(cond, msg):
|
| 78 |
+
if cond:
|
| 79 |
+
print(f" PASS: {msg}")
|
| 80 |
+
else:
|
| 81 |
+
print(f" FAIL: {msg}")
|
| 82 |
+
FAILS.append(msg)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class _Sandbox:
|
| 86 |
+
"""把留档目录重定向到临时目录(settings.LOGS_DIR 是调用时读取的)。"""
|
| 87 |
+
|
| 88 |
+
def __init__(self):
|
| 89 |
+
self.root = tempfile.mkdtemp(prefix="ksq-camera-log-test-")
|
| 90 |
+
self._saved = uvc.settings
|
| 91 |
+
uvc.settings = SimpleNamespace(
|
| 92 |
+
LOGS_DIR=os.path.join(self.root, "logs"))
|
| 93 |
+
|
| 94 |
+
def archive_dir(self):
|
| 95 |
+
return uvc._camera_log_archive_dir()
|
| 96 |
+
|
| 97 |
+
def make_runtime_dir(self, payload=HEALTHY_LOG, name=uvc._CAMERA_LOG_NAME):
|
| 98 |
+
runtime_dir = tempfile.mkdtemp(prefix="ksq-runtime-", dir=self.root)
|
| 99 |
+
if payload is not None:
|
| 100 |
+
with open(os.path.join(runtime_dir, name), "w",
|
| 101 |
+
encoding="utf-8") as handle:
|
| 102 |
+
handle.write(payload)
|
| 103 |
+
return runtime_dir
|
| 104 |
+
|
| 105 |
+
def close(self):
|
| 106 |
+
uvc.settings = self._saved
|
| 107 |
+
shutil.rmtree(self.root, ignore_errors=True)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _archived(box):
|
| 111 |
+
directory = box.archive_dir()
|
| 112 |
+
if not os.path.isdir(directory):
|
| 113 |
+
return []
|
| 114 |
+
return sorted(name for name in os.listdir(directory)
|
| 115 |
+
if name.endswith(uvc._CAMERA_LOG_NAME))
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def check_archive_basic(box):
|
| 119 |
+
print("\n[1] 留档基本行为")
|
| 120 |
+
runtime_dir = box.make_runtime_dir()
|
| 121 |
+
source = os.path.join(runtime_dir, uvc._CAMERA_LOG_NAME)
|
| 122 |
+
|
| 123 |
+
target = uvc._archive_camera_log(runtime_dir, "bus1-port2.2")
|
| 124 |
+
check(target is not None and os.path.isfile(target),
|
| 125 |
+
f"留档文件已生成({os.path.basename(target or 'None')})")
|
| 126 |
+
check(os.path.isfile(source), "源文件仍留在 runtime_dir(先拷后删)")
|
| 127 |
+
with open(target, "r", encoding="utf-8") as handle:
|
| 128 |
+
check(handle.read() == HEALTHY_LOG, "留档内容与源逐字节一致")
|
| 129 |
+
check("bus1-port2.2" in os.path.basename(target), "留档文件名带 tag")
|
| 130 |
+
check(os.path.dirname(target) == box.archive_dir(),
|
| 131 |
+
"留档落在 logs/camera_service/(与 main.log 同级、独立子目录)")
|
| 132 |
+
check(len(os.path.basename(target)) > len("_camera-service.log") + 8,
|
| 133 |
+
"留档文件名带时刻前缀(同名不同次会话不会互相覆盖)")
|
| 134 |
+
shutil.rmtree(runtime_dir, ignore_errors=True)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def check_missing_source(box):
|
| 138 |
+
print("\n[2] 没有 camera-service.log 时不报错")
|
| 139 |
+
runtime_dir = box.make_runtime_dir(payload=None)
|
| 140 |
+
logged = []
|
| 141 |
+
result = uvc._archive_camera_log(runtime_dir, "bus1-port2.2", logged.append)
|
| 142 |
+
check(result is None, "返回 None(静默跳过,不抛异常)")
|
| 143 |
+
check(logged == [], "连日志都不记(这不是异常,只是没证据可留)")
|
| 144 |
+
shutil.rmtree(runtime_dir, ignore_errors=True)
|
| 145 |
+
|
| 146 |
+
only_other = box.make_runtime_dir(payload="x", name="other.log")
|
| 147 |
+
check(uvc._archive_camera_log(only_other, "t") is None,
|
| 148 |
+
"目录里有别的文件但没有 camera-service.log → 仍返回 None")
|
| 149 |
+
shutil.rmtree(only_other, ignore_errors=True)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def check_archive_unwritable(box):
|
| 153 |
+
print("\n[3] 留档目录不可用时不打断清理")
|
| 154 |
+
blocker = os.path.join(box.root, "logs", "camera_service")
|
| 155 |
+
os.makedirs(os.path.dirname(blocker), exist_ok=True)
|
| 156 |
+
shutil.rmtree(blocker, ignore_errors=True) # 前面几项可能已建出目录
|
| 157 |
+
with open(blocker, "w", encoding="utf-8") as handle: # 目录位置被一个文件占住
|
| 158 |
+
handle.write("not a directory")
|
| 159 |
+
|
| 160 |
+
runtime_dir = box.make_runtime_dir()
|
| 161 |
+
logged = []
|
| 162 |
+
result = uvc._archive_camera_log(runtime_dir, "bus1-port2.2", logged.append)
|
| 163 |
+
check(result is None, "无法建目录时返回 None(不抛异常)")
|
| 164 |
+
check(logged and "留档失败" in logged[0],
|
| 165 |
+
f"把失败记进日志({logged[0] if logged else '没记'})")
|
| 166 |
+
|
| 167 |
+
os.unlink(blocker)
|
| 168 |
+
shutil.rmtree(runtime_dir, ignore_errors=True)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def check_prune(box):
|
| 172 |
+
print("\n[4] 只保留最近 20 份")
|
| 173 |
+
directory = box.archive_dir()
|
| 174 |
+
shutil.rmtree(directory, ignore_errors=True)
|
| 175 |
+
os.makedirs(directory, exist_ok=True)
|
| 176 |
+
# 造 25 份,文件名前缀是 %Y%m%d_%H%M%S(字典序即时间序)
|
| 177 |
+
names = [f"20260901_0000{index:02d}_bus1-port2.2_camera-service.log"
|
| 178 |
+
for index in range(25)]
|
| 179 |
+
for name in names:
|
| 180 |
+
with open(os.path.join(directory, name), "w", encoding="utf-8") as h:
|
| 181 |
+
h.write(name)
|
| 182 |
+
|
| 183 |
+
uvc._prune_camera_log_archive()
|
| 184 |
+
remaining = sorted(os.listdir(directory))
|
| 185 |
+
check(len(remaining) == uvc._CAMERA_LOG_ARCHIVE_KEEP,
|
| 186 |
+
f"25 份被裁到 {uvc._CAMERA_LOG_ARCHIVE_KEEP} 份"
|
| 187 |
+
f"(实际 {len(remaining)})")
|
| 188 |
+
check(remaining == sorted(names)[-uvc._CAMERA_LOG_ARCHIVE_KEEP:],
|
| 189 |
+
"被删的是最旧的 5 份,保留的是最新的 20 份")
|
| 190 |
+
shutil.rmtree(directory, ignore_errors=True)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def check_evidence_matcher(box):
|
| 194 |
+
print("\n[5] 摘录判据:健康的会话必须一条都不命中")
|
| 195 |
+
healthy = os.path.join(box.root, "healthy.log")
|
| 196 |
+
with open(healthy, "w", encoding="utf-8") as handle:
|
| 197 |
+
handle.write(HEALTHY_LOG)
|
| 198 |
+
hits = uvc._camera_log_evidence(healthy)
|
| 199 |
+
check(hits == [], f"健康日志零命中(实际 {hits})")
|
| 200 |
+
for label, line in (
|
| 201 |
+
("每 5 秒 stats 行", "[unit_1_left] fps_in=30.00 fps_out=29.98 "
|
| 202 |
+
"received=1500 output=1490 dropped=10 (+0) bad_jpeg=0 (+0) "
|
| 203 |
+
"bad_replaced=0 write_errors=0 queue=2"),
|
| 204 |
+
("退出汇总行", "[unit_1_left] received=1800 output=1795 dropped=10 "
|
| 205 |
+
"bad_jpeg=0 bad_replaced=0 write_errors=0 retries=0 stalls=0 "
|
| 206 |
+
"usb_resets=0"),
|
| 207 |
+
("档位权威行 xfers=", "[LIBUVC-QUIRK] VID:PID 0c45:636f alt=3 "
|
| 208 |
+
"payload=800 endpoint=800 frame=640x480 interval=333333 xfers=4 "
|
| 209 |
+
"xfer_bytes=3200"),
|
| 210 |
+
):
|
| 211 |
+
check(uvc._CAMERA_LOG_EVIDENCE.search(line) is None,
|
| 212 |
+
f"{label}不被当作证据(裸 dropped / stalls= 是噪声来源)")
|
| 213 |
+
|
| 214 |
+
print("\n[6] 告警行逐条命中,取末尾且限量")
|
| 215 |
+
trouble = os.path.join(box.root, "trouble.log")
|
| 216 |
+
with open(trouble, "w", encoding="utf-8") as handle:
|
| 217 |
+
handle.write(TROUBLE_LOG)
|
| 218 |
+
hits = uvc._camera_log_evidence(trouble, limit=99)
|
| 219 |
+
check(hits == EVIDENCE_LINES,
|
| 220 |
+
f"八条告警逐条命中且顺序不变(实际 {len(hits)} 条)")
|
| 221 |
+
|
| 222 |
+
limited = uvc._camera_log_evidence(trouble)
|
| 223 |
+
check(len(limited) == 6, f"默认只摘 6 条(实际 {len(limited)})")
|
| 224 |
+
check(limited == EVIDENCE_LINES[-6:],
|
| 225 |
+
"��的是最末 6 条(会话结束前发生了什么最要紧)")
|
| 226 |
+
check(uvc._camera_log_evidence(os.path.join(box.root, "nope.log")) == [],
|
| 227 |
+
"文件不存在时返回空表(不抛异常)")
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _manager(logged):
|
| 231 |
+
return uvc.UvcCameraServiceManager(
|
| 232 |
+
logger=logged.append, discovery_binary="/nonexistent/discover",
|
| 233 |
+
service_binary="/nonexistent/service")
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def check_stop_entry_end_to_end(box):
|
| 237 |
+
print("\n[7] _stop_entry_locked 端到端")
|
| 238 |
+
logged = []
|
| 239 |
+
manager = _manager(logged)
|
| 240 |
+
|
| 241 |
+
runtime_dir = box.make_runtime_dir(TROUBLE_LOG)
|
| 242 |
+
entry = {"process": None, "runtime_dir": runtime_dir,
|
| 243 |
+
"sockets": {}, "leases": 0, "tag": "bus1-port2.2"}
|
| 244 |
+
manager._stop_entry_locked(entry)
|
| 245 |
+
|
| 246 |
+
check(not os.path.exists(runtime_dir), "runtime_dir 已被 rmtree")
|
| 247 |
+
archived = _archived(box)
|
| 248 |
+
check(len(archived) == 1, f"日志被留档({archived})")
|
| 249 |
+
check(any("告警摘录" in line for line in logged),
|
| 250 |
+
"有告警时打摘录标题")
|
| 251 |
+
check(sum(1 for line in logged if line.startswith(" [")) == 6,
|
| 252 |
+
f"摘录行按原样带前缀缩进({len(logged)} 行日志)")
|
| 253 |
+
check(any("日志留档:" in line for line in logged),
|
| 254 |
+
"摘录之后给出留档路径")
|
| 255 |
+
check(logged.index(next(l for l in logged if "告警摘录" in l))
|
| 256 |
+
< logged.index(next(l for l in logged if "日志留档:" in l)),
|
| 257 |
+
"顺序:先摘录、后路径")
|
| 258 |
+
|
| 259 |
+
logged.clear()
|
| 260 |
+
healthy_dir = box.make_runtime_dir(HEALTHY_LOG)
|
| 261 |
+
manager._stop_entry_locked(
|
| 262 |
+
{"process": None, "runtime_dir": healthy_dir, "sockets": {},
|
| 263 |
+
"leases": 0, "tag": "bus1-port2.2"})
|
| 264 |
+
check(logged == [], f"健康会话不占 main.log(实际 {logged})")
|
| 265 |
+
# 同一秒内同 tag 的第二份:绝不覆盖上一份(留档的意义就是证据不会没了)
|
| 266 |
+
check(len(_archived(box)) == 2,
|
| 267 |
+
f"同秒同 tag 两次留档都不丢({_archived(box)})")
|
| 268 |
+
|
| 269 |
+
missing = os.path.join(box.root, "gone")
|
| 270 |
+
logged.clear()
|
| 271 |
+
manager._stop_entry_locked(
|
| 272 |
+
{"process": None, "runtime_dir": missing, "sockets": {},
|
| 273 |
+
"leases": 0, "tag": "bus1-port2.2"})
|
| 274 |
+
check(logged == [], "没有日志文件时全程静默(老条目/异常路径都走这里)")
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def check_service_tag(box):
|
| 278 |
+
print("\n[8] 留档身份 tag")
|
| 279 |
+
check(uvc._service_tag([{"bus": 1, "outer_path": "2.2"}]) == "bus1-port2.2",
|
| 280 |
+
"双 rig 靠 bus + 外口路径区分")
|
| 281 |
+
check(uvc._service_tag([{"bus": "3", "outer_path": "1.4"}])
|
| 282 |
+
== "bus3-port1.4", "bus 是字符串也能拼(扫描结果里并非恒为 int)")
|
| 283 |
+
check(uvc._service_tag([]) == "bus0-portunknown", "空 records 降级不抛")
|
| 284 |
+
check(uvc._service_tag([{"bus": None, "outer_path": ""}])
|
| 285 |
+
== "bus0-portunknown", "字段缺失降级成 unknown")
|
| 286 |
+
|
| 287 |
+
# 恶意/异常 tag 不能逃出留档目录(tag 来自设备拓扑,仍按不可信处理)
|
| 288 |
+
escaped = uvc._archive_camera_log(
|
| 289 |
+
box.make_runtime_dir(), "../../evil/../../x")
|
| 290 |
+
check(escaped is not None
|
| 291 |
+
and os.path.dirname(os.path.abspath(escaped))
|
| 292 |
+
== os.path.abspath(box.archive_dir()),
|
| 293 |
+
f"路径分隔符被替掉,留档仍在 logs/camera_service/({escaped})")
|
| 294 |
+
check("/" not in os.path.basename(escaped), "文件名里不含路径分隔符")
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def main():
|
| 298 |
+
box = _Sandbox()
|
| 299 |
+
try:
|
| 300 |
+
check_archive_basic(box)
|
| 301 |
+
check_missing_source(box)
|
| 302 |
+
check_archive_unwritable(box)
|
| 303 |
+
check_prune(box)
|
| 304 |
+
check_evidence_matcher(box)
|
| 305 |
+
check_stop_entry_end_to_end(box)
|
| 306 |
+
check_service_tag(box)
|
| 307 |
+
finally:
|
| 308 |
+
box.close()
|
| 309 |
+
|
| 310 |
+
print()
|
| 311 |
+
if FAILS:
|
| 312 |
+
print(f"FAIL: {len(FAILS)} 项未通过")
|
| 313 |
+
for msg in FAILS:
|
| 314 |
+
print(f" - {msg}")
|
| 315 |
+
return 1
|
| 316 |
+
print("PASS: camera-service 日志留档回归通过")
|
| 317 |
+
return 0
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
if __name__ == "__main__":
|
| 321 |
+
sys.exit(main())
|
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""部署脚本的**虚拟环境契约**:venv 坏了自己修,用错解释器直接拦住。
|
| 4 |
+
|
| 5 |
+
python tools/tests/test_deploy_shell_env_guard.py
|
| 6 |
+
|
| 7 |
+
**为什么要有这份测试**:客户报的「部署失败」绝大多数不是网络问题,而是
|
| 8 |
+
venv 本身坏了或用错了环境(详见 使用手册.md 附录 B)。这些保护全写在四个
|
| 9 |
+
分发壳(start.bat / start_lite.bat / start.sh / start_lite.sh)和两个入口
|
| 10 |
+
(main.py / main_lite.py)里,而它们**没有任何单元测试覆盖** —— 谁顺手把
|
| 11 |
+
那句 `pip install --upgrade pip` 加回来、或者把入口守卫挪到 PyQt5 import
|
| 12 |
+
之后,都不会有测试变红。这份测试就是那道闸。
|
| 13 |
+
|
| 14 |
+
覆盖:
|
| 15 |
+
[1] .bat 编码与行尾(GBK + CRLF —— 改错了 cmd 会乱码并静默失败)
|
| 16 |
+
[2] 静默升级 pip 已绝迹(它是「半装 pip」的唯一来源)
|
| 17 |
+
[3] venv 体检 + 离线自愈(ensurepip)+ 重建兜底,且体检在装依赖之前
|
| 18 |
+
[4] 环境隔离(PYTHONHOME / PYTHONPATH / 用户级 site-packages / conda 提示)
|
| 19 |
+
[5] 入口守卫:在 PyQt5 之前、规格与分发壳一致
|
| 20 |
+
[6] 守卫行为:缺依赖时退出码 2、开关能跳过
|
| 21 |
+
[7] 文档同步(使用手册.md 两个语种都写了 pip._internal.cli 这条)
|
| 22 |
+
[8] lite_package/ 里的副本没掉队(存在才查)
|
| 23 |
+
|
| 24 |
+
退出码 0 = 全部通过。
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import contextlib
|
| 30 |
+
import io
|
| 31 |
+
import os
|
| 32 |
+
import re
|
| 33 |
+
import sys
|
| 34 |
+
|
| 35 |
+
_BASE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 36 |
+
sys.path.insert(0, _BASE)
|
| 37 |
+
|
| 38 |
+
BAT_SHELLS = ["start.bat", "start_lite.bat"]
|
| 39 |
+
SH_SHELLS = ["start.sh", "start_lite.sh"]
|
| 40 |
+
ENTRIES = {"main.py": "main", "main_lite.py": "lite"}
|
| 41 |
+
|
| 42 |
+
_FAILS: list = []
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def check(tag: str, ok: bool, detail: str = "") -> None:
|
| 46 |
+
if ok:
|
| 47 |
+
print(f" ok {tag}")
|
| 48 |
+
else:
|
| 49 |
+
print(f" FAIL {tag}: {detail}")
|
| 50 |
+
_FAILS.append(f"{tag}: {detail}")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def read(path: str) -> str:
|
| 54 |
+
"""按各自编码读原文(newline='' 保留 CRLF,才能查行尾)。"""
|
| 55 |
+
|
| 56 |
+
enc = "gbk" if path.endswith(".bat") else "utf-8"
|
| 57 |
+
with open(os.path.join(_BASE, path), "r", encoding=enc, newline="") as fh:
|
| 58 |
+
return fh.read()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def code_lines(text: str, shell: str) -> str:
|
| 62 |
+
"""去掉注释行 —— 注释里出现「曾经有过那句命令」是允许的(也是刻意的)。"""
|
| 63 |
+
|
| 64 |
+
out = []
|
| 65 |
+
for line in text.splitlines():
|
| 66 |
+
stripped = line.strip()
|
| 67 |
+
if shell.endswith(".bat") and stripped.lower().startswith("rem"):
|
| 68 |
+
continue
|
| 69 |
+
if shell.endswith(".sh") and stripped.startswith("#"):
|
| 70 |
+
continue
|
| 71 |
+
out.append(line)
|
| 72 |
+
return "\n".join(out)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def shell_paths() -> list:
|
| 76 |
+
"""四个分发壳,外加 lite_package/ 里的副本(存在才查)。"""
|
| 77 |
+
|
| 78 |
+
paths = BAT_SHELLS + SH_SHELLS
|
| 79 |
+
for extra in ("lite_package/start_lite.bat", "lite_package/start_lite.sh"):
|
| 80 |
+
if os.path.exists(os.path.join(_BASE, extra)):
|
| 81 |
+
paths.append(extra)
|
| 82 |
+
return paths
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def test_bat_encoding() -> None:
|
| 86 |
+
print("[1] .bat 编码与行尾(GBK + CRLF)")
|
| 87 |
+
bats = BAT_SHELLS + (["lite_package/start_lite.bat"]
|
| 88 |
+
if os.path.exists(
|
| 89 |
+
os.path.join(_BASE, "lite_package/start_lite.bat"))
|
| 90 |
+
else [])
|
| 91 |
+
for name in bats:
|
| 92 |
+
with open(os.path.join(_BASE, name), "rb") as fh:
|
| 93 |
+
raw = fh.read()
|
| 94 |
+
try:
|
| 95 |
+
raw.decode("gbk")
|
| 96 |
+
gbk_ok = True
|
| 97 |
+
except UnicodeDecodeError:
|
| 98 |
+
gbk_ok = False
|
| 99 |
+
check(f"{name} 是 GBK", gbk_ok, "按 GBK 解不开(被存成 UTF-8 了?)")
|
| 100 |
+
check(f"{name} 无 BOM", not raw.startswith(b"\xef\xbb\xbf"),
|
| 101 |
+
"带 UTF-8 BOM,cmd 会报错")
|
| 102 |
+
check(f"{name} 全 CRLF", b"\n" not in raw.replace(b"\r\n", b""),
|
| 103 |
+
"有裸 LF 行尾")
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_no_silent_pip_upgrade() -> None:
|
| 107 |
+
print("[2] 静默升级 pip 已绝迹")
|
| 108 |
+
for name in shell_paths():
|
| 109 |
+
body = code_lines(read(name), name)
|
| 110 |
+
hits = [ln.strip() for ln in body.splitlines()
|
| 111 |
+
if re.search(r"pip\s+install\s+--upgrade\s+pip", ln)]
|
| 112 |
+
check(f"{name} 无 `pip install --upgrade pip`", not hits,
|
| 113 |
+
f"又在自动升级 pip(半装 pip 的来源): {hits[:1]}")
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def test_venv_health_and_heal() -> None:
|
| 117 |
+
print("[3] venv 体检 + 离线自愈 + 重建兜底")
|
| 118 |
+
for name in shell_paths():
|
| 119 |
+
text = code_lines(read(name), name)
|
| 120 |
+
lite = "lite" in name
|
| 121 |
+
venv = "venv_lite" if lite else "venv"
|
| 122 |
+
|
| 123 |
+
check(f"{name} 体检 pip", "-m pip --version" in text, "没有 pip 健康探测")
|
| 124 |
+
check(f"{name} 离线自愈", "ensurepip --upgrade" in text,
|
| 125 |
+
"没有 ensurepip 自救")
|
| 126 |
+
rebuild = ("rmdir /s /q" if name.endswith(".bat") else "rm -rf")
|
| 127 |
+
check(f"{name} 重建兜底", rebuild in text, f"没有 {rebuild} 重建路径")
|
| 128 |
+
check(f"{name} 指向 {venv}", f'"{venv}"' in text or f" {venv}" in text,
|
| 129 |
+
f"没提到 {venv}")
|
| 130 |
+
|
| 131 |
+
# 体检必须发生在装依赖之前 —— 顺序反了就成了「用坏 pip 去装依赖」
|
| 132 |
+
probe = text.find("-m pip --version")
|
| 133 |
+
install = text.find(":install_deps") if name.endswith(".bat") else \
|
| 134 |
+
text.find("install_req requirements")
|
| 135 |
+
check(f"{name} 体检先于装依赖", -1 < probe < install,
|
| 136 |
+
f"probe@{probe} install@{install}")
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def test_env_isolation() -> None:
|
| 140 |
+
print("[4] 环境隔离(外部环境串味)")
|
| 141 |
+
for name in shell_paths():
|
| 142 |
+
text = read(name)
|
| 143 |
+
win = name.endswith(".bat")
|
| 144 |
+
check(f"{name} 清 PYTHONHOME",
|
| 145 |
+
('set "PYTHONHOME="' in text) if win else ("unset PYTHONHOME" in text),
|
| 146 |
+
"没有清 PYTHONHOME")
|
| 147 |
+
check(f"{name} 清 PYTHONPATH",
|
| 148 |
+
('set "PYTHONPATH="' in text) if win else ("PYTHONPATH" in text),
|
| 149 |
+
"没有清 PYTHONPATH")
|
| 150 |
+
check(f"{name} 屏蔽用户级 site-packages", "PYTHONNOUSERSITE" in text,
|
| 151 |
+
"没有 PYTHONNOUSERSITE=1")
|
| 152 |
+
check(f"{name} 提示外部环境",
|
| 153 |
+
"VIRTUAL_ENV" in text and "CONDA_PREFIX" in text,
|
| 154 |
+
"没有 conda/venv 提示")
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def test_entry_guard() -> None:
|
| 158 |
+
print("[5] 入口守卫(在 PyQt5 之前 + 规格一致)")
|
| 159 |
+
from core.startup_guard import SPECS
|
| 160 |
+
|
| 161 |
+
for entry, app in ENTRIES.items():
|
| 162 |
+
text = read(entry)
|
| 163 |
+
guard_at = text.find("_enforce_env(")
|
| 164 |
+
pyqt_at = text.find("from PyQt5")
|
| 165 |
+
check(f"{entry} 调用守卫", guard_at != -1, "没有调用 startup_guard.enforce")
|
| 166 |
+
check(f"{entry} 守卫在 PyQt5 之前", -1 < guard_at < pyqt_at,
|
| 167 |
+
f"guard@{guard_at} pyqt@{pyqt_at}")
|
| 168 |
+
check(f"{entry} 传入 app={app!r}", f'"{app}"' in text, "app key 不对")
|
| 169 |
+
|
| 170 |
+
# 规格里的 venv 名与分发脚本名必须和分发壳实际使用的一致
|
| 171 |
+
for app, spec in SPECS.items():
|
| 172 |
+
for shell, key in (("start.bat" if app == "main" else "start_lite.bat",
|
| 173 |
+
"launcher_win"),
|
| 174 |
+
("start.sh" if app == "main" else "start_lite.sh",
|
| 175 |
+
"launcher_unix")):
|
| 176 |
+
check(f"SPECS[{app}][{key}] 与壳一致",
|
| 177 |
+
spec[key].lstrip("./") == shell, f"{spec[key]} != {shell}")
|
| 178 |
+
shell_text = read("start.bat" if app == "main" else "start_lite.bat")
|
| 179 |
+
vpy_marker = 'set "VPY=' + spec["venv"]
|
| 180 |
+
check(f"SPECS[{app}][venv] 与壳一致", vpy_marker in shell_text,
|
| 181 |
+
f"壳里的 VPY 不是 {spec['venv']}")
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def test_guard_behaviour() -> None:
|
| 185 |
+
print("[6] 守卫行为(缺依赖退出码 2 / 开关能跳过)")
|
| 186 |
+
from core import startup_guard
|
| 187 |
+
|
| 188 |
+
fake = {"venv": "venv", "modules": ("no_such_module_for_test_xyz",),
|
| 189 |
+
"entry": "main.py", "launcher_win": "start.bat",
|
| 190 |
+
"launcher_unix": "./start.sh"}
|
| 191 |
+
startup_guard.SPECS["__test__"] = fake
|
| 192 |
+
try:
|
| 193 |
+
buf = io.StringIO()
|
| 194 |
+
with contextlib.redirect_stdout(buf):
|
| 195 |
+
try:
|
| 196 |
+
startup_guard.enforce(_BASE, "__test__")
|
| 197 |
+
code = None
|
| 198 |
+
except SystemExit as exc:
|
| 199 |
+
code = exc.code
|
| 200 |
+
check("缺依赖 → 退出码 2", code == 2, f"实际 {code!r}")
|
| 201 |
+
out = buf.getvalue()
|
| 202 |
+
check("提示里给出启动命令", "start.bat" in out and "./start.sh" in out,
|
| 203 |
+
"没有可照抄的命令")
|
| 204 |
+
check("提示里点了缺什么", "no_such_module_for_test_xyz" in out, "没报缺哪个")
|
| 205 |
+
|
| 206 |
+
os.environ["DAQ_SKIP_VENV_GUARD"] = "1"
|
| 207 |
+
try:
|
| 208 |
+
buf = io.StringIO()
|
| 209 |
+
with contextlib.redirect_stdout(buf):
|
| 210 |
+
startup_guard.enforce(_BASE, "__test__")
|
| 211 |
+
check("开关能跳过", buf.getvalue() == "", "开关没生效")
|
| 212 |
+
finally:
|
| 213 |
+
del os.environ["DAQ_SKIP_VENV_GUARD"]
|
| 214 |
+
finally:
|
| 215 |
+
startup_guard.SPECS.pop("__test__", None)
|
| 216 |
+
|
| 217 |
+
# 依赖齐全时不该拦(开发机用自己的环境跑)
|
| 218 |
+
buf = io.StringIO()
|
| 219 |
+
with contextlib.redirect_stdout(buf):
|
| 220 |
+
startup_guard.SPECS["__test2__"] = dict(fake, modules=("os", "sys"))
|
| 221 |
+
try:
|
| 222 |
+
startup_guard.enforce(_BASE, "__test2__")
|
| 223 |
+
finally:
|
| 224 |
+
startup_guard.SPECS.pop("__test2__", None)
|
| 225 |
+
check("依赖齐全不拦", "WRONG PYTHON" not in buf.getvalue(), "被误拦了")
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def test_docs() -> None:
|
| 229 |
+
print("[7] 文档同步")
|
| 230 |
+
manual = read("使用手册.md")
|
| 231 |
+
check("手册写了 pip 损坏这条", manual.count("pip._internal.cli") >= 2,
|
| 232 |
+
f"只出现 {manual.count('pip._internal.cli')} 次(中英各一)")
|
| 233 |
+
for name in (BAT_SHELLS + SH_SHELLS):
|
| 234 |
+
check(f"{name} 错误 D 提到 pip 损坏",
|
| 235 |
+
"pip._internal.cli" in read(name), "错误 D 没讲 pip 损坏这条")
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def main() -> int:
|
| 239 |
+
print(f"项目根: {_BASE}\n")
|
| 240 |
+
test_bat_encoding()
|
| 241 |
+
test_no_silent_pip_upgrade()
|
| 242 |
+
test_venv_health_and_heal()
|
| 243 |
+
test_env_isolation()
|
| 244 |
+
test_entry_guard()
|
| 245 |
+
test_guard_behaviour()
|
| 246 |
+
test_docs()
|
| 247 |
+
|
| 248 |
+
print()
|
| 249 |
+
if _FAILS:
|
| 250 |
+
print(f"FAILED: {len(_FAILS)} 项")
|
| 251 |
+
for item in _FAILS:
|
| 252 |
+
print(" -", item)
|
| 253 |
+
return 1
|
| 254 |
+
print("ALL PASS")
|
| 255 |
+
return 0
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
if __name__ == "__main__":
|
| 259 |
+
sys.exit(main())
|
|
@@ -1,6 +1,7 @@
|
|
| 1 |
-
"""DropStats 计数器单测(v1.0.9)。
|
| 2 |
|
| 3 |
-
覆盖:inc 累计、snapshot 副本语义、clear、多线程自增一致性
|
|
|
|
| 4 |
|
| 5 |
用法:
|
| 6 |
venv/bin/python tools/tests/test_drop_stats.py
|
|
@@ -11,7 +12,7 @@ import threading
|
|
| 11 |
|
| 12 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 13 |
|
| 14 |
-
from core.pipeline import DropStats
|
| 15 |
|
| 16 |
FAILS = []
|
| 17 |
|
|
@@ -37,9 +38,55 @@ def main():
|
|
| 37 |
snap["a"] = 999
|
| 38 |
check(ds.snapshot()["a"] == 3, "snapshot 返回副本(改副本不影响计数)")
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
ds.clear()
|
| 41 |
check(ds.snapshot() == {}, "clear 清空")
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
# 多线程自增:8 线程 × 5000 次,两个键各半
|
| 44 |
N_THREADS, N_INC = 8, 5000
|
| 45 |
def worker(key):
|
|
|
|
| 1 |
+
"""DropStats 计数器单测(v1.0.9;v1.3.10 补 note_max 与帧数口径 helper)。
|
| 2 |
|
| 3 |
+
覆盖:inc 累计、note_max 峰值语义、snapshot 副本语义、clear、多线程自增一致性;
|
| 4 |
+
以及 is_frame_drop_key / frame_drop_total 的真值表(帧数口径的唯一判据)。
|
| 5 |
|
| 6 |
用法:
|
| 7 |
venv/bin/python tools/tests/test_drop_stats.py
|
|
|
|
| 12 |
|
| 13 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 14 |
|
| 15 |
+
from core.pipeline import DropStats, frame_drop_total, is_frame_drop_key
|
| 16 |
|
| 17 |
FAILS = []
|
| 18 |
|
|
|
|
| 38 |
snap["a"] = 999
|
| 39 |
check(ds.snapshot()["a"] == 3, "snapshot 返回副本(改副本不影响计数)")
|
| 40 |
|
| 41 |
+
# note_max:峰值语义(不能累加,否则第二次小滞后会把第一次大滞后加进去)
|
| 42 |
+
ds.note_max("lag_max_ms", 120)
|
| 43 |
+
ds.note_max("lag_max_ms", 40)
|
| 44 |
+
check(ds.snapshot()["lag_max_ms"] == 120, "note_max 保留峰值(小的不覆盖)")
|
| 45 |
+
ds.note_max("lag_max_ms", 250)
|
| 46 |
+
check(ds.snapshot()["lag_max_ms"] == 250, "note_max 更大的才覆盖")
|
| 47 |
+
ds.note_max("lag_max_ms", 250)
|
| 48 |
+
check(ds.snapshot()["lag_max_ms"] == 250, "note_max 等值不重复计")
|
| 49 |
+
ds.inc("k")
|
| 50 |
+
ds.note_max("lag_max_ms", 0)
|
| 51 |
+
check(ds.snapshot()["lag_max_ms"] == 250 and ds.snapshot()["k"] == 1,
|
| 52 |
+
"note_max 与 inc 互不干扰")
|
| 53 |
+
|
| 54 |
ds.clear()
|
| 55 |
check(ds.snapshot() == {}, "clear 清空")
|
| 56 |
|
| 57 |
+
# ── 帧数口径真值表 ─────────────────────────────────────
|
| 58 |
+
# 判据是「这个键能不能加进丢帧总数」,不是「键名看起来像什么」。
|
| 59 |
+
# 表里的 False 项覆盖全部会落进 drop_stats 的非帧键:`rgb_quality_snapshot()`
|
| 60 |
+
# 的 7 个(UI 前缀槽位名后落盘)+ pipeline 注入的 3 个空洞键 + 遗留的
|
| 61 |
+
# imu_overflow。漏掉任何一个,它就会被当成帧数加进「丢帧统计」,把用户
|
| 62 |
+
# 指去调编码器(旧名 readfail_episodes 就这么漏了两天)。
|
| 63 |
+
for key, want in [
|
| 64 |
+
("ext:gripper_rgb", True), # 外部队列满 —— 帧数
|
| 65 |
+
("sensor_queue", True), # 采集线程队列满 —— 帧数
|
| 66 |
+
("uvc:head_left_rgb", True), # UVC 槽位 —— 帧数
|
| 67 |
+
("gripper_rgb_gap_ms", False), # 空洞时长
|
| 68 |
+
("gripper_rgb_gap_max_ms", False),
|
| 69 |
+
("gripper_rgb_gap_count", False),
|
| 70 |
+
("gripper_rgb_emit_lag_max_ms", False),
|
| 71 |
+
("gripper_rgb_dispatch_lag_max_ms", False),
|
| 72 |
+
("gripper_rgb_readfail_ms", False),
|
| 73 |
+
("gripper_rgb_readfail_max_ms", False),
|
| 74 |
+
("gripper_rgb_readfail_stall_count", False), # 旧名 _episodes 曾漏网
|
| 75 |
+
("gripper_rgb_overwrite_count", False),
|
| 76 |
+
("gripper_rgb_reconnect_count", False),
|
| 77 |
+
("gripper_rgb_gap_max_at_ns", False), # 没进 drop_stats,留着当反例
|
| 78 |
+
("imu_overflow", False), # 遗留键(防丢缓冲超限次数)
|
| 79 |
+
]:
|
| 80 |
+
got = is_frame_drop_key(key)
|
| 81 |
+
check(got is want, f"is_frame_drop_key({key!r}) == {want}(实际 {got})")
|
| 82 |
+
|
| 83 |
+
mixed = {"ext:gripper_rgb": 3, "gripper_rgb_gap_ms": 4680,
|
| 84 |
+
"imu_overflow": 2, "gripper_rgb_overwrite_count": 37}
|
| 85 |
+
check(frame_drop_total(mixed) == 3,
|
| 86 |
+
f"混合字典只加帧数项: {frame_drop_total(mixed)} == 3")
|
| 87 |
+
check(frame_drop_total({}) == 0, "空字典 → 0")
|
| 88 |
+
check(frame_drop_total({"a_gap_ms": 5000}) == 0, "全是时长项 → 0")
|
| 89 |
+
|
| 90 |
# 多线程自增:8 线程 × 5000 次,两个键各半
|
| 91 |
N_THREADS, N_INC = 8, 5000
|
| 92 |
def worker(key):
|
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""落盘侧帧空洞计量测试(v1.3.10)—— 合成帧 + 假 writer,无真机无真 ffmpeg。
|
| 2 |
+
|
| 3 |
+
覆盖:写线程按帧自带 hardware_ns 计量空洞(口径与 tools/audit_frame_gaps.py
|
| 4 |
+
一致)、空洞闭合到门槛时当场打日志、门槛以下只记账不出声、无时间戳槽位退化为
|
| 5 |
+
宿主单调钟且不产生伪空洞、**每段重新锁时间基座**(否则第二段的钟差会被记成
|
| 6 |
+
一次天文数字级的空洞)、drop_stats 注入的键一律不算帧数、note_drop_stats 的
|
| 7 |
+
峰值/累加语义。
|
| 8 |
+
|
| 9 |
+
走**真实** `start_recording → _start_async` 路径(不是直接置 `_recording=True`
|
| 10 |
+
绕过),这样 `_ext_gap_watches` 的每段重置才真的被覆盖到。
|
| 11 |
+
|
| 12 |
+
用法:
|
| 13 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python tools/tests/test_ext_frame_gap.py
|
| 14 |
+
"""
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
import time
|
| 18 |
+
|
| 19 |
+
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
| 20 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(
|
| 21 |
+
os.path.dirname(os.path.abspath(__file__)))))
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
from PyQt5.QtCore import QObject, pyqtSignal
|
| 25 |
+
from PyQt5.QtWidgets import QApplication
|
| 26 |
+
|
| 27 |
+
import core.pipeline as pipeline_mod
|
| 28 |
+
from core.pipeline import CameraPipeline, frame_drop_total
|
| 29 |
+
|
| 30 |
+
OUT_ROOT = "/tmp/ext_frame_gap_test"
|
| 31 |
+
SLOT = "gripper_rgb" # 帧自带 hardware_ns
|
| 32 |
+
SLOT_MONO = "gripper_2_rgb" # 恒传 hw_ns=0(lite 路径)
|
| 33 |
+
H, W = 8, 8
|
| 34 |
+
|
| 35 |
+
STEP = 33_333_333 # 30fps
|
| 36 |
+
T0 = 7_000_000_000_000 # 第一段的帧钟基座
|
| 37 |
+
T1 = T0 + 1_000_000_000_000 # 第二段:换个基座(模拟设备/宿主钟不同源)
|
| 38 |
+
|
| 39 |
+
FAILS = []
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def check(cond, msg):
|
| 43 |
+
if cond:
|
| 44 |
+
print(f" PASS: {msg}")
|
| 45 |
+
else:
|
| 46 |
+
print(f" FAIL: {msg}")
|
| 47 |
+
FAILS.append(msg)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class FakeWriter(QObject):
|
| 51 |
+
"""假 writer:只记 set_drop_stats,其余接口吸收调用。"""
|
| 52 |
+
|
| 53 |
+
log_occurred = pyqtSignal(str)
|
| 54 |
+
|
| 55 |
+
encoder_label = "TEST"
|
| 56 |
+
episode_index = 1
|
| 57 |
+
task_dir = OUT_ROOT
|
| 58 |
+
|
| 59 |
+
def __init__(self):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.drop_stats = None
|
| 62 |
+
self.rows = 0
|
| 63 |
+
self.ended = False
|
| 64 |
+
|
| 65 |
+
def start_episode(self, *a, **k):
|
| 66 |
+
return True
|
| 67 |
+
|
| 68 |
+
def write_video_frame(self, *a, **k):
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
def write_frame_row(self, *a, **k):
|
| 72 |
+
self.rows += 1
|
| 73 |
+
|
| 74 |
+
def write_depth_frame(self, *a, **k):
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
def set_drop_stats(self, stats):
|
| 78 |
+
self.drop_stats = dict(stats)
|
| 79 |
+
|
| 80 |
+
def end_episode(self):
|
| 81 |
+
self.ended = True
|
| 82 |
+
|
| 83 |
+
def abort_episode(self):
|
| 84 |
+
self.ended = True
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def wait_for(pred, timeout=5.0, app=None):
|
| 88 |
+
deadline = time.time() + timeout
|
| 89 |
+
while time.time() < deadline:
|
| 90 |
+
if pred():
|
| 91 |
+
return True
|
| 92 |
+
if app is not None:
|
| 93 |
+
app.processEvents()
|
| 94 |
+
time.sleep(0.01)
|
| 95 |
+
return False
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def frame():
|
| 99 |
+
return np.zeros((H, W, 3), dtype=np.uint8)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def main():
|
| 103 |
+
app = QApplication(sys.argv)
|
| 104 |
+
writer = FakeWriter()
|
| 105 |
+
pipeline_mod.EgoDataWriter = lambda: writer
|
| 106 |
+
|
| 107 |
+
pip = CameraPipeline(OUT_ROOT)
|
| 108 |
+
pip.register_external_source(SLOT, (H, W), fps=30.0)
|
| 109 |
+
pip.register_external_source(SLOT_MONO, (H, W), fps=30.0)
|
| 110 |
+
|
| 111 |
+
logs = []
|
| 112 |
+
pip.recording_log.connect(logs.append)
|
| 113 |
+
|
| 114 |
+
# ── 第一段 ────────────────────────────────────────────
|
| 115 |
+
pip.start_recording(SLOT)
|
| 116 |
+
check(wait_for(lambda: pip._write_thread is not None
|
| 117 |
+
and pip._write_thread.is_alive(), app=app),
|
| 118 |
+
"写线程已启动(真实 start_recording → _start_async 路径)")
|
| 119 |
+
check(pip._ext_gap_watches == {},
|
| 120 |
+
"每段起始空洞看门狗为空(_start_async 重置)")
|
| 121 |
+
|
| 122 |
+
f = frame()
|
| 123 |
+
# 10 帧正常(33.3ms 一个)
|
| 124 |
+
for i in range(10):
|
| 125 |
+
pip.write_external_frame(SLOT, f, T0 + i * STEP)
|
| 126 |
+
# 一个 200ms 的洞:≥ 门槛(100ms) 但 < 告警门槛(500ms) → 只记账不出声
|
| 127 |
+
t = T0 + 9 * STEP + 233_333_333
|
| 128 |
+
for i in range(5):
|
| 129 |
+
pip.write_external_frame(SLOT, f, t + i * STEP)
|
| 130 |
+
# 一个 600ms 的洞 → 当场告警
|
| 131 |
+
hole_start = t + 4 * STEP
|
| 132 |
+
hole_len = 633_333_333
|
| 133 |
+
for i in range(5):
|
| 134 |
+
pip.write_external_frame(SLOT, f, hole_start + hole_len + i * STEP)
|
| 135 |
+
# 无时间戳槽位:hw_ns 恒 0 → 退化为出队瞬间的宿主单调钟
|
| 136 |
+
for _ in range(5):
|
| 137 |
+
pip.write_external_frame(SLOT_MONO, f, 0)
|
| 138 |
+
|
| 139 |
+
def consumed(slot):
|
| 140 |
+
w = pip._ext_gap_watches.get(slot)
|
| 141 |
+
return w.snapshot()["frames"] if w else 0
|
| 142 |
+
|
| 143 |
+
n_expect = 20 # 10 + 5 + 5(本槽位)
|
| 144 |
+
check(wait_for(lambda: consumed(SLOT) >= n_expect),
|
| 145 |
+
f"写线程消费完 {n_expect} 帧(实际 {consumed(SLOT)})")
|
| 146 |
+
|
| 147 |
+
snap = pip._ext_gap_watches[SLOT].snapshot()
|
| 148 |
+
check(snap["source"] == "hw", "帧自带时间戳的槽位基座 = hw")
|
| 149 |
+
check(snap["first_ns"] == T0, "基座帧 = 本段首帧")
|
| 150 |
+
check(snap["gap_count"] == 2, f"两个洞(200ms 与 633ms),实际 {snap['gap_count']}")
|
| 151 |
+
check(abs(snap["gap_max_ns"] - (hole_len - STEP)) < 1000,
|
| 152 |
+
f"最大洞 ≈ 600ms(实际 {snap['gap_max_ns'] / 1e6:.1f}ms)")
|
| 153 |
+
check(snap["gap_max_at_ns"] == hole_start,
|
| 154 |
+
"最大洞起点 = 洞前最后一帧的时刻")
|
| 155 |
+
expect_total = (233_333_333 - STEP) + (hole_len - STEP)
|
| 156 |
+
check(abs(snap["gap_ns"] - expect_total) < 2000,
|
| 157 |
+
f"累计空洞 ≈ {expect_total / 1e6:.1f}ms(实际 {snap['gap_ns'] / 1e6:.1f}ms)")
|
| 158 |
+
|
| 159 |
+
# 告警由写线程 emit、经 Qt 队列投到主线程(与 bridge 同源),要 processEvents
|
| 160 |
+
got_alert = wait_for(lambda: any("RGB 帧空洞" in l for l in logs), app=app)
|
| 161 |
+
alerts = [l for l in logs if "RGB 帧空洞" in l]
|
| 162 |
+
check(got_alert and len(alerts) == 1,
|
| 163 |
+
f"只对 ≥500ms 的那个洞告警(实际 {len(alerts)} 行)")
|
| 164 |
+
if alerts:
|
| 165 |
+
print(f" {alerts[0]}")
|
| 166 |
+
check("槽 gripper_rgb" in alerts[0] and "开录后 0.7s 起" in alerts[0],
|
| 167 |
+
"告警行含槽位与「开录后多久」(对应洞起点,不是告警时刻)")
|
| 168 |
+
|
| 169 |
+
mono = pip._ext_gap_watches.get(SLOT_MONO)
|
| 170 |
+
check(mono is not None and mono.snapshot()["source"] == "mono",
|
| 171 |
+
"hw_ns=0 的槽位退化为宿主单调钟基座")
|
| 172 |
+
check(mono is not None and mono.snapshot()["gap_count"] == 0,
|
| 173 |
+
"无时间戳槽位按出队节奏计量 → 不产生伪空洞")
|
| 174 |
+
|
| 175 |
+
# ── 第一段落盘注入 ────────────────────────────────────
|
| 176 |
+
finished = []
|
| 177 |
+
pip.recording_finished.connect(lambda sid, p: finished.append(sid))
|
| 178 |
+
pip.finish_recording(SLOT)
|
| 179 |
+
check(wait_for(lambda: finished, app=app),
|
| 180 |
+
"第一段结束(_finish_async 走完,writer 与 session 已清)")
|
| 181 |
+
stats = pip.last_drop_stats
|
| 182 |
+
check(stats.get(f"{SLOT}_gap_count") == 2, f"gap_count 落进 drop_stats: {stats}")
|
| 183 |
+
check(stats.get(f"{SLOT}_gap_max_ms") == 600,
|
| 184 |
+
f"gap_max_ms 取毫秒峰值: {stats.get(f'{SLOT}_gap_max_ms')}")
|
| 185 |
+
check(stats.get(f"{SLOT}_gap_ms") == round(expect_total / 1e6),
|
| 186 |
+
f"gap_ms 为累计毫秒: {stats.get(f'{SLOT}_gap_ms')}")
|
| 187 |
+
check(stats.get(f"{SLOT_MONO}_gap_count") is None,
|
| 188 |
+
"零空洞的槽位不落键(不写一堆没意义的 0)")
|
| 189 |
+
check(frame_drop_total(stats) == 0,
|
| 190 |
+
f"空洞键不算帧数(frame_drop_total = {frame_drop_total(stats)})")
|
| 191 |
+
check(writer.drop_stats == stats, "同一份统计注入 writer 元数据")
|
| 192 |
+
|
| 193 |
+
# ── 第二段:换时间基座,不许把钟差记成空洞 ──────────────
|
| 194 |
+
check(pip._writer is None and pip._session_path is None,
|
| 195 |
+
"第一段的 writer/session 引用已清(第二段不会被 _finish_async 回冲)")
|
| 196 |
+
writer.ended = False
|
| 197 |
+
logs.clear()
|
| 198 |
+
pip.start_recording(SLOT)
|
| 199 |
+
check(wait_for(lambda: pip._write_thread is not None
|
| 200 |
+
and pip._write_thread.is_alive(), app=app), "第二段写线程已启动")
|
| 201 |
+
check(pip._ext_gap_watches == {}, "第二段起始看门狗被重置(上一段的洞不带过来)")
|
| 202 |
+
for i in range(5):
|
| 203 |
+
pip.write_external_frame(SLOT, f, T1 + i * STEP)
|
| 204 |
+
check(wait_for(lambda: pip._ext_gap_watches.get(SLOT)
|
| 205 |
+
and pip._ext_gap_watches[SLOT].snapshot()["frames"] >= 5),
|
| 206 |
+
"第二段消费 5 帧")
|
| 207 |
+
snap2 = pip._ext_gap_watches[SLOT].snapshot()
|
| 208 |
+
check(snap2["first_ns"] == T1, "基座重新锁到第二段首帧")
|
| 209 |
+
check(snap2["gap_count"] == 0 and snap2["gap_ns"] == 0,
|
| 210 |
+
"换了钟基座也不产生伪空洞(这就是每段必须重置的理由)")
|
| 211 |
+
|
| 212 |
+
# ── note_drop_stats 语义 ──────────────────────────────
|
| 213 |
+
pip.note_drop_stats({f"{SLOT}_readfail_max_ms": 4681,
|
| 214 |
+
f"{SLOT}_readfail_ms": 4681,
|
| 215 |
+
f"{SLOT}_reconnect_count": 2,
|
| 216 |
+
f"{SLOT}_overwrite_count": 0})
|
| 217 |
+
snapped = pip._drop_stats.snapshot()
|
| 218 |
+
check(snapped.get(f"{SLOT}_readfail_max_ms") == 4681
|
| 219 |
+
and snapped.get(f"{SLOT}_readfail_ms") == 4681
|
| 220 |
+
and snapped.get(f"{SLOT}_reconnect_count") == 2,
|
| 221 |
+
f"采集侧计数并入本段: {snapped}")
|
| 222 |
+
check(f"{SLOT}_overwrite_count" not in snapped, "零值不落键")
|
| 223 |
+
pip.note_drop_stats({f"{SLOT}_readfail_max_ms": 120,
|
| 224 |
+
f"{SLOT}_reconnect_count": 1})
|
| 225 |
+
snapped = pip._drop_stats.snapshot()
|
| 226 |
+
check(snapped[f"{SLOT}_readfail_max_ms"] == 4681,
|
| 227 |
+
"*_max_ms 是峰值语义(后到的 120 不覆盖 4681)")
|
| 228 |
+
check(snapped[f"{SLOT}_reconnect_count"] == 3, "其余键累加")
|
| 229 |
+
check(frame_drop_total(snapped) == 0,
|
| 230 |
+
f"采集侧诊断键同样不算帧数({frame_drop_total(snapped)})")
|
| 231 |
+
|
| 232 |
+
pip.finish_recording(SLOT)
|
| 233 |
+
check(wait_for(lambda: writer.ended, app=app), "第二段结束")
|
| 234 |
+
|
| 235 |
+
print()
|
| 236 |
+
if FAILS:
|
| 237 |
+
print(f"FAIL: {len(FAILS)} 项未通过")
|
| 238 |
+
return 1
|
| 239 |
+
print("PASS: ext_frame_gap 单测全部通过")
|
| 240 |
+
return 0
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
if __name__ == "__main__":
|
| 244 |
+
sys.exit(main())
|
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""力矩阵列**落盘契约**:把「泵交给 writer 的东西」从 Python list 换成 ndarray
|
| 4 |
+
(v1.3.11 L1-1),列本身的 schema 与值必须一个字节都不变。
|
| 5 |
+
|
| 6 |
+
QT_QPA_PLATFORM=offscreen venv/bin/python \
|
| 7 |
+
tools/tests/test_force_matrix_schema_contract.py
|
| 8 |
+
|
| 9 |
+
**为什么要有这份测试**:`pa.array([list, list, ...], pa.list_(int16))` 对
|
| 10 |
+
Python list 是逐值装箱——185 帧 × 187500 点实测 **538ms 全程持 GIL**,正好
|
| 11 |
+
把原始流接收线程挡在 `recv()` 外面;服务端 16 包队列≈0.53s 一满就主动
|
| 12 |
+
close(2026-09-18 实测:55 次「完成」里 54 次收尾断链,而中止路径不写
|
| 13 |
+
parquet ⇒ 0/11)。改走 numpy 缓冲后同一列 **13.5ms / 最长停摆 3.6ms**
|
| 14 |
+
(噪声底 0.9ms)。但这条列是**数据主路径**,改错了就是静默数据损坏:
|
| 15 |
+
|
| 16 |
+
* `_note_matrix_dtype` 用 `isinstance(value[0], float)` 定型,而
|
| 17 |
+
`isinstance(np.float32(x), float)` 是 **False** ⇒ float32 矩阵会被
|
| 18 |
+
判成 int16,列类型错 + 精度真丢(不是报错,是悄悄截断);
|
| 19 |
+
* `if not value:` 对真数组直接 **抛 ValueError**(numpy≥1.25 的
|
| 20 |
+
「truth value of an empty array is ambiguous」)⇒ 每帧都炸;
|
| 21 |
+
* offsets 写错 ⇒ **行错位**,而总行数、列类型全都对得上,肉眼看不出来。
|
| 22 |
+
|
| 23 |
+
所以本测试**不引用新实现**:基准是冻结的旧表达式(`pa.array(list_of_lists)`),
|
| 24 |
+
把 writer 真写出的 parquet 与它逐字段、逐元素比。旧写法不认识 ndarray 时
|
| 25 |
+
本测试必须变红(先红后绿的改造纪律)。
|
| 26 |
+
|
| 27 |
+
覆盖:int16 档 / float32 档 / 两种入参(list 与 ndarray)/ 逐行混用 /
|
| 28 |
+
空行 / 缺键行 / 变长行 / 单帧 / 定型判定 / features 描述 / 停顿回归(软断言)。
|
| 29 |
+
退出码 0 = 全部通过。
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
from __future__ import annotations
|
| 33 |
+
|
| 34 |
+
import gc
|
| 35 |
+
import json
|
| 36 |
+
import os
|
| 37 |
+
import shutil
|
| 38 |
+
import sys
|
| 39 |
+
import tempfile
|
| 40 |
+
import threading
|
| 41 |
+
import time
|
| 42 |
+
|
| 43 |
+
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
| 44 |
+
|
| 45 |
+
import numpy as np
|
| 46 |
+
import pyarrow as pa
|
| 47 |
+
import pyarrow.parquet as pq
|
| 48 |
+
|
| 49 |
+
REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(
|
| 50 |
+
os.path.abspath(__file__))))
|
| 51 |
+
sys.path.insert(0, REPO_ROOT)
|
| 52 |
+
|
| 53 |
+
from core.egodata_writer import EgoDataWriter # noqa: E402
|
| 54 |
+
from core.gripper_codec import ( # noqa: E402
|
| 55 |
+
encode_gripper_force_matrix, encode_gripper_force_matrix_array)
|
| 56 |
+
|
| 57 |
+
MATRIX_KEY = "gripper_left_force_matrix"
|
| 58 |
+
COLUMN = f"observation.{MATRIX_KEY}"
|
| 59 |
+
DIM = 250 * 250 * 3 # 187500:一小帧力矩阵的元素数
|
| 60 |
+
|
| 61 |
+
_FAILS: list[str] = []
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def check(name: str, cond: bool, detail: str = ""):
|
| 65 |
+
tag = "PASS" if cond else "FAIL"
|
| 66 |
+
print(f" [{tag}] {name}" + (f" — {detail}" if detail else ""))
|
| 67 |
+
if not cond:
|
| 68 |
+
_FAILS.append(name)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# ── 基准:冻结的旧实现(改动前 writer 用的就是这一行)────────────
|
| 72 |
+
def legacy_column(values, item):
|
| 73 |
+
"""`pa.array([r.get(name, []) for r in rows], pa.list_(item))` 的等价冻结版。
|
| 74 |
+
|
| 75 |
+
刻意不复用被测代码:新旧要能互相对照,基准必须自己站着。
|
| 76 |
+
"""
|
| 77 |
+
return pa.array(list(values), pa.list_(item))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def item_of(dtype: str):
|
| 81 |
+
return pa.float32() if dtype == "float32" else pa.int16()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# ── fixture:一列的全部边界形状 ────────────────────────────────
|
| 85 |
+
def contact_matrix(value: float) -> np.ndarray:
|
| 86 |
+
m = np.zeros((250, 250, 3), np.float32)
|
| 87 |
+
m[105:135, 105:135, 2] = value
|
| 88 |
+
m[105:135, 105:135, 0] = value * 0.25
|
| 89 |
+
return m
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class Rows:
|
| 93 |
+
"""一列的行值序列;`as_` 决定每行交付给 writer 的形态。
|
| 94 |
+
|
| 95 |
+
同一份逻辑内容、三种交付形态(list / ndarray / 混用),
|
| 96 |
+
落盘结果必须**完全一致**——这正是「换入参类型不改契约」的定义。
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
def __init__(self):
|
| 100 |
+
self.raw = [] # (kind, payload)
|
| 101 |
+
for i in range(6):
|
| 102 |
+
self.raw.append(("mat", contact_matrix(3.0 + i)))
|
| 103 |
+
self.raw.append(("empty", None)) # 空行:有键、值为空
|
| 104 |
+
self.raw.append(("missing", None)) # 缺键行
|
| 105 |
+
self.raw.append(("short", contact_matrix(9.0)))
|
| 106 |
+
self.raw.append(("empty", None))
|
| 107 |
+
|
| 108 |
+
def encoded(self, spec: str, as_: str):
|
| 109 |
+
out = []
|
| 110 |
+
for kind, payload in self.raw:
|
| 111 |
+
if kind == "missing":
|
| 112 |
+
out.append(None)
|
| 113 |
+
continue
|
| 114 |
+
if kind == "empty":
|
| 115 |
+
out.append(np.zeros(0, np.float32) if as_ == "ndarray" else [])
|
| 116 |
+
continue
|
| 117 |
+
enc = (encode_gripper_force_matrix_array(payload, spec)
|
| 118 |
+
if as_ == "ndarray" else encode_gripper_force_matrix(payload, spec))
|
| 119 |
+
if kind == "short":
|
| 120 |
+
# 变长行:截短到 750(一行=一个力平面)——offsets 最容易错的地方
|
| 121 |
+
enc = enc[:750]
|
| 122 |
+
out.append(enc)
|
| 123 |
+
return out
|
| 124 |
+
|
| 125 |
+
def row_dicts(self, spec: str, as_: str):
|
| 126 |
+
rows = []
|
| 127 |
+
for enc in self.encoded(spec, as_):
|
| 128 |
+
rows.append({} if enc is None else {COLUMN: enc})
|
| 129 |
+
return rows
|
| 130 |
+
|
| 131 |
+
def reference(self, spec: str):
|
| 132 |
+
"""旧实现的基准列:逐行缺键 → 空列表(**不是 null**)。"""
|
| 133 |
+
return legacy_column([r.get(COLUMN, []) for r in self.row_dicts(spec, "list")],
|
| 134 |
+
item_of(spec))
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def write_episode(task_dir: str, row_dicts, default: str = ""):
|
| 138 |
+
writer = EgoDataWriter()
|
| 139 |
+
writer._task_dir = task_dir
|
| 140 |
+
writer._episode_index = 0
|
| 141 |
+
for i, row in enumerate(row_dicts):
|
| 142 |
+
gripper = {}
|
| 143 |
+
key = MATRIX_KEY if COLUMN in row else None
|
| 144 |
+
if key:
|
| 145 |
+
gripper[key] = row[COLUMN]
|
| 146 |
+
writer.write_frame_row(i, i / 30.0, gripper=gripper)
|
| 147 |
+
writer._write_data_parquet()
|
| 148 |
+
return writer, os.path.join(task_dir, "data", "chunk-000",
|
| 149 |
+
"episode-000.parquet")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def read_column(path: str):
|
| 153 |
+
return pq.read_table(path, columns=[COLUMN]).column(COLUMN).combine_chunks()
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# ── ① 两种档位 × 三种入参:schema 与值逐元素一致 ───────────────
|
| 157 |
+
def test_schema_and_values(tmp: str):
|
| 158 |
+
for spec in ("int16", "float32"):
|
| 159 |
+
ref = Rows().reference(spec)
|
| 160 |
+
for as_ in ("list", "ndarray", "mixed"):
|
| 161 |
+
sub = os.path.join(tmp, f"{spec}_{as_}")
|
| 162 |
+
r = Rows()
|
| 163 |
+
if as_ == "mixed":
|
| 164 |
+
# 逐行混用:偶数行 list、奇数行 ndarray(历史调用方与新调用方
|
| 165 |
+
# 同时存在时的形状;两边的 dtype 判定必须给出同一结论)
|
| 166 |
+
a = r.row_dicts(spec, "list")
|
| 167 |
+
b = r.row_dicts(spec, "ndarray")
|
| 168 |
+
rowdicts = [a[i] if i % 2 == 0 else b[i]
|
| 169 |
+
for i in range(len(a))]
|
| 170 |
+
else:
|
| 171 |
+
rowdicts = r.row_dicts(spec, as_)
|
| 172 |
+
_, path = write_episode(sub, rowdicts)
|
| 173 |
+
col = read_column(path)
|
| 174 |
+
tag = f"{spec}/{as_}"
|
| 175 |
+
check(f"{tag}: parquet 列类型 = list<{spec}>",
|
| 176 |
+
pq.read_schema(path).field(COLUMN).type == ref.type,
|
| 177 |
+
str(pq.read_schema(path).field(COLUMN).type))
|
| 178 |
+
check(f"{tag}: 行数一致",
|
| 179 |
+
len(col) == len(ref), f"{len(col)} vs {len(ref)}")
|
| 180 |
+
check(f"{tag}: 值与基准逐元素相等",
|
| 181 |
+
col.to_pylist() == ref.to_pylist())
|
| 182 |
+
check(f"{tag}: 无 null 元素(空行落成空 list)",
|
| 183 |
+
col.null_count == 0 and all(v is not None for v in col.to_pylist()))
|
| 184 |
+
# 行错位最隐蔽:单独再钉一次每行长度的序列
|
| 185 |
+
check(f"{tag}: 行长序列一致",
|
| 186 |
+
[len(v) for v in col.to_pylist()]
|
| 187 |
+
== [len(v) for v in ref.to_pylist()],
|
| 188 |
+
str([len(v) for v in col.to_pylist()]))
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
# ── ② 定型判定:numpy 标量必须与 Python 标量同判 ────────────────
|
| 192 |
+
def test_dtype_classification(tmp: str):
|
| 193 |
+
for spec in ("int16", "float32"):
|
| 194 |
+
seen = {}
|
| 195 |
+
for as_ in ("list", "ndarray"):
|
| 196 |
+
sub = os.path.join(tmp, f"cls_{spec}_{as_}")
|
| 197 |
+
w, path = write_episode(sub, Rows().row_dicts(spec, as_))
|
| 198 |
+
seen[as_] = w._matrix_dtype.get(MATRIX_KEY)
|
| 199 |
+
check(f"{spec}/{as_}: 定型 = {spec}",
|
| 200 |
+
seen[as_] == spec, str(seen[as_]))
|
| 201 |
+
# info.json 的 dtype/encoding 是读取端唯一依据,必须跟着一致
|
| 202 |
+
w._write_info_json()
|
| 203 |
+
feats = json.load(open(os.path.join(sub, "meta", "info.json"),
|
| 204 |
+
encoding="utf-8"))["features"][COLUMN]
|
| 205 |
+
want_enc = "row_flat_raw" if spec == "float32" else "row_diff_quantized"
|
| 206 |
+
check(f"{spec}/{as_}: features dtype/encoding 正确",
|
| 207 |
+
feats["dtype"] == spec and feats["encoding"] == want_enc,
|
| 208 |
+
str(feats))
|
| 209 |
+
check(f"{spec}: 两种入参定型一致(np.float32 不是 float!)",
|
| 210 |
+
seen["list"] == seen["ndarray"],
|
| 211 |
+
f"list={seen['list']} ndarray={seen['ndarray']}")
|
| 212 |
+
|
| 213 |
+
# 空 ndarray 首帧不定型(`if not value:` 对真数组会抛 ValueError)
|
| 214 |
+
w = EgoDataWriter()
|
| 215 |
+
w._task_dir = os.path.join(tmp, "empty_first")
|
| 216 |
+
w._episode_index = 0
|
| 217 |
+
w.write_frame_row(0, 0.0, gripper={MATRIX_KEY: np.zeros(0, np.int16)})
|
| 218 |
+
check("空 ndarray 首帧不抛异常且不定型",
|
| 219 |
+
w._matrix_dtype.get(MATRIX_KEY) is None, str(w._matrix_dtype))
|
| 220 |
+
w.write_frame_row(1, 1 / 30.0, gripper={
|
| 221 |
+
MATRIX_KEY: encode_gripper_force_matrix_array(contact_matrix(4.0), "int16")})
|
| 222 |
+
check("空 ndarray 之后仍能定型",
|
| 223 |
+
w._matrix_dtype.get(MATRIX_KEY) == "int16", str(w._matrix_dtype))
|
| 224 |
+
|
| 225 |
+
# 混型仍要显式报错(历史契约:不让 pyarrow 抛难懂的转换异常)
|
| 226 |
+
w2 = EgoDataWriter()
|
| 227 |
+
w2._task_dir = os.path.join(tmp, "mixed_spec")
|
| 228 |
+
w2._episode_index = 0
|
| 229 |
+
w2.write_frame_row(0, 0.0, gripper={
|
| 230 |
+
MATRIX_KEY: encode_gripper_force_matrix_array(contact_matrix(4.0), "int16")})
|
| 231 |
+
raised = None
|
| 232 |
+
try:
|
| 233 |
+
w2.write_frame_row(1, 0.5, gripper={
|
| 234 |
+
MATRIX_KEY: encode_gripper_force_matrix_array(
|
| 235 |
+
contact_matrix(4.0), "float32")})
|
| 236 |
+
except ValueError as exc:
|
| 237 |
+
raised = exc
|
| 238 |
+
check("ndarray 混型同样被拒绝(ValueError)", raised is not None,
|
| 239 |
+
str(raised)[:70] if raised else "未报错")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
# ── ③ 整列无矩阵 / 单帧 / 全空行 ───────────────────────────────
|
| 243 |
+
def test_degenerate(tmp: str):
|
| 244 |
+
# 整段一帧都没有矩阵:列不存在(与旧行为一致)
|
| 245 |
+
w, path = write_episode(os.path.join(tmp, "none"), [{}, {}, {}])
|
| 246 |
+
check("整段无矩阵 → 不出现该列",
|
| 247 |
+
COLUMN not in pq.read_schema(path).names,
|
| 248 |
+
str(pq.read_schema(path).names))
|
| 249 |
+
# 单帧
|
| 250 |
+
_, path1 = write_episode(os.path.join(tmp, "single"),
|
| 251 |
+
Rows().row_dicts("int16", "ndarray")[:1])
|
| 252 |
+
ref1 = legacy_column([Rows().encoded("int16", "list")[0]], pa.int16())
|
| 253 |
+
check("单帧列与基准一致",
|
| 254 |
+
read_column(path1).to_pylist() == ref1.to_pylist())
|
| 255 |
+
# 全空行:列在(键出现过),每行都是空 list
|
| 256 |
+
rowdicts = [{COLUMN: np.zeros(0, np.int16)} for _ in range(4)]
|
| 257 |
+
_, pathe = write_episode(os.path.join(tmp, "allempty"), rowdicts)
|
| 258 |
+
col = read_column(pathe)
|
| 259 |
+
check("全空行 → 列存在且每行为空 list",
|
| 260 |
+
COLUMN in pq.read_schema(pathe).names
|
| 261 |
+
and col.to_pylist() == [[], [], [], []],
|
| 262 |
+
str(col.to_pylist()))
|
| 263 |
+
check("全空行无 null",
|
| 264 |
+
col.null_count == 0)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# ── ④ 编码器契约:新函数返回 ndarray,旧函数仍返回 list ────────
|
| 268 |
+
def test_encoder_contract():
|
| 269 |
+
m = contact_matrix(5.75)
|
| 270 |
+
for spec in ("int16", "int16x10", "int16x1000", "float32"):
|
| 271 |
+
arr = encode_gripper_force_matrix_array(m, spec)
|
| 272 |
+
lst = encode_gripper_force_matrix(m, spec)
|
| 273 |
+
contiguous = isinstance(arr, np.ndarray) and bool(arr.flags["C_CONTIGUOUS"])
|
| 274 |
+
check(f"{spec}: 新函数返回 ndarray 且连续",
|
| 275 |
+
isinstance(arr, np.ndarray) and contiguous,
|
| 276 |
+
f"{type(arr).__name__} contiguous={contiguous}")
|
| 277 |
+
check(f"{spec}: 新函数 dtype 家族正确",
|
| 278 |
+
arr.dtype == (np.float32 if spec == "float32" else np.int16),
|
| 279 |
+
str(arr.dtype))
|
| 280 |
+
check(f"{spec}: 旧函数仍返回 list(历史调用方契约)",
|
| 281 |
+
isinstance(lst, list), type(lst).__name__)
|
| 282 |
+
check(f"{spec}: 两函数逐位同值",
|
| 283 |
+
arr.tolist() == lst)
|
| 284 |
+
# 返回的必须是**自己的副本**:矩阵来自 SDK 的单槽缓冲,若交出去的是
|
| 285 |
+
# 视图,录制中每帧都会被下一帧改写 ⇒ 落盘全是最后一帧(静默损坏)
|
| 286 |
+
src = contact_matrix(7.0)
|
| 287 |
+
arr = encode_gripper_force_matrix_array(src, "float32")
|
| 288 |
+
before = arr.copy()
|
| 289 |
+
src[:] = -1.0
|
| 290 |
+
check("新函数返回值不被源缓冲改写(是副本不是视图)",
|
| 291 |
+
np.array_equal(arr, before))
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
# ── ⑤ 停顿回归(软断言):ndarray 入参不得再逐值装箱 ────────────
|
| 295 |
+
def max_stall(fn) -> float:
|
| 296 |
+
"""跑 fn 的同时用心跳线程量「最长多久拿不到 GIL」(= 接收线程最长
|
| 297 |
+
进不去 recv() 的时间)。每 0.2ms 采一次,自己不抢 GIL。"""
|
| 298 |
+
stop = False
|
| 299 |
+
worst = [0.0]
|
| 300 |
+
|
| 301 |
+
def beat():
|
| 302 |
+
last = time.perf_counter()
|
| 303 |
+
while not stop:
|
| 304 |
+
time.sleep(0.0002)
|
| 305 |
+
now = time.perf_counter()
|
| 306 |
+
worst[0] = max(worst[0], now - last)
|
| 307 |
+
last = now
|
| 308 |
+
|
| 309 |
+
th = threading.Thread(target=beat, daemon=True)
|
| 310 |
+
th.start()
|
| 311 |
+
t0 = time.perf_counter()
|
| 312 |
+
fn()
|
| 313 |
+
dt = time.perf_counter() - t0
|
| 314 |
+
stop = True
|
| 315 |
+
th.join()
|
| 316 |
+
return dt, worst[0]
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def test_no_boxing(tmp: str):
|
| 320 |
+
rows, n = 30, 185000 # 30×185000=5.55M 元素,够看出量级
|
| 321 |
+
rng = np.random.default_rng(7)
|
| 322 |
+
arrs = [rng.integers(-4000, 4000, n, dtype=np.int16) for _ in range(rows)]
|
| 323 |
+
lists = [a.tolist() for a in arrs]
|
| 324 |
+
gc.disable()
|
| 325 |
+
try:
|
| 326 |
+
dt_new, stall_new = max_stall(
|
| 327 |
+
lambda: legacy_column(arrs, pa.int16()))
|
| 328 |
+
dt_old, stall_old = max_stall(
|
| 329 |
+
lambda: legacy_column(lists, pa.int16()))
|
| 330 |
+
finally:
|
| 331 |
+
gc.enable()
|
| 332 |
+
print(f" (同一列 {rows}×{n}:ndarray {dt_new*1000:.0f}ms/"
|
| 333 |
+
f"停顿 {stall_new*1000:.0f}ms;list {dt_old*1000:.0f}ms/"
|
| 334 |
+
f"停顿 {stall_old*1000:.0f}ms)")
|
| 335 |
+
check("软断言:ndarray 建列比 list 快 ≥4×(实测约 40×)",
|
| 336 |
+
dt_new * 4 < dt_old, f"{dt_new*1000:.0f}ms vs {dt_old*1000:.0f}ms")
|
| 337 |
+
check("软断言:ndarray 建列最长停顿 <100ms(服务端队列≈530ms 的量级)",
|
| 338 |
+
stall_new < 0.1, f"{stall_new*1000:.0f}ms")
|
| 339 |
+
del lists, arrs
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def main() -> int:
|
| 343 |
+
tmp = tempfile.mkdtemp(prefix="force_matrix_contract_")
|
| 344 |
+
try:
|
| 345 |
+
print("[1] 两档 × list/ndarray/混用:schema 与值")
|
| 346 |
+
test_schema_and_values(tmp)
|
| 347 |
+
print("[2] 定型判定(numpy 标量 / 空数组 / 混型)")
|
| 348 |
+
test_dtype_classification(tmp)
|
| 349 |
+
print("[3] 退化形状(无列 / 单帧 / 全空行)")
|
| 350 |
+
test_degenerate(tmp)
|
| 351 |
+
print("[4] 编码器契约(返回类型、副本语义)")
|
| 352 |
+
test_encoder_contract()
|
| 353 |
+
print("[5] 停顿回归(软断言)")
|
| 354 |
+
test_no_boxing(tmp)
|
| 355 |
+
finally:
|
| 356 |
+
shutil.rmtree(tmp, ignore_errors=True)
|
| 357 |
+
|
| 358 |
+
print()
|
| 359 |
+
if _FAILS:
|
| 360 |
+
print(f"FAILED: {len(_FAILS)} 项")
|
| 361 |
+
for f in _FAILS:
|
| 362 |
+
print(" -", f)
|
| 363 |
+
return 1
|
| 364 |
+
print("ALL PASS")
|
| 365 |
+
return 0
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
if __name__ == "__main__":
|
| 369 |
+
sys.exit(main())
|
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GapWatch 帧空洞看门狗单测(v1.3.10)。
|
| 2 |
+
|
| 3 |
+
覆盖:正常帧距不误报、空洞累计/峰值/发生位置、门槛边界、0 哨兵、
|
| 4 |
+
混源不产生伪空洞、时间倒退重新锚定、reset。
|
| 5 |
+
|
| 6 |
+
**这个类的口径是录制侧与离线审计脚本共用的那一份**,所以边界条件必须钉死:
|
| 7 |
+
2026-09-18 排查 episode-099 的 4.68s 空洞时,就是因为两边口径不一致 + 混源,
|
| 8 |
+
差点把「设备钟与宿主钟的基准差」当成一次天文数字级的空洞。
|
| 9 |
+
|
| 10 |
+
用法:
|
| 11 |
+
venv/bin/python tools/tests/test_frame_gap.py
|
| 12 |
+
"""
|
| 13 |
+
import os
|
| 14 |
+
import sys
|
| 15 |
+
|
| 16 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 17 |
+
|
| 18 |
+
from core.frame_gap import GapWatch
|
| 19 |
+
|
| 20 |
+
FRAME_NS = 33_333_333 # 30fps 标称
|
| 21 |
+
MIN_GAP_NS = 100_000_000 # 100ms ≈ 3 帧
|
| 22 |
+
|
| 23 |
+
FAILS = []
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def check(cond, msg):
|
| 27 |
+
if cond:
|
| 28 |
+
print(f" PASS: {msg}")
|
| 29 |
+
else:
|
| 30 |
+
print(f" FAIL: {msg}")
|
| 31 |
+
FAILS.append(msg)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def main():
|
| 35 |
+
# ── 空 / 单帧 ──────────────────────────────────────────
|
| 36 |
+
w = GapWatch(FRAME_NS, MIN_GAP_NS)
|
| 37 |
+
s = w.snapshot()
|
| 38 |
+
check(s["frames"] == 0 and s["gap_ns"] == 0 and s["source"] == "",
|
| 39 |
+
"空看门狗:零帧、零空洞、基座未锁")
|
| 40 |
+
check(w.note(1_000_000_000) == 0, "首帧不产生空洞")
|
| 41 |
+
check(w.snapshot()["frames"] == 1 and w.snapshot()["source"] == "hw",
|
| 42 |
+
"首帧锁定基座 hw 并计帧")
|
| 43 |
+
|
| 44 |
+
# ── 正常帧距 ───────────────────────────────────────────
|
| 45 |
+
w = GapWatch(FRAME_NS, MIN_GAP_NS)
|
| 46 |
+
t = 1_000_000_000
|
| 47 |
+
for _ in range(30):
|
| 48 |
+
w.note(t)
|
| 49 |
+
t += FRAME_NS
|
| 50 |
+
s = w.snapshot()
|
| 51 |
+
check(s["gap_ns"] == 0 and s["gap_count"] == 0, "30 帧 @30fps 零空洞")
|
| 52 |
+
check(s["frames"] == 30, "帧数 = 30")
|
| 53 |
+
check(s["span_ns"] == 29 * FRAME_NS, f"连续跨度 = 29 帧间隔(实际 {s['span_ns']})")
|
| 54 |
+
|
| 55 |
+
# 抖动(实测 29.9~37.5ms)不该报
|
| 56 |
+
w = GapWatch(FRAME_NS, MIN_GAP_NS)
|
| 57 |
+
t = 1_000_000_000
|
| 58 |
+
w.note(t)
|
| 59 |
+
for d in (29_900_000, 33_300_000, 37_500_000, 30_100_000):
|
| 60 |
+
t += d
|
| 61 |
+
w.note(t)
|
| 62 |
+
check(w.snapshot()["gap_count"] == 0, "29.9~37.5ms 抖动不算空洞")
|
| 63 |
+
|
| 64 |
+
# ── 门槛边界 ───────────────────────────────────────────
|
| 65 |
+
w = GapWatch(FRAME_NS, MIN_GAP_NS)
|
| 66 |
+
w.note(1_000_000_000)
|
| 67 |
+
w.note(1_000_000_000 + MIN_GAP_NS - 1)
|
| 68 |
+
check(w.snapshot()["gap_count"] == 0, "间隔 = 门槛-1ns → 不计(不许提前开火)")
|
| 69 |
+
w.note(1_000_000_000 + MIN_GAP_NS - 1 + MIN_GAP_NS)
|
| 70 |
+
check(w.snapshot()["gap_count"] == 1, "间隔 = 门槛 → 计入")
|
| 71 |
+
check(w.snapshot()["gap_ns"] == MIN_GAP_NS - FRAME_NS,
|
| 72 |
+
"空洞 = 间隔 - 标称间隔")
|
| 73 |
+
|
| 74 |
+
# ── 真洞:ep-099 的 4.68s ───────────────────────────────
|
| 75 |
+
w = GapWatch(FRAME_NS, MIN_GAP_NS)
|
| 76 |
+
base = 1_700_000_000_000_000_000
|
| 77 |
+
for i in range(45): # 45 帧正常
|
| 78 |
+
w.note(base + i * FRAME_NS)
|
| 79 |
+
hole_start = base + 44 * FRAME_NS # 洞前最后一帧(= row44)
|
| 80 |
+
w.note(hole_start + 4_680_800_000) # row45:4.68s 之后
|
| 81 |
+
for i in range(10):
|
| 82 |
+
w.note(hole_start + 4_680_800_000 + (i + 1) * FRAME_NS)
|
| 83 |
+
s = w.snapshot()
|
| 84 |
+
check(s["gap_count"] == 1, "4.68s 洞计 1 次")
|
| 85 |
+
check(abs(s["gap_ns"] - (4_680_800_000 - FRAME_NS)) < 1000,
|
| 86 |
+
f"空洞 ≈ 4647.5ms(实测 {s['gap_ns'] / 1e6:.1f}ms)")
|
| 87 |
+
check(s["gap_max_ns"] == s["gap_ns"], "峰值 = 累计(只有一个洞)")
|
| 88 |
+
check(s["gap_max_at_ns"] == hole_start,
|
| 89 |
+
"峰值位置 = 洞前最后一帧的时刻(能回指到 row44)")
|
| 90 |
+
check(s["first_ns"] == base, "first_ns = 本段首帧(相对时间的原点,与钟无关)")
|
| 91 |
+
check((s["gap_max_at_ns"] - s["first_ns"]) / 1e9 == 44 * FRAME_NS / 1e9,
|
| 92 |
+
"空洞起点可换算成「开录后 1.47s」(日志与审计脚本共用这个换算)")
|
| 93 |
+
check(s["frames"] == 56, "洞中丢的帧不计入(帧数只数到的帧)")
|
| 94 |
+
|
| 95 |
+
# ── 0 哨兵 与 负值时刻(早期段的设备钟是**有符号** 32 位,值可为负)──
|
| 96 |
+
w = GapWatch(FRAME_NS, MIN_GAP_NS)
|
| 97 |
+
check(w.note(0) == 0, "0 哨兵返回 0")
|
| 98 |
+
check(w.snapshot()["frames"] == 0 and w.snapshot()["source"] == "",
|
| 99 |
+
"0 哨兵不锁基座、不计帧")
|
| 100 |
+
check(w.note(1_000_000_000) == 0 and w.snapshot()["source"] == "hw",
|
| 101 |
+
"哨兵之后的首个有效帧才是基座")
|
| 102 |
+
|
| 103 |
+
# 负值**不是**哨兵:整段都可能落在负区(trunc32 段过零前),按 <= 0 跳过会
|
| 104 |
+
# 把整段负区当成「无戳」,下一个正值帧就成了新基座 —— 一次真空洞凭空消失
|
| 105 |
+
w = GapWatch(FRAME_NS, MIN_GAP_NS)
|
| 106 |
+
check(w.note(-2_000_000_000) == 0, "负时刻锁基座(不是哨兵,返回 0 只因是首帧)")
|
| 107 |
+
check(w.snapshot()["source"] == "hw" and w.snapshot()["frames"] == 1,
|
| 108 |
+
"负时刻锁了基座、计了帧(旧实现按 <=0 跳过,这里会挂)")
|
| 109 |
+
gap = w.note(-2_000_000_000 + 4_680_800_000) # 负区里的一次 4.68s 空洞
|
| 110 |
+
check(abs(gap - (4_680_800_000 - FRAME_NS)) < 1000,
|
| 111 |
+
f"负区里的空洞照常报({gap / 1e6:.1f}ms)")
|
| 112 |
+
check(w.note(3_000_000_000) > 0, "跨过零点(负→正)仍按真实间隔算,不重锚")
|
| 113 |
+
|
| 114 |
+
# ── 混源(本类最容易踩的坑)────────────────────────────
|
| 115 |
+
w = GapWatch(FRAME_NS, MIN_GAP_NS)
|
| 116 |
+
w.note(1_000_000_000, source="hw")
|
| 117 |
+
n = w.note(5_000_000_000, source="mono") # 换钟且跳了 4s
|
| 118 |
+
check(n == 0, "混源帧不产生空洞")
|
| 119 |
+
check(w.snapshot()["gap_ns"] == 0, "混源不污染累计")
|
| 120 |
+
check(w.snapshot()["frames"] == 2, "混源帧仍计帧")
|
| 121 |
+
check(w.snapshot()["source"] == "hw", "基座不被混源改写")
|
| 122 |
+
w.note(1_000_000_000 + FRAME_NS, source="hw") # 回到基座:锚点仍是 1s 那帧
|
| 123 |
+
check(w.snapshot()["gap_count"] == 0, "混源后回到基座不报伪空洞")
|
| 124 |
+
|
| 125 |
+
# ── 时间倒退 ───────────────────────────────────────────
|
| 126 |
+
w = GapWatch(FRAME_NS, MIN_GAP_NS)
|
| 127 |
+
w.note(10_000_000_000)
|
| 128 |
+
w.note(9_000_000_000) # 时钟回退 1s
|
| 129 |
+
s = w.snapshot()
|
| 130 |
+
check(s["gap_count"] == 0 and s["resyncs"] == 1,
|
| 131 |
+
"时间倒退 → 重新锚定(resyncs +1,不报空洞)")
|
| 132 |
+
w.note(9_000_000_000 + FRAME_NS)
|
| 133 |
+
check(w.snapshot()["gap_count"] == 0, "倒退后从新锚点正常计量")
|
| 134 |
+
|
| 135 |
+
# ── reset ──────────────────────────────────────────────
|
| 136 |
+
w = GapWatch(FRAME_NS, MIN_GAP_NS)
|
| 137 |
+
w.note(1_000_000_000)
|
| 138 |
+
w.note(1_000_000_000 + 5_000_000_000)
|
| 139 |
+
w.reset()
|
| 140 |
+
s = w.snapshot()
|
| 141 |
+
check(s["frames"] == 0 and s["gap_ns"] == 0 and s["gap_max_at_ns"] == 0
|
| 142 |
+
and s["resyncs"] == 0 and s["source"] == "", "reset 全清(含基座)")
|
| 143 |
+
w.note(7_000_000_000, source="mono")
|
| 144 |
+
check(w.snapshot()["source"] == "mono", "reset 后可换基座")
|
| 145 |
+
|
| 146 |
+
print()
|
| 147 |
+
if FAILS:
|
| 148 |
+
print(f"FAIL: {len(FAILS)} 项未通过")
|
| 149 |
+
return 1
|
| 150 |
+
print("PASS: frame_gap 单测全部通过")
|
| 151 |
+
return 0
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
if __name__ == "__main__":
|
| 155 |
+
sys.exit(main())
|
|
@@ -34,6 +34,7 @@ import numpy as np
|
|
| 34 |
from PyQt5.QtCore import QCoreApplication
|
| 35 |
|
| 36 |
from core.gripper.bridge import GripperBridge
|
|
|
|
| 37 |
|
| 38 |
FAILS = []
|
| 39 |
|
|
@@ -375,7 +376,9 @@ def main():
|
|
| 375 |
board_fields={"ST": "1", "PCT": "50"}, updated="10:00:00"))
|
| 376 |
bridge._latest_force["left"] = (0.0, 0.0, 400.0)
|
| 377 |
bridge._on_grip_check()
|
| 378 |
-
|
|
|
|
|
|
|
| 379 |
check(len(stats["state"]) >= 1
|
| 380 |
and stats["state"][-1]["gripped"] is True
|
| 381 |
and abs(stats["state"][-1]["pct"] - 50.0) < 0.01
|
|
@@ -562,6 +565,105 @@ def main():
|
|
| 562 |
bridge8._emitter.join(timeout=2.0)
|
| 563 |
bridge8.deleteLater()
|
| 564 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 565 |
if FAILS:
|
| 566 |
print(f"\nFAILED: {len(FAILS)}")
|
| 567 |
for f in FAILS:
|
|
|
|
| 34 |
from PyQt5.QtCore import QCoreApplication
|
| 35 |
|
| 36 |
from core.gripper.bridge import GripperBridge
|
| 37 |
+
from core.pipeline import is_frame_drop_key
|
| 38 |
|
| 39 |
FAILS = []
|
| 40 |
|
|
|
|
| 376 |
board_fields={"ST": "1", "PCT": "50"}, updated="10:00:00"))
|
| 377 |
bridge._latest_force["left"] = (0.0, 0.0, 400.0)
|
| 378 |
bridge._on_grip_check()
|
| 379 |
+
# 上一句 board 更新已经投过一条 state(fz 还是触觉那次的 88):必须等
|
| 380 |
+
# 力检查这条也到,否则断言拿到的是在途中的前一条(曾随机假红)
|
| 381 |
+
_pump_until(lambda: stats["state"] and stats["state"][-1]["fz"] == 400.0)
|
| 382 |
check(len(stats["state"]) >= 1
|
| 383 |
and stats["state"][-1]["gripped"] is True
|
| 384 |
and abs(stats["state"][-1]["pct"] - 50.0) < 0.01
|
|
|
|
| 565 |
bridge8._emitter.join(timeout=2.0)
|
| 566 |
bridge8.deleteLater()
|
| 567 |
|
| 568 |
+
print("── 8. RGB 采集质量仪表(v1.3.10)──")
|
| 569 |
+
bridge9, fakes9 = _run_open_flow()
|
| 570 |
+
cam9 = fakes9["reservation"].camera("decxin")._camera
|
| 571 |
+
logs9 = []
|
| 572 |
+
bridge9.log.connect(logs9.append)
|
| 573 |
+
frame9 = np.zeros((8, 8, 3), dtype=np.uint8)
|
| 574 |
+
|
| 575 |
+
# 假相机的 read 是全速返回帧的(真机 30fps):本节一开始就让它处于
|
| 576 |
+
# 「读不到帧」态,覆盖/滞后这类峰值口径才不被每秒几十万帧的噪声淹没
|
| 577 |
+
state9 = {"failing": True}
|
| 578 |
+
|
| 579 |
+
def _read9():
|
| 580 |
+
if state9["failing"]:
|
| 581 |
+
return False, None
|
| 582 |
+
return True, frame9
|
| 583 |
+
|
| 584 |
+
cam9.read.side_effect = _read9
|
| 585 |
+
time.sleep(0.05) # 等采集线程在途的那一帧落地(失败侧 sleep 5ms)
|
| 586 |
+
|
| 587 |
+
# 相机对象的 reconnect_count 是跨段累计的:基座在 reset 时取
|
| 588 |
+
cam9.reconnect_count = 5
|
| 589 |
+
bridge9.reset_rgb_quality()
|
| 590 |
+
snap9 = bridge9.rgb_quality_snapshot()
|
| 591 |
+
check(all(v == 0 for v in snap9.values()),
|
| 592 |
+
f"reset 后全零: {snap9}")
|
| 593 |
+
check(snap9["reconnect_count"] == 0, "跨段累计的重连数减掉基座后归零")
|
| 594 |
+
|
| 595 |
+
# 停摆侧的现场:最近传输错误 + 停摆期间重连了 2 次(真机上重连发生在
|
| 596 |
+
# 停摆起初,故在等告警之前就置好;告警行报的是此刻的段内增量)
|
| 597 |
+
cam9.last_transport_error = "timed out"
|
| 598 |
+
cam9.reconnect_count = 7
|
| 599 |
+
|
| 600 |
+
# emit 滞后:payload[1] 是采集时刻,投一帧 300ms 前的 → 峰值显出来。
|
| 601 |
+
# 采集线程此时在读失败(上面 sleep 已让它停手),这帧不会被顶掉
|
| 602 |
+
bridge9._post_frame("rgb", frame9, time.monotonic_ns() - 300_000_000)
|
| 603 |
+
_pump_until(lambda: bridge9.rgb_quality_snapshot()["emit_lag_max_ms"] >= 250)
|
| 604 |
+
check(bridge9.rgb_quality_snapshot()["emit_lag_max_ms"] >= 250,
|
| 605 |
+
f"emit 峰值滞后可读: {bridge9.rgb_quality_snapshot()['emit_lag_max_ms']}ms")
|
| 606 |
+
|
| 607 |
+
# 派发滞后(主线程侧,峰值语义)
|
| 608 |
+
bridge9.note_rgb_dispatch_lag(12_000_000)
|
| 609 |
+
bridge9.note_rgb_dispatch_lag(210_000_000)
|
| 610 |
+
bridge9.note_rgb_dispatch_lag(3_000_000)
|
| 611 |
+
snap9 = bridge9.rgb_quality_snapshot()
|
| 612 |
+
check(snap9["dispatch_lag_max_ms"] == 210, "派发滞后取峰值(小的不覆盖)")
|
| 613 |
+
|
| 614 |
+
# 采集侧停摆:read() 连续失败超门槛(1s) → 进入行 + 恢复行各一行
|
| 615 |
+
_pump_until(lambda: any("RGB 采集停摆" in m for m in logs9), timeout=3.0)
|
| 616 |
+
alerts = [m for m in logs9 if "RGB 采集停摆" in m]
|
| 617 |
+
check(len(alerts) == 1,
|
| 618 |
+
f"停摆超门槛打一行(实际 {len(alerts)} 行): {alerts[:1]}")
|
| 619 |
+
if alerts:
|
| 620 |
+
check("重连 2 次" in alerts[0] and "最近错误: timed out" in alerts[0],
|
| 621 |
+
"进入行含段内重连增量与最近传输错误")
|
| 622 |
+
state9["failing"] = False
|
| 623 |
+
_pump_until(lambda: any("已恢复" in m for m in logs9), timeout=3.0)
|
| 624 |
+
recovered = [m for m in logs9 if "已恢复" in m]
|
| 625 |
+
check(len(recovered) == 1,
|
| 626 |
+
f"恢复打一行(实际 {len(recovered)} 行): {recovered[:1]}")
|
| 627 |
+
if recovered:
|
| 628 |
+
check("本段视频该处会有一段静止" in recovered[0],
|
| 629 |
+
"恢复行点明视频后果(用户看得到的现象)")
|
| 630 |
+
check("最近错误: timed out" in recovered[0],
|
| 631 |
+
"恢复行仍带停摆期间的错误(read 成功会清掉相机侧字段)")
|
| 632 |
+
snap9 = bridge9.rgb_quality_snapshot()
|
| 633 |
+
check(snap9["readfail_max_ms"] >= 1000 and snap9["readfail_stall_count"] == 1,
|
| 634 |
+
f"停摆时长入账: {snap9['readfail_max_ms']}ms / "
|
| 635 |
+
f"{snap9['readfail_stall_count']} 次")
|
| 636 |
+
check(snap9["reconnect_count"] == 2,
|
| 637 |
+
f"重连只报段内增量 5→7: {snap9['reconnect_count']}")
|
| 638 |
+
check(bridge9.rgb_quality_snapshot()["readfail_ms"]
|
| 639 |
+
>= snap9["readfail_max_ms"],
|
| 640 |
+
"累计停摆 ≥ 单次峰值")
|
| 641 |
+
# 结构约束(比逐键真值表更能防漂移):快照的**每一个**键都会被 UI 原样
|
| 642 |
+
# 加前缀塞进 drop_stats,所以任何一个不以 _ms/_count 结尾的键都会被
|
| 643 |
+
# frame_drop_total 当成帧数加进「丢帧统计」——2026-09-18 的 readfail_*
|
| 644 |
+
# 就差点这么漏进去(当时的键名 _episodes 不在后缀表里)。
|
| 645 |
+
bad = [k for k in snap9 if is_frame_drop_key(k)]
|
| 646 |
+
check(not bad, f"快照键全部不算帧数(越界的键: {bad})")
|
| 647 |
+
|
| 648 |
+
# 覆盖计数:emitter 停掉后事件没人取,pending 恒挂 → 连投两帧必覆盖一帧。
|
| 649 |
+
# 采集线程必须先停下——它自由跑时每秒投几十万帧,计数没有确定基线
|
| 650 |
+
state9["failing"] = True
|
| 651 |
+
time.sleep(0.05) # 让在途的一次成功投递落地(失败侧 sleep 5ms)
|
| 652 |
+
bridge9._events.put(("_stop", ()))
|
| 653 |
+
bridge9._emitter.join(timeout=2.0)
|
| 654 |
+
before9 = bridge9.rgb_quality_snapshot()["overwrite_count"]
|
| 655 |
+
bridge9._post_frame("rgb", frame9, time.monotonic_ns())
|
| 656 |
+
bridge9._post_frame("rgb", frame9, time.monotonic_ns())
|
| 657 |
+
check(bridge9.rgb_quality_snapshot()["overwrite_count"] == before9 + 1,
|
| 658 |
+
f"latest-wins 覆盖记账({before9} → "
|
| 659 |
+
f"{bridge9.rgb_quality_snapshot()['overwrite_count']})")
|
| 660 |
+
# 非 rgb 帧槽覆盖不记进 RGB 仪表(双目有自己的空桶看门狗)
|
| 661 |
+
bridge9._post_frame("stereo_left", frame9, time.monotonic_ns())
|
| 662 |
+
bridge9._post_frame("stereo_left", frame9, time.monotonic_ns())
|
| 663 |
+
check(bridge9.rgb_quality_snapshot()["overwrite_count"] == before9 + 1,
|
| 664 |
+
"双目槽的覆盖不混进 RGB 仪表")
|
| 665 |
+
bridge9.deleteLater()
|
| 666 |
+
|
| 667 |
if FAILS:
|
| 668 |
print(f"\nFAILED: {len(FAILS)}")
|
| 669 |
for f in FAILS:
|
|
@@ -20,7 +20,7 @@ import numpy as np
|
|
| 20 |
from PyQt5.QtWidgets import QApplication
|
| 21 |
|
| 22 |
from config import settings
|
| 23 |
-
from core.pipeline import CameraPipeline
|
| 24 |
|
| 25 |
OUT_ROOT = "/tmp/imu_pending_test"
|
| 26 |
FAILS = []
|
|
@@ -144,10 +144,18 @@ def main():
|
|
| 144 |
time.sleep(0.02)
|
| 145 |
check(bool(finished), "recording_finished 触发(_finish_async 完成)")
|
| 146 |
check(writer.ended, "writer.end_episode 被调用")
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
f"last_drop_stats 快照: {pip.last_drop_stats}")
|
| 149 |
-
check(writer.drop_stats ==
|
| 150 |
"丢帧统计注入 writer(元数据回写路径)")
|
|
|
|
|
|
|
| 151 |
|
| 152 |
print()
|
| 153 |
if FAILS:
|
|
|
|
| 20 |
from PyQt5.QtWidgets import QApplication
|
| 21 |
|
| 22 |
from config import settings
|
| 23 |
+
from core.pipeline import CameraPipeline, frame_drop_total
|
| 24 |
|
| 25 |
OUT_ROOT = "/tmp/imu_pending_test"
|
| 26 |
FAILS = []
|
|
|
|
| 144 |
time.sleep(0.02)
|
| 145 |
check(bool(finished), "recording_finished 触发(_finish_async 完成)")
|
| 146 |
check(writer.ended, "writer.end_episode 被调用")
|
| 147 |
+
# v1.3.10 起落盘侧还会记帧空洞:本用例合成的时间轴是 A(i=0)/B(i=1)/F(i=5),
|
| 148 |
+
# F 与 B 之间正好跨 4 个标称间隔(133.3ms ≥ 100ms 门槛)——这不是噪声,
|
| 149 |
+
# 正是「帧确实到了队列、但落盘行之间有空」的形态,被如实记成 1 个 100ms 的洞。
|
| 150 |
+
expect = {"ext:stereo_left": 3, "imu_overflow": 2,
|
| 151 |
+
"stereo_left_gap_ms": 100, "stereo_left_gap_max_ms": 100,
|
| 152 |
+
"stereo_left_gap_count": 1}
|
| 153 |
+
check(pip.last_drop_stats == expect,
|
| 154 |
f"last_drop_stats 快照: {pip.last_drop_stats}")
|
| 155 |
+
check(writer.drop_stats == expect,
|
| 156 |
"丢帧统计注入 writer(元数据回写路径)")
|
| 157 |
+
check(frame_drop_total(pip.last_drop_stats) == 3,
|
| 158 |
+
"帧数口径只数 ext:(空洞键不算丢帧,否则用户会被指去调编码器)")
|
| 159 |
|
| 160 |
print()
|
| 161 |
if FAILS:
|
|
@@ -22,6 +22,7 @@ import shutil
|
|
| 22 |
import subprocess
|
| 23 |
import sys
|
| 24 |
import tempfile
|
|
|
|
| 25 |
|
| 26 |
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
| 27 |
|
|
@@ -45,17 +46,22 @@ def check(name: str, cond: bool, detail: str = ""):
|
|
| 45 |
|
| 46 |
def make_synthetic_session(root: str, n: int = 30,
|
| 47 |
tactile_zero: bool = False,
|
| 48 |
-
right_only: bool = False
|
|
|
|
| 49 |
"""合成含触觉 + IMU + 骨架 + RGB/深度视频的池化 episode,返回 parquet 路径。
|
| 50 |
|
| 51 |
tactile_zero: 触觉列全零(覆盖"触觉列存在但无数据"占位提示路径)。
|
| 52 |
right_only: 只有右手触觉列(覆盖"单面板回退:无左手数据时显示右手
|
| 53 |
并渲染矩阵、面板不得隐藏"的回归路径)。
|
|
|
|
|
|
|
| 54 |
"""
|
| 55 |
task = os.path.join(root, "synthetic_task" if not tactile_zero
|
| 56 |
else "synthetic_task_zero_tactile")
|
| 57 |
if right_only:
|
| 58 |
task += "_right_only"
|
|
|
|
|
|
|
| 59 |
os.makedirs(os.path.join(task, "data", "chunk-000"))
|
| 60 |
os.makedirs(os.path.join(task, "videos", "chunk-000", "d435_rgb"))
|
| 61 |
os.makedirs(os.path.join(task, "videos", "chunk-000", "d435_depth"))
|
|
@@ -80,7 +86,7 @@ def make_synthetic_session(root: str, n: int = 30,
|
|
| 80 |
[0.05 * j, 0.012 * k, 0.0]
|
| 81 |
for k in range(1, 6) for j in range(1, 5)], np.float32)
|
| 82 |
kpts = kpts @ rot.T
|
| 83 |
-
|
| 84 |
"episode_index": 1,
|
| 85 |
"frame_index": i,
|
| 86 |
"timestamp": float(i) / 30.0,
|
|
@@ -91,8 +97,21 @@ def make_synthetic_session(root: str, n: int = 30,
|
|
| 91 |
"observation.right_glove_imu_valid": (
|
| 92 |
np.where(np.arange(16) % 5 == 0, 0.0, 1.0)).tolist(),
|
| 93 |
"observation.right_hand_pose": kpts.reshape(-1).tolist(),
|
|
|
|
| 94 |
"observation.left_hand_pose": [0.0] * 63,
|
| 95 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
cols = {
|
| 97 |
"episode_index": pa.array([r["episode_index"] for r in rows],
|
| 98 |
pa.int64()),
|
|
@@ -115,8 +134,9 @@ def make_synthetic_session(root: str, n: int = 30,
|
|
| 115 |
[r["observation.left_hand_pose"] for r in rows],
|
| 116 |
pa.list_(pa.float32(), 63)),
|
| 117 |
}
|
|
|
|
|
|
|
| 118 |
if not right_only:
|
| 119 |
-
# 左手套:只有触觉、无 IMU(覆盖"触觉有 IMU 无"的组合路径)
|
| 120 |
cols["observation.left_glove"] = pa.array(
|
| 121 |
[r["observation.right_glove"] for r in rows],
|
| 122 |
pa.list_(pa.float32(), 256))
|
|
@@ -124,6 +144,17 @@ def make_synthetic_session(root: str, n: int = 30,
|
|
| 124 |
"shape": [16, 16]}}
|
| 125 |
else:
|
| 126 |
info_left = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
parquet_path = os.path.join(task, "data", "chunk-000", "episode-000.parquet")
|
| 128 |
pq.write_table(pa.table(cols), parquet_path)
|
| 129 |
|
|
@@ -355,6 +386,21 @@ def main() -> int:
|
|
| 355 |
grid_z = mod.render_tactile_grid(np.zeros((16, 16), np.float32),
|
| 356 |
side="right", w=780, h=560)
|
| 357 |
check("渲染: 全零矩阵不崩", grid_z.shape == (560, 780, 3))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
check("渲染: 手形热图函数已移除", not hasattr(mod, "render_tactile_hand"))
|
| 359 |
check("渲染: 左右手判定", mod.glove_side_of("right_glove") == "right"
|
| 360 |
and mod.glove_side_of("left_glove") == "left"
|
|
@@ -381,6 +427,9 @@ def main() -> int:
|
|
| 381 |
and not win.chk_imu.isHidden())
|
| 382 |
check("GUI: 触觉基线勾选可见", not win.chk_tactile_baseline.isHidden()
|
| 383 |
and win.chk_tactile_baseline.isChecked())
|
|
|
|
|
|
|
|
|
|
| 384 |
check("GUI: 骨架相机距离按整段数据一次拟合(绕腕)",
|
| 385 |
abs(win._skel_dists["right"]
|
| 386 |
- mod._fit_dist(s.keypoints["right"].reshape(30, 21, 3)
|
|
@@ -442,6 +491,11 @@ def main() -> int:
|
|
| 442 |
win._on_slider_moved(20)
|
| 443 |
win._on_slider_released()
|
| 444 |
check("GUI: 播放中拖动松手落定新位置", win.idx == 20, f"idx={win.idx}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 445 |
win.next_frame() # 下一拍按新起点推进(无时间流逝→原地)
|
| 446 |
check("GUI: 播放中拖动后不被弹回", win.idx == 20, f"idx={win.idx}")
|
| 447 |
win._play_t0 -= 3.0 / win.play_fps
|
|
@@ -504,6 +558,58 @@ def main() -> int:
|
|
| 504 |
and not win4.lbl_hand.pixmap().isNull())
|
| 505 |
win4.close()
|
| 506 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
# ── 真实录制(有则测)──
|
| 508 |
repo = os.path.dirname(os.path.dirname(os.path.dirname(
|
| 509 |
os.path.abspath(__file__))))
|
|
|
|
| 22 |
import subprocess
|
| 23 |
import sys
|
| 24 |
import tempfile
|
| 25 |
+
import time
|
| 26 |
|
| 27 |
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
| 28 |
|
|
|
|
| 46 |
|
| 47 |
def make_synthetic_session(root: str, n: int = 30,
|
| 48 |
tactile_zero: bool = False,
|
| 49 |
+
right_only: bool = False,
|
| 50 |
+
both_hands: bool = False) -> str:
|
| 51 |
"""合成含触觉 + IMU + 骨架 + RGB/深度视频的池化 episode,返回 parquet 路径。
|
| 52 |
|
| 53 |
tactile_zero: 触觉列全零(覆盖"触觉列存在但无数据"占位提示路径)。
|
| 54 |
right_only: 只有右手触觉列(覆盖"单面板回退:无左手数据时显示右手
|
| 55 |
并渲染矩阵、面板不得隐藏"的回归路径)。
|
| 56 |
+
both_hands: 左右手齐全(左手也有 IMU 与非零骨架,与真实双套录制一致;
|
| 57 |
+
覆盖"双手触觉/IMU/骨架各一个面板并排、左手在左")。
|
| 58 |
"""
|
| 59 |
task = os.path.join(root, "synthetic_task" if not tactile_zero
|
| 60 |
else "synthetic_task_zero_tactile")
|
| 61 |
if right_only:
|
| 62 |
task += "_right_only"
|
| 63 |
+
if both_hands:
|
| 64 |
+
task += "_both_hands"
|
| 65 |
os.makedirs(os.path.join(task, "data", "chunk-000"))
|
| 66 |
os.makedirs(os.path.join(task, "videos", "chunk-000", "d435_rgb"))
|
| 67 |
os.makedirs(os.path.join(task, "videos", "chunk-000", "d435_depth"))
|
|
|
|
| 86 |
[0.05 * j, 0.012 * k, 0.0]
|
| 87 |
for k in range(1, 6) for j in range(1, 5)], np.float32)
|
| 88 |
kpts = kpts @ rot.T
|
| 89 |
+
row = {
|
| 90 |
"episode_index": 1,
|
| 91 |
"frame_index": i,
|
| 92 |
"timestamp": float(i) / 30.0,
|
|
|
|
| 97 |
"observation.right_glove_imu_valid": (
|
| 98 |
np.where(np.arange(16) % 5 == 0, 0.0, 1.0)).tolist(),
|
| 99 |
"observation.right_hand_pose": kpts.reshape(-1).tolist(),
|
| 100 |
+
# 左手骨架默认全零占位(恒写列,覆盖"占位列被过滤")
|
| 101 |
"observation.left_hand_pose": [0.0] * 63,
|
| 102 |
+
}
|
| 103 |
+
if both_hands:
|
| 104 |
+
# 左手 IMU:绕 X 转 90° 的定值姿态(与右手的单位姿态可区分)
|
| 105 |
+
row["observation.left_glove_imu_quat"] = (np.tile(
|
| 106 |
+
[math.sqrt(0.5), 0.0, 0.0, math.sqrt(0.5)], 16) +
|
| 107 |
+
rng.normal(0, 0.02, 64)).tolist()
|
| 108 |
+
row["observation.left_glove_imu_valid"] = (
|
| 109 |
+
np.where(np.arange(16) % 3 == 0, 0.0, 1.0)).tolist()
|
| 110 |
+
# 左手骨架:右手模板镜像 X(手性不同,与右手面板可区分)
|
| 111 |
+
row["observation.left_hand_pose"] = (
|
| 112 |
+
kpts * np.array([-1.0, 1.0, 1.0], np.float32)
|
| 113 |
+
).reshape(-1).tolist()
|
| 114 |
+
rows.append(row)
|
| 115 |
cols = {
|
| 116 |
"episode_index": pa.array([r["episode_index"] for r in rows],
|
| 117 |
pa.int64()),
|
|
|
|
| 134 |
[r["observation.left_hand_pose"] for r in rows],
|
| 135 |
pa.list_(pa.float32(), 63)),
|
| 136 |
}
|
| 137 |
+
# 左手套默认只有触觉、无 IMU(覆盖"两手:触觉有 IMU 无"的组合路径),
|
| 138 |
+
# both_hands 时才算齐全
|
| 139 |
if not right_only:
|
|
|
|
| 140 |
cols["observation.left_glove"] = pa.array(
|
| 141 |
[r["observation.right_glove"] for r in rows],
|
| 142 |
pa.list_(pa.float32(), 256))
|
|
|
|
| 144 |
"shape": [16, 16]}}
|
| 145 |
else:
|
| 146 |
info_left = {}
|
| 147 |
+
if both_hands:
|
| 148 |
+
cols["observation.left_glove_imu_quat"] = pa.array(
|
| 149 |
+
[r["observation.left_glove_imu_quat"] for r in rows],
|
| 150 |
+
pa.list_(pa.float32(), 64))
|
| 151 |
+
cols["observation.left_glove_imu_valid"] = pa.array(
|
| 152 |
+
[r["observation.left_glove_imu_valid"] for r in rows],
|
| 153 |
+
pa.list_(pa.float32(), 16))
|
| 154 |
+
info_left["observation.left_glove_imu_quat"] = {
|
| 155 |
+
"dtype": "float32", "shape": [16, 4]}
|
| 156 |
+
info_left["observation.left_glove_imu_valid"] = {
|
| 157 |
+
"dtype": "float32", "shape": [16]}
|
| 158 |
parquet_path = os.path.join(task, "data", "chunk-000", "episode-000.parquet")
|
| 159 |
pq.write_table(pa.table(cols), parquet_path)
|
| 160 |
|
|
|
|
| 386 |
grid_z = mod.render_tactile_grid(np.zeros((16, 16), np.float32),
|
| 387 |
side="right", w=780, h=560)
|
| 388 |
check("渲染: 全零矩阵不崩", grid_z.shape == (560, 780, 3))
|
| 389 |
+
|
| 390 |
+
# 手指分区框要扣在"该手指的行落点"上:左手行序镜像(拇指 15-13),
|
| 391 |
+
# 翻转后拇指框仍在画面左侧 —— 旧写法把左右手的框整体对调了
|
| 392 |
+
def _leftmost(img, bgr):
|
| 393 |
+
m = np.all(img == np.array(bgr, np.uint8), axis=-1)
|
| 394 |
+
xs = np.nonzero(m.any(axis=0))[0]
|
| 395 |
+
return int(xs.min()) if len(xs) else -1
|
| 396 |
+
|
| 397 |
+
for _side in ("right", "left"):
|
| 398 |
+
g = mod.render_tactile_grid(np.zeros((16, 16), np.float32),
|
| 399 |
+
side=_side, w=780, h=560)
|
| 400 |
+
_t = _leftmost(g, mod._TACTILE_FINGER_BGR[0]) # Thumb 红
|
| 401 |
+
_p = _leftmost(g, mod._TACTILE_FINGER_BGR[4]) # Pinky 紫
|
| 402 |
+
check(f"渲染: {_side} 拇指框在小指框左边(拇指统一朝左)",
|
| 403 |
+
0 <= _t < _p, f"thumb@x={_t} pinky@x={_p}")
|
| 404 |
check("渲染: 手形热图函数已移除", not hasattr(mod, "render_tactile_hand"))
|
| 405 |
check("渲染: 左右手判定", mod.glove_side_of("right_glove") == "right"
|
| 406 |
and mod.glove_side_of("left_glove") == "left"
|
|
|
|
| 427 |
and not win.chk_imu.isHidden())
|
| 428 |
check("GUI: 触觉基线勾选可见", not win.chk_tactile_baseline.isHidden()
|
| 429 |
and win.chk_tactile_baseline.isChecked())
|
| 430 |
+
check("GUI: 触觉左右手各一个面板(左手在左)",
|
| 431 |
+
win.tactile_sensors == ["left_glove", "right_glove"],
|
| 432 |
+
f"{win.tactile_sensors}")
|
| 433 |
check("GUI: 骨架相机距离按整段数据一次拟合(绕腕)",
|
| 434 |
abs(win._skel_dists["right"]
|
| 435 |
- mod._fit_dist(s.keypoints["right"].reshape(30, 21, 3)
|
|
|
|
| 491 |
win._on_slider_moved(20)
|
| 492 |
win._on_slider_released()
|
| 493 |
check("GUI: 播放中拖动松手落定新位置", win.idx == 20, f"idx={win.idx}")
|
| 494 |
+
# 归零已流逝时间再 tick:上面的松手渲染本身要几十毫秒(深度 seek +
|
| 495 |
+
# 两路触觉网格),真实墙钟会漏进"无时间流逝"里 —— 渲染恰好跨过一
|
| 496 |
+
# 帧就假失败。与下面 -3.0/fps 是同一个套路:这条断言要测的是
|
| 497 |
+
# "tick 不重设节奏起点",不是渲染耗时。
|
| 498 |
+
win._play_t0 = time.perf_counter() - win.idx / win.play_fps
|
| 499 |
win.next_frame() # 下一拍按新起点推进(无时间流逝→原地)
|
| 500 |
check("GUI: 播放中拖动后不被弹回", win.idx == 20, f"idx={win.idx}")
|
| 501 |
win._play_t0 -= 3.0 / win.play_fps
|
|
|
|
| 558 |
and not win4.lbl_hand.pixmap().isNull())
|
| 559 |
win4.close()
|
| 560 |
|
| 561 |
+
# ── 左右手齐全(新数据形态:两只手套都有触觉 + IMU + 骨架)──
|
| 562 |
+
p5 = make_synthetic_session(tmp, both_hands=True)
|
| 563 |
+
s5 = mod.PooledSession(p5)
|
| 564 |
+
check("双手: 数据层两手齐全",
|
| 565 |
+
set(s5.tactile) == {"left_glove", "right_glove"}
|
| 566 |
+
and set(s5.imu_quats) == {"left_glove", "right_glove"}
|
| 567 |
+
and set(s5.keypoints) == {"left", "right"})
|
| 568 |
+
q5, v5 = s5.imu_frame("left_glove", 0)
|
| 569 |
+
check("渲染: IMU 标题带传感器名(左右手可区分)",
|
| 570 |
+
not np.array_equal(
|
| 571 |
+
mod.render_imu_panel(q5, v5, w=640, h=240,
|
| 572 |
+
label="left_glove"),
|
| 573 |
+
mod.render_imu_panel(q5, v5, w=640, h=240,
|
| 574 |
+
label="right_glove")),
|
| 575 |
+
"同一份四元数、只有标题不同 → 画布必须不同")
|
| 576 |
+
win5 = mod.DemoWindow()
|
| 577 |
+
# IMU 面板的渲染闸门是 isVisible()(窗口 show 过才为真),别的
|
| 578 |
+
# 用例只查 isHidden() 所以不用 show;这条要真渲染 IMU 就得 show
|
| 579 |
+
win5.show()
|
| 580 |
+
app.processEvents()
|
| 581 |
+
win5.load(p5)
|
| 582 |
+
app.processEvents()
|
| 583 |
+
check("双手: 触觉左右各一个面板(左手在左)",
|
| 584 |
+
win5.tactile_sensors == ["left_glove", "right_glove"])
|
| 585 |
+
# 截下 _show_image 的入参:面板数直接看拼出来的画布宽度,比数
|
| 586 |
+
# pixmap 可靠(pixmap 是缩放后的,看不出几块)
|
| 587 |
+
grabbed = {}
|
| 588 |
+
orig_show = mod.DemoWindow.__dict__["_show_image"]
|
| 589 |
+
mod.DemoWindow._show_image = staticmethod(
|
| 590 |
+
lambda lbl, bgr: grabbed.__setitem__(lbl, np.asarray(bgr)))
|
| 591 |
+
try:
|
| 592 |
+
win5.render_frame(0)
|
| 593 |
+
app.processEvents()
|
| 594 |
+
win5.chk_imu.setChecked(True) # 有骨架时 IMU 默认隐藏
|
| 595 |
+
app.processEvents()
|
| 596 |
+
finally:
|
| 597 |
+
mod.DemoWindow._show_image = orig_show
|
| 598 |
+
hand_img = grabbed[win5.lbl_hand]
|
| 599 |
+
pw = max(680, (win5.lbl_hand.width() - 24) // 2)
|
| 600 |
+
check("双手: 触觉画布 = 左右两块并排 + 24px 间隙",
|
| 601 |
+
hand_img.shape[1] == 2 * pw + 24,
|
| 602 |
+
f"{hand_img.shape[1]} vs {2 * pw + 24}")
|
| 603 |
+
sw = max(480, (win5.lbl_skel.width() or 1280) // 2)
|
| 604 |
+
check("双手: 骨架画布 = 左右两块并排 + 8px 间隙",
|
| 605 |
+
grabbed[win5.lbl_skel].shape[1] == 2 * sw + 8,
|
| 606 |
+
f"{grabbed[win5.lbl_skel].shape[1]} vs {2 * sw + 8}")
|
| 607 |
+
iw = max(((win5.lbl_imu.width() or 880) - 4) // 2, 480)
|
| 608 |
+
check("双手: IMU 画布 = 左右两块并排 + 4px 间隙",
|
| 609 |
+
grabbed[win5.lbl_imu].shape[1] == 2 * iw + 4,
|
| 610 |
+
f"{grabbed[win5.lbl_imu].shape[1]} vs {2 * iw + 4}")
|
| 611 |
+
win5.close()
|
| 612 |
+
|
| 613 |
# ── 真实录制(有则测)──
|
| 614 |
repo = os.path.dirname(os.path.dirname(os.path.dirname(
|
| 615 |
os.path.abspath(__file__))))
|
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RawStallWatch 原始流接收停滞看门狗单测(v1.3.11 L0-2)。
|
| 2 |
+
|
| 3 |
+
覆盖:首包不产生间隔、正常包距静默、>stall 计数但不打行、≥alert 打一行、
|
| 4 |
+
repeat 内不重复、恢复后重新武装、单调钟倒退忽略、reset 全清。
|
| 5 |
+
|
| 6 |
+
它守的那条链(2026-09-18 查实):SLAM 进程是原始流的**服务端**,16 包队列
|
| 7 |
+
≈0.53s 满就判 stereo loss 并主动 close;客户端接收线程一旦被 GIL 卡住
|
| 8 |
+
(当时怀疑是 ``_write_data_parquet`` 建力矩阵列 1.6s×2),断链就必然发生。
|
| 9 |
+
这个类的读数就是把那条推断变成数字——所以阈值与去抖行为必须钉死。
|
| 10 |
+
|
| 11 |
+
用法:
|
| 12 |
+
venv/bin/python tools/tests/test_raw_stall_watch.py
|
| 13 |
+
"""
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
|
| 17 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 18 |
+
|
| 19 |
+
from core.gripper.rgb_quality import RawStallWatch
|
| 20 |
+
|
| 21 |
+
MS = 1_000_000
|
| 22 |
+
STALL_NS = 100 * MS # >100ms 计入
|
| 23 |
+
ALERT_NS = 300 * MS # ≥300ms 打行
|
| 24 |
+
REPEAT_NS = 5_000 * MS
|
| 25 |
+
|
| 26 |
+
FAILS = []
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def check(cond, msg):
|
| 30 |
+
if cond:
|
| 31 |
+
print(f" PASS: {msg}")
|
| 32 |
+
else:
|
| 33 |
+
print(f" FAIL: {msg}")
|
| 34 |
+
FAILS.append(msg)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def make():
|
| 38 |
+
return RawStallWatch(stall_ns=STALL_NS, alert_ns=ALERT_NS,
|
| 39 |
+
repeat_ns=REPEAT_NS)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def main():
|
| 43 |
+
# ── 首包与健康包距 ─────────────────────────────────────
|
| 44 |
+
w = make()
|
| 45 |
+
check(w.note_recv(1_000 * MS) == [], "首包无前驱 → 不产生间隔、不打行")
|
| 46 |
+
s = w.snapshot()
|
| 47 |
+
check(s["gap_max_ns"] == 0 and s["stall_count"] == 0 and s["packets"] == 1,
|
| 48 |
+
"首包只计包数")
|
| 49 |
+
check(w.note_recv(1_004 * MS) == [], "正常包距(4ms)静默")
|
| 50 |
+
check(w.note_recv(1_008 * MS) == [], "连续正常包距静默")
|
| 51 |
+
s = w.snapshot()
|
| 52 |
+
check(s["gap_max_ns"] == 4 * MS, "峰值记到 4ms")
|
| 53 |
+
check(s["stall_count"] == 0 and s["stall_ns"] == 0, "正常包距不计停滞")
|
| 54 |
+
|
| 55 |
+
# ── 门槛边界 ───────────────────────────────────────────
|
| 56 |
+
w = make()
|
| 57 |
+
w.note_recv(0)
|
| 58 |
+
check(w.note_recv(STALL_NS - 1) == [], "恰好低于 stall 门槛 → 不计")
|
| 59 |
+
check(w.snapshot()["stall_count"] == 0, "低于门槛不计数")
|
| 60 |
+
check(w.note_recv(2 * STALL_NS - 1) == [], "恰好等于门槛 → 计数但不打行")
|
| 61 |
+
s = w.snapshot()
|
| 62 |
+
check(s["stall_count"] == 1 and s["stall_ns"] == STALL_NS,
|
| 63 |
+
f"命中门槛计入 1 次({s['stall_count']} 次 / {s['stall_ns']}ns)")
|
| 64 |
+
|
| 65 |
+
# ── ≥alert 打一行,repeat 内不重复 ─────────────────────
|
| 66 |
+
w = make()
|
| 67 |
+
w.note_recv(0)
|
| 68 |
+
lines = w.note_recv(ALERT_NS)
|
| 69 |
+
check(len(lines) == 1, f"≥alert 打一行(实际 {len(lines)} 行)")
|
| 70 |
+
check("停滞 300ms" in lines[0] and "本段已停顿 1 次" in lines[0],
|
| 71 |
+
f"行内含毫秒与累计次数: {lines[0]}")
|
| 72 |
+
got = w.note_recv(ALERT_NS + ALERT_NS) # 再停 300ms
|
| 73 |
+
check(got == [], "repeat 窗口内不重复打行")
|
| 74 |
+
got = w.note_recv(ALERT_NS * 2 + REPEAT_NS) # 距上次告警已过 repeat
|
| 75 |
+
check(len(got) == 1 and "仍未恢复" in got[0],
|
| 76 |
+
f"超 repeat 打「仍未恢复」行: {got[:1]}")
|
| 77 |
+
s = w.snapshot()
|
| 78 |
+
check(s["stall_count"] == 3, "三次停顿全计数")
|
| 79 |
+
check(s["gap_max_ns"] == REPEAT_NS and s["stall_ns"] == ALERT_NS * 2 + REPEAT_NS,
|
| 80 |
+
f"峰值取最大({s['gap_max_ns'] // MS}ms)、总停顿累加"
|
| 81 |
+
f"({s['stall_ns'] // MS}ms)")
|
| 82 |
+
|
| 83 |
+
# ── 恢复 → 重新武装 ────────────────────────────────────
|
| 84 |
+
w = make()
|
| 85 |
+
w.note_recv(0)
|
| 86 |
+
check(len(w.note_recv(ALERT_NS)) == 1, "第一次抽风打行")
|
| 87 |
+
check(w.note_recv(ALERT_NS + 2 * MS) == [], "恢复正常包距不打行")
|
| 88 |
+
lines = w.note_recv(ALERT_NS + 2 * MS + ALERT_NS)
|
| 89 |
+
check(len(lines) == 1 and "停滞 300ms" in lines[0],
|
| 90 |
+
"恢复后再次抽风重新打「进入」行(不是「仍未恢复」)")
|
| 91 |
+
|
| 92 |
+
# ── 单调钟倒退(防御)──────────────────────────────────
|
| 93 |
+
w = make()
|
| 94 |
+
w.note_recv(10 * MS)
|
| 95 |
+
check(w.note_recv(9 * MS) == [], "时间倒退不打行")
|
| 96 |
+
s = w.snapshot()
|
| 97 |
+
check(s["gap_max_ns"] == 0 and s["stall_count"] == 0, "倒退不计停滞")
|
| 98 |
+
check(s["packets"] == 2, "倒退仍计包数(包确实到了)")
|
| 99 |
+
|
| 100 |
+
# ── reset ──────────────────────────────────────────────
|
| 101 |
+
w = make()
|
| 102 |
+
w.note_recv(0)
|
| 103 |
+
w.note_recv(ALERT_NS)
|
| 104 |
+
w.reset()
|
| 105 |
+
s = w.snapshot()
|
| 106 |
+
check(all(v == 0 for v in s.values()), f"reset 全清: {s}")
|
| 107 |
+
check(w.note_recv(0) == [], "reset 后重新等首包")
|
| 108 |
+
|
| 109 |
+
# ── 真实场景:断链黑洞(跨重连的��隔也要计)────────────
|
| 110 |
+
w = make()
|
| 111 |
+
w.note_recv(0)
|
| 112 |
+
lines = w.note_recv(1_200 * MS) # 断链 → 1.2s 后重连首包
|
| 113 |
+
s = w.snapshot()
|
| 114 |
+
check(s["gap_max_ns"] == 1_200 * MS, "跨断链的 1.2s 黑洞计入峰值")
|
| 115 |
+
check(len(lines) == 1 and "1200ms" in lines[0],
|
| 116 |
+
f"黑洞同样打行(这是「停止即断链」最直接的读数): {lines[:1]}")
|
| 117 |
+
|
| 118 |
+
print()
|
| 119 |
+
if FAILS:
|
| 120 |
+
print(f"FAIL: {len(FAILS)} 项未通过")
|
| 121 |
+
return 1
|
| 122 |
+
print("PASS: RawStallWatch 单测全部通过")
|
| 123 |
+
return 0
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
sys.exit(main())
|
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""RgbReadWatch / MaxLagWatch 单测(v1.3.10)。
|
| 2 |
+
|
| 3 |
+
覆盖:三态告警(进入/限频/恢复)、**门槛边界不许提前开火**、短促抖动静默但记账、
|
| 4 |
+
恢复行的停摆时长、进行中的停摆计入快照、覆盖计数、滞后峰值、reset。
|
| 5 |
+
|
| 6 |
+
去抖契约照抄 core/gripper/slam/process_controller.py 的 FaysRateAlarm:健康态静默,
|
| 7 |
+
一次抽风只留两行(进入 + 恢复),长期故障按 repeat 限频。这里的断言就是那个契约。
|
| 8 |
+
|
| 9 |
+
用法:
|
| 10 |
+
venv/bin/python tools/tests/test_rgb_quality.py
|
| 11 |
+
"""
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 16 |
+
|
| 17 |
+
from core.gripper.rgb_quality import MaxLagWatch, RgbReadWatch
|
| 18 |
+
|
| 19 |
+
ALERT_NS = 1_000_000_000 # 1s
|
| 20 |
+
REPEAT_NS = 30_000_000_000 # 30s
|
| 21 |
+
T0 = 1_000_000_000_000
|
| 22 |
+
|
| 23 |
+
FAILS = []
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def check(cond, msg):
|
| 27 |
+
if cond:
|
| 28 |
+
print(f" PASS: {msg}")
|
| 29 |
+
else:
|
| 30 |
+
print(f" FAIL: {msg}")
|
| 31 |
+
FAILS.append(msg)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def new_watch():
|
| 35 |
+
return RgbReadWatch(alert_ns=ALERT_NS, repeat_ns=REPEAT_NS, tag="夹爪-RGB")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def main():
|
| 39 |
+
# ── 健康态:完全静默 ────────────────────────────────────
|
| 40 |
+
w = new_watch()
|
| 41 |
+
check(w.note_ok(T0) == [], "健康帧不产生日志行")
|
| 42 |
+
check(w.note_ok(T0 + 33_000_000) == [], "持续健康仍然静默")
|
| 43 |
+
s = w.snapshot()
|
| 44 |
+
check(s == {"readfail_ns": 0, "readfail_max_ns": 0,
|
| 45 |
+
"readfail_stall_count": 0, "overwrite_count": 0},
|
| 46 |
+
f"健康态快照全零: {s}")
|
| 47 |
+
|
| 48 |
+
# ── 门槛边界:alert-1ns 不许开火 ────────────────────────
|
| 49 |
+
w = new_watch()
|
| 50 |
+
w.note_fail(T0)
|
| 51 |
+
check(w.note_fail(T0 + ALERT_NS - 1) == [],
|
| 52 |
+
"停摆 = 门槛-1ns → 不开火(防误报的关键断言)")
|
| 53 |
+
lines = w.note_fail(T0 + ALERT_NS)
|
| 54 |
+
check(len(lines) == 1, "停摆 = 门槛 → 开火一次")
|
| 55 |
+
print(f" {lines[0]}")
|
| 56 |
+
check("RGB 采集停摆 1.0s" in lines[0] and lines[0].startswith("[夹爪-RGB告警]"),
|
| 57 |
+
"进入行含停摆时长与标签")
|
| 58 |
+
check(lines[0].count(";最近错误") == 0, "无错误信息时不留空尾巴")
|
| 59 |
+
|
| 60 |
+
# ── 限频:repeat 之前闭嘴,到点再喊一次 ─────────────────
|
| 61 |
+
check(w.note_fail(T0 + ALERT_NS + REPEAT_NS - 1) == [],
|
| 62 |
+
"持续停摆未到 repeat → 静默(不刷屏)")
|
| 63 |
+
lines = w.note_fail(T0 + ALERT_NS + REPEAT_NS)
|
| 64 |
+
check(len(lines) == 1 and "仍未恢复" in lines[0],
|
| 65 |
+
"到 repeat → 打一行「仍未恢复」")
|
| 66 |
+
print(f" {lines[0]}")
|
| 67 |
+
check(w.note_fail(T0 + ALERT_NS + REPEAT_NS + 1) == [],
|
| 68 |
+
"重复行之后立刻又静默(限频生效)")
|
| 69 |
+
|
| 70 |
+
# ── 恢复:收尾一行 + 记账 ──────────────────────────────
|
| 71 |
+
stall_end = T0 + 4_680_800_000
|
| 72 |
+
lines = w.note_ok(stall_end, reconnects=2, error="timed out")
|
| 73 |
+
check(len(lines) == 1 and "已恢复" in lines[0], "报过警的停摆恢复时打一行收尾")
|
| 74 |
+
print(f" {lines[0]}")
|
| 75 |
+
check("停摆 4.7s" in lines[0] and "重连 2 次" in lines[0]
|
| 76 |
+
and "最近错误: timed out" in lines[0], "恢复行含停摆时长/重连/最近错误")
|
| 77 |
+
check("本段视频该处会有一段静止" in lines[0], "恢复行点明视频后果(用户看得到的现象)")
|
| 78 |
+
s = w.snapshot()
|
| 79 |
+
check(s["readfail_ns"] == 4_680_800_000, "恢复后停摆时长入账")
|
| 80 |
+
check(s["readfail_max_ns"] == 4_680_800_000, "峰值入账")
|
| 81 |
+
check(s["readfail_stall_count"] == 1, "停摆次数 1")
|
| 82 |
+
check(w.note_ok(stall_end + 33_000_000) == [], "恢复之后回到静默")
|
| 83 |
+
|
| 84 |
+
# ── 短促抖动:静默但记账(不许因为没报警就不算数)────────
|
| 85 |
+
w = new_watch()
|
| 86 |
+
w.note_fail(T0)
|
| 87 |
+
w.note_fail(T0 + 200_000_000)
|
| 88 |
+
check(w.note_ok(T0 + 300_000_000) == [], "未达门槛的抖动不产生任何日志行")
|
| 89 |
+
s = w.snapshot()
|
| 90 |
+
check(s["readfail_ns"] == 300_000_000 and s["readfail_stall_count"] == 1,
|
| 91 |
+
"未报警的停摆照样入账(日志静默 ≠ 没发生)")
|
| 92 |
+
|
| 93 |
+
# ── 多次停摆:累计 + 取最大 ────────────────────────────
|
| 94 |
+
w = new_watch()
|
| 95 |
+
w.note_fail(T0)
|
| 96 |
+
w.note_ok(T0 + 2_000_000_000)
|
| 97 |
+
w.note_fail(T0 + 10_000_000_000)
|
| 98 |
+
w.note_ok(T0 + 11_000_000_000)
|
| 99 |
+
s = w.snapshot()
|
| 100 |
+
check(s["readfail_ns"] == 3_000_000_000, "两次停摆累计 3s")
|
| 101 |
+
check(s["readfail_max_ns"] == 2_000_000_000, "峰值取大的那次(2s)")
|
| 102 |
+
check(s["readfail_stall_count"] == 2, "停摆次数 2")
|
| 103 |
+
|
| 104 |
+
# ── 进行中的停摆:给 now_ns 才计入 ──────────────────────
|
| 105 |
+
w = new_watch()
|
| 106 |
+
w.note_fail(T0)
|
| 107 |
+
check(w.snapshot()["readfail_ns"] == 0,
|
| 108 |
+
"不给 now_ns → 进行中的停摆不计(快���是「已闭合」口径)")
|
| 109 |
+
s = w.snapshot(now_ns=T0 + 5_000_000_000)
|
| 110 |
+
check(s["readfail_ns"] == 5_000_000_000 and s["readfail_max_ns"] == 5_000_000_000
|
| 111 |
+
and s["readfail_stall_count"] == 1, "给 now_ns → 进行中的停摆也计入")
|
| 112 |
+
check(w.snapshot(now_ns=T0 + 7_000_000_000)["readfail_ns"] == 7_000_000_000,
|
| 113 |
+
"进行中停摆随 now_ns 增长(录制中途停摆也能报出时长)")
|
| 114 |
+
|
| 115 |
+
# ── 错误信息:只在报过警的恢复行里出现,且截断 ──────────
|
| 116 |
+
w = new_watch()
|
| 117 |
+
w.note_fail(T0)
|
| 118 |
+
check(w.note_ok(T0 + ALERT_NS, reconnects=1, error="timed out") == [],
|
| 119 |
+
"未达门槛的停摆即使有传输错误也静默(重连次数另有 _reconnect_count 兜底)")
|
| 120 |
+
|
| 121 |
+
w = new_watch()
|
| 122 |
+
w.note_fail(T0)
|
| 123 |
+
w.note_fail(T0 + ALERT_NS) # 先真的报一次警
|
| 124 |
+
lines = w.note_ok(T0 + 2 * ALERT_NS, error="x" * 500)
|
| 125 |
+
check(len(lines) == 1 and lines[0].count("x") == 60,
|
| 126 |
+
"超长错误信息截断到 60 字符(不刷屏)")
|
| 127 |
+
|
| 128 |
+
# ── 覆盖计数 ───────────────────────────────────────────
|
| 129 |
+
w = new_watch()
|
| 130 |
+
w.note_overwrite()
|
| 131 |
+
w.note_overwrite(36)
|
| 132 |
+
check(w.snapshot()["overwrite_count"] == 37, "覆盖计数累加")
|
| 133 |
+
check(w.note_ok(T0) == [] and w.snapshot()["readfail_ns"] == 0,
|
| 134 |
+
"覆盖计数与采集停顿互不干扰")
|
| 135 |
+
|
| 136 |
+
# ── reset ──────────────────────────────────────────────
|
| 137 |
+
w = new_watch()
|
| 138 |
+
w.note_fail(T0)
|
| 139 |
+
w.note_ok(T0 + 2_000_000_000)
|
| 140 |
+
w.note_overwrite(5)
|
| 141 |
+
w.reset()
|
| 142 |
+
s = w.snapshot()
|
| 143 |
+
check(s == {"readfail_ns": 0, "readfail_max_ns": 0,
|
| 144 |
+
"readfail_stall_count": 0, "overwrite_count": 0}, "reset 全清")
|
| 145 |
+
check(w.note_fail(T0 + 10_000_000_000) == [],
|
| 146 |
+
"reset 后重新计门槛(不继承上一段的停摆起点)")
|
| 147 |
+
|
| 148 |
+
# ── MaxLagWatch ────────────────────────────────────────
|
| 149 |
+
m = MaxLagWatch("emit")
|
| 150 |
+
check(m.snapshot() == {"lag_max_ns": 0, "lag_samples": 0}, "初始零")
|
| 151 |
+
m.note(5_000_000)
|
| 152 |
+
m.note(210_000_000)
|
| 153 |
+
m.note(12_000_000)
|
| 154 |
+
s = m.snapshot()
|
| 155 |
+
check(s["lag_max_ns"] == 210_000_000, "取峰值(平均值会被 30Hz 小抖动稀释)")
|
| 156 |
+
check(s["lag_samples"] == 3, "样本数 3")
|
| 157 |
+
m.note(-1)
|
| 158 |
+
check(m.snapshot()["lag_samples"] == 3, "负滞后丢弃(时钟毛刺不算样本)")
|
| 159 |
+
m.note(0)
|
| 160 |
+
check(m.snapshot()["lag_samples"] == 4 and m.snapshot()["lag_max_ns"] == 210_000_000,
|
| 161 |
+
"0 是合法滞后(正好赶上)")
|
| 162 |
+
m.reset()
|
| 163 |
+
check(m.snapshot() == {"lag_max_ns": 0, "lag_samples": 0}, "reset 全清")
|
| 164 |
+
|
| 165 |
+
print()
|
| 166 |
+
if FAILS:
|
| 167 |
+
print(f"FAIL: {len(FAILS)} 项未通过")
|
| 168 |
+
return 1
|
| 169 |
+
print("PASS: rgb_quality 单测全部通过")
|
| 170 |
+
return 0
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
sys.exit(main())
|
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stopwatch 收尾分段计时单测(v1.3.11 L0-1)。
|
| 2 |
+
|
| 3 |
+
覆盖:lap 语义(距上一次 lap)、同名累加、未命中阶段显示 0ms 而不是省略、
|
| 4 |
+
order 钉顺序、total_ms、snapshot 是副本。
|
| 5 |
+
|
| 6 |
+
这个类只被停止通路调用(持 GIL 的窗口里),所以它的契约里有一条不成文的
|
| 7 |
+
要求:**别把 lap 写成会 sleep/分配大对象的东西**。测试里顺带钉住「format
|
| 8 |
+
不抛异常、不依赖阶段是否命中」,因为日志行是在 end_episode 之后打的,
|
| 9 |
+
一旦它抛异常,整个收尾线程会静默死掉(daemon 线程无人看)。
|
| 10 |
+
|
| 11 |
+
用法:
|
| 12 |
+
venv/bin/python tools/tests/test_stopwatch.py
|
| 13 |
+
"""
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 19 |
+
|
| 20 |
+
from core.timing import Stopwatch
|
| 21 |
+
|
| 22 |
+
FAILS = []
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def check(cond, msg):
|
| 26 |
+
if cond:
|
| 27 |
+
print(f" PASS: {msg}")
|
| 28 |
+
else:
|
| 29 |
+
print(f" FAIL: {msg}")
|
| 30 |
+
FAILS.append(msg)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def main():
|
| 34 |
+
# ── 空表 ───────────────────────────────────────────────
|
| 35 |
+
sw = Stopwatch()
|
| 36 |
+
check(sw.snapshot() == {}, "空表:没有阶段")
|
| 37 |
+
check(sw.total_ms() == 0, "空表:total 0")
|
| 38 |
+
check(sw.format() == "", "空表:format 是空串")
|
| 39 |
+
|
| 40 |
+
# ── lap 语义 ───────────────────────────────────────────
|
| 41 |
+
sw = Stopwatch()
|
| 42 |
+
time.sleep(0.02)
|
| 43 |
+
ms = sw.lap("a")
|
| 44 |
+
check(20 <= ms < 400, f"lap 记的是距上一次 lap 的耗时(实测 {ms}ms)")
|
| 45 |
+
ms2 = sw.lap("b")
|
| 46 |
+
check(ms2 < 20, f"紧邻的 lap 接近 0(实测 {ms2}ms)")
|
| 47 |
+
check(sw.snapshot() == {"a": ms, "b": ms2}, "snapshot 保留插入序")
|
| 48 |
+
|
| 49 |
+
# ── 同名累加(多路 ffmpeg / 同一段被调多次)──────────────
|
| 50 |
+
sw = Stopwatch()
|
| 51 |
+
sw.lap("flush")
|
| 52 |
+
time.sleep(0.01)
|
| 53 |
+
sw.lap("flush")
|
| 54 |
+
got = sw.snapshot()["flush"]
|
| 55 |
+
check(10 <= got < 400, f"同名 lap 累加而不是覆盖(实测 {got}ms,应≥10)")
|
| 56 |
+
check(list(sw.snapshot()) == ["flush"], "累加后仍只有一个键")
|
| 57 |
+
|
| 58 |
+
# ── add:并入别处测得的耗时(writer 的 flush/parquet/meta)──
|
| 59 |
+
sw = Stopwatch()
|
| 60 |
+
sw.lap("join")
|
| 61 |
+
sw.add("flush", 1500)
|
| 62 |
+
sw.add("parquet", 3200)
|
| 63 |
+
sw.add("flush", 100)
|
| 64 |
+
snap = sw.snapshot()
|
| 65 |
+
check(snap["flush"] == 1600, "add 也累加")
|
| 66 |
+
check(sw.total_ms() == snap["join"] + 1600 + 3200, "total = 各段之和")
|
| 67 |
+
|
| 68 |
+
# ── format:未命中的阶段显示 0ms,不省略 ────────────────
|
| 69 |
+
sw = Stopwatch()
|
| 70 |
+
sw.add("flush", 12)
|
| 71 |
+
sw.add("parquet", 34)
|
| 72 |
+
check("flush=12ms parquet=34ms" in sw.format(), "format 输出键=值ms")
|
| 73 |
+
order = ["join", "flush", "parquet", "meta"]
|
| 74 |
+
txt = sw.format(order)
|
| 75 |
+
check(txt == "join=0ms flush=12ms parquet=34ms meta=0ms",
|
| 76 |
+
f"order 钉顺序且未命中显示 0ms(得到 {txt!r})")
|
| 77 |
+
check(sw.format([]) == "", "order 为空 → 空串")
|
| 78 |
+
|
| 79 |
+
# ── snapshot 是副本(调用方改不动内部状态)──────────────
|
| 80 |
+
sw = Stopwatch()
|
| 81 |
+
sw.add("a", 5)
|
| 82 |
+
snap = sw.snapshot()
|
| 83 |
+
snap["a"] = 999
|
| 84 |
+
check(sw.snapshot()["a"] == 5, "snapshot 返回副本")
|
| 85 |
+
|
| 86 |
+
print()
|
| 87 |
+
if FAILS:
|
| 88 |
+
print(f"FAIL: {len(FAILS)} 项未通过")
|
| 89 |
+
return 1
|
| 90 |
+
print("PASS: Stopwatch 单测全部通过")
|
| 91 |
+
return 0
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
sys.exit(main())
|