diff --git a/.github/workflows/camera-studio.yml b/.github/workflows/camera-studio.yml index 2437b0e..c9c5374 100644 --- a/.github/workflows/camera-studio.yml +++ b/.github/workflows/camera-studio.yml @@ -41,10 +41,10 @@ jobs: $ErrorActionPreference = "Stop" $base = "https://rdkstudio.bj.bcebos.com/rdkstudio-new/win32" $installer = Join-Path $env:RUNNER_TEMP "studio-installer.exe" - curl.exe -fLsS --retry 2 --max-time 240 -o $installer "$base/RDK%20Studio%20Setup%201.5.8.exe" + curl.exe -fLsS --retry 2 --max-time 420 -o $installer "$base/RDK%20Studio%20Setup%201.7.0.exe" if ($LASTEXITCODE -ne 0) { throw "Studio download failed" } $actual = [Convert]::ToBase64String([Security.Cryptography.SHA512]::HashData([IO.File]::ReadAllBytes($installer))) - if ($actual -ne "qqbJOHcWnddZSHkBHR+0T4nKftZhRrKBaSgLmlhK4NTcbvSoiNEXfGedHQyfLGFTW7lgfjKyrE4ph198rDysgg==") { throw "Studio installer checksum mismatch" } + if ($actual -ne "G11qbKE2BSPZgGWYU0MUJ1uZtwrLOy7ZwRGHyD1AUHBBxyLCNjVMAo3o1UWiE4oF3XJCJIaqeJskHGvMApt5XA==") { throw "Studio installer checksum mismatch" } $unpacked = Join-Path $env:RUNNER_TEMP "Studio payload" 7z x -y "-o$unpacked" $installer | Out-Null if ($LASTEXITCODE -ne 0) { throw "NSIS extraction failed" } diff --git a/README.md b/README.md index bd0a1a9..52e0d11 100644 --- a/README.md +++ b/README.md @@ -23,11 +23,11 @@ https://47.110.142.255/ducklab-mcp/mcp/ 详见 [plugins/duck-lab/README.md](plugins/duck-lab/README.md) · [完整指南](docs/duck-lab-mcp-guide.md) -### RDK Camera AI — 相机调试与视觉 Workshop(1.5.7) +### RDK Camera AI — 相机调试与视觉 Workshop(1.5.14) -学员可在 RDK Studio 打开 180 分钟课堂工作台,跟踪原训练 Run,在等待期间做两轮 Gamma 和工位支持的单项调参,按 A/B/C 分流并导出成果。真实采图、ISP 回读与上板检测需要连接已配置的设备服务。 +日常相机调试(点亮、采流诊断、AI 看图调 ISP、恢复与验收)与 180 分钟课堂工作台:10 参数线性域 ISP、2-Pass 自动诊断、Bayer RAW、离线标定、X5 检测,按 A/B/C 分流并导出成果。真实采图、ISP 回读与上板检测需要连接已配置的设备服务;未配置连接时,插件仍提供版本查询与连接诊断两个工具,并给出配置指引。 -macOS 和 Windows 使用同一份 [Studio 插件 ZIP](dist/rdk-camera-workshop-1.5.7.zip)。通过扩展中心导入,要求选择目录时先解压,选择含 `plugin.json` 的目录。Studio 1.5.8 还需按插件说明在 MCP 设置登记两组工具。进入新对话,输入「打开视觉 Workshop 课堂工作台」。[插件使用说明](plugins/rdk-camera-workshop/README.md) +macOS 和 Windows 使用同一份 [Studio 插件 ZIP](dist/rdk-camera-workshop-1.5.14.zip)。通过扩展中心导入,要求选择目录时先解压,选择含 `plugin.json` 的目录。宿主未自动注册 MCP 时(如 Studio 1.5.8),在解压后的插件目录运行 `node mcp/studio-config.mjs`,按输出的配置在 MCP 设置中登记服务。进入新对话,输入「开始 180 分钟视觉 Workshop,打开课堂工作台,一步步带我完成」。[插件使用说明](plugins/rdk-camera-workshop/README.md) ### d-obs-agent — 可观测平台查询助手(0.1.0) diff --git a/dist/rdk-camera-workshop-1.5.13.zip b/dist/rdk-camera-workshop-1.5.13.zip new file mode 100644 index 0000000..160d572 Binary files /dev/null and b/dist/rdk-camera-workshop-1.5.13.zip differ diff --git a/dist/rdk-camera-workshop-1.5.14.zip b/dist/rdk-camera-workshop-1.5.14.zip new file mode 100644 index 0000000..2aeb1f0 Binary files /dev/null and b/dist/rdk-camera-workshop-1.5.14.zip differ diff --git a/marketplace.json b/marketplace.json index a2aac47..c17616a 100644 --- a/marketplace.json +++ b/marketplace.json @@ -20,14 +20,14 @@ { "name": "rdk-camera-workshop", "description": "日常相机调试:拍照、点亮、采流诊断、AI 看图调 ISP、读回与恢复。180 分钟视觉 Workshop:三图采集、RoboGO 提交与原 Run 跟踪、ISP、A/B/C 分流、X5 检测和成果留证。", - "version": "1.5.7", + "version": "1.5.14", "author": { "name": "D-Robotics" }, "source": { "source": "local", "path": "plugins/rdk-camera-workshop", - "sha256": "5144c9284efa5fe73ffe7e316ec8f8738451a2d2a052992e66c5d0aa61319c51" + "sha256": "66c59670d589d207def8ac54bb023fcbbb231101818ceb3714a0faa3bb242c78" } }, { diff --git a/plugins/rdk-camera-workshop/.mcp.json b/plugins/rdk-camera-workshop/.mcp.json index f1bc80d..b4de7cb 100644 --- a/plugins/rdk-camera-workshop/.mcp.json +++ b/plugins/rdk-camera-workshop/.mcp.json @@ -8,6 +8,47 @@ ], "env": { "RDK_CAMERA_WORKSHOP_ONBOARDING": "1" + }, + "permissions": { + "default": "approval", + "tools": { + "vision_ai_debug_preview": "readonly", + "vision_ai_debug_status": "readonly", + "vision_calibration_apply_plan": "readonly", + "vision_calibration_asset_list": "readonly", + "vision_calibration_engines": "readonly", + "vision_calibration_task_get": "readonly", + "vision_calibration_task_list": "readonly", + "vision_calibration_task_result": "readonly", + "vision_camera_controls_get": "readonly", + "vision_camera_frame_preview": "readonly", + "vision_camera_knowledge_get": "readonly", + "vision_camera_knowledge_search": "readonly", + "vision_camera_preview_frame": "readonly", + "vision_camera_probe": "readonly", + "vision_camera_readiness": "readonly", + "vision_camera_response_analyze": "readonly", + "vision_camera_stream_analyze": "readonly", + "vision_camera_workflow": "readonly", + "vision_connection_status": "readonly", + "vision_experiment_get": "readonly", + "vision_experiment_list": "readonly", + "vision_isp_tuning_download": "readonly", + "vision_isp_tuning_export": "readonly", + "vision_isp_tuning_get": "readonly", + "vision_pipeline_validate": "readonly", + "vision_plugin_version": "readonly", + "vision_workshop_capabilities": "readonly", + "vision_workshop_delivery": "readonly", + "vision_workshop_export": "readonly", + "vision_workshop_runtime_status": "readonly", + "vision_ai_debug_start": "approval", + "vision_calibration_apply": "approval", + "vision_calibration_task_create": "approval", + "vision_calibration_task_run": "approval", + "vision_camera_bringup_flow": "approval", + "vision_experiment_create": "approval" + } } }, "rdk-vision-workshop": { @@ -16,7 +57,7 @@ "args": [ "mcp/server.mjs" ], - "requestTimeoutMs": 30000, + "requestTimeoutMs": 120000, "permissions": { "default": "deny", "tools": { @@ -28,8 +69,14 @@ "vision_course_camera": "approval", "vision_course_camera_status": "readonly", "vision_course_preflight": "readonly", + "vision_course_calibration_recompute": "readonly", + "vision_course_calibration_demo": "readonly", + "vision_course_calibration_status": "readonly", + "vision_course_calibration": "approval", + "vision_course_isp_example": "readonly", "vision_course_isp": "approval", - "vision_course_isp_status": "readonly" + "vision_course_isp_status": "readonly", + "vision_course_detection_status": "readonly" } } } diff --git a/plugins/rdk-camera-workshop/.qoder-plugin/plugin.json b/plugins/rdk-camera-workshop/.qoder-plugin/plugin.json index 6bffc09..44b5925 100644 --- a/plugins/rdk-camera-workshop/.qoder-plugin/plugin.json +++ b/plugins/rdk-camera-workshop/.qoder-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "rdk-camera-workshop", - "version": "1.5.7", + "version": "1.5.14", "description": "日常相机调试:拍照、点亮、采流诊断、AI 看图调 ISP、读回与恢复。180 分钟视觉 Workshop:三图采集、RoboGO 提交与原 Run 跟踪、ISP、A/B/C 分流、X5 检测和成果留证。", "author": { "name": "D-Robotics" diff --git a/plugins/rdk-camera-workshop/README.md b/plugins/rdk-camera-workshop/README.md index c1f5758..24fa1b7 100644 --- a/plugins/rdk-camera-workshop/README.md +++ b/plugins/rdk-camera-workshop/README.md @@ -1,19 +1,7 @@ -# RDK Camera AI 1.5.7 +# RDK Camera AI 1.5.14 -在 RDK Studio 的扩展中心从 D-Robotics 官方市场源安装 RDK Camera AI,或下载 ZIP 后导入。选择器要求目录时,先解压并选择含 `plugin.json` 的文件夹。macOS 和 Windows 使用同一份插件。首次使用可查询插件版本与连接状态;相机服务连接信息由本工位提供。升级前请关闭旧课堂页。 +在 RDK Studio 导入包含 `plugin.json` 的目录并启用扩展即可同时使用日常相机调试与 180 分钟视觉 Workshop。 -- **日常相机调试**。在 Studio 助手说「用 RDK Camera AI 帮我点亮相机,读取当前 ISP」。按[相机操作技能](skills/rdk-camera-workshop/SKILL.md)执行。 -- **180 分钟视觉 Workshop**。在 Studio 助手说「打开 180 分钟视觉 Workshop,继续我的工位」。通过 `vision_course_view` 打开本机工作台,按[课程操作稿](skills/rdk-vision-workshop/references/course-runbook.md)推进。 -- **工位连接预检**。用 `vision_course_preflight` 或工作台的「运行连接预检」核对相机服务、X5 和实时画面。首次接入时从页面的「关联相机实验」绑定正确设备。 -- **课堂 ISP**。保存原始版本,完成跟做和自主两轮 Gamma。每轮留下调前与调后实拍、独立参数回读和取舍。升级前关闭旧课堂页。讲师可现场缩短曝光,在相同增益下查看调前、调后实拍和恢复回读,也可切换五项实机归档。 -- **拍照与三张基线**。在工位关联相机实验后打开「照片与三张基线图」,从图卡查看采集、归档与原件下载。也可通过 `vision_course_camera` 发起,使用 `vision_course_camera_status` 查看回执。渲染条件缺失时保留已归档的图并提示如何继续。 - -实际相机操作沿用相机适配器及原连接配置。课堂工作台保存相机证据,需要时可绑定当前相机实验。训练需本组 RoboGO 授权。提交、查询原 Run、PTQ 和板端验收按课程步骤完成。 - -相机连接器读取 `~/.config/rdk-camera-workshop/connection.json` 或 `RDK_CAMERA_WORKSHOP_CONFIG` 指定的私有文件。可运行 `node mcp/setup.mjs doctor` 核对连接。 - -Studio 1.5.8 需要显式登记两组 MCP。安装 Node.js 22 或更新版本,在解压后的插件目录(请保留该目录)用终端或 PowerShell 执行 `node mcp/studio-config.mjs`。在 Studio 的 MCP 配置中添加输出的两组服务,保留已有的其他服务,然后新建对话。该命令只输出本机配置。如果旧版 Studio 图形导入提示「审批签名配置缺失」,可从保留的解压目录生成配置,在 Studio 的 MCP 设置完成登记;需要图形导入时,请使用已修复审批配置的 Studio 版本。已有单独安装的视觉 Workshop 可接续到同名课程工具。已保存的课程进度可从工作台导入,按需重新附入实拍或回读附件。 - -工位、RoboGO 与板端归档配置见[课堂工作台配置](WORKSHOP.md)和[设备操作](device/README.md)。 - -学员在同一个课堂工作台里可以读取工位可写项目,单次调一个曝光、增益、对比度、锐度或白平衡数值。保留调前调后实拍、独立回读和取舍。真机逐项验收。 +- **日常相机调试**:按 [相机操作技能](skills/rdk-camera-workshop/SKILL.md) 执行点亮、采流诊断、AI 看图调 ISP、恢复与验收。 +- **视觉 Workshop(v0.8.1)**:调用 `vision_course_view` 打开可视化工作台,支持 10 参数线性域 ISP、2-Pass 自动诊断、Bayer RAW、7 场景离线标定与板端检测,详见 [WORKSHOP.md](WORKSHOP.md)。 +- **连接自检**:`node mcp/setup.mjs doctor`(私有凭据仅存放于 `~/.config/rdk-camera-workshop/`)。 diff --git a/plugins/rdk-camera-workshop/SOURCE-MANIFEST.json b/plugins/rdk-camera-workshop/SOURCE-MANIFEST.json index e7ce4c2..ab77a3a 100644 --- a/plugins/rdk-camera-workshop/SOURCE-MANIFEST.json +++ b/plugins/rdk-camera-workshop/SOURCE-MANIFEST.json @@ -1,52 +1,58 @@ { - "version": "1.5.7", - "cameraBaseVersion": "1.3.0", - "courseVersion": "0.7.8", + "version": "1.5.14", + "variant": "studio", + "cameraSourceVersion": "1.2.0", + "courseSourceVersion": "0.8.1", "files": [ { "path": ".mcp.json", - "bytes": 953, - "sha256": "c179a20edffc1031c5c9ea169176d4f252d82ddda9f436a686fd36696f2d6ede" + "bytes": 3226, + "sha256": "1f80c8f7ccc322c834c85bd90a65cd24343e99a1b4c6de15e49e9b8901be8308" }, { - "path": "README.md", - "bytes": 3114, - "sha256": "65156a52a4559f8b939b7eceb1c07491bff06bb2d01f52e2e981b791c5f45088" + "path": "device/README.md", + "bytes": 6120, + "sha256": "28d4bfe283b829677834f19e66385426d2c6afaf37ae184c1f3319e43d004a0f" }, { - "path": "WORKSHOP.md", - "bytes": 6535, - "sha256": "ea8b858945248d3a9c17daff1be4c2d4b62cb04995350b269b605767d0b29018" + "path": "device/x5-course-detect.py", + "bytes": 22098, + "sha256": "114adcb22ab5193b620f29151e72d18f54a771bfc61504a6393634314c9b6334" }, { - "path": "device/README.md", - "bytes": 3189, - "sha256": "c32be12e8f90b5f8ba316c55b660bf287b466f3907415e6d23fc6ae90336760d" + "path": "device/x5-station-bridge.py", + "bytes": 8932, + "sha256": "d24baedd40eeaf65fcf63664df9ff3915b3c9086a57a0235f0084457ca8730c0" }, { - "path": "device/x5-course-detect.py", - "bytes": 16503, - "sha256": "0e6ba28ad381b185cf355cd97503dcc4e84f65be6c3849d36314258d60399715" + "path": "mcp/board-launcher.mjs", + "bytes": 8257, + "sha256": "fb11e2d5f87631867abc906fa51882fbf7f29b923f29d2ac13654bb7483a6066" }, { "path": "mcp/bridge.mjs", - "bytes": 20945, - "sha256": "21f3992572ae522b901f92d0dba746037b93c1a04ae7e342642d8d180a9a7286" + "bytes": 52261, + "sha256": "d7374e5023692e89659abcf16feff46d8bc7710131dc34dfc166dbda7708aa62" }, { - "path": "mcp/camera-source.mjs", - "bytes": 34915, - "sha256": "323c26468b00b1fb214be8aa165a3c3d5e901d2108695588b9f4b6c05a65db42" + "path": "mcp/calibration-chat.mjs", + "bytes": 13441, + "sha256": "3d54e3d698dc8e0421ee2d1d739e7ac3e7b4ef2e44d5b61dddd52bd64479a45f" }, { - "path": "mcp/course-evidence.mjs", - "bytes": 11581, - "sha256": "77a248cb87adeb3a1f23fc87441989d447086d85cb110f1867ee60f9719b19a3" + "path": "mcp/calibration-visual.mjs", + "bytes": 11372, + "sha256": "f64b97c0043e58103b8c664e079a68801b34820c0eb5967fd9149c545b8b2cc6" }, { - "path": "mcp/course-server.mjs", - "bytes": 3302, - "sha256": "c924c272744c460194ea1fd1b29a3ecd09b00cc1fe83a2c1fdb8172b2eca50e2" + "path": "mcp/camera-source.mjs", + "bytes": 46572, + "sha256": "23b470c5f0c58c3eb23bfa1aaee8bc5a178cad7bd55c42981955bb9d9c5cc7c7" + }, + { + "path": "mcp/course-evidence.mjs", + "bytes": 17471, + "sha256": "c330d8283ab498dd9758141072883af331381077cff4387c795a5fd0b7ab3a1d" }, { "path": "mcp/course.mjs", @@ -54,69 +60,79 @@ "sha256": "eb535520727bc623cb07ee57677cdf9202573a086eda5a8dc166e7f624decb73" }, { - "path": "mcp/entrypoint.mjs", - "bytes": 442, - "sha256": "6f2a1f1c0bbc834f88393e2c5fc14ce42ae0266ddf5aeb8c610ed6d5f709ff80" + "path": "mcp/guide.mjs", + "bytes": 22159, + "sha256": "71643d78595a295e5e273d9599320e50ad6ea21bd1556d86bda4af11b099610e" }, { - "path": "mcp/guide.mjs", - "bytes": 19269, - "sha256": "e0bc18cfbf77b0fc5e338e95e4f8781668a23d47d79f80689d02d8a5b2b7de54" + "path": "mcp/isp-codec.mjs", + "bytes": 33007, + "sha256": "80ac7d2cace17eea20b5a093cb31c09a2c31af5ea6a2ac1eedad425e67abc4bc" + }, + { + "path": "mcp/isp-example.mjs", + "bytes": 31059, + "sha256": "f38272bfa4bd3f6b74c6313c46c9924568ed84c1e99972e30e76238183bcfaeb" }, { "path": "mcp/learner-isp.mjs", - "bytes": 4500, - "sha256": "796655530fc444768e5f361a0e5b7fa92ee716e65c608119538b5e671c2ef467" + "bytes": 15361, + "sha256": "82af3475330a71dd0f7d87afc219765330713695bd12831859d7c39841e489bb" }, { "path": "mcp/robogo.mjs", - "bytes": 12286, - "sha256": "1f8e187ed5962de5e9342527a1a9b30c22a0dce290b4e7b26f6067241ab108dc" + "bytes": 13011, + "sha256": "d34c039684c015740e7e860ace6ede8341e1d8b5b0301579219d691f540d6d7d" }, { "path": "mcp/server.mjs", - "bytes": 9329, - "sha256": "b3402a7554006863b5363e8214fded7d05d026e5715fda7fe24a737ec95dd2a9" + "bytes": 24421, + "sha256": "44fc103c8aea6d54c56ba98277fc487690d7e4c1ebfc2e3b2e7019d4478122ae" }, { "path": "mcp/setup.mjs", - "bytes": 9766, - "sha256": "d1ec2b34b2caabc37236031d5c82781a994ccc81acd1035b4010549665fe0a79" + "bytes": 11542, + "sha256": "85c7b3c650c899a9bfa70d9f8412ec5b65b041ffea2a9bcb5356c61b0208fbee" }, { "path": "mcp/steps.mjs", - "bytes": 11195, - "sha256": "3d9ef481a1dfc76730aabf1ccf8fa26927071a55a0cc5b8126108aad52b66234" + "bytes": 11113, + "sha256": "bfe2f673c0bf524ab7d9365366b62d5a4a560511de7c6d33f0ff8b746284f6c9" }, { "path": "mcp/studio-config.mjs", - "bytes": 1221, - "sha256": "97af94689d072de87ca3788143936a7af12f0fb79a3e969df7276e3da25b76c3" + "bytes": 1591, + "sha256": "283737e07e0cfc327fc4604accbd15a3f07bcf5f6b462c9e42ef14291b8dfbd8" + }, + { + "path": "mcp/upstream-calibration.mjs", + "bytes": 2156, + "sha256": "4e13e39ffff70a1363fe982056abdc6571ac38eaa886310e6d787e597126a6d8" }, { "path": "mcp/workbench-session.mjs", - "bytes": 5684, - "sha256": "54c72b1a4a0982a5ee38a03e205426771250eb4a986e0f1ac104fd6f88dc01c8" + "bytes": 23968, + "sha256": "3396aa6e8ad689219ea98ca4e85dbd426d80bd13da00e70a76447f0f03531070" }, { "path": "mcp/workbench-state.mjs", - "bytes": 908, - "sha256": "1f31ae11b96e296d75f18e52343c7b715679b53b08bde5df294f5b8940b7e6f3" + "bytes": 1092, + "sha256": "6cdd04b976d94f40e6d54ef9bcd0959f69caa5df7ed9ee30e3d88abcbb93a71c" }, { "path": "mcp/workbench.mjs", - "bytes": 48128, - "sha256": "14ff3af8d1fff7482e073073d25fc0e57fad516e8a3c0c16b5ddccc22645d7cd" + "bytes": 92530, + "sha256": "b94bdc9a994c598c7da2269e9e379b5bff9871f129b33396b8547d5b40c0c88a" }, { "path": "plugin.json", - "bytes": 613, - "sha256": "edfa56ad1ed0bc80ff46dd590e03448b7abd33446c303b55111160cf37dc87af" + "bytes": 710, + "sha256": "a857ddc6bfab14f4f26a07dced51305f0ad3fa9fd53a176e7d77bbd9de1bb413" }, { - "path": "skills/rdk-camera-workshop/SKILL.md", - "bytes": 20153, - "sha256": "a5aa5ebdab0ac34f725754c53a7e213770f6468fa232481fb5063dcd77e78494" + "path": "README.md", + "bytes": 664, + "sha256": "8b8e77dbe62084205f5801234b071ebaf91481c1e01adbde77d77bb0ed70445b" }, { "path": "skills/rdk-camera-workshop/assets/new-sensor-profile-worksheet.json", @@ -130,8 +146,13 @@ }, { "path": "skills/rdk-camera-workshop/references/imx415-compatibility-and-recovery.md", - "bytes": 85776, - "sha256": "53b2760e6e3ce27362d9af3c2926f9dfed212f0a2fa52ae4002fdaaab1d95dff" + "bytes": 87650, + "sha256": "c8fab6c2d139e34deab52f9b5764693305b0660610cf53ea51c3faff87e90ebc" + }, + { + "path": "skills/rdk-camera-workshop/references/ispstudio-calibration.md", + "bytes": 17165, + "sha256": "d929f8b4f64d627fb57f97875faa3095f98d4ff3f3b2fea34b09227564455959" }, { "path": "skills/rdk-camera-workshop/references/new-sensor-ai-workflow.md", @@ -140,8 +161,8 @@ }, { "path": "skills/rdk-camera-workshop/references/systematic-isp-search.md", - "bytes": 88324, - "sha256": "90ab63b7068cca49c029520b1f9c7e162116c5626d58c3ae599ccc12a3bba126" + "bytes": 89824, + "sha256": "2e8e767f599e2fbf9bc5419cb2e8d6b4a12ecc470a0eae14b88249cbefa780d7" }, { "path": "skills/rdk-camera-workshop/scripts/continuous_frame_pump.py", @@ -209,84 +230,174 @@ "sha256": "d3997954d50c661d96e90c7b420cd2197d907427993d0cc9912fe67a07873bda" }, { - "path": "skills/rdk-vision-workshop/SKILL.md", - "bytes": 4661, - "sha256": "f18367d7e3fb509d107f627e92925cd1918783a87d0c50a7d7397a949e4aedfd" + "path": "skills/rdk-camera-workshop/SKILL.md", + "bytes": 16033, + "sha256": "7414fd911453633c665ac54b2015d163844f3930ab92652b3c4ef7f8aded3660" }, { "path": "skills/rdk-vision-workshop/assets/course-plan.json", - "bytes": 3688, - "sha256": "f8aeb967b75dffe62b54075f145d106486a9c42f8bbfb70263084a54da2543b1" + "bytes": 3690, + "sha256": "b2fe930ce017124378b4ef707fee71d0f779e4f4ad892c8bd82f32f04759ffd2" + }, + { + "path": "skills/rdk-vision-workshop/assets/ddc-2026-12-06.json", + "bytes": 3939, + "sha256": "90c84414d6a8f6a824369823e9ac6dcb05650c0b87ecafff7b8002ec63df37de" }, { "path": "skills/rdk-vision-workshop/references/course-runbook.md", - "bytes": 2774, - "sha256": "6053a88d1382c433c89a98e3d4604205e6ef3ad3cf4b70dbc97e29ac671b7482" + "bytes": 2814, + "sha256": "100441b4badf78b3f795e9a82f1a728fcb65fbe085428189288c9f4b23d9751d" }, { "path": "skills/rdk-vision-workshop/references/tuning-handoff.md", "bytes": 1600, "sha256": "9af5f4243be8f6f1d15db73cb06fc6453226dd407d204b989cc873f8caa5587c" }, + { + "path": "skills/rdk-vision-workshop/SKILL.md", + "bytes": 16715, + "sha256": "3c83506d5856a75d7f96827fd4360c8664ef4dbcadfd8e62c75fff681505ceb2" + }, { "path": "web/app.mjs", - "bytes": 51015, - "sha256": "e701e70c67cef60f116700f728c9fef2a340ef3d0be10e6613cdb82294200872" + "bytes": 114902, + "sha256": "28728283b5e9cfd81b450c1944e7aed91797448a2a5b87198042df5625246d3a" }, { "path": "web/board-panel.mjs", - "bytes": 14315, - "sha256": "84151b69d794287d552f0bc95a36e89bbedf1912d4538ac5d81625700f4930e0" + "bytes": 30640, + "sha256": "5d5f6e68050dd8253f634e5da04ed0fd3d31ca0f3dd1e4657b9e8ceb48a767f7" + }, + { + "path": "web/calibration-demo/exercise.json", + "bytes": 455, + "sha256": "608abdd29fc0326d9a7754394f33222f75194eac9878ac4f7c53685c4af6433e" + }, + { + "path": "web/calibration-demo/flat-after.png", + "bytes": 605, + "sha256": "b610b86008de30547f221da55b5b837bb74de44aee6f92f3e7658415d8319332" + }, + { + "path": "web/calibration-demo/flat-before.png", + "bytes": 1132, + "sha256": "164ac29e1ae6a5888ac8c797ff4f3565e2c1fa2ef8382f7d5489251b0cadbe36" + }, + { + "path": "web/calibration-demo/preview.png", + "bytes": 2600, + "sha256": "361583151e68d274ddd86244e3e01128d3f950c0a3a61f7a810b075d903947a2" + }, + { + "path": "web/calibration-demo/result.json", + "bytes": 1241, + "sha256": "a3e8bdc05555a0c23ce06cc6e4a550fcc636641791858bfefc0915300d997fe4" + }, + { + "path": "web/calibration-demo/static-calibrations.json", + "bytes": 221920, + "sha256": "deeee2a8f6f5e24c302eeb451cccbd8012c63229b356bf7c05d375532375e700" + }, + { + "path": "web/calibration-exercise.mjs", + "bytes": 12999, + "sha256": "aee486acc3b854b412ac7f08325e8825a44c981319164944e39e4a343b452655" + }, + { + "path": "web/calibration-panel.mjs", + "bytes": 54187, + "sha256": "0187b9f79df372f67892ca446753c5f5536c6bbf306f8fac82f4756836ded377" }, { "path": "web/camera-panel.mjs", - "bytes": 9483, - "sha256": "26265f23ff56d155f1f8574ca990bee592703a76c890e4bc26d4e2ec80d679de" + "bytes": 10039, + "sha256": "6061472d8d751c778d79313bb184dac878d9e7a0dff31d0c2f54735d15cda09c" }, { "path": "web/capture-panel.mjs", - "bytes": 10654, - "sha256": "d29ecc6e03dbec59977ca47c122b385e6d18d204237402845a96c07d5f743620" + "bytes": 11314, + "sha256": "f8071f420e335ee78eea45b489f55753593598aa5e96ce49f89cd14fdde89b58" + }, + { + "path": "web/image-compare.mjs", + "bytes": 24642, + "sha256": "c6cdf29b65df57eb691aa27f355b03269fa13adb6819bc5a1bba4634ac145941" }, { "path": "web/index.html", - "bytes": 10652, - "sha256": "716e32269e8231fb5bae494f1347c50f28ab7462f5fb23b459f7448e30ff6740" + "bytes": 39186, + "sha256": "a3751c29bffb057e84e61f5f01ddd2f0f32e2924ea1f1069b08f8a2a132a9641" + }, + { + "path": "web/isp-demo.mjs", + "bytes": 2011, + "sha256": "395120ff36884c078fd529bbcd03bcb8dd185adaf8ce9766ccaf27ba31c63e07" + }, + { + "path": "web/isp-demo/brightness-after.jpg", + "bytes": 57671, + "sha256": "6058cba14031c8199ed17278255a8ecf0ea2356a2d19b4f87a05c1e442bd5d2d" + }, + { + "path": "web/isp-demo/brightness-before.jpg", + "bytes": 61456, + "sha256": "3e52c68df60bf511aa5cfdaea01073fca491c63214c54d2b389d87b10da12214" }, { "path": "web/isp-demo/contrast-after.jpg", - "bytes": 71623, - "sha256": "5ffa615224277a31145ce79017ea32a6ca522259d6dc0efa01f41090ecf95342" + "bytes": 43470, + "sha256": "c8b2c459fb7225cf9f2cc7db8d37cbb063cd11e998f37b2b6bda4679889747df" }, { "path": "web/isp-demo/contrast-before.jpg", - "bytes": 71685, - "sha256": "d049f28cb84465f1de74d5b91c5f3c720a6d080d6f1a29d7ec8b6462bc7aa2ee" + "bytes": 23404, + "sha256": "3e9e0b5a27890c3103859f37fdcfb7a0e8c8a67f8efd66d74c48833742b8dbfb" }, { "path": "web/isp-demo/exposure-after.jpg", - "bytes": 71180, - "sha256": "43f86325e054e203e7ec7cb8d7aa4fbde1daadf9698b915c48adb75b5e48022a" + "bytes": 61282, + "sha256": "64d376d2098cb3a1c803dd6c8676a522ad0fb7f8064c29f45db1754674a7afeb" }, { "path": "web/isp-demo/exposure-before.jpg", - "bytes": 71176, - "sha256": "6a3819bc3240730bc325bcaaccd03e368e485a2ece29012e4ca9df7fc67d7a14" + "bytes": 55850, + "sha256": "0b957e0db409ffb78a3f2b52ebe986d1e9f86e576fe7d85e5481e52e6a92d9cf" }, { "path": "web/isp-demo/gain-after.jpg", - "bytes": 60806, - "sha256": "96d97f39b2b17f067d431c9b2ef3172edd1450e953fc1372a4c12f69ca19ab84" + "bytes": 60348, + "sha256": "5aade47580d473c0b7908973799a7ace677f9ea6f52fee0b04f79ebc520005ea" }, { "path": "web/isp-demo/gain-before.jpg", - "bytes": 61299, - "sha256": "28123fcf673ac532002ca18bd8e26df52b01e09ba2d199f0783dedf305043664" + "bytes": 53692, + "sha256": "9745e52e8fe078eb60434b89958bf3db44ceca29d33d75e57357dbf95022e6f8" + }, + { + "path": "web/isp-demo/hue-after.jpg", + "bytes": 62294, + "sha256": "eeab2cd8ce07eac176106dacfe86b030b5805a6e605625f9170d719d6d42a20f" + }, + { + "path": "web/isp-demo/hue-before.jpg", + "bytes": 61620, + "sha256": "1a6cb15977be32f4cbe321d8cae91f5570ef79f33988342b1cc3afd8f92605a7" }, { "path": "web/isp-demo/manifest.json", - "bytes": 8325, - "sha256": "c2aab897b9277f2468e008566481e71560e22a0f6e70462c74676bc2985f35f2" + "bytes": 14229, + "sha256": "7c9618b03582d625b155f42458688d6d819fcb1c4448789c83ffc78e56f31d54" + }, + { + "path": "web/isp-demo/saturation-after.jpg", + "bytes": 65648, + "sha256": "abda7211b4c940b0276d2e62956f4b864a88ee19db8455c581c9f30d0247f0ab" + }, + { + "path": "web/isp-demo/saturation-before.jpg", + "bytes": 55127, + "sha256": "9764627be9c0c0b1861776d4df54cdd639ca22851f97cc26e8d5c508f223824a" }, { "path": "web/isp-demo/sharpness-after.jpg", @@ -300,39 +411,83 @@ }, { "path": "web/isp-demo/white-balance-after.jpg", - "bytes": 15390, - "sha256": "c733e171fef81a28d0e4ff44d87a7b095aa51e725919599a9c2854ad9d1e3f7c" + "bytes": 63313, + "sha256": "2fbe1b4135c2ba39bb8dd8a385d88bb048231d1de68def458836a10a2ae78895" }, { "path": "web/isp-demo/white-balance-before.jpg", - "bytes": 15654, - "sha256": "0faf51c30f821ae471826eefdeae06d2f414bc8999c467700bb381c8266e060c" + "bytes": 63513, + "sha256": "1749dde3a72087baab76411f1c1c0b18ac93c7f4a2c6f3e3e2999a1c09a7137f" }, { - "path": "web/isp-demo.mjs", - "bytes": 1895, - "sha256": "0c45270472c6e836f21d198676a149bd80f0fe98ef9276f56aff0bd28943a539" + "path": "web/isp-engine.mjs", + "bytes": 36147, + "sha256": "ecc78f06eea5341da570b1ad9f878c419b0f63466eb6d0e9d7f56f0f65bb4c57" + }, + { + "path": "web/isp-example/backlight/gamma-20.jpg", + "bytes": 101448, + "sha256": "117006eac3be6dbba38b989618e73aa8bbbfb0b6a5acc39dda6ea367d5732be2" + }, + { + "path": "web/isp-example/colorchecker/gamma-20.jpg", + "bytes": 70503, + "sha256": "157799ae44052a0940c206f1377c68efa67323e2f063d8f8d2ed440f6cb8be49" + }, + { + "path": "web/isp-example/gamma-20.png", + "bytes": 56256, + "sha256": "5c594fd8a6ee82be41d53d6504a555e31013e38745fbc33cd858c6eae73e450b" + }, + { + "path": "web/isp-example/hazy/gamma-20.jpg", + "bytes": 91502, + "sha256": "7f3c3adcb2421bae5e9e797fa77088487e00a974ee810061650415c18bc1d082" + }, + { + "path": "web/isp-example/lowlight/gamma-20.jpg", + "bytes": 67956, + "sha256": "5a7e68e798d4605ba895d7d6500cc4461e614edee245aecf0164f518aa9d2b3c" + }, + { + "path": "web/isp-example/macro_detail/gamma-20.jpg", + "bytes": 62778, + "sha256": "70346aa2c0cddab563f69114e4e94968a3fac0d061c4b9c81e1a990deb6491d6" + }, + { + "path": "web/isp-example/scenes.json", + "bytes": 11537, + "sha256": "c95eba4b8984c5a0eb99e727cd3a7718d15a6c1d0b974c7d5f9d9f780f82d4ff" + }, + { + "path": "web/isp-example/warm_wb/gamma-20.jpg", + "bytes": 41219, + "sha256": "935deb5a39cc0efe47651178bf587627c185ea7e7bb80d936a1811042bbdd5d0" }, { "path": "web/isp-panel.mjs", - "bytes": 32127, - "sha256": "13101b4cab28a9c4b658e9bbd33c6e06a29ea59adb09e64c4dc883610708f877" + "bytes": 42928, + "sha256": "db004ec98a08c2608b3580d1f8f32801089d60588af6056cc7e160c7a8e87d96" }, { "path": "web/preflight-panel.mjs", - "bytes": 5047, - "sha256": "0cf9b378e6aa835445e7f70029dd797d64d06dc87c7d15e063869714b8a1bd77" + "bytes": 6870, + "sha256": "1d5223eb1a0dfd6dff11789f4c6eb405035988b853cd8ad565cbf7b291a804ea" }, { "path": "web/style.css", - "bytes": 16670, - "sha256": "5c2fa4ac83188dd5739766599d01ec958ad2da13e6997c28523c215675cec1cd" + "bytes": 47216, + "sha256": "38be0fe33d8d17e3e585dfb96ffcefa6f57e0888011192294b51021a86272463" }, { "path": "web/zip.mjs", - "bytes": 1748, - "sha256": "ef91dc431132e31b7624eaed7da4fb9e90c1f2cd54ba2e28a74e67b45457d33e" + "bytes": 1912, + "sha256": "8d6d81aec3ee27200ac1a6b27c31cfef3ac6ec9100797c40c4eb3d9287d4912b" + }, + { + "path": "WORKSHOP.md", + "bytes": 8233, + "sha256": "dfb7c3f0fc2941a11486d632410eb06665a6e4921cdac291006a5fea1984b52b" } - ], - "extendsSha256": "3cc106f04ac8df47503ffa27302b3d5b3451f865f4082f6e4ff08196fe0cc858" + ] } diff --git a/plugins/rdk-camera-workshop/WORKSHOP.md b/plugins/rdk-camera-workshop/WORKSHOP.md index 2cf44f0..fe696d9 100644 --- a/plugins/rdk-camera-workshop/WORKSHOP.md +++ b/plugins/rdk-camera-workshop/WORKSHOP.md @@ -1,41 +1,45 @@ # 视觉 Pipeline · 180 分钟 Workshop -在 Studio 逐步完成 X5 + IMX415 点亮、Gamma、RoboGO 异步训练、A/B/C 分流和个人成果归档。依据 [180 分钟课程安排](skills/rdk-vision-workshop/assets/course-plan.json)。 +在 Studio 逐步完成 X5 + IMX415 点亮、Gamma、RoboGO 异步训练、A/B/C 分流和个人成果归档。依据 [飞书课程方案](https://horizonrobotics.feishu.cn/docx/UdhhdVXYXoPLgfxmZ32cJBSAnRb)。 1. 解压,在 Studio AI 能力的扩展中心从目录导入插件。选择包含 plugin.json 的目录。 -2. 若宿主没有自动注册 MCP,从实际安装目录运行 `node mcp/studio-config.mjs`。在 Studio 设置的 MCP 服务导入配置,保留其他服务。检查工位预检与状态查询,拍摄、ISP 操作和 `vision_course_sync` 按 Studio 的审批权限执行。 +2. 若宿主没有自动注册 MCP,从实际安装目录运行 `node mcp/studio-config.mjs`。在 Studio 设置的 MCP 服务导入配置,保留其他服务。检查实验预检与状态查询,拍摄、ISP 操作和 `vision_course_sync` 按 Studio 的审批权限执行。 3. 在 Studio 输入“开始 180 分钟视觉 Workshop,打开课堂工作台,一步步带我完成”。助手用 `vision_course_next` 和 `vision_course_view`,再用宿主网页入口打开返回的本机工作台。 -4. 工作台每次展示当前一个动作、完成条件和 Run 状态。学员从 RoboGO 或相机工具核对本人的真实回执,再添加到当前工位。助手可以用 `vision_course_sync` 让工作台显示已实际取得的回执引用。用「设定进度」可以标记彩排时间,实际课堂用「开始计时」。Gamma 对照从相机工具添加现场图片,按提示在选图和写理由后揭晓。 -5. 在「本工位相机实验」关联 Camera Workshop 的实际实验。工作台沿用该相机插件的本机私有连接配置,可查看帧时间、ISP 实际回读和相机 AI Run。点击「附入成果包」可保存帧与对应回执;有同一 Run 的前后实拍和匹配回读时,可直接打开对照。归档帧按采集时间核对,关联实验不会启动采集或调参。 +4. 点选课堂流程中的任意模块可以先看内容,包括训练条件、Run 检查和部署路径。训练提交和选择部署路径仍按课堂时段及实际条件开放。学员从 RoboGO 或相机工具取得真实回执,再添加到当前实验。助手可以用 `vision_course_sync` 同步已取得的回执。用「设定进度」标记彩排时间,课堂用「开始计时」。Gamma 实拍从相机工具添加,先选图并写理由,再揭晓参数。 +5. 在「本组相机实验」关联 Camera Workshop 的实际实验。工作台沿用该相机插件的本机私有连接配置,可查看帧时间、ISP 实际回读和相机 AI Run。点击「附入成果包」可保存帧与对应回执;有同一 Run 的前后实拍和匹配回读时,可直接打开对照。归档帧按采集时间核对,关联实验不会启动采集或调参。 6. 保存进度 JSON 可以在另一轮继续。添加实际文件后下载个人成果 ZIP,打开检查手册、清单、附件、完成路径和待完成项。浏览器重新打开时需重新选择附件。 -「当前一步」直接带学员进入对应页面。连接预检可写入本工位服务和设备回执。保存原始 ISP 后完成两轮 Gamma。第 1 轮从示范目标跟做,第 2 轮填写自己的目标。每轮单独保存相机实拍、独立回读和取舍。用同一份期初配置开始两轮,保留候选后先恢复期初配置。 +含 Workshop 的 RDK Camera AI 合包与本独立插件共用 `rdk-vision-workshop` MCP 服务。若 Studio 显示服务冲突,在扩展中心停用不使用的版本。若以前手动注册了同名服务,在设置中移除那个旧连接,再检测当前启用的插件。 -课堂当前步骤直接展示对应工具,其他工具可从「其他工位工具与记录」打开。训练提交后可在当前步骤上方查看原 Run 进度和分流时间。对照图支持同步放大同一区域,Gamma 曲线用实际 SDK 回读绘制。SDK 回执可展开查看,完整原件随成果包导出。 +「当前一步」直接带学员进入对应页面。连接预检可写入本组服务和设备回执。保存原始 ISP 后完成两轮 Gamma。第 1 轮从示范目标跟做,第 2 轮填写自己的目标。每轮单独保存相机实拍、独立回读和取舍。用同一份期初配置开始两轮,保留候选后先恢复期初配置。讲师可在实验切换曝光、增益、对比度、锐度和白平衡的既有实机对照。 -讲师在相机采流后展开「讲师演示」,保存期初 ISP,保持机位和光照固定,再点「拍摄曝光对照」。工作台使用同一手动模拟增益拍摄调前、调后图,将曝光时间按传感器行周期缩短约一半,独立核对前后读值并恢复期初配置。看到「对照完成,原值已恢复」后,即可查看两张实拍并将证据导入个人成果包。曝光、增益、对比度、锐度和白平衡仍可选看归档实拍。 +关联相机实验后,可以在 Studio 桌面聊天里说「用视觉 Workshop 拍一张,直接显示在对话里」。插件等本轮照片归档后把实拍交给聊天。新版 Studio 自动提供本机媒体目录。手动注册课程 MCP 的旧版 Studio 可在 MCP 配置中将 `RDK_VISION_COURSE_STUDIO_MEDIA_DIR` 指向当前 Studio 数据目录下的 `agent-downloads`(绝对路径),再重新连接课程 MCP。已在运行的旧实验需要在导出进度并结束实验后重开,才能返回本轮拍照请求 ID。 -工位可在训练卡记录 RoboGO 原 Run 及其状态回执。参加者已有外部训练产物时,组织者可给课程 MCP 配置 `RDK_VISION_COURSE_TRAINING_RECEIPT`,指向本组 `vision-course-x5-evidence-v1` 回执,工作台在读取时标明训练来源。训练回执与 RoboGO 平台任务分别记录。 +也可以说「把第 1 轮 Gamma 调前调后实拍放在聊天里」或「显示本组最近一张带框检测图」。Gamma 和单项 ISP 都使用该轮归档和独立回读。带框图附当前帧的类别、框数和最高置信度,连续取景留在板端检测工作台。并排对照需要支持对照图的 Studio 版本。 + +实验可在训练卡记录 RoboGO 原 Run 及其状态回执。参加者已有外部训练产物时,组织者可给课程 MCP 配置 `RDK_VISION_COURSE_TRAINING_RECEIPT`,指向本组 `vision-course-x5-evidence-v1` 回执,工作台在读取时标明训练来源。训练回执与 RoboGO 平台任务分别记录。 组织者可以把课程板端运行目录同步到本机,设置 `RDK_VISION_COURSE_BOARD_ARCHIVE`。B 可配置独立的 `RDK_VISION_COURSE_PRESET_BOARD_ARCHIVE`,工作台按已登记的预置 SHA-256 核对该目录。学员读取相应板端结果,核对模型、帧、ISP 和恢复,再保存到成果包。运行和同步方法见[板端操作说明](device/README.md)。 Camera Workshop 默认从用户配置目录的 `connection.json` 读取服务设置。若使用自定义位置,可给 Studio 中课程 MCP 设置环境变量 `RDK_CAMERA_WORKSHOP_CONFIG`,值为该私有文件的绝对路径。凭据保留在相机插件的私有文件中。 -MCP 打开的本机工作台跨对话保留,重新调用 `vision_course_view` 可返回同一工位。工作台闲置 8 小时后停止服务,重启后从本机恢复记录和待核对提交。跨场次可用独立的 `RDK_VISION_COURSE_SESSION_DIR` 区分工位。升级前下载进度并关闭旧工作台,升级后按需导入。也可独立运行 `node mcp/workbench.mjs`,打开终端打印的本机地址,并用 `--resume FILE` 恢复进度。要通过插件提交训练请从 Studio 的 MCP 入口打开工位。 +MCP 打开的本机工作台跨对话保留,重新调用 `vision_course_view` 可返回同一实验。工作台闲置 8 小时后停止服务,重启后从本机恢复记录和待核对提交。跨场次可用独立的 `RDK_VISION_COURSE_SESSION_DIR` 区分实验。升级前下载进度并关闭旧工作台,升级后按需导入。也可独立运行 `node mcp/workbench.mjs`,打开终端打印的本机地址,并用 `--resume FILE` 恢复进度。要通过插件提交训练请从 Studio 的 MCP 入口打开实验。 -工作台和课程工具处理本机工位记录。相机、RoboGO、PTQ 和板端操作由实际宿主工具执行。参考 [完整课程操作稿](skills/rdk-vision-workshop/references/course-runbook.md)。 +工作台和课程工具处理本机实验记录。相机、RoboGO、PTQ 和板端操作由实际宿主工具执行。参考 [完整课程操作稿](skills/rdk-vision-workshop/references/course-runbook.md)。 ## RoboGO 原 Run 学员从训练卡「连接 RoboGO」进入官方 SSO 授权。进程重启后重新授权。工作台每约 20 秒只读核对原 Run,直至失败或核实 X5 INT8 产物,也可按「刷新原 Run」。若原 Run 的响应没有附带唯一且明确标为 X5 INT8 的制品摘要,A 保持待核对。下载后把 .bin 的 SHA-256 与原 Run、PTQ 和上板回执比对。 -组织方核对本组 RoboGO 镜像、算力、计费、挂载和配额后,在 `~/.config/rdk-vision-workshop/training-profile.json` 保存工位模板,也可用 `RDK_VISION_ROBOGO_TRAINING_PROFILE` 指定私有 JSON 的绝对路径。模板与凭据分开保存。工作台会重新读取文件,可在已授权工位补齐。JSON 的 `input` 使用官方 `training_jobs.prepare_create` 所需字段,按课程设置 YOLOv8s、640 和 100 轮。确认页显示预检的实际参数,确认后发起一次提交。结果不明确时,从 RoboGO 任务列表核对并绑定原任务。工位也可在 RoboGO 网页提交,再录入原任务 ID。 +组织方核对本组 RoboGO 镜像、算力、计费、挂载和配额后,在 `~/.config/rdk-vision-workshop/training-profile.json` 保存实验模板,也可用 `RDK_VISION_ROBOGO_TRAINING_PROFILE` 指定私有 JSON 的绝对路径。模板与凭据分开保存。工作台会重新读取文件,可在已授权实验补齐。JSON 的 `input` 使用官方 `training_jobs.prepare_create` 所需字段,按课程设置 YOLOv8s、640 和 100 轮。确认页显示预检的实际参数,确认后发起一次提交。结果不明确时,从 RoboGO 任务列表核对并绑定原任务。实验也可在 RoboGO 网页提交,再录入原任务 ID。 + + +### 自然语言图片 ISP 调试(7 套高代表性场景 + 本地图片 + 7 项实时模拟 + 8 项讲师实拍对照) -## 学员单项 ISP 实操 +课堂提供 7 套免接相机即可练习的典型 ISP 示例场景:`lowlight`(暗光机器人工作台)、`backlight`(逆光通道机器人 HDR)、`warm_wb`(暖黄偏色室内桌面)、`hazy`(起雾泛白智慧仓库)、`macro_detail`(多色精密零件与刻度尺)、`colorchecker`(24 色卡 + 21 阶灰阶 + 西门子星标板)和 `chart`(经典合成测试卡,MCP 空参默认)。在 Studio 对话里既可以直接用自然语言调节任意示例场景或任意本地图片(`imagePath`)的全部 7 项 ISP 参数(曝光 EV / Gamma / 亮度 / 对比度 / 饱和度 / 白平衡冷暖 / 锐度 USM)及 `preset`(如 `recommended` / `dehaze` / `cool_wb` / `lowlight_rescue`),即时生成带 5 项量化指标与自动诊断告警的前后对照图并支持 `outputPath` 导出;调用后还会通过 SSE 自动同步到已打开的工作台「示例图练习」滑块与卷帘视图。工作台内同样支持「导入本地图」「下载调优图」、卷帘对比、2.5× 同步放大镜与实时双层 RGB/亮度直方图;「讲师八项演示」展示曝光、增益、对比度、锐度、白平衡、亮度、饱和度、色调共 8 组带真实回读哈希的 X5 实拍对照。 -学员在同一个课堂工作台里可以读取工位可写项目,单次调一个曝光、增益、对比度、锐度或白平衡数值。保留调前调后实拍、独立回读和取舍。真机逐项验收。 -保存期初配置后读取参数。未返回可写范围或仍在自动模式的项目按工位状态锁定。X5 原生锐度需要相机服务支持单字段候选。保留后先恢复,才能开始另一项。 +### 学员单项 ISP 实操 -## 打开课堂工作台 +先保存期初 ISP,再读取本组的可写参数。曝光、增益、对比度、锐度、白平衡按当前实验协议和模式显示;一次只提交一个数值。白平衡的各通道是独立选项。X5 的原生锐度需要相机服务支持单字段候选,且快照带手动可写范围。 -支持入口的 Studio 可从已安装插件卡进入。也可在新对话调用课堂工具后点击返回的链接。工作台提供继续原工位或独立练习,训练排队或运行时可直接进入 ISP。 +记录同一区域的调前和调后新帧、独立回读及保留或恢复理由。保留后先恢复期初 ISP 才能开始另一项。新增流程的真实板端验收按实验单独记录。 diff --git a/plugins/rdk-camera-workshop/device/README.md b/plugins/rdk-camera-workshop/device/README.md index f9bae73..170d804 100644 --- a/plugins/rdk-camera-workshop/device/README.md +++ b/plugins/rdk-camera-workshop/device/README.md @@ -2,7 +2,7 @@ `x5-course-detect.py` 使用现有 X5 Camera SDK 适配器和 RDK Model Zoo 的 Ultralytics YOLO Detect。原生 X5 验收需要与相机板卡匹配的私有配置、已有的适配器模块、Model Zoo 检测 wrapper 与 Python 工具、合格的 ISP 候选和课程静态图。 -先在 Studio 逐工位执行 probe,并检查实验没有进行中的调试或待恢复写入。独占诊断使用与原 daemon 相同的用户与私有配置。开始前停止同一 systemd 相机服务,确认没有第二个采集进程。退出后检查原始 ISP 回读及停流,再启动原服务。 +先在 Studio 为各组相机执行 probe,并检查实验没有进行中的调试或待恢复写入。独占诊断使用与原 daemon 相同的用户与私有配置。开始前停止同一 systemd 相机服务,确认没有第二个采集进程。退出后检查原始 ISP 回读及停流,再启动原服务。 ```sh python3 device/x5-course-detect.py \ @@ -20,8 +20,43 @@ Model Zoo 目录包含 `ultralytics_yolo_det.py` 及兼容的 `utils/py_utils` 课堂做一次 Gamma 对照时,改用 `--gamma-toolkit `,保存原始、候选、恢复三张图。已加载配置且只核对推理时使用 `--current-isp`。Gamma 试验使用单独的恢复账本和当前实际相机状态。结束后检查运行目录的 `receipt.json`、三份 ISP 回读以及图片。 -将同一运行目录完整同步到本机私有工位目录,把绝对路径配置为课程 MCP 的 `RDK_VISION_COURSE_BOARD_ARCHIVE`。导入工作台前仍要核对模型 SHA-256 与本组产物一致。运行成功、检测框数量、学员认为是否检出目标在页面中分别记录。 +将同一运行目录完整同步到本机私有实验目录,把绝对路径配置为课程 MCP 的 `RDK_VISION_COURSE_BOARD_ARCHIVE`。导入工作台前仍要核对模型 SHA-256 与本组产物一致。运行成功、检测框数量、学员认为是否检出目标在页面中分别记录。 + +## 为本组实验配置 Studio 一键检测 + +助教在 Studio 所在电脑上配置一个可信的启动程序。配置保存为当前用户可写的私有 JSON,`RDK_VISION_COURSE_BOARD_LAUNCHER` 指向其绝对路径。实验已打开时,先导出进度,再重开同一个实验加载配置。 + +```json +{ + "archiveRoot": "/absolute/path/to/private/board-archives", + "experimentId": "<本组已关联的相机实验 UUID>", + "profiles": { + "A": { + "executable": "/absolute/path/to/python3", + "args": ["/absolute/path/to/x5-station-bridge.py", "client", "--config", "/absolute/path/to/own-client.json"], + "modelSha256": "<本组 X5 BIN 的 64 位十六进制 SHA-256>", + "supportsApprovedIsp": true, + "supportsIspComparison": true + }, + "B": { + "executable": "/absolute/path/to/python3", + "args": ["/absolute/path/to/x5-station-bridge.py", "client", "--config", "/absolute/path/to/preset-client.json"], + "modelSha256": "<预置 X5 BIN 的 64 位十六进制 SHA-256>" + } + } +} +``` + +运行目录须提前存在。Windows 使用本机可执行文件和目录的绝对路径。每个路径绑定一个实际模型,B 可省略。启动程序只接收固定参数,由助教配置同一块板卡的可信连接、Model Zoo、课程样张和适配器。启动时提供以下环境变量。 + +仓库的 `x5-station-bridge.py` 提供了 SSH 启动器。将它与检测 runner 放到板上固定目录。电脑的 `*-client.json` 填 `sshHost`(已配置且校验过主机密钥的 OpenSSH 别名)、`boardBridge`(板上的启动器绝对路径)和 `boardConfig`(板端配置绝对路径)。可用 `sshExecutable` 指定本机的 OpenSSH、`sshConfig` 指定本机私有的 OpenSSH 配置。该别名需要已有的非交互授权。 + +板端配置填 `model`、`profile`、`staticImage`、`modelZoo`、`cameraModule`、`cameraConfig`、`runner` 和 `runRoot` 的绝对路径,再填实际的 `cameraService`、`cameraUser`、可选的 `seconds`(1–60)。`runRoot` 由相机用户持有并只向该用户开放;服务管理由已授权的 SSH 账户执行。 -课堂展示运行中的检测时,从开跑开始持续同步该运行目录。优先使用本工位已配置的共享目录或文件同步,保留 runner 的文件名,先同步带框 JPEG 和回读文件,再原子替换 `receipt.json`。Runner 每约半秒发布一次进度。同一 Run 的 SDK 帧时间持续推进时,工作台才显示「实时更新」。同步停住时仍可看最近已验证帧,结束后显示「本轮归档帧」。等待写完的文件会自动重新读取,哈希不匹配需要排查归档来源。 +- `RDK_COURSE_RUN_ID` 为本轮 UUID,传给板端的 `--run-id`。 +- `RDK_COURSE_MODEL_SHA256` 为已选模型的 SHA-256。板端再次根据实际 BIN 校验。 +- `RDK_COURSE_RUN_ARCHIVE` 为本机本轮目录。同步板端的同名实拍、结果图及 ISP 回读之后,原子替换本机的 `receipt.json`。实时同步时先同步对应 JPEG。进程结束前完成同步和原相机服务清理。标准输出及错误写入本机本轮的 `runner.log`。 +- `RDK_COURSE_APPROVED_ISP` 为空时用 `--current-isp`。该值为文件路径且本组启动器支持时,将文件通过可信连接传到板端私有目录,以相机服务用户持有的 0600 文件传入 `--approved-isp`。板端会比对期初配置、核对 Gamma 生效曲线、完成检测后恢复和独立回读。配置与检测结果留在本组实验。 +- 更新电脑和 X5 两端启动器及板端检测 runner 后,可启用 `supportsIspComparison`。对照入口仅接受单独修改活动 Gamma 曲线的已核对配置。学员确认机位、照明和课程目标固定后,两段各采集 `seconds` 秒。检测完成、原始配置独立回读一致且停流后,可圈定同一目标区域,计算检出帧、连续检出帧和不匹配框,并把统计和原始回执一起导出。 -检测结束后在同一个检测区点「采用回执并留证」。工作台核对模型、实际 ISP、帧及恢复回执。随后可以选择观察的类别、记录目标是否检出和依据。运行成功可以有零个检测框,学员按实际场景判断。 +工作台只会采用本轮 ID、模型 SHA-256、ISP 回读和停流均匹配的结果。未配置时可手动运行板端入口并读取归档。若工作台突然退出并留下 `.course-detection-active`,先由助教确认板端运行进程已结束、原始 ISP 和停流已核对,再移除空的占用目录。 diff --git a/plugins/rdk-camera-workshop/device/x5-course-detect.py b/plugins/rdk-camera-workshop/device/x5-course-detect.py index 73d74fe..00d4fce 100644 --- a/plugins/rdk-camera-workshop/device/x5-course-detect.py +++ b/plugins/rdk-camera-workshop/device/x5-course-detect.py @@ -1,7 +1,6 @@ #!/usr/bin/env python3 """Run the course model on a qualified X5 camera adapter in an exclusive session.""" import argparse -import uuid import base64 import hashlib import importlib.util @@ -13,10 +12,13 @@ import statistics import sys import time +from uuid import UUID, uuid4 CLASSES = ('park', 'qrcode', 'obstacle') OUTPUT_NAMES = ('output0', '326', '334', '342', '350', '358') OUTPUT_SHAPES = [(1, size, size, channels) for size in (80, 40, 20) for channels in (3, 64)] +SCORE_THRESHOLD = .25 +NMS_THRESHOLD = .70 def sha256(blob): @@ -58,9 +60,18 @@ def preview_bgr(camera, data, info, cv2, np): uv = raw[info['size_y']:].reshape(height // 2, info['stride_uv'])[:, :width].reshape(height // 2, width // 2, 2) y_small = cv2.resize(y, (960, 540), interpolation=cv2.INTER_AREA) uv_small = cv2.resize(uv, (480, 270), interpolation=cv2.INTER_AREA) - png = camera.frame_tools.nv12_to_png(y_small.tobytes(), uv_small.tobytes(), width=960, height=540, - y_stride=960, uv_stride=960, matrix=camera.config['colorMatrix'], color_range=camera.config['colorRange'], compression_level=1) - return cv2.imdecode(np.frombuffer(png, dtype=np.uint8), cv2.IMREAD_COLOR) + y_table, r_table, b_table, gu_table, gv_table = ( + np.asarray(table, dtype=np.int32) for table in camera.frame_tools._nv12_tables( + camera.config['colorMatrix'], camera.config['colorRange']) + ) + y_codes = y_table[y_small].reshape(270, 2, 480, 2) + u, v = uv_small[:, :, 0], uv_small[:, :, 1] + offsets = (b_table[u], gu_table[u] + gv_table[v], r_table[v]) + bgr = np.empty((540, 960, 3), dtype=np.uint8) + for channel, offset in enumerate(offsets): + values = (y_codes + offset[:, None, :, None] + 32768) >> 16 + bgr[:, :, channel] = np.clip(values, 0, 255).reshape(540, 960) + return bgr def archive_frame(camera, output, prefix, expected_hash): @@ -74,17 +85,48 @@ def archive_frame(camera, output, prefix, expected_hash): 'tuningHash': expected_hash, 'sdkTimestampNs': frame['evidence']['sdkTimestampNs']} +def without_active_gamma_curve(config): + modules = config['modules'] + gamma = dict(modules['gamma']) + key = {0: 'auto_attr.curve', 1: 'manual_attr.curve'}[gamma['mode']] + gamma.pop(key) + return {**config, 'modules': {**modules, 'gamma': gamma}} + + +def ensure_no_camera_daemon_conflict(): + proc = Path('/proc') + if not proc.is_dir(): + return + self_pid = os.getpid() + for entry in proc.iterdir(): + if not entry.name.isdigit() or int(entry.name) == self_pid: + continue + try: + cmdline = (entry / 'cmdline').read_bytes().replace(b'\x00', b' ').decode('utf-8', 'ignore') + except OSError: + continue + if 'vision-x5-camera.py' in cmdline: + raise RuntimeError('camera_daemon_running_conflict') + + def main(args): if platform.machine() != 'aarch64': raise RuntimeError('x5_aarch64_runtime_required') import cv2 import numpy as np + # This pipeline already overlaps the SDK and BPU workers. Keep OpenCV's + # resize and encode threads bounded on the X5 CPU. + cv2.setNumThreads(2) model_sha = model_binding(args.profile, args.model) effect = args.effect.read_bytes() if args.effect else None if effect is not None and sha256(effect) != args.effect_sha256: raise ValueError('isp_candidate_sha256_mismatch') native = load_module('course_vision_x5_camera', args.camera_module) native_config = native.read_private_json(args.camera_config) + approved = native.read_private_json(args.approved_isp) if args.approved_isp else None + if approved and (native.digest(approved['config']) != approved['hash'] + or native.digest(approved['originalConfig']) != approved['originalHash']): + raise ValueError('approved_isp_sha256_mismatch') environment = native.gpio_permission_environment(native_config) if environment is not None: os.execve(sys.executable, [sys.executable, str(Path(__file__).resolve()), *sys.argv[1:]], environment) @@ -109,10 +151,23 @@ def main(args): native_config['stateDir']=str(args.output.with_name(args.output.name+'-sdk-state')) sys.path.insert(0, str(args.gamma_toolkit)) from x5_gamma_tuning_candidate import tuning_candidate as candidate_builder + if approved is not None: + gamma_mode = approved.get('config', {}).get('modules', {}).get('gamma', {}).get('mode') + curve_key = {0: 'gamma.auto_attr.curve', 1: 'gamma.manual_attr.curve'}.get(gamma_mode) + if curve_key and curve_key not in native_config.get('ispFieldPolicies', {}): + native_config = dict(native_config) + policies = dict(native_config.get('ispFieldPolicies', {})) + policies[curve_key] = { + 'min': 0, + 'max': 1023, + 'evidenceRef': f'Approved classroom Gamma ({curve_key}) with independent SDK readback', + } + native_config['ispFieldPolicies'] = policies sys.path.insert(0, str(args.model_zoo)) zoo = load_module('ultralytics_yolo_det', args.model_zoo/'ultralytics_yolo_det.py') detector = zoo.UltralyticsYOLODetect(zoo.UltralyticsYOLODetectConfig( - model_path=str(args.model), classes_num=3, resize_type=0, score_thres=.25, nms_thres=.70)) + model_path=str(args.model), classes_num=3, resize_type=0, + score_thres=SCORE_THRESHOLD, nms_thres=NMS_THRESHOLD)) detector.set_scheduling_params(priority=0, bpu_cores=[0]) if (detector.input_w, detector.input_h) != (640, 640) or tuple(detector.output_names) != OUTPUT_NAMES: raise RuntimeError('bpu_runtime_tensor_mismatch') @@ -138,7 +193,7 @@ def infer(image): return detections, elapsed args.output.mkdir(mode=0o700, exist_ok=False) - report = {'schema':'rdk.vision-course-board.v1','runId':str(uuid.uuid4()),'modelSha256':model_sha,'effectSha256':args.effect_sha256,'classes':CLASSES, + report = {'schema':'rdk.vision-course-board.v1','runId':str(args.run_id or uuid4()),'modelSha256':model_sha,'effectSha256':args.effect_sha256,'classes':CLASSES, 'status':'started','stage':'model_loaded','restoration':'not_run','frames':[], 'phases':{}} report_file = args.output/'receipt.json' write_json(report_file, report) @@ -149,8 +204,10 @@ def infer(image): if not cv2.imwrite(str(args.output/'static-detection.jpg'), static): raise RuntimeError('static_evidence_write_failed') report['staticBpu'] = {'detections':findings,'forwardMs':ms, - 'imageSha256':sha256(args.static_image.read_bytes())} + 'imageSha256':sha256(args.static_image.read_bytes()), + 'outputImageSha256':sha256((args.output/'static-detection.jpg').read_bytes())} report['stage']='static_bpu_verified';write_json(report_file,report) + ensure_no_camera_daemon_conflict() camera = native.Camera(native_config) if camera.unconfirmed or camera.cleanup_required or camera.changed: report.update(status='failed', failure='previous_camera_recovery_required') @@ -165,7 +222,7 @@ def infer(image): raise RuntimeError('imx415_required') camera.start() report['cameraIdentity'] = camera.identity() - original = camera.execute('tuning_get',{}) + original = camera.execute('tuning_export',{}) write_json(args.output/'original-isp.json',original) report['ispSnapshots']={'original-isp.json':sha256((args.output/'original-isp.json').read_bytes())} timestamp = 0 @@ -174,14 +231,21 @@ def collect(phase, expected_hash, duration): start=time.monotonic() first=len(report['frames']) report['stage']=phase;write_json(report_file,report) - next_preview=0 + rows_pending=[] + verified_at=start + if current_isp_hash() != expected_hash: + raise RuntimeError('isp_changed_before_frame') while time.monotonic()-start < duration: - row = infer_frame(phase, expected_hash, timestamp) + row = infer_frame(phase, expected_hash, timestamp, len(report['frames'])+len(rows_pending)) timestamp=int(row['sdkTimestampNs']) - report['frames'].append(row) - if time.monotonic()>next_preview: + rows_pending.append(row) + # The runner owns the stream and only publishes a batch when + # the readback at its two boundaries matches the selected ISP. + if time.monotonic()-verified_at>=.65 or len(rows_pending)>=6: + verify_pending(rows_pending,expected_hash) + verified_at=time.monotonic() write_json(report_file,report) - next_preview=time.monotonic()+0.5 + verify_pending(rows_pending,expected_hash) if len(report['frames'])==first: raise RuntimeError('no_live_frames') rows=report['frames'][first:] @@ -190,32 +254,45 @@ def collect(phase, expected_hash, duration): 'bestQrcodeScore':max((d['score'] for d in findings),default=None), 'medianForwardMs':statistics.median(row['forwardMs'] for row in rows), 'processingFps':len(rows)/(time.monotonic()-start)} - def infer_frame(phase, expected_hash, cursor): + def current_isp_hash(): + with camera.lock: + if camera.cleanup_required or camera.unconfirmed: + raise RuntimeError('camera_state_unconfirmed') + return camera.full_isp().digest(camera.configuration(camera.controls())) + + def verify_pending(rows, expected_hash): + if not rows: + return + if current_isp_hash() != expected_hash: + raise RuntimeError('isp_changed_during_frames') + report['frames'].extend(rows) + rows.clear() + + def infer_frame(phase, expected_hash, cursor, number): begin = time.monotonic() with camera.lock: if camera.cleanup_required or camera.unconfirmed: raise RuntimeError('camera_state_unconfirmed') - active = camera.full_isp().digest(camera.configuration(camera.controls())) - if active != expected_hash: - raise RuntimeError('isp_changed_before_frame') blob, info = camera.take_frame(False) - if camera.full_isp().digest(camera.configuration(camera.controls())) != active: - raise RuntimeError('isp_changed_during_frame') + captured = time.monotonic() evidence = camera.frame_evidence(info) current = int(evidence['sdkTimestampNs']) if current <= cursor: raise RuntimeError('camera_frame_not_fresh') image = preview_bgr(camera, blob, info, cv2, np) + converted = time.monotonic() detections, ms = infer(image) + detected = time.monotonic() ok, jpg = cv2.imencode('.jpg',image) if not ok: raise RuntimeError('frame_encode_failed') - number = len(report['frames']) filename = f'frame-{number:05d}.jpg' frame_bytes = jpg.tobytes() (args.output/filename).write_bytes(frame_bytes) return {'file':filename,'imageSha256':sha256(frame_bytes),'sdkTimestampNs':str(current),'phase':phase, - 'modelSha256':model_sha,'tuningHash':active,'forwardMs':ms, + 'modelSha256':model_sha,'tuningHash':expected_hash,'forwardMs':ms, + 'captureMs':(captured-begin)*1000,'conversionMs':(converted-captured)*1000, + 'inferenceWorkMs':(detected-converted)*1000, 'frameWorkMs':(time.monotonic()-begin)*1000,'detections':detections} expected=original @@ -227,6 +304,24 @@ def infer_frame(phase, expected_hash, cursor): wrote_configuration=True candidate=camera.execute('apply_tuning',{'tuning':staged,'tuningHash':native.digest(staged)}) report['gamma']['curveReadback']=candidate['evidence']['streamVerification'].get('gammaCurrentCurve') + elif approved is not None: + if not camera.same_configuration(original['config'],approved['originalConfig']): + raise RuntimeError('approved_isp_original_mismatch') + if args.compare_approved: + # Every other setting must match the baseline to attribute the change to Gamma. + if without_active_gamma_curve(approved['config']) != without_active_gamma_curve(approved['originalConfig']): + raise RuntimeError('comparison_requires_gamma_only') + report['comparison']={'durationPerPhaseSec':args.seconds,'width':960,'height':540, + 'scoreThreshold':SCORE_THRESHOLD,'nmsThreshold':NMS_THRESHOLD, + 'approvedBaselineHash':approved['originalHash']} + report['baselineTuningHash']=original['readbackHash'] + collect('before',original['readbackHash'],args.seconds) + wrote_configuration=True + candidate=camera.execute('apply_tuning',{'tuning':approved['config'],'tuningHash':approved['hash']}) + active_curve = candidate['evidence']['streamVerification'].get('gammaCurrentCurve') + if active_curve is None or active_curve.get('status') != 'verified': + raise RuntimeError('approved_gamma_current_curve_unconfirmed') + report['approvedGamma'] = {'hash':approved['hash'],'curveReadback':active_curve} elif effect is not None: if not original.get('contentBase64'): raise RuntimeError('original_effect_library_required') @@ -234,14 +329,14 @@ def infer_frame(phase, expected_hash, cursor): candidate=camera.execute('tuning_load',{'contentBase64':base64.b64encode(effect).decode(),'sha256':args.effect_sha256}) if wrote_configuration: expected=camera.execute('tuning_export',{}) - if expected['readbackHash']!=candidate['readbackHash']: + if expected['readbackHash']!=candidate['readbackHash'] or approved and expected['readbackHash']!=approved['hash']: raise RuntimeError('isp_candidate_readback_mismatch') report['tuningHash']=expected['readbackHash'] write_json(args.output/'loaded-isp.json',expected) report['ispSnapshots']['loaded-isp.json']=sha256((args.output/'loaded-isp.json').read_bytes()) if candidate_builder: report['gamma']['images']['after']=archive_frame(camera,args.output,'B-candidate',expected['readbackHash']) - collect('after' if candidate_builder else 'live',expected['readbackHash'],args.seconds) + collect('after' if candidate_builder or args.compare_approved else 'live',expected['readbackHash'],args.seconds) report['status']='captured' except BaseException as error: report.update(status='failed', failure=str(error)) @@ -262,11 +357,14 @@ def infer_frame(phase, expected_hash, cursor): if report.get('gamma') and independent['readbackHash']==original['readbackHash']: report['gamma']['images']['restored']=archive_frame(camera,args.output,'A2-restored',independent['readbackHash']) elif original is not None: + final = camera.execute('tuning_export', {}) + if final['readbackHash'] != original['readbackHash']: + raise RuntimeError('current_isp_changed_during_run') report['restoration']='no_write' camera.execute('preview_stop',{}) report['previewStopped']=True except BaseException as error: - report.update(restoration='unconfirmed', restorationFailure=str(error)) + report.update(status='failed', restoration='unconfirmed', restorationFailure=str(error)) raise finally: try: @@ -285,11 +383,16 @@ def infer_frame(phase, expected_hash, cursor): mode=parser.add_mutually_exclusive_group(required=True) mode.add_argument('--effect',type=lambda value:Path(value).resolve()) mode.add_argument('--current-isp',action='store_true') + mode.add_argument('--approved-isp',type=lambda value:Path(value).resolve()) + parser.add_argument('--compare-approved',action='store_true') mode.add_argument('--gamma-toolkit',type=lambda value:Path(value).resolve()) parser.add_argument('--effect-sha256') parser.add_argument('--gamma-strength',type=float,default=.8) parser.add_argument('--seconds',type=int,choices=range(1,61),default=30,metavar='1..60') + parser.add_argument('--run-id',type=UUID,help='Run ID issued by the classroom workbench.') options=parser.parse_args() + if options.compare_approved and not options.approved_isp: + parser.error('Comparison requires an approved Gamma snapshot.') if bool(options.effect)!=bool(options.effect_sha256) or options.gamma_toolkit and not 0 MAX_ASSET: + raise ValueError('board_asset_size_limit') + temporary = output / (name + '.part') + temporary.write_bytes(content) + temporary.replace(output / name) + finally: + process.stdout.close() + return process.wait() + + +def board(options): + import fcntl + import hashlib + import pwd + + config = config_from(options.config) + model = Path(config['model']) + if hashlib.sha256(model.read_bytes()).hexdigest() != options.model_hash: + raise ValueError('station_model_sha256_mismatch') + run_id = str(uuid.UUID(options.run_id)) + root = Path(config['runRoot']) + archive = root / run_id + service = config['cameraService'] + if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.@-]*\.service', service): + raise ValueError('invalid_camera_service') + user = pwd.getpwnam(config['cameraUser']) + lock = (root / '.station-detector.lock').open('a') + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + journal = Path(config_from(config['cameraConfig'])['stateDir']) / 'isp-write.json' + if journal.exists(): + state = config_from(journal) + if state.get('cleanupRequired') or state.get('outcome') in ('pending','unconfirmed','confirmed'): + raise RuntimeError('previous_camera_recovery_required') + payload = sys.stdin.buffer.read(MAX_ASSET + 1) + if len(payload) > MAX_ASSET: + raise ValueError('approved_isp_size_limit') + if options.comparison and not payload: + raise ValueError('comparison_requires_approved_gamma') + mode = ['--current-isp'] + isp = None + if payload: + isp = root / (run_id + '.isp.json') + fd = os.open(isp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, 'wb') as handle: + os.fchown(handle.fileno(), user.pw_uid, user.pw_gid) + handle.write(payload) + mode = ['--approved-isp', str(isp)] + if options.comparison: + mode.append('--compare-approved') + + def send(name, content): + print(json.dumps({'file': name, 'base64': base64.b64encode(content).decode('ascii')}, + separators=(',', ':')), flush=True) + + receipt = archive / 'receipt.json' + sent = set() + previous = None + + def publish(final): + nonlocal previous + if not receipt.is_file(): + return + content = receipt.read_bytes() + if previous == content and not final: + return + report = json.loads(content) + assets = [*report.get('ispSnapshots', {})] + if report.get('staticBpu'): + assets.append('static-detection.jpg') + frames = report['frames'] if final else report['frames'][-6:] + assets.extend(frame['file'] for frame in frames) + for name in assets: + if name not in sent and ARCHIVED.fullmatch(name): + send(name, (archive / name).read_bytes()) + sent.add(name) + if previous != content: + send('receipt.json', content) + previous = content + + def service_command(operation): + subprocess.run(['systemctl', operation, service], stdout=subprocess.DEVNULL, check=True) + + service_command('is-active') + # root maintains the service. The camera process uses the existing + # unprivileged SDK user so the original private ISP journal is reused. + flags = {'profile': 'profile', 'model': 'model', 'static-image': 'staticImage', 'model-zoo': 'modelZoo', + 'camera-module': 'cameraModule', 'camera-config': 'cameraConfig'} + arguments = [value for flag, name in flags.items() for value in ('--' + flag, config[name])] + command = ['runuser', '-u', user.pw_name, '--', 'python3', config['runner'], *arguments, *mode, + '--output', str(archive), '--run-id', run_id, '--seconds', str(config.get('seconds', 28))] + log_file = root / (run_id + '.log') + try: + service_command('stop') + with log_file.open('xb') as log, subprocess.Popen(command, stdout=log, stderr=log) as worker: + try: + while worker.poll() is None: + publish(False) + time.sleep(.13) + publish(True) + finally: + if worker.poll() is None: + worker.terminate() + try: + worker.wait(timeout=15) + except subprocess.TimeoutExpired: + worker.kill() + worker.wait(timeout=5) + send('board-run.log', log_file.read_bytes()) + return worker.returncode + finally: + if isp is not None: + try: + isp.unlink(missing_ok=True) + except OSError: + pass + try: + service_command('start') + service_command('is-active') + finally: + lock.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('side', choices=('client', 'board')) + parser.add_argument('--config', required=True) + parser.add_argument('--run-id') + parser.add_argument('--model-hash') + parser.add_argument('--comparison', action='store_true') + options = parser.parse_args() + if options.side == 'client': + return client(options) + if not options.run_id or not options.model_hash: + parser.error('Board mode requires the run ID and model hash.') + + def stop(_signal, _frame): + raise KeyboardInterrupt + + signal.signal(signal.SIGTERM, stop) + signal.signal(signal.SIGHUP, stop) + return board(options) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/plugins/rdk-camera-workshop/mcp/board-launcher.mjs b/plugins/rdk-camera-workshop/mcp/board-launcher.mjs new file mode 100644 index 0000000..6ca2375 --- /dev/null +++ b/plugins/rdk-camera-workshop/mcp/board-launcher.mjs @@ -0,0 +1,142 @@ +import {spawn} from 'node:child_process'; +import {createHash,randomUUID} from 'node:crypto'; +import {closeSync,existsSync,lstatSync,mkdirSync,openSync,readFileSync,renameSync,rmdirSync,unlinkSync,writeFileSync} from 'node:fs'; +import path from 'node:path'; +import {boardEvidence} from './course-evidence.mjs'; + +export function createBoardLauncher(configFile=process.env.RDK_VISION_COURSE_BOARD_LAUNCHER,{onChange}={}) { + const idPattern=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; + const modelPattern=/^[a-f0-9]{64}$/; + const validProfile=value=>path.isAbsolute(value.executable)&&Array.isArray(value.args)&&value.args.length<=32&& + value.args.every(arg=>typeof arg==='string'&&arg.length<=4096&&!arg.includes('\0'))&&modelPattern.test(value.modelSha256); + let config; + let issue='board_launcher_unconfigured'; + if(configFile) { + try { + if(!path.isAbsolute(configFile)) throw new Error(); + const source=lstatSync(configFile); + const writableByOthers=value=>process.platform!=='win32'&&(value.uid!==process.getuid()||Boolean(value.mode&0o022)); + if(!source.isFile()||source.size>32768||writableByOthers(source)) throw new Error(); + const data=JSON.parse(readFileSync(configFile,'utf8')); + const profiles=data.profiles??{[data.path]:data}; + if(!path.isAbsolute(data.archiveRoot)) throw new Error(); + const archive=lstatSync(data.archiveRoot); + if(!archive.isDirectory()||writableByOthers(archive)|| + !idPattern.test(data.experimentId)||!Object.keys(profiles).length|| + Object.entries(profiles).some(([route,value])=>!['A','B'].includes(route)||!validProfile(value))) throw new Error(); + config={...data,profiles}; + } catch {issue='board_launcher_invalid';} + } + const lease=config&&path.join(config.archiveRoot,'.course-detection-active'); + const pointer=route=>path.join(config.archiveRoot,'last-'+config.experimentId+'-'+route+'.json'); + const runs=new Map(); + function profile(selection) { + if(!['A','B'].includes(selection.path)) return; + const value=config?.profiles[selection.path]; + if(value&&value.modelSha256===selection.modelHash) return value; + } + function ready(selection) { + if(!config) return issue; + if(!profile(selection)) return 'board_launcher_model_unbound'; + if(selection.experimentId!==config.experimentId) return 'board_launcher_camera_unbound'; + if(!selection.available) return 'board_launcher_route_unready'; + if(selection.cameraBusy) return 'board_launcher_camera_busy'; + if(running()) return [...runs.values()].some(run=>run.state==='running')?'board_launcher_running':'board_launcher_locked'; + } + function current(selection) { + if(!profile(selection)||selection.experimentId!==config.experimentId) return; + if(runs.has(selection.path)) return runs.get(selection.path); + try { + const filepath=pointer(selection.path); + const file=lstatSync(filepath); + if(!file.isFile()||file.size>4096) return; + const {id,modelHash}=JSON.parse(readFileSync(filepath,'utf8')); + if(!idPattern.test(id)||modelHash!==selection.modelHash) return; + const run={id,state:'completed',evidence:boardEvidence(path.join(config.archiveRoot,id),{runId:id})}; + runs.set(selection.path,run); + return run; + } catch {return;} + } + function status(selection) { + const reason=ready(selection); + const run=current(selection); + const canUseApprovedIsp=Boolean(profile(selection)?.supportsApprovedIsp===true&&selection.approvedIsp); + return {ready:!reason,reason,canUseApprovedIsp, + canCompareIsp:canUseApprovedIsp&&profile(selection)?.supportsIspComparison===true&&selection.comparisonEligible===true, + ...(run?{run:{id:run.id,state:run.state,error:run.error}}:{})}; + } + function running() {return Boolean(lease&&existsSync(lease));} + function evidence(selection) {return current(selection)?.evidence;} + function start(selection,mode='current') { + const reason=ready(selection); + if(reason) throw new Error(reason); + const target=profile(selection); + if(!['current','approved','comparison'].includes(mode)) throw new Error('board_launcher_isp_unavailable'); + const comparison=mode==='comparison'; + if(comparison&&(target.supportsIspComparison!==true||!selection.comparisonEligible)) throw new Error('board_launcher_comparison_unavailable'); + const approved=mode==='current'?undefined:selection.approvedIsp; + const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex'); + if(mode!=='current'&&(target.supportsApprovedIsp!==true||!approved?.config||!approved.originalConfig|| + hash(approved.originalConfig)!==approved.originalHash||hash(approved.config)!==approved.hash)) { + throw new Error('board_launcher_isp_unavailable'); + } + try {mkdirSync(lease,{mode:0o700});} + catch (error) {throw new Error(error.code==='EEXIST'?'board_launcher_locked':'board_launcher_start_failed');} + const id=randomUUID(); + const directory=path.join(config.archiveRoot,id); + const settings=approved?path.join(directory,'approved-isp.json'):''; + const next={id,state:'running',evidence:boardEvidence(directory,{runId:id})}; + let log,child; + try { + mkdirSync(directory,{mode:0o700}); + if(approved) writeFileSync(settings,JSON.stringify(approved),{mode:0o600,flag:'wx'}); + log=openSync(path.join(directory,'runner.log'),'wx',0o600); + child=spawn(target.executable,target.args,{shell:false,windowsHide:true,stdio:['ignore',log,log], + env:{...process.env,RDK_COURSE_RUN_ID:id,RDK_COURSE_RUN_ARCHIVE:directory, + RDK_COURSE_MODEL_SHA256:target.modelSha256,RDK_COURSE_APPROVED_ISP:settings, + RDK_COURSE_COMPARE_ISP:comparison?'1':'0'}}); + } catch { + rmdirSync(lease); + throw new Error('board_launcher_start_failed'); + } finally {if(log!==undefined) closeSync(log);} + runs.set(selection.path,next); + let startFailed=false; + let timedOut=false; + child.once('error',()=>{startFailed=true;}); + const timeout=setTimeout(()=>{timedOut=true;child.kill();},comparison?300000:180000); + child.once('close',async code=>{ + clearTimeout(timeout); + const temporary=path.join(lease,'receipt.json'); + try { + if(timedOut||startFailed||code!==0) throw new Error(timedOut?'board_launcher_timeout':startFailed?'board_launcher_start_failed':'board_launcher_run_failed'); + const {view}=await next.evidence.get(target.modelSha256); + if(view.status!=='completed'||!view.previewStopped||!view.staticBpu||!view.latestDetection|| + !['verified','no_write'].includes(view.restoration)) throw new Error('board_launcher_receipt_incomplete'); + if(approved&&(view.readbackHash!==approved.hash||view.restoration!=='verified'||!view.approvedGamma)) throw new Error('board_launcher_receipt_incomplete'); + if(comparison) { + if(view.comparison?.settings.approvedBaselineHash!==approved.originalHash||view.comparison?.after.tuningHash!==approved.hash) { + throw new Error('board_launcher_receipt_incomplete'); + } + await next.evidence.file(target.modelSha256,view.comparison.before.file,view.receiptSha256); + } + await next.evidence.file(target.modelSha256,view.latestDetection.file,view.receiptSha256); + await next.evidence.file(target.modelSha256,'loaded-isp.json',view.receiptSha256); + if(view.restoration==='verified') await next.evidence.file(target.modelSha256,'restored-isp.json',view.receiptSha256); + const latest=pointer(selection.path); + writeFileSync(temporary,JSON.stringify({id,modelHash:target.modelSha256}),{flag:'wx',mode:0o600}); + renameSync(temporary,latest); + next.state='completed'; + } catch (error) { + next.state='failed'; + next.error=error.message.startsWith('board_launcher_')?error.message:'board_launcher_receipt_incomplete'; + } finally { + try { if(existsSync(temporary)) unlinkSync(temporary); } catch {} + try {rmdirSync(lease);} + catch {next.state='failed';next.error='board_launcher_locked';} + try { onChange?.(next); } catch {} + } + }); + return status(selection); + } + return {status,start,running,evidence}; +} diff --git a/plugins/rdk-camera-workshop/mcp/bridge.mjs b/plugins/rdk-camera-workshop/mcp/bridge.mjs index 997e82f..0b69367 100644 --- a/plugins/rdk-camera-workshop/mcp/bridge.mjs +++ b/plugins/rdk-camera-workshop/mcp/bridge.mjs @@ -1,8 +1,8 @@ #!/usr/bin/env node /** Bounded stdio MCP transport for the reviewed d-obs camera tools. Node >= 22. */ -import { isEntrypoint } from './entrypoint.mjs'; -import { constants, readFileSync } from 'node:fs'; -import { access, open, realpath } from 'node:fs/promises'; +import { constants, readFileSync, realpathSync } from 'node:fs'; +import { createHash, randomUUID } from 'node:crypto'; +import { access, mkdir, open, realpath, rename, rm, writeFile } from 'node:fs/promises'; import { homedir } from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; @@ -10,23 +10,80 @@ import { once } from 'node:events'; const MAX_INPUT_BYTES = 24 * 1024 * 1024; const MAX_BYTES = 96 * 1024 * 1024; +const MAX_LIBRARY_BYTES = 16 * 1024 * 1024; const MAX_CONCURRENT = 4; const DEFAULT_TIMEOUT_MS = 150_000; const ENDPOINT = '/api/ops/vision-workshop/mcp'; +const REST_ENDPOINT = '/api/ops/observability/vision-workshop'; const modulePath = fileURLToPath(import.meta.url); const protocols = new Set(['2024-11-05', '2025-03-26', '2025-06-18']); const onboarding = process.env.RDK_CAMERA_WORKSHOP_ONBOARDING === '1'; -const PLUGIN_VERSION = JSON.parse(readFileSync(new URL('../plugin.json', import.meta.url), 'utf8')).version; +const PLUGIN_VERSION = '1.5.14'; +const RESOLVED_PLUGIN_VERSION = (() => { + if (PLUGIN_VERSION !== '1.3.0') return PLUGIN_VERSION; + try { + const parsed = JSON.parse(readFileSync(new URL('../plugin.json', import.meta.url), 'utf8')); + return typeof parsed?.version === 'string' && parsed.version.trim() ? parsed.version.trim() : PLUGIN_VERSION; + } catch { return PLUGIN_VERSION; } +})(); const connectionTool = { - name: 'vision_connection_status', description: '检查本机相机服务连接配置。首次安装或远端工具缺失时先调用;仅验证配置,不表示设备在线。', + name: 'vision_connection_status', description: '只读。检查本机相机服务连接配置(不代表设备在线)。', inputSchema: { type: 'object', properties: {}, additionalProperties: false }, annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }, }; const versionTool = { - name: 'vision_plugin_version', description: '返回本插件版本号。用于检查是否有更新版本可用。', + name: 'vision_plugin_version', description: '只读。返回本插件版本号。', inputSchema: { type: 'object', properties: {}, additionalProperties: false }, annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }, }; +const artifactIdPattern = '^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$'; +const artifactId = new RegExp(artifactIdPattern); +const sha256Pattern = '^[a-f0-9]{64}$'; +const sha256 = new RegExp(sha256Pattern); +const libraryDownloadTool = { + name: 'vision_isp_tuning_download', + description: '只读。按导出回执的 experimentId、artifactId、sha256 保存已校验效果库原文件,返回 Studio 下载入口或本机路径。', + inputSchema: { type: 'object', properties: { + experimentId: { type: 'string', pattern: artifactIdPattern }, + artifactId: { type: 'string', pattern: artifactIdPattern }, + sha256: { type: 'string', pattern: sha256Pattern }, + byteLength: { type: 'integer', minimum: 1, maximum: MAX_LIBRARY_BYTES }, + }, required: ['experimentId', 'artifactId', 'sha256'], additionalProperties: false }, + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }, +}; +const safeIdPattern = '^[A-Za-z0-9][A-Za-z0-9_:-]{0,127}$'; +const safeId = new RegExp(safeIdPattern); +const bringupFlowTool = { + name: 'vision_camera_bringup_flow', + description: '一键确定性点亮与建基线编排:按安全顺序依次执行 probe(含恢复围栏检查)→ bringup → pipeline_validate → capture_frame(可选)→ controls_get,并在捕获首帧后直接返回 Studio 内联预览图与可调参数清单。任一阶段失败立即停止并返回精确阶段与修复建议,绝不跳过恢复门禁。', + inputSchema: { type: 'object', properties: { + experimentId: { type: 'string', pattern: safeIdPattern }, + scene: { type: 'string', minLength: 1, maxLength: 120 }, + captureBaselineFrame: { type: 'boolean' }, + includePreview: { type: 'boolean' }, + }, required: ['experimentId'], additionalProperties: false }, + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false }, +}; +const aiDebugPreviewTool = { + name: 'vision_ai_debug_preview', + description: '只读。读取指定 AI 调试 Run 的原始帧与最优/终态/最新实拍帧,校验 SHA-256 后合成带亮度/暗部/高光/原尺寸锐度与平坦区噪声差值的竖向前后对照图,直接内联展示在 Studio 聊天界面。', + inputSchema: { type: 'object', properties: { + experimentId: { type: 'string', pattern: safeIdPattern }, + runId: { type: 'string', pattern: safeIdPattern }, + compareTarget: { type: 'string', enum: ['best', 'final', 'latest'] }, + }, required: ['experimentId', 'runId'], additionalProperties: false }, + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }, +}; +const framePreviewTool = { + name: 'vision_camera_frame_preview', + description: '只读。读取当前实验已归档的真实相机帧(frameId)并直接内联展示在 Studio 聊天或 MCP 客户端中,不重新采集。', + inputSchema: { type: 'object', properties: { + experimentId: { type: 'string', pattern: safeIdPattern }, + frameId: { type: 'string', pattern: safeIdPattern }, + label: { type: 'string', minLength: 1, maxLength: 120 }, + }, required: ['experimentId', 'frameId'], additionalProperties: false }, + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true }, +}; // Deliberately omit vision_workshop_execute: this transport has no arbitrary operation executor. const TOOL_ARGUMENTS = new Map(Object.entries({ vision_workshop_capabilities: ['search', 'limit', 'offset'], vision_workshop_runtime_status: [], vision_experiment_list: ['limit', 'offset'], @@ -38,19 +95,19 @@ const TOOL_ARGUMENTS = new Map(Object.entries({ vision_tuning_baseline_import: ['experimentId', 'config', 'rules'], vision_camera_knowledge_search: ['q', 'board', 'sensorModel'], vision_camera_knowledge_get: ['knowledgeId', 'section'], vision_ai_debug_start: ['experimentId', 'goal', 'maxRounds'], - vision_ai_debug_status: ['experimentId', 'runId'], vision_ai_debug_cancel: ['experimentId', 'runId'], - vision_ai_debug_restore_original: ['experimentId', 'runId'], + vision_ai_debug_status: ['experimentId', 'runId'], vision_ai_debug_cancel: ['experimentId', 'runId'], vision_ai_debug_restore_original: ['experimentId', 'runId'], vision_camera_probe: ['experimentId'], vision_pipeline_validate: ['experimentId'], vision_camera_bringup: ['experimentId'], vision_camera_preview_start: ['experimentId', 'mode'], vision_camera_preview_stop: ['experimentId'], vision_camera_preview_frame: ['experimentId', 'afterSdkTimestampNs'], vision_camera_controls_get: ['experimentId'], vision_camera_controls_set: ['experimentId', 'values'], vision_camera_capture_frame: ['experimentId', 'scene', 'candidateId'], vision_raw_capture: ['experimentId', 'scene'], - vision_isp_generate: ['experimentId', 'goal', 'frameIds'], vision_isp_process_raw: ['experimentId', 'sampleId', 'candidateId'], + vision_isp_generate: ['experimentId', 'goal', 'frameIds', 'targetAnalysisFrameId'], vision_isp_process_raw: ['experimentId', 'sampleId', 'candidateId'], vision_isp_apply: ['experimentId', 'candidateId'], vision_isp_restore: ['experimentId', 'baselineId', 'candidateId'], vision_image_evaluate: ['experimentId', 'imageId', 'rating', 'notes'], vision_image_compare: ['experimentId', 'baselineImageId', 'candidateImageId', 'roi'], vision_workshop_export: ['experimentId', 'includeRaw'], vision_isp_tuning_get: ['experimentId'], vision_isp_tuning_load: ['experimentId', 'contentBase64', 'sha256', 'artifactRole', 'artifactId'], vision_isp_tuning_export: ['experimentId'], vision_calibration_asset_import: ['experimentId', 'measurement'], vision_calibration_asset_list: ['experimentId'], - vision_calibration_task_create: ['experimentId', 'operation', 'inputs', 'options'], vision_calibration_task_list: ['experimentId'], + vision_calibration_engines: ['experimentId'], + vision_calibration_task_create: ['experimentId', 'operation', 'engine', 'inputs', 'options'], vision_calibration_task_list: ['experimentId'], vision_calibration_task_get: ['experimentId', 'taskId'], vision_calibration_task_run: ['experimentId', 'taskId'], vision_calibration_task_result: ['experimentId', 'taskId'], vision_calibration_apply_plan: ['experimentId', 'taskId'], vision_calibration_apply: ['experimentId', 'taskId', 'options'], @@ -61,7 +118,8 @@ const READ_ONLY = new Set([ 'vision_camera_workflow', 'vision_camera_stream_analyze', 'vision_camera_response_analyze', 'vision_workshop_delivery', 'vision_camera_probe', 'vision_pipeline_validate', 'vision_camera_preview_frame', 'vision_camera_controls_get', 'vision_workshop_export', 'vision_isp_tuning_get', 'vision_isp_tuning_export', 'vision_calibration_asset_list', 'vision_calibration_task_list', - 'vision_calibration_task_get', 'vision_calibration_task_result', 'vision_calibration_apply_plan', + 'vision_calibration_engines', 'vision_calibration_task_get', 'vision_calibration_task_result', 'vision_calibration_apply_plan', + 'vision_ai_debug_preview', 'vision_camera_frame_preview', ]); const record = value => value !== null && typeof value === 'object' && !Array.isArray(value); const onlyKeys = (value, allowed) => record(value) && Object.keys(value).every(key => allowed.includes(key)); @@ -69,16 +127,31 @@ const rpcError = (id, code, message) => ({ jsonrpc: '2.0', id: id ?? null, error class BridgeError extends Error { constructor(code) { super(code); } } const fail = code => { throw new BridgeError(code); }; const remediation = { + camera_setup_node_22_required: '连接自检需要 Node.js 22 或更高版本。升级后重新运行 doctor。', camera_bridge_unconfigured: '尚未配置连接。运行 configure,并指定服务 URL、认证类型和已有私有凭据文件。', camera_bridge_config_invalid: '连接配置字段不完整:url、auth.type(sso/admin)、credentialFile(绝对路径)为必填,且不含其他字段。', camera_bridge_url_invalid: '服务地址须为 HTTPS(本机可为 loopback HTTP),路径以 /api/ops/vision-workshop/mcp 结尾,且不含 query、hash 或内嵌凭据。', camera_bridge_timeout_invalid: 'timeoutMs 须为 1–300000 的整数。', camera_bridge_private_file_permissions_invalid: '连接配置与凭据文件须由当前用户持有,POSIX 权限为 600。', camera_bridge_private_file_inside_package: '将连接配置和凭据移到插件及源码仓库之外。', + camera_bridge_credential_unavailable: '无法读取配置指向的凭据文件。请检查凭据文件是否存在、当前用户能否读取,再重新运行连接自检。', camera_bridge_credential_invalid: '凭据文件为空或含控制字符;在原服务重新导出后重试。', camera_bridge_remote_http_401: '认证失效,请在原服务更新凭据后重试。', camera_bridge_remote_http_403: '当前身份无权访问该服务,请核对服务权限与入口。', + camera_bridge_remote_http_404: '当前身份下未找到该记录。请核对原实验和归档 ID。', + camera_bridge_remote_http_409: '设备或实验存在状态冲突(如恢复未确认、归档额度满或基线变更)。请先调用 vision_camera_readiness / vision_experiment_get 核对后再决定恢复或新建实验。', + camera_bridge_remote_http_422: '参数未满足当前驱动/SDK 约束或校验失败。请核对 controls_get 范围/量化步进、或检查是否需要先点亮开流(probe → bringup → pipeline_validate)。', + camera_bridge_remote_http_429: '设备正被另一项操作占用(未写入硬件)。请等待当前操作完成后重试,无需执行恢复。', + camera_bridge_remote_http_502: '设备执行或回读异常,请先调用 vision_experiment_get / vision_camera_readiness 核对真实状态,切勿盲目重放写操作。', + camera_bridge_remote_http_503: '相机服务暂时不可用或存储落盘受阻;若为恢复操作返回,请核对回读状态而非重复写硬件。', camera_bridge_remote_transport_failed: '无法访问相机服务,请检查服务运行状态、地址和网络。', + camera_bridge_artifact_integrity_failed: '效果库字节与导出回执不一致。请核对原实验和归档 ID。', + camera_bridge_artifact_save_failed: '效果库已读取,保存失败。请检查本机下载目录的写权限和可用空间。', + camera_bridge_frame_integrity_failed: '归档帧图像内容与回执 SHA-256 或 PNG/JPEG 格式不符,已拒绝展示。', + camera_bridge_frame_unavailable: '当前实验尚无可供预览的归档帧,请先完成拍照或等待 AI 调试采帧。', + camera_setup_runtime_tool_missing: '服务端缺少运行状态工具,尚不能确认连接可用;升级相机服务后重新自检。', + camera_setup_runtime_invalid: '运行状态回执为空、格式不符或未返回成功;核对相机服务入口与版本后重新自检。', + camera_setup_runtime_unavailable: '运行状态工具执行失败;先检查相机服务及当前身份权限,再重新自检。', }; export function describeError(code) { return remediation[code] ?? '检查服务地址、私有文件和认证类型;参阅 README 的连接与自检说明。'; @@ -144,17 +217,427 @@ export async function validateConfiguration(filename = resolveConfigPath()) { function redact(value, credential) { return JSON.parse(JSON.stringify(value, (_key, item) => typeof item === 'string' ? item.split(credential).join('[redacted]') : item)); } -async function boundedBody(response, controller) { - if (Number(response.headers.get('content-length')) > MAX_BYTES) { controller.abort(); fail('camera_bridge_remote_response_too_large'); } +async function boundedBytes(response, controller, limit = MAX_BYTES) { + if (Number(response.headers.get('content-length')) > limit) { controller.abort(); fail('camera_bridge_remote_response_too_large'); } if (!response.body) fail('camera_bridge_remote_response_invalid'); const reader = response.body.getReader(); const chunks = []; let length = 0; - for (;;) { - const { value, done } = await reader.read(); if (done) break; - length += value.byteLength; - if (length > MAX_BYTES) { controller.abort(); await reader.cancel().catch(() => {}); fail('camera_bridge_remote_response_too_large'); } - chunks.push(Buffer.from(value)); + try { + for (;;) { + const { value, done } = await reader.read(); if (done) break; + length += value.byteLength; + if (length > limit) { controller.abort(); await reader.cancel().catch(() => {}); fail('camera_bridge_remote_response_too_large'); } + chunks.push(Buffer.from(value)); + } + } finally { reader.releaseLock(); } + return Buffer.concat(chunks, length); +} + +function credentialHeaders(config) { + return { [config.authType === 'admin' ? 'x-admin-token' : 'x-rdk-sso-session']: config.credential }; +} + +async function saveLibrary(args) { + const config = await connection(); + const address = new URL(config.url); + const mount = address.pathname.slice(0, -ENDPOINT.length); + address.pathname = mount + REST_ENDPOINT + '/experiments/' + args.experimentId + '/vendor-artifacts/' + args.artifactId + '/download'; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), config.timeoutMs); + let bytes; + try { + const response = await fetch(address, { redirect: 'error', signal: controller.signal, headers: { accept: 'application/json', ...credentialHeaders(config) } }); + if (!response.ok) { + await response.body?.cancel(); + fail('camera_bridge_remote_http_' + response.status); + } + if (response.headers.get('content-type')?.split(';')[0] !== 'application/json' || + response.headers.get('x-vision-sha256') !== args.sha256) { + await response.body?.cancel(); + fail('camera_bridge_artifact_integrity_failed'); + } + bytes = await boundedBytes(response, controller, MAX_LIBRARY_BYTES); + if (!bytes.length || args.byteLength !== undefined && args.byteLength !== bytes.length || + createHash('sha256').update(bytes).digest('hex') !== args.sha256) fail('camera_bridge_artifact_integrity_failed'); + } catch (error) { + if (error instanceof BridgeError) throw error; + fail('camera_bridge_remote_transport_failed'); + } finally { clearTimeout(timer); } + + const mediaDir = process.env.RDK_CAMERA_WORKSHOP_STUDIO_MEDIA_DIR; + const studio = mediaDir && path.isAbsolute(mediaDir); + const directory = studio ? mediaDir : path.join(homedir(), 'Downloads'); + const filename = 'camera-isp-' + args.artifactId + '.json'; + const savedPath = path.join(directory, filename); + const temporary = path.join(directory, '.camera-isp-' + randomUUID() + '.tmp'); + try { + await mkdir(directory, { recursive: true, mode: 0o700 }); + await writeFile(temporary, bytes, { mode: 0o600, flag: 'wx' }); + await rename(temporary, savedPath); + } catch { fail('camera_bridge_artifact_save_failed'); } + finally { await rm(temporary, { force: true }).catch(() => {}); } + return { experimentId: args.experimentId, artifactId: args.artifactId, filename, sha256: args.sha256, byteLength: bytes.length, + ...(studio ? { downloadUrl: '/api/local-files/' + filename } : { savedPath }) }; +} + +let optionalCodecPromise; +function loadOptionalCodec() { + if (!optionalCodecPromise) { + optionalCodecPromise = (async () => { + for (const rel of ['./isp-codec.mjs', '../../rdk-vision-workshop/mcp/isp-codec.mjs']) { + try { return await import(new URL(rel, import.meta.url).href); } catch {} + } + return null; + })(); + } + return optionalCodecPromise; +} + +function detectImageMime(bytes) { + if (bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71 + && bytes[4] === 13 && bytes[5] === 10 && bytes[6] === 26 && bytes[7] === 10) return 'image/png'; + if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8) return 'image/jpeg'; + return null; +} + +async function fetchArchivedFrame(experimentId, frameId, expectedSha256) { + const config = await connection(); + const address = new URL(config.url); + const mount = address.pathname.slice(0, -ENDPOINT.length); + address.pathname = mount + REST_ENDPOINT + '/experiments/' + encodeURIComponent(experimentId) + '/frames/' + encodeURIComponent(frameId); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), config.timeoutMs); + let bytes; + try { + const response = await fetch(address, { redirect: 'error', signal: controller.signal, headers: { accept: 'image/png, image/jpeg', ...credentialHeaders(config) } }); + if (!response.ok) { + await response.body?.cancel(); + fail('camera_bridge_remote_http_' + response.status); + } + bytes = await boundedBytes(response, controller, 32 * 1024 * 1024); + } catch (error) { + if (error instanceof BridgeError) throw error; + fail('camera_bridge_remote_transport_failed'); + } finally { clearTimeout(timer); } + const mimeType = detectImageMime(bytes); + if (!mimeType) fail('camera_bridge_frame_integrity_failed'); + const digest = createHash('sha256').update(bytes).digest('hex'); + if (expectedSha256 && sha256.test(expectedSha256) && digest !== expectedSha256) fail('camera_bridge_frame_integrity_failed'); + return { bytes, mimeType, sha256: digest }; +} + +function studioPreviewDir() { + const dir = process.env.RDK_CAMERA_WORKSHOP_STUDIO_MEDIA_DIR || process.env.RDK_VISION_COURSE_STUDIO_MEDIA_DIR; + return dir && path.isAbsolute(dir) ? dir : null; +} + +async function formatVisualResult(statusObj, primaryImage, fallbackImages = [primaryImage]) { + const mediaDir = studioPreviewDir(); + if (mediaDir && primaryImage?.bytes?.length) { + try { + const ext = primaryImage.mimeType === 'image/png' ? '.png' : '.jpg'; + const digest = primaryImage.sha256 || createHash('sha256').update(primaryImage.bytes).digest('hex'); + const filename = 'camera-preview-' + digest.slice(0, 16) + ext; + const savedPath = path.join(mediaDir, filename); + const tempPath = path.join(mediaDir, '.camera-preview-' + randomUUID() + '.tmp'); + await mkdir(mediaDir, { recursive: true, mode: 0o700 }); + try { + await writeFile(tempPath, primaryImage.bytes, { mode: 0o600, flag: 'wx' }); + await rename(tempPath, savedPath); + } finally { await rm(tempPath, { force: true }).catch(() => {}); } + return { + content: [{ type: 'text', text: JSON.stringify({ + ...statusObj, + __type: 'studio_local_preview', + ok: statusObj.ok ?? true, + imageUrl: '/api/local-files/' + filename, + mimeType: primaryImage.mimeType, + sha256: digest, + ...(primaryImage.label ? { label: primaryImage.label } : {}), + }) }], + isError: false, + }; + } catch { + // Fall through to standard MCP image blocks when Studio media dir is not writable. + } + } + const content = [{ type: 'text', text: JSON.stringify(statusObj) }]; + for (const img of fallbackImages) { + if (img?.bytes?.length) { + content.push({ type: 'image', mimeType: img.mimeType, data: img.bytes.toString('base64') }); + } + } + return { content, isError: false }; +} + +function parseRemoteToolPayload(rpcResponse) { + if (!rpcResponse || rpcResponse.error) { + return { ok: false, error: rpcResponse?.error?.message ?? 'camera_bridge_remote_rpc_error', raw: rpcResponse }; + } + const textPart = rpcResponse.result?.content?.find(item => item?.type === 'text')?.text ?? ''; + let parsed = null; + try { parsed = JSON.parse(textPart); } catch {} + const isErr = rpcResponse.result?.isError === true || parsed?.ok === false; + return { ok: !isErr, data: parsed, text: textPart, isError: isErr }; +} + +async function callRemoteAtom(name, args) { + const res = await remote({ jsonrpc: '2.0', id: 'bridge-' + randomUUID(), method: 'tools/call', params: { name, arguments: args } }); + return parseRemoteToolPayload(res); +} + +function extractFrameRef(payload) { + if (!record(payload)) return null; + const f = record(payload.frame) ? payload.frame : record(payload.result?.frame) ? payload.result.frame : payload; + const frameId = typeof f.frameId === 'string' ? f.frameId : typeof f.id === 'string' ? f.id : undefined; + const frameHash = typeof f.frameHash === 'string' ? f.frameHash : typeof f.hash === 'string' ? f.hash : typeof f.sha256 === 'string' ? f.sha256 : undefined; + return frameId ? { frameId, frameHash } : null; +} + +function summarizeWritableControls(controlsPayload) { + const controls = record(controlsPayload?.controls) ? controlsPayload.controls + : record(controlsPayload?.result?.controls) ? controlsPayload.result.controls + : record(controlsPayload) ? controlsPayload : {}; + const list = []; + for (const [name, row] of Object.entries(controls)) { + if (record(row) && row.writable === true) { + list.push({ + name, + value: row.value, + ...(row.min !== undefined ? { min: row.min } : {}), + ...(row.max !== undefined ? { max: row.max } : {}), + ...(row.step !== undefined ? { step: row.step } : {}), + ...(row.active !== undefined ? { active: row.active } : {}), + }); + } + } + return list; +} + +async function runBringupFlow(args) { + const { experimentId, scene = '点亮首帧基线', captureBaselineFrame = true, includePreview = true } = args; + const stages = []; + + // Stage 1: Probe & recovery fence safety gate + const probed = await callRemoteAtom('vision_camera_probe', { experimentId }); + if (!probed.ok) { + return { content: [{ type: 'text', text: JSON.stringify({ + ok: false, experimentId, failedStage: 'probe', stages: [{ stage: 'probe', status: 'failed', error: probed.error ?? probed.data?.error ?? probed.text }], + hint: '相机探测失败:请先核对 vision_workshop_runtime_status 与实验绑定的 targetId,确认相机服务在线与硬件连接。', + }) }], isError: true }; + } + const facts = record(probed.data?.facts) ? probed.data.facts : record(probed.data?.result?.facts) ? probed.data.result.facts : {}; + if (facts.cleanupRequired === true || facts.writeOutcome === 'unconfirmed') { + return { content: [{ type: 'text', text: JSON.stringify({ + ok: false, experimentId, failedStage: 'probe_recovery_fence', + stages: [{ stage: 'probe', status: 'blocked_recovery_required', facts }], + hint: '设备存在未确认的恢复围栏(cleanupRequired 或 writeOutcome:unconfirmed):禁止继续点亮或写入,请先调用 vision_camera_readiness 并执行 vision_isp_restore 完成恢复。', + }) }], isError: true }; + } + stages.push({ stage: 'probe', status: 'completed', streaming: facts.streaming ?? null }); + + // Stage 2: Bringup (runs before pipeline_validate to support X5 HBN cold-start order as well as UVC) + const brought = await callRemoteAtom('vision_camera_bringup', { experimentId }); + if (!brought.ok) { + return { content: [{ type: 'text', text: JSON.stringify({ + ok: false, experimentId, failedStage: 'bringup', + stages: [...stages, { stage: 'bringup', status: 'failed', error: brought.error ?? brought.data?.error ?? brought.text }], + hint: '相机点亮/开流失败:请查看 MIPI 排线、I2C 总线、X5 镜像/SDK 版本兼容性(imx415-compatibility-and-recovery.md)或核对是否被其他流占用。', + }) }], isError: true }; + } + stages.push({ stage: 'bringup', status: 'completed' }); + + // Stage 3: Pipeline validate + const validated = await callRemoteAtom('vision_pipeline_validate', { experimentId }); + if (!validated.ok) { + return { content: [{ type: 'text', text: JSON.stringify({ + ok: false, experimentId, failedStage: 'pipeline_validate', + stages: [...stages, { stage: 'pipeline_validate', status: 'failed', error: validated.error ?? validated.data?.error ?? validated.text }], + hint: '管线校验未通过:相机已尝试点亮但输出流未满足校验条件,请检查 vision_camera_stream_analyze 与设备日志。', + }) }], isError: true }; + } + stages.push({ stage: 'pipeline_validate', status: 'completed' }); + + // Stage 4: Optional baseline frame capture + let frameRef = null; + if (captureBaselineFrame) { + const captured = await callRemoteAtom('vision_camera_capture_frame', { experimentId, scene }); + if (!captured.ok) { + return { content: [{ type: 'text', text: JSON.stringify({ + ok: false, experimentId, failedStage: 'capture_frame', + stages: [...stages, { stage: 'capture_frame', status: 'failed', error: captured.error ?? captured.data?.error ?? captured.text }], + hint: '点亮与校验通过但首帧抓拍失败:请确认相机未进入休眠或归档额度未满,可调用 vision_camera_readiness 复核。', + }) }], isError: true }; + } + frameRef = extractFrameRef(captured.data); + stages.push({ stage: 'capture_frame', status: 'completed', ...(frameRef ?? {}) }); + } + + // Stage 5: Read actual writable controls for immediate ISP tuning handoff + const ctrl = await callRemoteAtom('vision_camera_controls_get', { experimentId }); + const writableControls = ctrl.ok ? summarizeWritableControls(ctrl.data) : []; + stages.push({ stage: 'controls_get', status: ctrl.ok ? 'completed' : 'warning', writableCount: writableControls.length }); + + const summary = { + ok: true, + experimentId, + stages, + ...(frameRef ? { frame: { ...frameRef, scene } } : {}), + writableControls, + nextStep: '相机点亮、管线校验与基线采集已完成;可直接调用 vision_ai_debug_start 提交自然语言 ISP 调优目标,并在完成后用 vision_ai_debug_preview 查看前后对比图。', + }; + + if (includePreview && frameRef?.frameId) { + try { + const img = await fetchArchivedFrame(experimentId, frameRef.frameId, frameRef.frameHash); + return formatVisualResult(summary, { ...img, label: '实机点亮首帧 · ' + scene }); + } catch { + // Keep bringup receipt intact even if preview download fails. + } + } + return { content: [{ type: 'text', text: JSON.stringify(summary) }], isError: false }; +} + +function formatDebugMetricsFooter(beforeStats, afterStats) { + if (!record(beforeStats) || !record(afterStats)) return ''; + const parts = []; + if (typeof beforeStats.meanLuma === 'number' && typeof afterStats.meanLuma === 'number') { + parts.push(`Y ${(beforeStats.meanLuma * 255).toFixed(0)}->${(afterStats.meanLuma * 255).toFixed(0)}`); + } + if (typeof beforeStats.nearBlackRatio === 'number' && typeof afterStats.nearBlackRatio === 'number') { + parts.push(`DARK ${(beforeStats.nearBlackRatio * 100).toFixed(1)}%->${(afterStats.nearBlackRatio * 100).toFixed(1)}%`); + } + if (typeof beforeStats.nearWhiteRatio === 'number' && typeof afterStats.nearWhiteRatio === 'number') { + parts.push(`CLIP ${(beforeStats.nearWhiteRatio * 100).toFixed(1)}%->${(afterStats.nearWhiteRatio * 100).toFixed(1)}%`); + } + if (typeof beforeStats.edgeGradientMean === 'number' && typeof afterStats.edgeGradientMean === 'number') { + parts.push(`EDGE ${(beforeStats.edgeGradientMean * 255).toFixed(1)}->${(afterStats.edgeGradientMean * 255).toFixed(1)}`); + } + if (typeof beforeStats.flatPatchNoiseProxy === 'number' && typeof afterStats.flatPatchNoiseProxy === 'number') { + parts.push(`NOISE ${(beforeStats.flatPatchNoiseProxy * 255).toFixed(2)}->${(afterStats.flatPatchNoiseProxy * 255).toFixed(2)}`); } - try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks, length))); } + return parts.join(' | '); +} + +async function runAiDebugPreview(args) { + const { experimentId, runId, compareTarget = 'best' } = args; + const statusRes = await callRemoteAtom('vision_ai_debug_status', { experimentId, runId }); + if (!statusRes.ok) { + return { content: [{ type: 'text', text: JSON.stringify({ + ok: false, experimentId, runId, error: statusRes.error ?? statusRes.data?.error ?? statusRes.text, + hint: '读取 AI 调试状态失败:请确认 experimentId 与 runId 属于当前身份。', + }) }], isError: true }; + } + const run = record(statusRes.data?.run) ? statusRes.data.run : record(statusRes.data) ? statusRes.data : {}; + const originalFrameId = run.original?.frameId; + const originalHash = run.original?.frameHash; + const iterations = Array.isArray(run.iterations) ? run.iterations : []; + const lastIter = iterations.at(-1); + const latestObs = lastIter?.after ?? lastIter?.before; + const bestIter = typeof run.best?.iteration === 'number' ? iterations.find(it => it?.index === run.best.iteration) : undefined; + const bestObs = bestIter?.before?.frameId === run.best?.frameId ? bestIter.before : bestIter?.after?.frameId === run.best?.frameId ? bestIter.after : undefined; + + let targetKind = compareTarget; + let targetFrameId = compareTarget === 'final' ? run.final?.frameId + : compareTarget === 'latest' ? latestObs?.frameId + : run.best?.frameId; + let targetHash = compareTarget === 'final' ? run.final?.frameHash + : compareTarget === 'latest' ? latestObs?.frameHash + : run.best?.frameHash; + if (!targetFrameId) { + targetKind = run.best?.frameId ? 'best' : run.final?.frameId ? 'final' : 'latest'; + targetFrameId = run.best?.frameId ?? run.final?.frameId ?? latestObs?.frameId; + targetHash = run.best?.frameHash ?? run.final?.frameHash ?? latestObs?.frameHash; + } + if (!originalFrameId && !targetFrameId) fail('camera_bridge_frame_unavailable'); + + const beforeId = originalFrameId ?? targetFrameId; + const afterId = targetFrameId ?? originalFrameId; + const beforeImg = await fetchArchivedFrame(experimentId, beforeId, beforeId === originalFrameId ? originalHash : targetHash); + const afterImg = afterId === beforeId ? beforeImg : await fetchArchivedFrame(experimentId, afterId, targetHash); + + const beforeStats = iterations[0]?.before?.statistics; + const afterStats = targetKind === 'best' ? (bestObs?.statistics ?? latestObs?.statistics) : latestObs?.statistics; + const footerLine = formatDebugMetricsFooter(beforeStats, afterStats); + + const payload = { + ok: true, + experimentId, + runId, + status: run.status ?? 'unknown', + adjustmentCount: run.adjustmentCount ?? 0, + goalSatisfied: run.goalSatisfied ?? false, + stopReason: run.stopReason ?? null, + compareTarget: targetKind, + sameFrame: beforeId === afterId, + originalFrameId: beforeId, + targetFrameId: afterId, + ...(beforeStats && afterStats ? { + metricsSummary: { + original: { + meanLuma: Number(beforeStats.meanLuma.toFixed(4)), + nearBlackRatio: Number(beforeStats.nearBlackRatio.toFixed(4)), + nearWhiteRatio: Number(beforeStats.nearWhiteRatio.toFixed(4)), + ...(typeof beforeStats.edgeGradientMean === 'number' ? { edgeGradientMean: Number(beforeStats.edgeGradientMean.toFixed(5)) } : {}), + ...(typeof beforeStats.flatPatchNoiseProxy === 'number' ? { flatPatchNoiseProxy: Number(beforeStats.flatPatchNoiseProxy.toFixed(5)) } : {}), + }, + target: { + meanLuma: Number(afterStats.meanLuma.toFixed(4)), + nearBlackRatio: Number(afterStats.nearBlackRatio.toFixed(4)), + nearWhiteRatio: Number(afterStats.nearWhiteRatio.toFixed(4)), + ...(typeof afterStats.edgeGradientMean === 'number' ? { edgeGradientMean: Number(afterStats.edgeGradientMean.toFixed(5)) } : {}), + ...(typeof afterStats.flatPatchNoiseProxy === 'number' ? { flatPatchNoiseProxy: Number(afterStats.flatPatchNoiseProxy.toFixed(5)) } : {}), + }, + }, + } : {}), + }; + + const codec = await loadOptionalCodec(); + if (codec && beforeId !== afterId) { + try { + const decA = codec.decodeImageBuffer(beforeImg.bytes, beforeImg.mimeType === 'image/png' ? '.png' : '.jpg'); + const decB = codec.decodeImageBuffer(afterImg.bytes, afterImg.mimeType === 'image/png' ? '.png' : '.jpg'); + const maxW = 840; + const scale = decA.width > maxW ? maxW / decA.width : 1; + const w = Math.max(2, Math.round(decA.width * scale) & ~1); + const h = Math.max(2, Math.round(decA.height * scale) & ~1); + const rgbA = (decA.width === w && decA.height === h) ? decA.data : codec.resizeRgbBilinear(decA.width, decA.height, decA.data, w, h); + const rgbB = (decB.width === w && decB.height === h) ? decB.data : codec.resizeRgbBilinear(decB.width, decB.height, decB.data, w, h); + const cmp = codec.composeCompareRgb(w, h, rgbA, rgbB, { + topLabel: 'ORIGINAL CAMERA FRAME', + bottomLabel: 'AI DEBUG ' + String(targetKind).toUpperCase() + ' (R' + String(run.adjustmentCount ?? 0) + ')', + barHeight: 34, + footerLine, + footerHeight: 28, + }); + const cmpBytes = codec.encodeJpeg(cmp.width, cmp.height, cmp.data, 90); + const cmpSha = createHash('sha256').update(cmpBytes).digest('hex'); + return formatVisualResult( + { ...payload, composedCompare: true }, + { bytes: cmpBytes, mimeType: 'image/jpeg', sha256: cmpSha, label: '真机 AI 调试前后对照(原始 vs ' + targetKind + ')' }, + [{ bytes: cmpBytes, mimeType: 'image/jpeg', sha256: cmpSha }], + ); + } catch { + // Fallback gracefully if frame cannot be decoded by pure-JS codec. + } + } + + return formatVisualResult( + { ...payload, composedCompare: false }, + { ...afterImg, label: '真机 AI 调试实拍(' + targetKind + ')' }, + beforeId === afterId ? [afterImg] : [beforeImg, afterImg], + ); +} + +async function runFramePreview(args) { + const img = await fetchArchivedFrame(args.experimentId, args.frameId); + return formatVisualResult( + { ok: true, experimentId: args.experimentId, frameId: args.frameId }, + { ...img, label: args.label ?? ('真机归档帧 · ' + args.frameId.slice(0, 8)) }, + ); +} + +function decodeResponse(bytes) { + try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); } catch { fail('camera_bridge_remote_response_invalid'); } } async function remote(message) { @@ -163,12 +646,11 @@ async function remote(message) { try { const response = await fetch(config.url, { method: 'POST', redirect: 'error', signal: controller.signal, - headers: { 'content-type': 'application/json', accept: 'application/json', 'x-rdk-ops-action': 'observability', - [config.authType === 'admin' ? 'x-admin-token' : 'x-rdk-sso-session']: config.credential }, + headers: { 'content-type': 'application/json', accept: 'application/json', 'x-rdk-ops-action': 'observability', ...credentialHeaders(config) }, body: JSON.stringify(message), }); if (!response.ok) fail('camera_bridge_remote_http_' + response.status); - const data = await boundedBody(response, controller); + const data = decodeResponse(await boundedBytes(response, controller)); if (!record(data) || data.jsonrpc !== '2.0' || data.id !== message.id || (!record(data.result) && !record(data.error))) fail('camera_bridge_remote_response_invalid'); if (record(data.error)) return rpcError(message.id, Number.isInteger(data.error.code) ? data.error.code : -32002, 'camera_bridge_remote_rpc_error'); if (message.method === 'tools/list') { @@ -180,6 +662,12 @@ async function remote(message) { ...(record(tool.annotations) ? tool.annotations : {}), readOnlyHint: READ_ONLY.has(tool.name), destructiveHint: !READ_ONLY.has(tool.name), idempotentHint: READ_ONLY.has(tool.name), } })); + if (names.has('vision_isp_tuning_export')) data.result.tools.push(libraryDownloadTool); + if (names.has('vision_camera_probe') && names.has('vision_camera_bringup') && names.has('vision_pipeline_validate') && names.has('vision_camera_capture_frame')) { + data.result.tools.push(bringupFlowTool); + } + if (names.has('vision_ai_debug_status')) data.result.tools.push(aiDebugPreviewTool); + if (names.has('vision_camera_capture_frame')) data.result.tools.push(framePreviewTool); } const result = redact(data, config.credential); if (Buffer.byteLength(JSON.stringify(result)) + 1 > MAX_BYTES) fail('camera_bridge_remote_response_too_large'); @@ -200,7 +688,7 @@ async function dispatch(message) { if (message.id === undefined || message.id === null) return null; const id = message.id; const params = message.params ?? {}; if (!record(params)) return rpcError(id, -32602, 'invalid params'); - if (message.method === 'initialize') return { jsonrpc: '2.0', id, result: { protocolVersion: protocols.has(params.protocolVersion) ? params.protocolVersion : '2025-06-18', capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'rdk-camera-workshop-http-bridge', version: PLUGIN_VERSION }, ...(process.platform === 'win32' ? { instructions: 'Windows file ACLs are not verified by this bridge. Protect the private configuration and credential files with owner-only ACLs.' } : {}) } }; + if (message.method === 'initialize') return { jsonrpc: '2.0', id, result: { protocolVersion: protocols.has(params.protocolVersion) ? params.protocolVersion : '2025-06-18', capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'rdk-camera-workshop-http-bridge', version: RESOLVED_PLUGIN_VERSION }, ...(process.platform === 'win32' ? { instructions: 'Windows file ACLs are not verified by this bridge. Protect the private configuration and credential files with owner-only ACLs.' } : {}) } }; if (message.method === 'ping') return { jsonrpc: '2.0', id, result: {} }; if (message.method === 'tools/list') { if (!onlyKeys(params, ['cursor', '_meta'])) return rpcError(id, -32602, 'invalid params'); @@ -225,7 +713,52 @@ async function dispatch(message) { } if (params.name === versionTool.name) { if (!onlyKeys(params, ['name', 'arguments', '_meta']) || !onlyKeys(params.arguments ?? {}, [])) return rpcError(id, -32602, 'invalid params'); - return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify({ version: PLUGIN_VERSION }) }], isError: false } }; + return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify({ version: RESOLVED_PLUGIN_VERSION }) }], isError: false } }; + } + if (params.name === libraryDownloadTool.name) { + const args = params.arguments; + if (!onlyKeys(params, ['name', 'arguments', '_meta']) || !onlyKeys(args, ['experimentId', 'artifactId', 'sha256', 'byteLength']) || + ![args.experimentId, args.artifactId].every(value => typeof value === 'string' && artifactId.test(value)) || + typeof args.sha256 !== 'string' || !sha256.test(args.sha256) || + args.byteLength !== undefined && (!Number.isSafeInteger(args.byteLength) || args.byteLength < 1 || args.byteLength > MAX_LIBRARY_BYTES)) { + return rpcError(id, -32602, 'invalid camera library reference'); + } + const file = await saveLibrary(args); + return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify(file) }], isError: false } }; + } + if (params.name === bringupFlowTool.name) { + const args = params.arguments; + if (!onlyKeys(params, ['name', 'arguments', '_meta']) || !onlyKeys(args, ['experimentId', 'scene', 'captureBaselineFrame', 'includePreview']) || + typeof args.experimentId !== 'string' || !safeId.test(args.experimentId) || + (args.scene !== undefined && (typeof args.scene !== 'string' || !args.scene.trim() || args.scene.length > 120)) || + (args.captureBaselineFrame !== undefined && typeof args.captureBaselineFrame !== 'boolean') || + (args.includePreview !== undefined && typeof args.includePreview !== 'boolean')) { + return rpcError(id, -32602, 'invalid camera bringup flow arguments'); + } + const run = () => runBringupFlow(args).then(result => ({ jsonrpc: '2.0', id, result })); + const operation = toolChain.then(run, run); toolChain = operation.then(() => {}, () => {}); return operation; + } + if (params.name === aiDebugPreviewTool.name) { + const args = params.arguments; + if (!onlyKeys(params, ['name', 'arguments', '_meta']) || !onlyKeys(args, ['experimentId', 'runId', 'compareTarget']) || + typeof args.experimentId !== 'string' || !safeId.test(args.experimentId) || + typeof args.runId !== 'string' || !safeId.test(args.runId) || + (args.compareTarget !== undefined && !['best', 'final', 'latest'].includes(args.compareTarget))) { + return rpcError(id, -32602, 'invalid ai debug preview arguments'); + } + const run = () => runAiDebugPreview(args).then(result => ({ jsonrpc: '2.0', id, result })); + const operation = toolChain.then(run, run); toolChain = operation.then(() => {}, () => {}); return operation; + } + if (params.name === framePreviewTool.name) { + const args = params.arguments; + if (!onlyKeys(params, ['name', 'arguments', '_meta']) || !onlyKeys(args, ['experimentId', 'frameId', 'label']) || + typeof args.experimentId !== 'string' || !safeId.test(args.experimentId) || + typeof args.frameId !== 'string' || !safeId.test(args.frameId) || + (args.label !== undefined && (typeof args.label !== 'string' || !args.label.trim() || args.label.length > 120))) { + return rpcError(id, -32602, 'invalid frame preview arguments'); + } + const run = () => runFramePreview(args).then(result => ({ jsonrpc: '2.0', id, result })); + const operation = toolChain.then(run, run); toolChain = operation.then(() => {}, () => {}); return operation; } const allowed = TOOL_ARGUMENTS.get(params.name); const args = params.arguments ?? {}; @@ -280,6 +813,11 @@ export async function runBridge() { else if (pending.length) await schedule(pending); await Promise.all(active); await outputChain; } -if (isEntrypoint(import.meta)) { +// The host may launch the server through an 8.3 short name or another letter case than the module URL, so only canonical forms may be compared. +export function sameModulePath(left, right) { + try { return path.relative(realpathSync.native(left), realpathSync.native(right)) === ''; } catch { return false; } +} +const isMainEntry = typeof import.meta.main === 'boolean' ? import.meta.main : Boolean(process.argv[1]) && sameModulePath(process.argv[1], modulePath); +if (isMainEntry) { runBridge().catch(async () => { await output(rpcError(null, -32603, 'camera_bridge_stdio_failed')).catch(() => {}); process.exitCode = 1; }); } diff --git a/plugins/rdk-camera-workshop/mcp/bridge.test.mjs b/plugins/rdk-camera-workshop/mcp/bridge.test.mjs deleted file mode 100644 index 0cc480f..0000000 --- a/plugins/rdk-camera-workshop/mcp/bridge.test.mjs +++ /dev/null @@ -1,366 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { spawn } from 'node:child_process'; -import { createServer } from 'node:http'; -import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { resolveConfigPath } from './bridge.mjs'; - -const bridge = fileURLToPath(new URL('./bridge.mjs', import.meta.url)); -test('stdio bridge negotiates the MCP version used by older Studio clients', async () => { - const { responses } = await run([rpc(1, 'initialize', { protocolVersion: '2024-11-05' })], '/missing-camera-bridge-config'); - assert.equal(responses[0].result.protocolVersion, '2024-11-05'); -}); -const endpoint = '/dobs/api/ops/vision-workshop/mcp'; -const secret = 'fixture-camera-private-credential-never-printed'; -const rpc = (id, method, params = {}) => ({ jsonrpc: '2.0', id, method, params }); -const tool = name => ({ name, description: 'Fixture reviewed tool', inputSchema: { type: 'object', properties: {}, additionalProperties: false } }); -const reply = (response, message, result) => { response.writeHead(200, { 'content-type': 'application/json' }); response.end(JSON.stringify({ jsonrpc: '2.0', id: message.id, result })); }; - -async function withFixture(handler, body) { - const directory = await mkdtemp(path.join(tmpdir(), 'camera-mcp-bridge-')); - const requests = []; - const server = createServer(async (request, response) => { - const chunks = []; for await (const chunk of request) chunks.push(chunk); - let message; try { message = JSON.parse(Buffer.concat(chunks).toString()); } catch { message = null; } - requests.push({ url: request.url, headers: request.headers, message }); - try { await handler(request, response, message); } - catch { if (!response.headersSent) response.writeHead(500); response.end(); } - }); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - const url = 'http://127.0.0.1:' + server.address().port + endpoint; - const credentialFile = path.join(directory, 'credential.txt'); - const configFile = path.join(directory, 'connection.json'); - await writeFile(credentialFile, ' ' + secret + '\n', { mode: 0o600 }); - const saveConfig = async (patch = {}, mode = 0o600) => { - await writeFile(configFile, JSON.stringify({ url, auth: { type: 'admin', credentialFile }, ...patch }), { mode }); - await chmod(configFile, mode); return configFile; - }; - await saveConfig(); - try { await body({ url, directory, requests, credentialFile, configFile, saveConfig }); } - finally { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); await rm(directory, { recursive: true, force: true }); } -} -async function run(messages, configFile, timeoutMs = 10_000) { - const child = spawn(process.execPath, [bridge], { env: { ...process.env, RDK_CAMERA_WORKSHOP_CONFIG: configFile }, stdio: ['pipe', 'pipe', 'pipe'] }); - let stdout = ''; let stderr = ''; - child.stdout.on('data', data => { stdout += data; }); child.stderr.on('data', data => { stderr += data; }); - const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs); - const exit = new Promise((resolve, reject) => { child.once('error', reject); child.once('close', (code, signal) => resolve({ code, signal })); }); - child.stdin.on('error', () => {}); - child.stdin.end(typeof messages === 'string' ? messages : messages.map(message => JSON.stringify(message)).join('\n') + '\n'); - const status = await exit; clearTimeout(timer); - assert.equal(status.code, 0, 'bridge subprocess must exit normally: ' + stderr); - assert.equal(stderr, '', 'bridge must not log on stderr'); - const lines = stdout.trim().split('\n').filter(Boolean); - const responses = lines.map(line => JSON.parse(line)); - assert.ok(responses.every(response => response.jsonrpc === '2.0')); - assert.ok(lines.every(line => Buffer.byteLength(line) + 1 <= 96 * 1024 * 1024)); - assert.ok(!stdout.includes(secret), 'credentials must not appear on stdout'); - return { responses, stdout }; -} - -test('default private config path is independent of shell environment and initialize/ping do not claim remote readiness', async () => { - assert.equal(resolveConfigPath({}, '/owner-home'), path.join('/owner-home', '.config', 'rdk-camera-workshop', 'connection.json')); - const directory = await mkdtemp(path.join(tmpdir(), 'camera-mcp-unconfigured-')); - try { - const { responses } = await run([ - rpc(1, 'initialize', { protocolVersion: '2025-03-26' }), - { jsonrpc: '2.0', method: 'notifications/initialized' }, rpc(2, 'ping'), rpc(3, 'tools/list'), - ], path.join(directory, 'missing.json')); - assert.equal(responses.length, 3); - assert.equal(responses.find(item => item.id === 1).result.protocolVersion, '2025-03-26'); - assert.deepEqual(responses.find(item => item.id === 2).result, {}); - assert.match(responses.find(item => item.id === 3).error.message, /unconfigured/); - } finally { await rm(directory, { recursive: true, force: true }); } -}); - -test('HTTP requests inherit the exact admin credential and action guard while only reviewed typed tools are listed', async () => { - await withFixture((request, response, message) => { - assert.equal(request.url, endpoint); - assert.equal(request.headers['x-admin-token'], secret); - assert.equal(request.headers['x-rdk-sso-session'], undefined); - assert.equal(request.headers['x-rdk-ops-action'], 'observability'); - reply(response, message, { tools: [tool('vision_camera_knowledge_search'), tool('vision_workshop_runtime_status'), tool('vision_experiment_create'), tool('vision_workshop_execute'), tool('vision_unreviewed_shell'), tool('platform_operations_execute')] }); - }, async ({ configFile, requests }) => { - const { responses } = await run([rpc(1, 'tools/list')], configFile); - assert.deepEqual(responses[0].result.tools.map(item => item.name), ['vision_camera_knowledge_search', 'vision_workshop_runtime_status', 'vision_experiment_create']); - assert.equal(requests.length, 1); - }); -}); - -test('SSO auth uses the SSO header without creating an admin identity and errors redact echoed credentials', async () => { - await withFixture((request, response, message) => { - assert.equal(request.headers['x-rdk-sso-session'], secret); assert.equal(request.headers['x-admin-token'], undefined); - reply(response, message, { isError: true, content: [{ type: 'text', text: 'upstream failed with ' + secret }] }); - }, async ({ saveConfig, credentialFile }) => { - const configFile = await saveConfig({ auth: { type: 'sso', credentialFile } }); - const { responses } = await run([rpc(1, 'tools/call', { name: 'vision_camera_knowledge_search', arguments: { q: 'IMX415' } })], configFile); - assert.equal(responses[0].result.isError, true); assert.match(responses[0].result.content[0].text, /\[redacted\]/); - }); -}); - -test('workflow tools are discoverable read-only atoms and forward only owned-evidence selectors', async () => { - await withFixture((_request, response, message) => { - if (message.method === 'tools/list') reply(response, message, { tools: [tool('vision_camera_workflow'), tool('vision_camera_stream_analyze'), tool('unreviewed_driver_shell')] }); - else reply(response, message, { content: [{ type: 'text', text: JSON.stringify(message.params.arguments) }], isError: false }); - }, async ({ configFile, requests }) => { - const args = { experimentId: 'owned-experiment', runIds: ['saved-run'], expectedFps: 30, tolerancePercent: 5, minimumDurationSeconds: 60 }; - const { responses } = await run([rpc(1, 'tools/list'), rpc(2, 'tools/call', { name: 'vision_camera_workflow', arguments: { experimentId: 'owned-experiment' } }), rpc(3, 'tools/call', { name: 'vision_camera_stream_analyze', arguments: args }), rpc(4, 'tools/call', { name: 'vision_camera_stream_analyze', arguments: { ...args, samples: [{ fps: 30 }] } })], configFile); - const byId = new Map(responses.map(response => [response.id, response])); - assert.deepEqual(byId.get(1).result.tools.map(item => item.name), ['vision_camera_workflow', 'vision_camera_stream_analyze']); - assert.ok(byId.get(1).result.tools.every(item => item.annotations.readOnlyHint && item.annotations.idempotentHint)); - assert.deepEqual(JSON.parse(byId.get(3).result.content[0].text), args); - assert.ok(byId.get(4).error); assert.equal(requests.length, 3, 'fabricated frame samples must never reach the service'); - }); -}); - -test('A1/B/A2 response atom is discoverable read-only and forwards archive selectors, never paths or metrics', async () => { - await withFixture((_request, response, message) => { - if (message.method === 'tools/list') reply(response, message, { tools: [tool('vision_camera_response_analyze')] }); - else reply(response, message, { content: [{ type: 'text', text: JSON.stringify(message.params.arguments) }], isError: false }); - }, async ({ configFile, requests }) => { - const args = { experimentId: 'owned-experiment', baselineFrameIds: ['a1', 'a2', 'a3'], candidateFrameIds: ['b1', 'b2', 'b3'], restoredFrameIds: ['r1', 'r2', 'r3'], roi: { x: 0, y: 0, width: 10, height: 10 } }; - const { responses } = await run([rpc(1, 'tools/list'), rpc(2, 'tools/call', { name: 'vision_camera_response_analyze', arguments: args }), ...[{ path: '/private/frame.png' }, { metrics: { improved: true } }, { contentBase64: 'ZmFrZQ==' }].map((extra, index) => rpc(index + 3, 'tools/call', { name: 'vision_camera_response_analyze', arguments: { ...args, ...extra } }))], configFile); - const byId = new Map(responses.map(response => [response.id, response])); - assert.equal(byId.get(1).result.tools[0].annotations.readOnlyHint, true); assert.equal(byId.get(1).result.tools[0].annotations.idempotentHint, true); - assert.equal(byId.get(1).result.tools[0].annotations.destructiveHint, false); - assert.deepEqual(JSON.parse(byId.get(2).result.content[0].text), args); - for (const id of [3, 4, 5]) assert.ok(byId.get(id).error); - assert.equal(requests.length, 2, 'only discovery and bounded archive selectors reach the server'); - }); -}); - -test('unknown tools, generic execution, arbitrary target fields and malformed argument containers are rejected locally', async () => { - await withFixture((_request, response) => response.end(), async ({ configFile, requests }) => { - const inputs = [ - { name: 'vision_workshop_execute', arguments: { operationId: 'POST arbitrary' } }, - { name: 'vision_unreviewed_shell', arguments: {} }, - { name: 'vision_camera_probe', arguments: { experimentId: 'x', host: 'external.invalid' } }, - { name: 'vision_camera_probe', arguments: { experimentId: 'x', path: '/arbitrary' } }, - { name: 'vision_camera_probe', arguments: { experimentId: 'x', command: 'unsafe' } }, - { name: 'vision_camera_probe', arguments: [] }, - ]; - const { responses } = await run(inputs.map((params, index) => rpc(index, 'tools/call', params)), configFile); - assert.equal(responses.length, inputs.length); assert.ok(responses.every(item => item.error.code === -32602)); assert.equal(requests.length, 0); - }); -}); - -test('reviewed experiment and baseline aliases can be forwarded without a generic operation executor', async () => { - await withFixture((_request, response, message) => reply(response, message, { content: [{ type: 'text', text: JSON.stringify(message.params) }], isError: false }), async ({ configFile, requests }) => { - const names = ['vision_workshop_runtime_status', 'vision_experiment_list', 'vision_experiment_get', 'vision_experiment_create', 'vision_tuning_baseline_import']; - const args = [{}, { limit: 10, offset: 10 }, { experimentId: 'fixture' }, { title: 'IMX415', goal: '资料核对', board: 'RDK X5' }, { experimentId: 'fixture', config: { exposure: 1 }, rules: [] }]; - const { responses } = await run(names.map((name, index) => rpc(index, 'tools/call', { name, arguments: args[index] })), configFile); - assert.ok(responses.every(item => item.result.isError === false)); assert.deepEqual(requests.map(item => item.message.params.name), names); - assert.deepEqual(requests[1].message.params.arguments, { limit: 10, offset: 10 }); - }); -}); - -test('a saved tuning artifact ID is forwarded without requiring model-supplied file bytes', async () => { - await withFixture((_request, response, message) => reply(response, message, { content: [{ type: 'text', text: 'fixture' }], isError: false }), async ({ configFile, requests }) => { - const args = { experimentId: 'experiment', artifactId: 'saved-artifact' }; - const { responses } = await run([rpc(1, 'tools/call', { name: 'vision_isp_tuning_load', arguments: args })], configFile); - assert.equal(responses[0].result.isError, false); assert.deepEqual(requests[0].message.params.arguments, args); - }); -}); - -test('bounded catalog pages and named knowledge sections retain their exact typed arguments', async () => { - await withFixture((_request, response, message) => reply(response, message, { content: [{ type: 'text', text: 'fixture' }], isError: false }), async ({ configFile, requests }) => { - const inputs = [{ name: 'vision_workshop_capabilities', arguments: { search: 'tuning', limit: 4, offset: 4 } }, { name: 'vision_camera_knowledge_get', arguments: { knowledgeId: 'x5-yahboom-imx415', section: 'facts' } }]; - const { responses } = await run(inputs.map((params, index) => rpc(index, 'tools/call', params)), configFile); - assert.ok(responses.every(item => item.result.isError === false)); - assert.deepEqual(requests.map(item => item.message.params), inputs); - }); -}); - -test('redirects are denied and never follow the credential to a different path', async () => { - await withFixture((_request, response) => { response.writeHead(307, { location: '/credential-destination' }); response.end(); }, async ({ configFile, requests }) => { - const { responses } = await run([rpc(1, 'tools/list')], configFile); - assert.match(responses[0].error.message, /remote_transport_failed/); assert.equal(requests.length, 1); assert.equal(requests[0].url, endpoint); - }); -}); - -test('timeouts and disconnects have no automatic retry or recovery claim', async () => { - for (const disconnect of [false, true]) { - await withFixture((request, _response) => { if (disconnect) request.socket.destroy(); }, async ({ saveConfig, requests }) => { - // Allow the cold child-process fetch to reach the server under concurrent typechecks. - // The fixture never replies: the same single-request/no-retry assertions still test timeout handling. - const configFile = await saveConfig({ timeoutMs: 1000 }); - const { responses } = await run([rpc(1, 'tools/call', { name: 'vision_isp_apply', arguments: { experimentId: 'fixture', candidateId: 'candidate' } })], configFile); - assert.match(responses[0].error.message, /execution outcome unknown.*no automatic retry.*deviceRuns.*Restoration is unconfirmed/); - assert.equal(requests.length, 1); - }); - } -}); - -test('invalid URLs, config schemas and credentials fail before opening a remote connection', async () => { - await withFixture((_request, response) => response.end(), async ({ saveConfig, requests, credentialFile }) => { - for (const url of ['http://external.invalid' + endpoint, 'https://user:secret@example.invalid' + endpoint, 'https://example.invalid/arbitrary', 'https://example.invalid' + endpoint + '?token=secret', 'https://example.invalid' + endpoint + '#secret', 'https://example.invalid' + endpoint + '?']) { - const { responses } = await run([rpc(1, 'tools/list')], await saveConfig({ url })); assert.match(responses[0].error.message, /url_invalid/); - } - const { responses } = await run([rpc(1, 'tools/list')], await saveConfig({ auth: { type: 'admin', credentialFile, token: secret } })); - assert.match(responses[0].error.message, /config_invalid/); assert.equal(requests.length, 0); - }); -}); - -test('private files must be outside the package and POSIX files have exact owner-only permissions', async () => { - await withFixture((_request, response) => response.end(), async ({ configFile, saveConfig, credentialFile, requests }) => { - const inside = await run([rpc(1, 'tools/list')], bridge); assert.match(inside.responses[0].error.message, /private_file_inside_package/); - if (process.platform !== 'win32') { - await chmod(configFile, 0o644); - const looseConfig = await run([rpc(1, 'tools/list')], configFile); assert.match(looseConfig.responses[0].error.message, /permissions_invalid/); - await saveConfig(); await chmod(credentialFile, 0o644); - const looseCredential = await run([rpc(1, 'tools/list')], configFile); assert.match(looseCredential.responses[0].error.message, /permissions_invalid/); - } - assert.equal(requests.length, 0); - }); -}); - -test('oversized input is rejected once and the next valid newline message is still processed', async () => { - const input = 'x'.repeat(24 * 1024 * 1024 + 1) + '\n' + JSON.stringify(rpc(2, 'ping')) + '\n'; - const { responses } = await run(input, path.join(tmpdir(), 'missing-camera-config.json')); - assert.equal(responses.length, 2); assert.match(responses[0].error.message, /input_too_large/); assert.deepEqual(responses[1].result, {}); -}); - -test('oversized upstream output and invalid JSON-RPC receipts are real errors', async () => { - for (const oversized of [true, false]) { - await withFixture((_request, response, message) => { - response.writeHead(200, { 'content-type': 'application/json', ...(oversized ? { 'content-length': String(96 * 1024 * 1024 + 1) } : {}) }); - response.end(oversized ? '{}' : JSON.stringify({ jsonrpc: '2.0', id: message.id + 100, result: { tools: [] } })); - }, async ({ configFile }) => { - const { responses } = await run([rpc(1, 'tools/list')], configFile); - assert.match(responses[0].error.message, oversized ? /response_too_large/ : /response_invalid/); - }); - } -}); - -test('reads have bounded parallelism and all tool calls execute serially in input order', async () => { - let running = 0; let maximum = 0; - await withFixture(async (_request, response, message) => { - running++; maximum = Math.max(maximum, running); - await new Promise(resolve => setTimeout(resolve, 35)); running--; - reply(response, message, message.method === 'tools/list' ? { tools: [tool('vision_camera_probe')] } : { content: [{ type: 'text', text: 'fixture result, hardware unverified' }], isError: false }); - }, async ({ configFile, requests }) => { - const reads = await run(Array.from({ length: 9 }, (_, index) => rpc(index, 'tools/list')), configFile); - assert.equal(reads.responses.length, 9); assert.ok(maximum > 1 && maximum <= 4); - maximum = 0; requests.length = 0; - await run(Array.from({ length: 6 }, (_, index) => rpc(index, 'tools/call', { name: 'vision_camera_probe', arguments: { experimentId: String(index) } })), configFile); - assert.equal(maximum, 1); assert.deepEqual(requests.map(item => item.message.id), [0, 1, 2, 3, 4, 5]); - }); -}); - -test('parse errors and unknown methods keep stdout strictly JSON-RPC and never reflect submitted secrets', async () => { - const input = secret + '\n' + JSON.stringify(rpc(1, secret)) + '\n' + JSON.stringify({ jsonrpc: '2.0', id: {}, method: 'ping' }) + '\n'; - const { responses } = await run(input, path.join(tmpdir(), 'missing-camera-config.json')); - assert.deepEqual(responses.map(item => item.error.code), [-32700, -32601, -32600]); -}); - -test('native ISP/calibration tools preserve actual schemas and enforce semantic read/write annotations', async () => { - const reads = ['vision_isp_tuning_get', 'vision_isp_tuning_export', 'vision_calibration_asset_list', 'vision_calibration_task_list', 'vision_calibration_task_get', 'vision_calibration_task_result', 'vision_calibration_apply_plan']; - const writes = ['vision_isp_tuning_load', 'vision_calibration_asset_import', 'vision_calibration_task_create', 'vision_calibration_task_run', 'vision_calibration_apply']; - const names = [...reads, ...writes]; - await withFixture((_request, response, message) => reply(response, message, message.method === 'tools/list' - ? { tools: [...names.map(name => ({ ...tool(name), annotations: { readOnlyHint: true } })), tool('vision_unreviewed_shell')] } - : { content: [{ type: 'text', text: 'SDK protocol fixture; hardware unverified' }], isError: false }), async ({ configFile, requests }) => { - const args = name => name === 'vision_isp_tuning_load' ? { experimentId: 'fixture', contentBase64: 'e30=', sha256: 'a'.repeat(64) } - : name === 'vision_calibration_asset_import' ? { experimentId: 'fixture', measurement: {} } - : name === 'vision_calibration_task_create' ? { experimentId: 'fixture', operation: 'blc', inputs: [], options: {} } - : name === 'vision_calibration_task_list' ? { experimentId: 'fixture' } - : name.includes('task_') || name.includes('apply') ? { experimentId: 'fixture', taskId: 'fixture-task' } : { experimentId: 'fixture' }; - const { responses } = await run([rpc(1, 'tools/list'), ...names.map((name, index) => rpc(index + 2, 'tools/call', { name, arguments: args(name) }))], configFile); - const catalog = responses.find(item => item.id === 1).result.tools; - assert.deepEqual(catalog.map(item => item.name), names); - for (const listed of catalog) { - assert.equal(listed.annotations.readOnlyHint, reads.includes(listed.name)); - assert.equal(listed.annotations.idempotentHint, reads.includes(listed.name)); - assert.equal(listed.annotations.destructiveHint, writes.includes(listed.name)); - assert.deepEqual(listed.inputSchema, tool(listed.name).inputSchema); - } - assert.ok(responses.filter(item => item.id !== 1).every(item => item.result?.isError === false), JSON.stringify(responses.filter(item => item.error))); - assert.deepEqual(requests.filter(item => item.message.method === 'tools/call').map(item => item.message.params.name), names); - assert.ok(requests.every(item => item.url === endpoint && item.headers['x-admin-token'] === secret && item.headers['x-rdk-ops-action'] === 'observability')); - const rejected = await run(['path', 'command', 'result'].map((key, index) => rpc(index, 'tools/call', { name: 'vision_calibration_apply', arguments: { experimentId: 'fixture', taskId: 'task', [key]: 'untrusted' } })), configFile); - assert.ok(rejected.responses.every(item => item.error.code === -32602)); assert.equal(requests.length, names.length + 1); - }); -}); - -test('a bounded RAW result larger than two MiB remains usable through real HTTP and stdio', async () => { - const actual = Buffer.alloc(3 * 1024 * 1024, 17).toString('base64'); - await withFixture((_request, response, message) => reply(response, message, { content: [{ type: 'text', text: JSON.stringify({ contentBase64: actual, hardwareVerified: false }) }] }), async ({ configFile, requests }) => { - const { responses } = await run([rpc(1, 'tools/call', { name: 'vision_raw_capture', arguments: { experimentId: 'fixture', scene: 'RAW protocol fixture' } })], configFile); - assert.equal(JSON.parse(responses[0].result.content[0].text).contentBase64, actual); assert.equal(requests.length, 1); - }); -}); - -test('a failed semantic read does not claim an unknown hardware write', async () => { - await withFixture(request => request.socket.destroy(), async ({ configFile, requests }) => { - const { responses } = await run([rpc(1, 'tools/call', { name: 'vision_calibration_task_result', arguments: { experimentId: 'fixture', taskId: 'task' } })], configFile); - assert.match(responses[0].error.message, /transport_failed/); assert.doesNotMatch(responses[0].error.message, /execution outcome unknown|Restoration/); assert.equal(requests.length, 1); - }); -}); - -test('delivery tools preserve operator boundaries and candidate reload role without opening generic execution', async () => { - const inputs = [ - ['vision_workshop_delivery', { experimentId:'fixture' }], - ['vision_acceptance_plan_save', { experimentId:'fixture', plan:{scene:'fixture',lighting:'synthetic',criteria:[]} }], - ['vision_delivery_target_select', {experimentId:'fixture',targetId:'vendor:fixture'}], - ['vision_acceptance_record', {experimentId:'fixture',record:{report:'Operator fixture, no measured hardware'}}], - ['vision_isp_tuning_load', {experimentId:'fixture',contentBase64:'e30=',sha256:'a'.repeat(64),artifactRole:'vendor_effect_library_candidate'}], - ]; - await withFixture((_request,response,message)=>reply(response,message,message.method==='tools/list'?{tools:inputs.map(([name])=>tool(name))}:{content:[{type:'text',text:'Protocol fixture only'}],isError:false}),async({configFile,requests})=>{ - const {responses}=await run([rpc(0,'tools/list'),...inputs.map(([name,args],index)=>rpc(index+1,'tools/call',{name,arguments:args}))],configFile); - assert.ok(responses.every(item=>item.result&&!item.error));const catalog=responses.find(item=>item.id===0).result.tools; - for(const item of catalog) assert.equal(item.annotations.readOnlyHint,item.name==='vision_workshop_delivery'); - assert.deepEqual(requests.filter(item=>item.message.method==='tools/call').map(item=>item.message.params.arguments),inputs.map(([,args])=>args)); - const rejected=await run([rpc(9,'tools/call',{name:'vision_acceptance_record',arguments:{experimentId:'fixture',record:{},userId:'injected-owner'}})],configFile);assert.equal(rejected.responses[0].error.code,-32602); - }); -}); - -test('host onboarding keeps a local diagnostic tool available with no private config', async () => { - const directory = await mkdtemp(path.join(tmpdir(), 'camera-first-install-')); - try { - const child = spawn(process.execPath, [bridge], { cwd: directory, env: { ...process.env, RDK_CAMERA_WORKSHOP_CONFIG: path.join(directory, 'missing.json'), RDK_CAMERA_WORKSHOP_ONBOARDING: '1' }, stdio: ['pipe', 'pipe', 'pipe'] }); - let stdout = ''; child.stdout.on('data', bytes => { stdout += bytes; }); - const exited = new Promise(resolve => child.on('close', resolve)); - child.stdin.end([rpc(0, 'initialize'), rpc(1, 'tools/list'), rpc(2, 'tools/call', { name: 'vision_connection_status', arguments: {} })].map(JSON.stringify).join('\n') + '\n'); - assert.equal(await exited, 0); - const responses = stdout.trim().split('\n').map(line => JSON.parse(line)); - assert.deepEqual(responses.find(item => item.id === 1).result.tools.map(tool => tool.name), ['vision_connection_status', 'vision_plugin_version']); - const status = JSON.parse(responses.find(item => item.id === 2).result.content[0].text); - assert.equal(status.code, 'camera_bridge_unconfigured'); assert.equal(status.hardware, 'unverified'); - assert.ok(!stdout.includes(directory)); - } finally { await rm(directory, { recursive: true, force: true }); } -}); - -test('connection status adds a path-free remediation hint for the reported code', async () => { - const directory = await mkdtemp(path.join(tmpdir(), 'camera-status-hint-')); - try { - const child = spawn(process.execPath, [bridge], { cwd: directory, env: { ...process.env, RDK_CAMERA_WORKSHOP_CONFIG: path.join(directory, 'missing.json'), RDK_CAMERA_WORKSHOP_ONBOARDING: '1' }, stdio: ['pipe', 'pipe', 'pipe'] }); - let stdout = ''; child.stdout.on('data', bytes => { stdout += bytes; }); - const exited = new Promise(resolve => child.on('close', resolve)); - child.stdin.end([rpc(0, 'initialize'), rpc(4, 'tools/call', { name: 'vision_connection_status', arguments: {} })].map(JSON.stringify).join('\n') + '\n'); - assert.equal(await exited, 0); - const responses = stdout.trim().split('\n').map(line => JSON.parse(line)); - const status = JSON.parse(responses.find(item => item.id === 4).result.content[0].text); - assert.equal(status.code, 'camera_bridge_unconfigured'); - assert.match(status.hint, /configure/); - assert.ok(!stdout.includes(directory)); - } finally { await rm(directory, { recursive: true, force: true }); } -}); - -test('errors on every transport path carry the remediation hint without local paths', async () => { - const directory = await mkdtemp(path.join(tmpdir(), 'camera-error-hint-')); - try { - const child = spawn(process.execPath, [bridge], { cwd: directory, env: { ...process.env, RDK_CAMERA_WORKSHOP_CONFIG: path.join(directory, 'missing.json') }, stdio: ['pipe', 'pipe', 'pipe'] }); - let stdout = ''; child.stdout.on('data', bytes => { stdout += bytes; }); - const exited = new Promise(resolve => child.on('close', resolve)); - child.stdin.end([rpc(0, 'initialize'), rpc(6, 'tools/call', { name: 'vision_workshop_runtime_status', arguments: {} })].map(JSON.stringify).join('\n') + '\n'); - assert.equal(await exited, 0); - const responses = stdout.trim().split('\n').map(line => JSON.parse(line)); - const error = responses.find(item => item.id === 6).error; - assert.equal(error.code, -32001); - assert.match(error.message, /camera_bridge_unconfigured: 尚未配置连接/); - assert.ok(!stdout.includes(directory)); - } finally { await rm(directory, { recursive: true, force: true }); } -}); diff --git a/plugins/rdk-camera-workshop/mcp/calibration-chat.mjs b/plugins/rdk-camera-workshop/mcp/calibration-chat.mjs new file mode 100644 index 0000000..4fa85af --- /dev/null +++ b/plugins/rdk-camera-workshop/mcp/calibration-chat.mjs @@ -0,0 +1,235 @@ +import { cameraIdPattern } from './steps.mjs'; + +const id=new RegExp(cameraIdPattern); +const mode=/^[A-Za-z0-9_-]{1,128}$/; +const engines=['ispstudio','ispcal-lsc','numpy']; +const idSchema={type:'string',pattern:cameraIdPattern}; +const num=(min,max)=>({type:'number',minimum:min,maximum:max}); +const blackLevelsSchema={type:'object',properties:{R:num(0,65534),Gr:num(0,65534),Gb:num(0,65534),B:num(0,65534)}, + required:['R','Gr','Gb','B'],additionalProperties:false}; +const roiSchema={type:'object',properties:{ + x:{type:'integer',minimum:0,multipleOf:2},y:{type:'integer',minimum:0,multipleOf:2}, + width:{type:'integer',minimum:4,multipleOf:2},height:{type:'integer',minimum:4,multipleOf:2}}, + required:['x','y','width','height'],additionalProperties:false}; +const schema=(properties,required=[])=>({type:'object',properties,required,additionalProperties:false}); + +export const calibrationStatusSchema=schema({ + action:{type:'string',enum:['overview','task','result','apply_plan']}, + experimentId:idSchema,taskId:idSchema, +}); +export const calibrationActionSchema=schema({ + action:{type:'string',enum:['create_dark','create_lsc','create_awb','create_ccm','run']}, + experimentId:idSchema,taskId:idSchema, + engine:{type:'string',enum:engines}, + sampleIds:{type:'array',items:idSchema,minItems:3,maxItems:32,uniqueItems:true}, + sensorMode:{type:'string',pattern:mode.source}, + darkConfirmed:{type:'boolean',const:true}, + illuminantId:{type:'string',pattern:mode.source}, + luxSamples:{type:'array',items:{type:'number',exclusiveMinimum:0},minItems:5,maxItems:256}, + blackLevels:blackLevelsSchema, + grid:{type:'object',properties:{rows:{type:'integer',minimum:2,maximum:33},cols:{type:'integer',minimum:2,maximum:33}}, + required:['rows','cols'],additionalProperties:false}, + groups:{type:'array',minItems:2,maxItems:8,items:{type:'object',properties:{ + illuminantId:{type:'string',pattern:mode.source}, + colorTemperatureK:num(1000,25000), + roi:roiSchema, + sampleIds:{type:'array',items:idSchema,minItems:3,maxItems:16,uniqueItems:true}}, + required:['illuminantId','colorTemperatureK','roi','sampleIds'],additionalProperties:false}}, + assetId:idSchema, +},['action','experimentId']); + +function fields(data,allowed) { + if(!data||typeof data!=='object'||Array.isArray(data)||Object.keys(data).some(key=>!allowed.includes(key))) { + throw new Error('camera_calibration_invalid'); + } +} +const validId=value=>typeof value==='string'&&id.test(value); +const validMode=value=>typeof value==='string'&&mode.test(value); +const validBlack=bl=>Boolean(bl&&typeof bl==='object'&&!Array.isArray(bl)&& + ['R','Gr','Gb','B'].every(ch=>typeof bl[ch]==='number'&&Number.isFinite(bl[ch])&&bl[ch]>=0&&bl[ch]<=65534)); +const validRoi=r=>Boolean(r&&typeof r==='object'&&!Array.isArray(r)&& + Number.isInteger(r.x)&&r.x>=0&&r.x%2===0&&Number.isInteger(r.y)&&r.y>=0&&r.y%2===0&& + Number.isInteger(r.width)&&r.width>=4&&r.width%2===0&&Number.isInteger(r.height)&&r.height>=4&&r.height%2===0); +const validSamples=(list,min=3,max=32)=>Array.isArray(list)&&list.length>=min&&list.length<=max&& + list.every(validId)&&new Set(list).size===list.length; + +export function pickCalibrationEngine(operation, requested, availableEngines=[]) { + const ready=new Set((availableEngines??[]).filter(e=>e?.available).map(e=>e.id)); + if(requested!==undefined) { + if(!engines.includes(requested)) throw new Error('camera_calibration_invalid'); + if(requested==='ispcal-lsc'&&operation!=='lsc') throw new Error('camera_calibration_invalid'); + return requested; + } + if(operation==='lsc') { + if(ready.has('ispcal-lsc')) return 'ispcal-lsc'; + if(ready.has('ispstudio')) return 'ispstudio'; + return 'numpy'; + } + return ready.has('ispstudio')?'ispstudio':'numpy'; +} + +export function validateCalibrationStatus(data) { + fields(data,['action','experimentId','taskId']); + const action=data.action===undefined?'overview':data.action; + if(action==='overview') { + if(data.taskId!==undefined||data.experimentId!==undefined&&!validId(data.experimentId)) { + throw new Error('camera_calibration_invalid'); + } + } else if(!['task','result','apply_plan'].includes(action)||!validId(data.taskId)||!validId(data.experimentId)) { + throw new Error('camera_calibration_invalid'); + } + return {...data,action}; +} + +export function validateCalibrationAction(data) { + const action=data?.action; + if(action==='create_dark') { + fields(data,['action','experimentId','sampleIds','sensorMode','darkConfirmed','engine']); + if(data.darkConfirmed!==true) throw new Error('vision_calibration_blocked_light_dark_capture_required'); + if(!validSamples(data.sampleIds)||!validMode(data.sensorMode)) throw new Error('camera_calibration_invalid'); + if(data.engine!==undefined&&!['ispstudio','numpy'].includes(data.engine)) throw new Error('camera_calibration_invalid'); + } else if(action==='create_lsc') { + fields(data,['action','experimentId','sampleIds','sensorMode','illuminantId','luxSamples','blackLevels','grid','engine']); + if(!validSamples(data.sampleIds)||!validMode(data.sensorMode)||!validMode(data.illuminantId)|| + !validBlack(data.blackLevels)||!Array.isArray(data.luxSamples)||data.luxSamples.length<5||data.luxSamples.length>256|| + data.luxSamples.some(v=>typeof v!=='number'||!Number.isFinite(v)||v<=0)|| + !data.grid||!Number.isInteger(data.grid.rows)||!Number.isInteger(data.grid.cols)|| + data.grid.rows<2||data.grid.rows>33||data.grid.cols<2||data.grid.cols>33) { + throw new Error('camera_calibration_invalid'); + } + if(data.engine!==undefined&&!engines.includes(data.engine)) throw new Error('camera_calibration_invalid'); + } else if(action==='create_awb') { + fields(data,['action','experimentId','sensorMode','blackLevels','groups','engine']); + if(!validMode(data.sensorMode)||!validBlack(data.blackLevels)|| + !Array.isArray(data.groups)||data.groups.length<2||data.groups.length>8) { + throw new Error('camera_calibration_invalid'); + } + const seenSamples=new Set(),seenLights=new Set(); + for(const g of data.groups) { + if(!g||typeof g!=='object'||!validMode(g.illuminantId)||seenLights.has(g.illuminantId)|| + typeof g.colorTemperatureK!=='number'||!Number.isFinite(g.colorTemperatureK)|| + g.colorTemperatureK<1000||g.colorTemperatureK>25000||!validSamples(g.sampleIds,3,16)) { + throw new Error('camera_calibration_invalid'); + } + if(!validRoi(g.roi)) throw new Error('vision_calibration_roi_bounds_or_bayer_alignment_invalid'); + seenLights.add(g.illuminantId); + for(const sid of g.sampleIds) { + if(seenSamples.has(sid)) throw new Error('camera_calibration_invalid'); + seenSamples.add(sid); + } + } + if(seenSamples.size>32) throw new Error('camera_calibration_invalid'); + if(data.engine!==undefined&&!['ispstudio','numpy'].includes(data.engine)) throw new Error('camera_calibration_invalid'); + } else if(action==='create_ccm') { + fields(data,['action','experimentId','assetId','engine']); + if(!validId(data.assetId)) throw new Error('camera_calibration_invalid'); + if(data.engine!==undefined&&!['ispstudio','numpy'].includes(data.engine)) throw new Error('camera_calibration_invalid'); + } else { + fields(data,['action','experimentId','taskId']); + if(action!=='run'||!validId(data.taskId)) throw new Error('camera_calibration_invalid'); + } + if(!validId(data.experimentId)) throw new Error('camera_calibration_invalid'); + return data; +} + +export function calibrationCaptureMetadata(sample) { + const {exposureUs,gain}=sample?.metadata??{}; + if(Number.isFinite(exposureUs)&&exposureUs>=1&&exposureUs<=60_000_000&& + Number.isFinite(gain)&&gain>=.0001&&gain<=65_536) return {exposureUs,analogGain:gain}; +} + +export function darkTaskInput(args,catalog) { + const engine=pickCalibrationEngine('blc',args.engine,catalog.engines); + const inputs=args.sampleIds.map(sampleId=>{ + const sample=catalog.samples.find(item=>item.id===sampleId); + const metadata=calibrationCaptureMetadata(sample); + if(!metadata) throw new Error('camera_calibration_sample_unavailable'); + return {sampleId,capture:{target:'lens_covered_dark',source:'recorded-camera-artifact', + preprocessing:'sensor_raw_unprocessed',sensorMode:args.sensorMode,...metadata,lightBlocked:true}}; + }); + return {operation:'blc',engine,inputs}; +} + +export function lscTaskInput(args,catalog) { + const engine=pickCalibrationEngine('lsc',args.engine,catalog.engines); + const inputs=args.sampleIds.map(sampleId=>{ + const sample=catalog.samples.find(item=>item.id===sampleId); + const metadata=calibrationCaptureMetadata(sample); + if(!metadata) throw new Error('camera_calibration_sample_unavailable'); + return {sampleId,capture:{target:'neutral_uniform_flat_field',source:'recorded-camera-artifact', + preprocessing:'sensor_raw_unprocessed',sensorMode:args.sensorMode,...metadata, + illuminantId:args.illuminantId, + illuminationUniformity:{method:'independent_meter_grid',luxSamples:args.luxSamples}}}; + }); + return {operation:'lsc',engine,inputs,options:{blackLevels:args.blackLevels,grid:args.grid}}; +} + +export function awbTaskInput(args,catalog) { + const engine=pickCalibrationEngine('awb',args.engine,catalog.engines); + const inputs=[]; + for(const group of args.groups) { + for(const sampleId of group.sampleIds) { + const sample=catalog.samples.find(item=>item.id===sampleId); + const metadata=calibrationCaptureMetadata(sample); + if(!metadata) throw new Error('camera_calibration_sample_unavailable'); + inputs.push({sampleId,capture:{target:'neutral_gray_card',source:'recorded-camera-artifact', + preprocessing:'sensor_raw_unprocessed',sensorMode:args.sensorMode,...metadata, + illuminantId:group.illuminantId,colorTemperatureK:group.colorTemperatureK,roi:group.roi}}); + } + } + return {operation:'awb',engine,inputs,options:{blackLevels:args.blackLevels}}; +} + +export function ccmTaskInput(args,catalog) { + const engine=pickCalibrationEngine('ccm',args.engine,catalog.engines); + const asset=catalog.assets?.find(item=>item.id===args.assetId); + if(!asset) throw new Error('camera_calibration_sample_unavailable'); + return {operation:'ccm',engine,inputs:[{artifactId:asset.id}]}; +} + +export function matchingDarkTask(task,input) { + if(task.engine!==input.engine||task.operation!==input.operation|| + JSON.stringify(task.options??{})!==JSON.stringify(input.options??{})|| + task.inputs?.length!==input.inputs.length) return false; + return input.inputs.every(item=>task.inputs.some(stored=> + stored.artifactId===(item.sampleId??item.artifactId)&& + JSON.stringify(stored.capture??null)===JSON.stringify(item.capture??null))); +} + +export function summarizeCalibrationTask(task) { + const {id,operation,status,engine,engineSourceSha256,result,error,attempt,inputs}=task; + return {id,operation,status,engine,engineSourceSha256,attempt,inputCount:inputs?.length,result,error}; +} + +export function summarizeCalibration(action,data,experimentId) { + if(action==='overview') { + const {engines,tasks,assets,samples,frames}=data; + return {engines,counts:{tasks:tasks.length,measurementAssets:assets.length,rawSamples:samples.length,frames:frames.length}, + tasks:tasks.slice(-16).reverse().map(summarizeCalibrationTask), + rawSamples:samples.slice(-32).reverse().map(sample=>({id:sample.id,scene:sample.metadata?.scene,source:sample.source, + sha256:sample.hash,...calibrationCaptureMetadata(sample)})), + measurementAssets:assets.slice(-16).reverse().map(({id,kind,sha256})=>({id,kind,sha256}))}; + } + if(action==='task') return {task:summarizeCalibrationTask(data.task),pendingRequest:data.pendingRequest}; + if(action==='result') { + const {operation,executor,format,algorithm,hardwareVerification,qualityVerification,outputSha256, + taskManifestSha256,inputArtifacts,parameters}=data.result; + return {result:{operation,executor,format,algorithm,hardwareVerification,qualityVerification,outputSha256, + taskManifestSha256,inputArtifacts,method:parameters.method, + ...(['blc','ccm','awb'].includes(operation)?{values:parameters.values}:{fullParameters:'workbench_download'})}}; + } + const {taskId,operation,status,mappingAvailability,runtimeMapping,hardwareVerification,qualityVerification, + writesDevice,prerequisites}=data.plan; + const awbIlluminants=Array.isArray(data.plan?.availableIlluminantIds)?data.plan.availableIlluminantIds + :Array.isArray(data.plan?.illuminantIds)?data.plan.illuminantIds:undefined; + const nextDeviceTool=runtimeMapping?.status==='declared'&&experimentId&&taskId + ?{tool:'vision_calibration_apply', + arguments:{experimentId,taskId,...(operation==='awb'?{options:{illuminantId:awbIlluminants?.[0]??'<光源ID>'}}:{})}, + ...(awbIlluminants?.length?{availableIlluminantIds:awbIlluminants}:{}), + note:operation==='awb' + ?'AWB 标定含多光源结果,需先核对 result 中的 illuminantId,经学员明确确认后带 options:{illuminantId} 由相机插件 vision_calibration_apply 执行上板并拍验证帧。' + :'需经学员明确确认后由相机插件设备写工具执行上板并拍验证帧。'} + :undefined; + return {plan:{taskId,operation,status,mappingAvailability,runtimeMapping,hardwareVerification,qualityVerification, + writesDevice,prerequisites,...(nextDeviceTool?{nextDeviceTool}:{})}}; +} diff --git a/plugins/rdk-camera-workshop/mcp/calibration-visual.mjs b/plugins/rdk-camera-workshop/mcp/calibration-visual.mjs new file mode 100644 index 0000000..7173f22 --- /dev/null +++ b/plugins/rdk-camera-workshop/mcp/calibration-visual.mjs @@ -0,0 +1,231 @@ +import { createHash } from 'node:crypto'; +import { deflateSync } from 'node:zlib'; + +const CHANNELS = ['R', 'Gr', 'Gb', 'B']; +const CHANNEL_COLORS = { + R: [225, 29, 72], + Gr: [22, 163, 74], + Gb: [13, 148, 136], + B: [37, 99, 235], +}; + +// Compact 5x7 uppercase/digits/punctuation bitmap font for crisp zero-dep PNG labels. +const FONT = { + ' ': [0,0,0,0,0,0,0], + '0': [14,17,19,21,25,17,14], '1': [4,12,4,4,4,4,14], '2': [14,17,1,6,8,16,31], + '3': [14,17,1,6,1,17,14], '4': [2,6,10,18,31,2,2], '5': [31,16,30,1,1,17,14], + '6': [6,8,16,30,17,17,14], '7': [31,1,2,4,8,8,8], '8': [14,17,17,14,17,17,14], + '9': [14,17,17,15,1,2,12], + 'A': [14,17,17,31,17,17,17], 'B': [30,17,17,30,17,17,30], 'C': [14,17,16,16,16,17,14], + 'D': [30,17,17,17,17,17,30], 'E': [31,16,16,30,16,16,31], 'F': [31,16,16,30,16,16,16], + 'G': [14,17,16,23,17,17,15], 'H': [17,17,17,31,17,17,17], 'I': [14,4,4,4,4,4,14], + 'J': [7,2,2,2,18,18,12], 'K': [17,18,20,24,20,18,17], 'L': [16,16,16,16,16,16,31], + 'M': [17,27,21,21,17,17,17], 'N': [17,25,21,19,17,17,17], 'O': [14,17,17,17,17,17,14], + 'P': [30,17,17,30,16,16,16], 'Q': [14,17,17,17,21,18,13], 'R': [30,17,17,30,20,18,17], + 'S': [15,16,16,14,1,1,30], 'T': [31,4,4,4,4,4,4], 'U': [17,17,17,17,17,17,14], + 'V': [17,17,17,17,17,10,4], 'W': [17,17,17,21,21,27,17], 'X': [17,17,10,4,10,17,17], + 'Y': [17,17,10,4,4,4,4], 'Z': [31,1,2,4,8,16,31], + '.': [0,0,0,0,0,12,12], ',': [0,0,0,0,4,4,8], ':': [0,4,4,0,4,4,0], + '-': [0,0,0,31,0,0,0], '+': [0,4,4,31,4,4,0], '/': [1,2,2,4,8,8,16], + '=': [0,0,31,0,31,0,0], '(': [2,4,8,8,8,4,2], ')': [8,4,2,2,2,4,8], + '%': [25,25,2,4,8,19,19], '_': [0,0,0,0,0,0,31], 'x': [0,0,17,10,4,10,17], +}; + +const CRC_TABLE = new Uint32Array(256); +for (let i = 0; i < 256; i++) { + let c = i; + for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); + CRC_TABLE[i] = c >>> 0; +} +function crc32(buf) { + let c = 0xffffffff; + for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} +function pngChunk(type, data) { + const len = Buffer.alloc(4); len.writeUInt32BE(data.length, 0); + const tag = Buffer.from(type, 'ascii'); + const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(Buffer.concat([tag, data])), 0); + return Buffer.concat([len, tag, data, crc]); +} +function encodePng(width, height, rgb) { + const stride = width * 3; + const raw = Buffer.alloc((stride + 1) * height); + for (let y = 0; y < height; y++) { + raw[y * (stride + 1)] = 0; + rgb.copy(raw, y * (stride + 1) + 1, y * stride, (y + 1) * stride); + } + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; ihdr[9] = 2; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0; + return Buffer.concat([ + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), + pngChunk('IHDR', ihdr), + pngChunk('IDAT', deflateSync(raw, { level: 6 })), + pngChunk('IEND', Buffer.alloc(0)), + ]); +} + +function createCanvas(width, height, bg = [248, 250, 252]) { + const buf = Buffer.alloc(width * height * 3); + for (let i = 0; i < width * height; i++) { + buf[i * 3] = bg[0]; buf[i * 3 + 1] = bg[1]; buf[i * 3 + 2] = bg[2]; + } + const setPx = (x, y, c) => { + const ix = Math.round(x), iy = Math.round(y); + if (ix < 0 || iy < 0 || ix >= width || iy >= height) return; + const o = (iy * width + ix) * 3; + buf[o] = c[0]; buf[o + 1] = c[1]; buf[o + 2] = c[2]; + }; + const rect = (x, y, w, h, c) => { + const x0 = Math.max(0, Math.round(x)), y0 = Math.max(0, Math.round(y)); + const x1 = Math.min(width, Math.round(x + w)), y1 = Math.min(height, Math.round(y + h)); + for (let yy = y0; yy < y1; yy++) { + for (let xx = x0; xx < x1; xx++) { + const o = (yy * width + xx) * 3; + buf[o] = c[0]; buf[o + 1] = c[1]; buf[o + 2] = c[2]; + } + } + }; + const border = (x, y, w, h, c) => { + rect(x, y, w, 1, c); rect(x, y + h - 1, w, 1, c); + rect(x, y, 1, h, c); rect(x + w - 1, y, 1, h, c); + }; + const text = (str, x, y, c = [15, 23, 42], scale = 2) => { + let cx = Math.round(x); + for (const ch of String(str)) { + const key = ch === 'x' ? 'x' : ch.toUpperCase(); + const rows = FONT[key] ?? FONT[' ']; + for (let r = 0; r < 7; r++) { + for (let col = 0; col < 5; col++) { + if (rows[r] & (1 << (4 - col))) rect(cx + col * scale, y + r * scale, scale, scale, c); + } + } + cx += 6 * scale; + } + }; + return { width, height, buf, setPx, rect, border, text, toPng: () => encodePng(width, height, buf) }; +} + +function heatColor(t) { + const u = Math.max(0, Math.min(1, t)); + return [ + Math.round(28 + 224 * u), + Math.round(62 + 112 * u), + Math.round(116 - 61 * u), + ]; +} + +const fmt = (v, d = 3) => (Number.isFinite(v) ? Number(v).toFixed(d) : '--'); + +export function renderCalibrationResultPng(result) { + if (!result || typeof result !== 'object') return null; + const op = result.operation; + const params = result.parameters ?? {}; + const values = params.values; + const engine = String(result.executor ?? 'offline').replace(/^cpu-offline-/, ''); + const W = 720, H = 400; + const canvas = createCanvas(W, H, [248, 250, 252]); + canvas.rect(0, 0, W, 56, [15, 23, 42]); + canvas.border(0, 0, W, H, [203, 213, 225]); + let label = ''; + + if (op === 'blc' && CHANNELS.every(c => Number.isFinite(values?.[c]) && values[c] >= 0)) { + label = `离线黑电平标定结果 (BLC · ${engine})`; + canvas.text(`BLC RESULT ENGINE:${engine}`, 24, 21, [248, 250, 252], 2); + const maxVal = Math.max(1, ...CHANNELS.map(c => values[c])); + CHANNELS.forEach((ch, idx) => { + const y = 84 + idx * 66; + const val = values[ch]; + const spread = params.statistics?.[ch]?.frameMeanSpreadCodes ?? params.statistics?.[ch]?.frameMedianSpreadCodes; + canvas.rect(24, y, W - 48, 52, [255, 255, 255]); + canvas.border(24, y, W - 48, 52, [226, 232, 240]); + canvas.text(ch, 40, y + 18, CHANNEL_COLORS[ch], 2); + const barX = 96, barW = 340, fillW = Math.max(4, Math.round((val / maxVal) * barW)); + canvas.rect(barX, y + 16, barW, 20, [241, 245, 249]); + canvas.rect(barX, y + 16, fillW, 20, CHANNEL_COLORS[ch]); + canvas.text(`${fmt(val, 2)} DN`, 452, y + 12, [15, 23, 42], 2); + if (Number.isFinite(spread)) canvas.text(`SPREAD ${fmt(spread, 2)}`, 452, y + 34, [100, 116, 139], 1); + }); + canvas.text('UNIT: RAW DN CODES UNVERIFIED ON DEVICE', 24, H - 28, [100, 116, 139], 1); + } else if (op === 'lsc' && Number.isInteger(params.grid?.rows) && Number.isInteger(params.grid?.cols) && + CHANNELS.every(c => Array.isArray(values?.[c]) && values[c].length === params.grid.rows)) { + const { rows, cols } = params.grid; + label = `离线镜头阴影增益热力图 (LSC ${rows}x${cols} · ${engine})`; + canvas.text(`LSC GAIN MAP ${rows}x${cols} ENGINE:${engine}`, 24, 21, [248, 250, 252], 2); + const flat = CHANNELS.flatMap(c => values[c].flat()).filter(Number.isFinite); + const low = Math.min(...flat), high = Math.max(...flat); + const tileW = 152, tileH = 152, gap = 16, startX = 32, startY = 82; + CHANNELS.forEach((ch, idx) => { + const tx = startX + idx * (tileW + gap); + canvas.rect(tx - 4, startY - 4, tileW + 8, tileH + 54, [255, 255, 255]); + canvas.border(tx - 4, startY - 4, tileW + 8, tileH + 54, [226, 232, 240]); + const map = values[ch]; + const cellW = tileW / cols, cellH = tileH / rows; + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + const g = map[r][c]; + const t = high === low ? 0 : (g - low) / (high - low); + canvas.rect(tx + c * cellW, startY + r * cellH, Math.ceil(cellW), Math.ceil(cellH), heatColor(t)); + } + } + const chVals = map.flat(); + const chMin = Math.min(...chVals), chMax = Math.max(...chVals); + canvas.text(ch, tx + 4, startY + tileH + 8, CHANNEL_COLORS[ch], 2); + canvas.text(`${fmt(chMin, 2)}-${fmt(chMax, 2)}x`, tx + 38, startY + tileH + 14, [51, 65, 85], 1); + canvas.text(`CORNER/CTR`, tx + 4, startY + tileH + 30, [100, 116, 139], 1); + }); + // Shared colorbar + const barX = 110, barY = 322, barW = 500, barH = 18; + for (let i = 0; i < barW; i++) canvas.rect(barX + i, barY, 1, barH, heatColor(i / (barW - 1))); + canvas.border(barX, barY, barW, barH, [148, 163, 184]); + canvas.text(`${fmt(low, 2)}x`, 32, barY + 2, [15, 23, 42], 2); + canvas.text(`${fmt(high, 2)}x`, barX + barW + 14, barY + 2, [15, 23, 42], 2); + canvas.text('WARMER COLOR = HIGHER SHADING COMPENSATION GAIN', 110, 356, [100, 116, 139], 1); + } else if (op === 'ccm' && Array.isArray(values) && values.length === 3 && values.every(r => Array.isArray(r) && r.length === 3)) { + label = `离线色彩矩阵标定结果 (CCM 3x3 · ${engine})`; + canvas.text(`CCM 3x3 MATRIX ENGINE:${engine}`, 24, 21, [248, 250, 252], 2); + const rgbNames = ['R', 'G', 'B']; + const cellW = 160, cellH = 68, startX = 140, startY = 96; + rgbNames.forEach((n, c) => canvas.text(`IN ${n}`, startX + c * (cellW + 12) + 46, 74, [71, 85, 105], 2)); + for (let r = 0; r < 3; r++) { + const y = startY + r * (cellH + 12); + canvas.text(`OUT ${rgbNames[r]}`, 32, y + 26, [71, 85, 105], 2); + for (let c = 0; c < 3; c++) { + const v = values[r][c]; + const x = startX + c * (cellW + 12); + const bg = r === c ? [219, 234, 254] : v < 0 ? [254, 243, 199] : [241, 245, 249]; + canvas.rect(x, y, cellW, cellH, bg); + canvas.border(x, y, cellW, cellH, r === c ? [59, 130, 246] : [203, 213, 225]); + canvas.text((v >= 0 ? '+' : '') + fmt(v, 4), x + 20, y + 26, [15, 23, 42], 2); + } + } + const tr = params.statistics?.trainRmseLinear; + const ho = params.statistics?.heldoutRmseLinear; + canvas.text(`TRAIN RMSE: ${fmt(tr, 5)} HELDOUT RMSE: ${fmt(ho, 5)}`, 32, H - 36, [51, 65, 85], 2); + } else if (op === 'awb' && Array.isArray(values) && values.length > 0) { + label = `离线白平衡多光源增益结果 (AWB · ${engine})`; + canvas.text(`AWB GAINS BY CCT ENGINE:${engine}`, 24, 21, [248, 250, 252], 2); + const rows = [...values].sort((a, b) => a.colorTemperatureK - b.colorTemperatureK).slice(0, 5); + const maxGain = Math.max(2, ...rows.flatMap(r => [r.redGain, r.greenGain, r.blueGain]).filter(Number.isFinite)); + rows.forEach((light, idx) => { + const y = 78 + idx * 58; + canvas.rect(24, y, W - 48, 48, [255, 255, 255]); + canvas.border(24, y, W - 48, 48, [226, 232, 240]); + canvas.text(`${String(light.illuminantId).slice(0, 6)} ${Math.round(light.colorTemperatureK)}K`, 36, y + 16, [15, 23, 42], 2); + const bx = 250, bw = 280; + const rg = Math.max(4, Math.round((light.redGain / maxGain) * bw)); + const bg = Math.max(4, Math.round((light.blueGain / maxGain) * bw)); + canvas.rect(bx, y + 8, rg, 12, CHANNEL_COLORS.R); + canvas.rect(bx, y + 26, bg, 12, CHANNEL_COLORS.B); + canvas.text(`R:${fmt(light.redGain, 2)}x`, bx + bw + 14, y + 8, CHANNEL_COLORS.R, 1); + canvas.text(`B:${fmt(light.blueGain, 2)}x`, bx + bw + 14, y + 28, CHANNEL_COLORS.B, 1); + }); + canvas.text('GREEN GAIN = 1.00x BASELINE UNVERIFIED ON DEVICE', 24, H - 24, [100, 116, 139], 1); + } else { + return null; + } + + const bytes = canvas.toPng(); + return { bytes, sha256: createHash('sha256').update(bytes).digest('hex'), label }; +} diff --git a/plugins/rdk-camera-workshop/mcp/camera-source.mjs b/plugins/rdk-camera-workshop/mcp/camera-source.mjs index 3db96ac..56c4086 100644 --- a/plugins/rdk-camera-workshop/mcp/camera-source.mjs +++ b/plugins/rdk-camera-workshop/mcp/camera-source.mjs @@ -1,10 +1,15 @@ import { createHash } from 'node:crypto'; import { constants } from 'node:fs'; -import { open } from 'node:fs/promises'; +import { open, realpath } from 'node:fs/promises'; import { homedir } from 'node:os'; import path from 'node:path'; import { cameraIdPattern } from './steps.mjs'; -import { learnerOptions, publicLearnerOptions, checkedLearnerValue, singleFieldMatches } from './learner-isp.mjs'; +import { + learnerOptions, publicLearnerOptions, checkedLearnerValue, singleFieldMatches, + MULTI_TUNE_FIELDS, quantizeControlToHardware, planHardwareIspFromFrame, +} from './learner-isp.mjs'; +import { analyzeIspImage } from '../web/isp-engine.mjs'; +import { decodeImageAuto, resizeRgb } from './isp-codec.mjs'; const mcpSuffix='/api/ops/vision-workshop/mcp'; const restSuffix='/api/ops/observability/vision-workshop'; @@ -32,7 +37,8 @@ function readbackDetails(receipt, experiment) { async function readPrivate(file,limit) { if (typeof file!=='string'||!path.isAbsolute(file)) throw new Error('camera_configuration_invalid'); - const handle=await open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0)); + const resolved=await realpath(file); + const handle=await open(resolved,constants.O_RDONLY|(constants.O_NOFOLLOW??0)); try { const stat=await handle.stat(); if(!stat.isFile()||stat.size>limit||process.platform!=='win32'&&((stat.mode&0o777)!==0o600||stat.uid!==process.getuid())) { @@ -64,35 +70,43 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO async function fetchArchive(suffix,{body,limit=maxBytes}={}) { let result; try { - const config=JSON.parse(await readPrivate(configFile,32768)); + const config=JSON.parse(await readPrivate(configFile,65536)); const url=new URL(config.url); if(url.username||url.password||url.search||url.hash||!url.pathname.endsWith(mcpSuffix)|| !(url.protocol==='https:'||url.protocol==='http:'&&['localhost','127.0.0.1','[::1]'].includes(url.hostname))|| !['admin','sso'].includes(config.auth?.type)) throw new Error('camera_configuration_invalid'); - const secret=(await readPrivate(config.auth.credentialFile,16384)).trim(); + const secret=(await readPrivate(config.auth.credentialFile,16384).catch(error=>{ + if(error.code==='ENOENT') throw new Error('camera_credential_missing'); + throw error; + })).trim(); if(!secret||/[\u0000-\u001f\u007f]/u.test(secret)) throw new Error('camera_configuration_invalid'); + const configuredTimeout=Number.isSafeInteger(config.timeoutMs)&&config.timeoutMs>=1&&config.timeoutMs<=300000?config.timeoutMs:undefined; result={url:url.origin+url.pathname.slice(0,-mcpSuffix.length)+restSuffix, + timeoutMs:configuredTimeout, headers:{[config.auth.type==='admin'?'x-admin-token':'x-rdk-sso-session']:secret}}; } catch(error) { + if(error.message==='camera_credential_missing') throw error; throw new Error(error.code==='ENOENT'?'camera_unconfigured':'camera_configuration_invalid'); } let response; const headers={...result.headers,...(body===undefined?{}:{'content-type':'application/json','x-rdk-ops-action':'observability'})}; + const timeoutMs=result.timeoutMs??(body===undefined?15000:120000); try { response=await fetch(result.url+suffix,{headers,redirect:'error', ...(body===undefined?{}:{method:'POST',body:JSON.stringify(body)}), - signal:AbortSignal.timeout(body===undefined?15000:120000)}); } + signal:AbortSignal.timeout(timeoutMs)}); } catch { throw new Error(body===undefined?'camera_service_unreachable':'camera_capture_unconfirmed'); } if(!response.ok) { if(response.status===401||response.status===403) { await response.body?.cancel(); throw new Error('camera_auth_required'); } - if(body!==undefined&&response.headers.get('content-type')?.startsWith('application/json')) { + if(response.headers.get('content-type')?.startsWith('application/json')) { const bytes=await responseBytes(response,256*1024); let receipt; try {receipt=JSON.parse(bytes.toString('utf8'));} catch {} + if(receipt?.error==='quota_exceeded') throw new Error('camera_archive_quota_full'); if(/^vision_[a-z0-9_]{1,90}$/.test(receipt?.error)) throw new Error(receipt.error); - throw new Error('camera_service_error'); + throw new Error(response.status===404?'camera_archive_missing':'camera_service_error'); } await response.body?.cancel(); throw new Error(response.status===404?'camera_archive_missing':'camera_service_error'); @@ -112,7 +126,7 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO } catch { throw new Error('camera_response_invalid'); } } async function list() { - const {experiments}=await json('/experiments?view=index&limit=30'); + const {experiments}=await json('/experiments?view=index&limit=100'); if(!Array.isArray(experiments)) throw new Error('camera_response_invalid'); return experiments.filter(exp=>cameraId.test(exp?.id)&&typeof exp.title==='string').map(exp=>({id:exp.id,title:exp.title,sensorModel:exp.sensorModel,updatedAt:exp.updatedAt})); } @@ -216,7 +230,9 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO // able to complete using the SDK getter returned by restore_tuning. const ordinary=async operation=>{ try { return await operation(); } - catch (error) { if(error.message!=='vision_device_history_capacity') throw error; } + catch (error) { + if(!['vision_device_history_capacity','vision_device_archive_capacity'].includes(error.message)) throw error; + } }; const probe=await ordinary(()=>device(experiment,'probe',{})); const facts=probe?.result?.facts; @@ -272,14 +288,22 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO if(result.evidence?.writeOutcome==='unconfirmed') throw new Error('camera_recovery_required'); return result.controls; } + async function ensureStreaming(experiment) { + try { + const {result}=await device(experiment,'pipeline_validate',{}); + if(result.passed!==true) throw new Error('camera_isp_stream_required'); + } catch(error) { + if(error.message==='vision_device_checks_failed') throw new Error('camera_isp_stream_required'); + throw error; + } + } async function learnerSetup(binding,original) { const experiment=await experimentArchive(binding); if(experiment.targetId!==original.adapterId||experiment.baseline?.id!==original.baselineId|| experiment.baseline.hash!==original.hash) throw new Error('camera_isp_snapshot_changed'); // The X5 probe creates a new SDK snapshot while streaming. Use the // current-frame check so validation preserves the saved tuning anchor. - const {result}=await device(experiment,'pipeline_validate',{}); - if(result.passed!==true) throw new Error('camera_isp_stream_required'); + await ensureStreaming(experiment); const beforeReadback=await ispReadback(experiment); if(beforeReadback.hash!==original.hash) throw new Error('camera_isp_snapshot_changed'); const controls=await controlsReadback(experiment); @@ -316,7 +340,7 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO onPhase('learner_apply',undefined,true); const {result,deviceRun}=await (candidate ? device(experiment,'apply_tuning',{candidateId:candidate.id}) - : device(experiment,'controls_set',{values:{[option.id]:value}})); + : device(experiment,'controls_set',{values:{[option.id]:normalized}})); onPhase('learner_verify',{writeReceipt:deviceRun.id}); const afterReadback=await ispReadback(experiment); if(candidate&&(result.appliedHash!==candidate.hash||result.readbackHash!==candidate.hash||afterReadback.hash!==candidate.hash)|| @@ -338,9 +362,8 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO experiment.baseline?.id!==original.baselineId||experiment.baseline.hash!==original.hash) { throw new Error('camera_isp_snapshot_changed'); } - const {result}=await device(experiment,'probe',{}); - if(result.facts?.cleanupRequired===true||result.facts?.writeOutcome==='unconfirmed') throw new Error('camera_recovery_required'); - if(result.facts?.streaming!==true) throw new Error('camera_isp_stream_required'); + // Use pipeline_validate instead of probe so X5 does not rotate snapshotId while streaming. + await ensureStreaming(experiment); if((await ispReadback(experiment)).hash!==original.hash) throw new Error('camera_isp_snapshot_changed'); const readControls=()=>controlsReadback(experiment); const controls=await readControls(); @@ -365,7 +388,7 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO } const line=time.nativeLinePeriodUs; const lines=Math.max(Math.ceil(time.min/line-1e-5),Math.round(time.value/line/2)); - const targetUs=Math.fround(lines*line/1e6)*1e6; + const targetUs=Math.fround(Math.fround(line/1e6)*lines)*1e6; if(targetUstime.max||targetUs>=time.value) throw new Error('camera_exposure_no_room'); const verifyExposure=(readback,expectedUs)=>{ const exposure=readback.config.modules?.exposure; @@ -396,7 +419,7 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO BigInt(after.sdkTimestampNs)<=BigInt(before.sdkTimestampNs)) throw new Error('camera_exposure_freshness_failed'); onPhase('exposure_verify',{after,afterReadback,afterUs:targetUs}); } - async function gammaTrial(binding,original,goal,onPhase) { + async function prepareGamma(binding,original,goal,onPhase) { const experiment=await experimentArchive(binding); if(experiment.targetId!==original.adapterId||experiment.baseline?.id!==original.baselineId|| experiment.baseline.hash!==original.hash) { @@ -408,8 +431,19 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO const before=await capture(binding,'isp',{scene:'课堂 Gamma 对照 · 原始'}); if(before.tuningHash!==original.hash||!before.sdkTimestampNs) throw new Error('camera_isp_readback_invalid'); onPhase('gamma_plan',{before}); - const {candidate}=await json('/experiments/'+experiment.id+'/candidates', - {body:{frameIds:[before.id],goal:'课程 Gamma 单次对照,只允许修改 Gamma 曲线,不切换模式。观察目标:'+goal}}); + let candidate; + let localFallback=false; + try { + ({candidate}=await json('/experiments/'+experiment.id+'/candidates', + {body:{frameIds:[before.id],goal:'课程 Gamma 单次对照,只允许修改 Gamma 曲线,不切换模式。观察目标:'+goal}})); + } catch(error) { + if(error.message!=='vision_model_disabled') throw error; + const capabilities=await json('/capabilities'); + if(capabilities.classroomGammaCandidate!==true) throw error; + localFallback=true; + ({candidate}=await json('/experiments/'+experiment.id+'/classroom-gamma-candidate', + {body:{baselineId:original.baselineId,baselineHash:original.hash,frameId:before.id,goal}})); + } const mode=original.config.modules?.gamma?.mode; const field=mode===0?'auto_attr.curve':mode===1?'manual_attr.curve':undefined; const stripCurve=config=>{ @@ -417,8 +451,9 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO const {[field]:_curve,...settings}=gamma??{}; return {...config,modules:{...otherModules,gamma:settings}}; }; + const validSource=localFallback?candidate?.source==='manual':candidate?.source==='model'; if(!field||!Array.isArray(candidate?.tuning?.modules?.gamma?.[field])|| - candidate?.source!=='model'||!cameraId.test(candidate.id)||candidate.baselineHash!==original.hash|| + !validSource||!cameraId.test(candidate.id)||candidate.baselineHash!==original.hash|| candidate.baselineId!==original.baselineId||!candidate.frameIds?.includes(before.id)|| !hash.test(candidate.hash)||!record(candidate.tuning)||sha256(JSON.stringify(candidate.tuning))!==candidate.hash|| candidate.hash===original.hash||!Array.isArray(candidate.patches)||!candidate.patches.length|| @@ -426,10 +461,34 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO JSON.stringify(stripCurve(candidate.tuning))!==JSON.stringify(stripCurve(original.config))) { throw new Error('camera_gamma_candidate_rejected'); } - if((await ispReadback(experiment)).hash!==original.hash) throw new Error('camera_isp_snapshot_changed'); - onPhase('gamma_apply',{before,candidateId:candidate.id},true); - const result=await applyGammaFrame(binding,experiment,candidate,before.sdkTimestampNs,()=>onPhase('gamma_verify')); - return {before,beforeReadback,...result,candidateId:candidate.id}; + const beforeCurve=original.config.modules.gamma[field].slice(0,64); + const curve=candidate.tuning.modules.gamma[field].slice(0,64); + if([beforeCurve,curve].some(nodes=>nodes.length!==64||nodes.some(n=>!Number.isInteger(n)||n<0||n>1023))) { + throw new Error('camera_gamma_candidate_rejected'); + } + const model=localFallback?'bounded-gamma-local':(typeof candidate.model==='string'?candidate.model.replace(/[\u0000-\u001f\u007f]/gu,' ').trim().slice(0,100):undefined); + const reasons=[...new Set(candidate.patches.map(patch=>typeof patch.reason==='string'? + patch.reason.replace(/[\u0000-\u001f\u007f]/gu,' ').trim().slice(0,220):'').filter(Boolean))].slice(0,3); + return {before,candidateId:candidate.id,hash:candidate.hash,baselineHash:original.hash, + ...(model?{model}:{}),reasons,beforeCurve,curve}; + } + async function applyPreparedGamma(binding,original,proposal,onPhase) { + const experiment=await experimentArchive(binding); + const beforeReadback=await ispReadback(experiment); + if(experiment.targetId!==original.adapterId||experiment.baseline?.id!==original.baselineId|| + experiment.baseline.hash!==original.hash||beforeReadback.hash!==original.hash|| + proposal.baselineHash!==original.hash||proposal.before.tuningHash!==original.hash) { + throw new Error('camera_isp_snapshot_changed'); + } + onPhase('gamma_apply',{before:proposal.before,candidateId:proposal.candidateId},true); + const result=await applyGammaFrame(binding,experiment,{id:proposal.candidateId,hash:proposal.hash}, + proposal.before.sdkTimestampNs,()=>onPhase('gamma_verify')); + return {before:proposal.before,beforeReadback,...result,candidateId:proposal.candidateId}; + } + async function gammaTrial(binding,original,goal,onPhase) { + const proposal=await prepareGamma(binding,original,goal,onPhase); + const result=await applyPreparedGamma(binding,original,proposal,onPhase); + return {...result,proposal}; } async function confirmIsp(binding,original,expectedHash) { const experiment=await experimentArchive(binding); @@ -461,7 +520,8 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO if(!experiment.targetId) throw new Error('vision_device_adapter_required'); let readbackHash; if(kind==='render') { - const readback=await device(experiment,'tuning_get',{}); + // tuning_export reads current ISP hash without rotating X5 snapshotId or overwriting experiment.baseline. + const readback=await device(experiment,'tuning_export',{}); readbackHash=readback.result?.readbackHash; if(!hash.test(readbackHash)) throw new Error('camera_response_invalid'); } @@ -543,5 +603,179 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO report(layer,{status:'blocked',code}); } } - return {list,inspect,frame,capture,captureFile,preflight,saveOriginalIsp,restoreOriginalIsp,exposureTrial,gammaTrial,reloadGamma,confirmIsp,getLearnerOptions,learnerTrial}; + async function calibration(binding, action, input, taskId) { + if(!cameraId.test(binding?.experimentId)) throw new Error('camera_binding_invalid'); + const root='/experiments/'+binding.experimentId+'/calibration'; + if(action==='overview') { + const [experiment,engines,assets,tasks]=await Promise.all([ + experimentArchive(binding),json(root+'/engines'),json(root+'/assets'),json(root+'/tasks'), + ]); + if(!Array.isArray(engines.engines)||!Array.isArray(assets.assets)|| + !Array.isArray(tasks.tasks)||!Array.isArray(experiment.samples)) throw new Error('camera_response_invalid'); + return { + engines:engines.engines,tasks:tasks.tasks,assets:assets.assets, + samples:experiment.samples.map(({id,source,metadata,hash})=>({id,source,metadata,hash})), + frames:experiment.cameraFrames.map(({id,scene,width,height,hash})=>({id,scene,width,height,hash})), + }; + } + if(action==='create') return json(root+'/tasks',{body:input}); + if(action==='import_measurement') return json(root+'/assets',{body:{measurement:input}}); + if(!cameraId.test(taskId)) throw new Error('camera_calibration_invalid'); + const task=root+'/tasks/'+taskId; + if(action==='task') return json(task); + if(action==='run') return json(task+'/run',{body:{}}); + if(action==='result') return json(task+'/result'); + if(action==='apply_plan') return json(task+'/apply-plan'); + throw new Error('camera_calibration_invalid'); + } + async function analyzeArchivedFrame(binding, asset) { + try { + const file = await captureFile(binding, 'isp', asset); + const dec = decodeImageAuto(file.bytes); + const small = resizeRgb(dec.data, dec.width, dec.height, 480); + return analyzeIspImage(small.data, small.width, small.height, 3); + } catch { + return null; + } + } + async function autoPlanHardwareIsp(binding, original, goal = '') { + const experiment = await experimentArchive(binding); + if (experiment.targetId !== original.adapterId || experiment.baseline?.id !== original.baselineId || + experiment.baseline.hash !== original.hash) throw new Error('camera_isp_snapshot_changed'); + await ensureStreaming(experiment); + const readback = await ispReadback(experiment); + const controls = await controlsReadback(experiment); + const frameAsset = await capture(binding, 'isp', { scene: 'AI 自主硬件 ISP 诊断采样' }); + const metrics = await analyzeArchivedFrame(binding, frameAsset); + if (!metrics) throw new Error('camera_isp_analysis_unavailable'); + const plan = planHardwareIspFromFrame(metrics, controls, goal); + const currentSnapshot = {}; + for (const k of ['autoExposure', 'autoWhiteBalance', ...MULTI_TUNE_FIELDS]) { + if (controls[k] && controls[k].value !== undefined) { + currentSnapshot[k] = { + value: controls[k].value, + ...(Number.isFinite(controls[k].min) ? { min: controls[k].min, max: controls[k].max } : {}), + writable: controls[k].writable !== false, + }; + } + } + return { + frame: frameAsset, + readback, + goal: goal || undefined, + metrics, + currentControls: currentSnapshot, + ...plan, + plannedAt: new Date().toISOString(), + }; + } + async function multiHardwareTrial(binding, original, { values, goal, reason }, onPhase) { + if (!values || typeof values !== 'object' || Array.isArray(values)) { + throw new Error('camera_isp_action_invalid'); + } + const requestedEntries = Object.entries(values).filter(([, v]) => typeof v === 'number' && Number.isFinite(v)); + if (!requestedEntries.length || requestedEntries.some(([k]) => !MULTI_TUNE_FIELDS.includes(k))) { + throw new Error('camera_isp_action_invalid'); + } + const experiment = await experimentArchive(binding); + if (experiment.targetId !== original.adapterId || experiment.baseline?.id !== original.baselineId || + experiment.baseline.hash !== original.hash) throw new Error('camera_isp_snapshot_changed'); + await ensureStreaming(experiment); + + const beforeReadback = await ispReadback(experiment); + let controls = await controlsReadback(experiment); + const beforeControls = {}; + for (const [k] of requestedEntries) { + if (controls[k] !== undefined) beforeControls[k] = controls[k].value; + } + + onPhase('multi_before'); + const before = await capture(binding, 'isp', { scene: 'AI 联调真机 ISP · 调前' }); + if (before.tuningHash !== beforeReadback.hash || !before.sdkTimestampNs) { + throw new Error('camera_isp_readback_invalid'); + } + const beforeMetrics = await analyzeArchivedFrame(binding, before); + + // Prepare manual AE / AWB automatically if required by requested controls + const modePatch = {}; + const needManualAe = requestedEntries.some(([k]) => k === 'exposureUs' || k === 'gain'); + const needManualAwb = requestedEntries.some(([k]) => k === 'redGain' || k === 'blueGain'); + if (needManualAe && controls.autoExposure?.value === true) { + if (controls.autoExposure.writable === false) throw new Error('camera_exposure_unavailable'); + modePatch.autoExposure = false; + } + if (needManualAwb && controls.autoWhiteBalance?.value === true) { + if (controls.autoWhiteBalance.writable === false) throw new Error('camera_awb_unavailable'); + modePatch.autoWhiteBalance = false; + } + + onPhase('multi_apply', { + kind: 'multi', + label: '多参数硬件联调 (' + requestedEntries.map(([k]) => k).join('+') + ')', + before, + beforeReadback, + beforeValues: beforeControls, + requestedValues: Object.fromEntries(requestedEntries), + ...(beforeMetrics ? { beforeMetrics } : {}), + ...(goal ? { goal } : {}), + ...(reason ? { reason } : {}), + }, true); + + const modeReceipts = []; + if (Object.keys(modePatch).length > 0) { + const { deviceRun } = await device(experiment, 'controls_set', { values: modePatch }); + modeReceipts.push(deviceRun.id); + controls = await controlsReadback(experiment); + } + + // Hardware-quantize every requested field against fresh manual control limits + const quantized = {}; + for (const [k, rawVal] of requestedEntries) { + const row = controls[k]; + if (!row || row.writable === false) throw new Error('camera_learner_control_unavailable'); + quantized[k] = quantizeControlToHardware(row, rawVal); + } + + const { deviceRun } = await device(experiment, 'controls_set', { values: quantized }); + onPhase('multi_verify', { writeReceipt: deviceRun.id, modeReceipts, appliedValues: quantized }); + + const afterReadback = await ispReadback(experiment); + const afterControls = await controlsReadback(experiment); + const verifiedValues = {}; + for (const [k, targetVal] of Object.entries(quantized)) { + const actual = afterControls[k]?.value; + if (!Number.isFinite(actual) || Math.abs(actual - targetVal) > Math.max(1e-3, Math.abs(targetVal) * 0.03)) { + throw new Error('camera_learner_readback_mismatch'); + } + verifiedValues[k] = actual; + } + + onPhase('multi_verify', { afterReadback, afterValues: verifiedValues }); + const after = await capture(binding, 'isp', { scene: 'AI 联调真机 ISP · 调后' }); + if (after.tuningHash !== afterReadback.hash || !after.sdkTimestampNs || + BigInt(after.sdkTimestampNs) <= BigInt(before.sdkTimestampNs)) { + throw new Error('camera_learner_freshness_failed'); + } + const afterMetrics = await analyzeArchivedFrame(binding, after); + onPhase('multi_saved', { + after, + ...(afterMetrics ? { afterMetrics } : {}), + ...(beforeMetrics && afterMetrics ? { + metricsDelta: { + meanLuma: Number((afterMetrics.meanLuma - beforeMetrics.meanLuma).toFixed(2)), + darkPct: Number((afterMetrics.darkPct - beforeMetrics.darkPct).toFixed(2)), + clipPct: Number((afterMetrics.clipPct - beforeMetrics.clipPct).toFixed(2)), + meanSat: Number((afterMetrics.meanSat - beforeMetrics.meanSat).toFixed(2)), + edgeSharpness: Number((afterMetrics.edgeSharpness - beforeMetrics.edgeSharpness).toFixed(2)), + wbCastIndex: Number((afterMetrics.wbCastIndex - beforeMetrics.wbCastIndex).toFixed(1)), + }, + } : {}), + }); + } + return { + calibration,list,inspect,frame,capture,captureFile,preflight, + saveOriginalIsp,restoreOriginalIsp,exposureTrial,gammaTrial, + prepareGamma,applyPreparedGamma,reloadGamma,confirmIsp, + getLearnerOptions,learnerTrial,autoPlanHardwareIsp,multiHardwareTrial, + }; } diff --git a/plugins/rdk-camera-workshop/mcp/course-evidence.mjs b/plugins/rdk-camera-workshop/mcp/course-evidence.mjs index 2d40f5e..2d5d31f 100644 --- a/plugins/rdk-camera-workshop/mcp/course-evidence.mjs +++ b/plugins/rdk-camera-workshop/mcp/course-evidence.mjs @@ -10,6 +10,7 @@ const snapshotLimit=8*1024*1024; const digest=bytes=>createHash('sha256').update(bytes).digest('hex'); const classes=['park','qrcode','obstacle']; const detectionPhases=['before','after','live']; +const comparisonOverlap=.30; const sdkTime=value=>typeof value==='string'&&/^\d{1,20}$/.test(value); const validDetection=value=>classes.includes(value?.class)&&typeof value.score==='number'&&value.score>=0&&value.score<=1; @@ -19,8 +20,10 @@ function detectionFrame(frame,modelHash) { !detectionPhases.includes(frame.phase)||!Number.isFinite(frame.forwardMs)||frame.forwardMs<0|| !Array.isArray(frame.detections)||frame.detections.length>1000||!frame.detections.every(validDetection)) return; const counts=Object.fromEntries(classes.map(label=>[label,frame.detections.filter(item=>item.class===label).length])); + const maxScores={}; + for(const {class:label,score} of frame.detections) maxScores[label]=Math.max(maxScores[label]??0,score); return {file:frame.file,sha256:frame.imageSha256,tuningHash:frame.tuningHash,sdkTimestampNs:frame.sdkTimestampNs, - kind:'detection_'+frame.phase,phase:frame.phase,forwardMs:frame.forwardMs,counts}; + kind:'detection_'+frame.phase,phase:frame.phase,forwardMs:frame.forwardMs,counts,maxScores}; } async function boundedFile(filename,limit,missing) { @@ -78,21 +81,27 @@ export async function externalTrainingReceipt(filename=process.env.RDK_VISION_CO manifest.value.files.filter(row=>typeof row?.file==='string'&&row.file.startsWith('train/')&&sha.test(row.imageSha256)).length===ptq.calibrationImages) { proof.calibration_manifest=`训练分组 ${ptq.calibrationImages} 张 · dataset-manifest.json sha256:${manifest.sha256}`; } - return {source:'external',dataset:data.dataset.source,device:training.device,epochs:training.epochsCompleted, + const runId=training.id??data.runId; + return {source:'external',...(typeof runId==='string'&&runId.trim()&&runId.length<=300?{runId}:{}), + dataset:data.dataset.source,device:training.device,epochs:training.epochsCompleted, requestedEpochs:data.training.epochsRequested,validationQrcodeBoxes:data.dataset.validationQrcodeBoxes, modelSha256:data.ptq.modelSha256,checkpointSha256:data.training.checkpointSha256, calibrationImages:ptq.calibrationImages,receiptSha256:digest(bytes),evidence:proof}; } -export function boardEvidence(directory=process.env.RDK_VISION_COURSE_BOARD_ARCHIVE) { +export function boardEvidence(directory=process.env.RDK_VISION_COURSE_BOARD_ARCHIVE,{runId}={}) { async function get(modelHash) { if(!directory||!path.isAbsolute(directory)) throw new Error('board_archive_unconfigured'); const bytes=await boundedFile(path.join(directory,'receipt.json'),receiptLimit,'board_receipt_pending'); const report=JSON.parse(bytes); const expected=modelHash?.replace(/^sha256:/,''); + if(runId&&report.runId!==runId) throw new Error('board_receipt_pending'); if(report.schema!=='rdk.vision-course-board.v1'||!sha.test(report.modelSha256)|| report.modelSha256!==expected||JSON.stringify(report.classes)!==JSON.stringify(classes)) throw new Error('board_model_mismatch'); const assets=[]; + if(sha.test(report.staticBpu?.outputImageSha256)) { + assets.push({file:'static-detection.jpg',sha256:report.staticBpu.outputImageSha256,kind:'static_detection'}); + } for(const phase of ['before','after','restored']) { const image=report.gamma?.images?.[phase]; if(image&&/^(A1-original|B-candidate|A2-restored)\.png$/.test(image.file)&&sha.test(image.sha256)) { @@ -117,14 +126,28 @@ export function boardEvidence(directory=process.env.RDK_VISION_COURSE_BOARD_ARCH }])); const snapshotNames=report.tuningHash?['original-isp.json','loaded-isp.json']:[]; if(report.restoration==='verified') snapshotNames.push('restored-isp.json'); + const representative=(phase,hash)=>detections.findLast(frame=>frame.phase===phase&&frame.tuningHash===hash&& + assets.some(asset=>asset.file===frame.file&&asset.sha256===frame.sha256)); + const settings=report.comparison; + const before=representative('before',report.baselineTuningHash); + const after=representative('after',report.tuningHash); + const comparison=report.status==='completed'&&report.restoration==='verified'&&report.previewStopped===true&& + report.approvedGamma?.hash===report.tuningHash&&report.approvedGamma?.curveReadback?.status==='verified'&&before&&after&& + before.tuningHash!==after.tuningHash&&BigInt(before.sdkTimestampNs)0&&settings.durationPerPhaseSec<=60&&settings.scoreThreshold===.25&&settings.nmsThreshold===.70&& + sha.test(settings.approvedBaselineHash)? + {before,after,settings}:undefined; const view={status:report.status,stage:report.stage,modelSha256:report.modelSha256,staticBpu:report.staticBpu, phases:viewsByPhase,frameCount:frames.length,restoration:report.restoration,previewStopped:report.previewStopped, failure:report.failure??report.restorationFailure,cameraIdentity:report.cameraIdentity, gamma:report.gamma&&{scope:report.gamma.scope,strength:report.gamma.strength,curveReadback:report.gamma.curveReadback}, targetObservation:report.targetObservation,readbackHash:report.tuningHash,assets,snapshotNames,receiptSha256:digest(bytes), + ...(report.approvedGamma?.hash===report.tuningHash&&report.approvedGamma?.curveReadback?.status==='verified'?{approvedGamma:true}:{}), ...(latestDetection?{latestDetection}:{}), + ...(comparison?{comparison}:{}), ...(typeof report.runId==='string'&&/^[a-f0-9-]{36}$/.test(report.runId)?{runId:report.runId}:{})}; - return {view,bytes,snapshots:report.ispSnapshots}; + return {view,bytes,snapshots:report.ispSnapshots,detections,frames}; } async function snapshot(current,name) { if(!current.view.snapshotNames.includes(name)) throw new Error('board_asset_missing'); @@ -139,7 +162,7 @@ export function boardEvidence(directory=process.env.RDK_VISION_COURSE_BOARD_ARCH } else if(digest(JSON.stringify(data.config))!==data.readbackHash) throw new Error('board_asset_integrity_failed'); const kind={'original-isp.json':'before','loaded-isp.json':'after','restored-isp.json':'restored'}[name]; const expected=kind==='after'||kind==='before'&¤t.view.restoration==='no_write'?current.view.readbackHash: - current.view.assets.find(asset=>asset.kind===kind)?.tuningHash; + current.view.comparison?.[kind]?.tuningHash??current.view.assets.find(asset=>asset.kind===kind)?.tuningHash; if(expected&&data.readbackHash!==expected) throw new Error('board_asset_integrity_failed'); return {bytes,hash:data.readbackHash}; } @@ -157,20 +180,79 @@ export function boardEvidence(directory=process.env.RDK_VISION_COURSE_BOARD_ARCH if(digest(bytes)!==expected.sha256) throw new Error('board_asset_integrity_failed'); return {type:name.endsWith('.png')?'image/png':'image/jpeg',bytes}; } - async function preview(modelHash,knownSha256) { - const {view}=await get(modelHash); + async function preview(modelHash,knownSha256,batch=false) { + const {view,detections}=await get(modelHash); const frame=view.latestDetection; if(!frame||frame.sha256===knownSha256) return {view}; - try { - const bytes=await boundedFile(path.join(directory,frame.file),imageLimit,'board_asset_missing'); - if(digest(bytes)!==frame.sha256||bytes[0]!==0xff||bytes[1]!==0xd8||bytes.at(-2)!==0xff||bytes.at(-1)!==0xd9) { + async function image(detection) { + const bytes=await boundedFile(path.join(directory,detection.file),imageLimit,'board_asset_missing'); + if(digest(bytes)!==detection.sha256||bytes[0]!==0xff||bytes[1]!==0xd8||bytes.at(-2)!==0xff||bytes.at(-1)!==0xd9) { throw new Error('board_asset_integrity_failed'); } - return {view,imageBase64:bytes.toString('base64')}; + return bytes.toString('base64'); + } + try { + if(batch&&knownSha256&&view.runId&&view.status==='started') { + const cursor=detections.find(item=>item.sha256===knownSha256); + const fresh=detections.filter(item=>item.phase===frame.phase&&item.tuningHash===frame.tuningHash&& + (!cursor||BigInt(item.sdkTimestampNs)>BigInt(cursor.sdkTimestampNs))&& + view.assets.some(asset=>asset.file===item.file&&asset.sha256===item.sha256)).slice(-4); + const frames=await Promise.all(fresh.map(async item=>({frame:item,imageBase64:await image(item)}))); + return {view,frames}; + } + return {view,imageBase64:await image(frame)}; } catch(error) { if(error.message==='board_asset_missing') return {view,previewPending:true}; throw error; } } - return {get,file,preview}; + async function score(modelHash,{receiptSha256,label,region,targetAbsent=false}) { + const normalizedHash=typeof modelHash==='string'?modelHash.replace(/^sha256:/,''):modelHash; + const current=await get(normalizedHash); + const {view}=current; + if(view.receiptSha256!==receiptSha256) throw new Error('board_receipt_changed'); + if(!view.comparison) throw new Error('board_comparison_unavailable'); + if(typeof targetAbsent!=='boolean'||(targetAbsent?(label!==undefined||region!==undefined): + !classes.includes(label)||!Array.isArray(region)||region.length!==4|| + !region.every(value=>Number.isFinite(value)&&value>=0&&value<=1)|| + region[2]<=region[0]||region[3]<=region[1])) throw new Error('board_comparison_region_invalid'); + await snapshot(current,'loaded-isp.json'); + await snapshot(current,'restored-isp.json'); + const {settings}=view.comparison; + const target=region?.map((value,index)=>value*(index%2?settings.height:settings.width)); + const area=([left,top,right,bottom])=>Math.max(0,right-left)*Math.max(0,bottom-top); + const numberSet=new Set(current.detections.map(frame=>frame.file)); + const results={}; + for(const phase of ['before','after']) { + const sample=view.comparison[phase]; + const frames=current.frames.filter(row=>row?.phase===phase&&row.modelSha256===normalizedHash&&row.tuningHash===sample.tuningHash&&numberSet.has(row.file)); + const times=frames.map(row=>BigInt(row.sdkTimestampNs)); + if(frames.length!==view.phases[phase]?.frames||times.some((time,i)=>i>0&&time<=times[i-1])|| + phase==='after'&×[0]<=BigInt(view.comparison.before.sdkTimestampNs)|| + new Set(frames.map(row=>row.file)).size!==frames.length|| + frames.some(row=>row.detections.some(({box})=>!Array.isArray(box)||box.length!==4||!box.every(Number.isFinite)|| + box[0]>=box[2]||box[1]>=box[3]))) throw new Error('board_comparison_unavailable'); + await file(normalizedHash,sample.file,receiptSha256); + let matchedFrames=0,unmatchedBoxes=0,bestScore=null,consecutive=0,longestMatch=0; + for(const {detections} of frames) { + const matched=detections.filter(({class:detected,box})=>{ + if(!target||detected!==label) return false; + const [left,top,right,bottom]=box.map((value,index)=>Math.max(0,Math.min(index%2?settings.height:settings.width,value))); + const overlap=area([Math.max(left,target[0]),Math.max(top,target[1]),Math.min(right,target[2]),Math.min(bottom,target[3])]); + return overlap>0&&overlap/(area(target)+area([left,top,right,bottom])-overlap)>=comparisonOverlap; + }); + if(matched.length) { + matchedFrames++; + longestMatch=Math.max(longestMatch,++consecutive); + bestScore=Math.max(bestScore??0,...matched.map(item=>item.score)); + } else consecutive=0; + unmatchedBoxes+=detections.length-matched.length; + } + results[phase]={frames:frames.length,matchedFrames,longestMatch,unmatchedBoxes,bestScore,tuningHash:sample.tuningHash,sample}; + } + return {schema:'rdk.vision-course-comparison.v1',runId:view.runId,modelSha256:view.modelSha256,receiptSha256, + settings,targetAbsent,region,label,...(targetAbsent?{}:{iouThreshold:comparisonOverlap}), + restoration:view.restoration,previewStopped:view.previewStopped,results}; + } + return {get,file,preview,score}; } diff --git a/plugins/rdk-camera-workshop/mcp/course-server.mjs b/plugins/rdk-camera-workshop/mcp/course-server.mjs deleted file mode 100644 index 004e791..0000000 --- a/plugins/rdk-camera-workshop/mcp/course-server.mjs +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env node -// Read-only course planner: no network, process execution, hardware or writes. -import { isEntrypoint } from './entrypoint.mjs'; -import { readFileSync } from 'node:fs'; -import { createInterface } from 'node:readline'; -const plan = JSON.parse(readFileSync(new URL('../skills/rdk-vision-workshop/assets/course-plan.json', import.meta.url), 'utf8')); -plan.guideMarkdown = readFileSync(new URL('../skills/rdk-vision-workshop/references/course-runbook.md', import.meta.url), 'utf8'); -plan.tuningHandoffMarkdown = readFileSync(new URL('../skills/rdk-vision-workshop/references/tuning-handoff.md', import.meta.url), 'utf8'); -const {version}=JSON.parse(readFileSync(new URL('../plugin.json',import.meta.url),'utf8')); -const tools = [ - { name:'vision_course_plan', description:'读取180分钟视觉Workshop时间、阶段与证据清单。只读课程资料,不探测设备或宣称执行通过。', inputSchema:{type:'object',properties:{},additionalProperties:false},annotations:{readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}}, - { name:'vision_course_stage', description:'读取指定课程阶段的方法、时间预算与退出证据;不操作相机/GPU/BPU。',inputSchema:{type:'object',properties:{stageId:{type:'string',enum:plan.schedule.map(s=>s.id)}},required:['stageId'],additionalProperties:false},annotations:{readOnlyHint:true,destructiveHint:false,idempotentHint:true,openWorldHint:false}} -]; -const result = data => ({content:[{type:'text',text:JSON.stringify(data)}],isError:false}); -function args(value, keys) { - if(!value || typeof value!=='object'||Array.isArray(value)||Object.keys(value).some(k=>!keys.includes(k)))throw new Error('invalid_arguments'); - return value; -} -export function dispatch(req){ - if(!req || req.jsonrpc!=='2.0'||typeof req.method!=='string')return {jsonrpc:'2.0',id:req?.id??null,error:{code:-32600,message:'Invalid request'}}; - if(req.id===undefined)return null; - try{ - let out; - if(req.method==='initialize')out={protocolVersion:'2024-11-05',capabilities:{tools:{listChanged:false}},serverInfo:{name:'rdk-vision-workshop',version}}; - else if(req.method==='ping')out={}; - else if(req.method==='tools/list')out={tools}; - else if(req.method==='tools/call'){ - const a=args(req.params?.arguments??{},req.params?.name==='vision_course_stage'?['stageId']:[]); - if(req.params?.name==='vision_course_plan')out=result(plan); - else if(req.params?.name==='vision_course_stage'){ - const stage=plan.schedule.find(s=>s.id===a.stageId);if(!stage)throw new Error('unknown_stage'); - out=result({schema:plan.schema,executionStatus:'planning_only',stage,limitations:plan.limitations}); - }else throw new Error('unknown_tool'); - }else return {jsonrpc:'2.0',id:req.id,error:{code:-32601,message:'Method not found'}}; - return {jsonrpc:'2.0',id:req.id,result:out}; - }catch(e){return {jsonrpc:'2.0',id:req.id,result:{content:[{type:'text',text:JSON.stringify({error:e.message,executionStatus:'not_executed'})}],isError:true}};} -} -if(isEntrypoint(import.meta)){ - const rl=createInterface({input:process.stdin,crlfDelay:Infinity}); - rl.on('line',line=>{let out;try{out=dispatch(JSON.parse(line))}catch{out={jsonrpc:'2.0',id:null,error:{code:-32700,message:'Parse error'}}}if(out)process.stdout.write(JSON.stringify(out)+'\n')}); -} diff --git a/plugins/rdk-camera-workshop/mcp/course-server.test.mjs b/plugins/rdk-camera-workshop/mcp/course-server.test.mjs deleted file mode 100644 index 08ca309..0000000 --- a/plugins/rdk-camera-workshop/mcp/course-server.test.mjs +++ /dev/null @@ -1,24 +0,0 @@ -import test from 'node:test'; -import { fileURLToPath } from 'node:url'; -import assert from 'node:assert/strict'; -import { spawn } from 'node:child_process'; -import { dispatch } from './course-server.mjs'; -let id=0; -const rpc=(name,a={})=>dispatch({jsonrpc:'2.0',id:++id,method:'tools/call',params:{name,arguments:a}}); -test('course is contiguous 180 minutes with break included and no execution claim',()=>{ - const p=JSON.parse(rpc('vision_course_plan').result.content[0].text); - assert.equal(p.executionStatus,'planning_only');assert.equal(p.schedule[0].start,0);assert.equal(p.schedule.at(-1).end,180); - assert.equal(p.schedule.reduce((n,s)=>n+s.minutes,0),180); - p.schedule.forEach((s,i)=>{if(i)assert.equal(s.start,p.schedule[i-1].end);assert.ok(s.end>s.start)}); - assert.equal(p.breakPolicy.endMinute-p.breakPolicy.startMinute,10); -}); -test('reject unrecognized stage, extra fields and supplied success flags',()=>{ - for(const [name,a] of [['vision_course_stage',{stageId:'unknown'}],['vision_course_plan',{passed:true}],['vision_course_stage',{stageId:'live',executionStatus:'passed'}],['vision_course_stage',[]]])assert.equal(rpc(name,a).result.isError,true); - const s=JSON.parse(rpc('vision_course_stage',{stageId:'deploy'}).result.content[0].text);assert.equal(s.stage.start,130);assert.equal(s.executionStatus,'planning_only'); -}); -test('real stdio start from a directory with spaces, list/call and notification',async()=>{ - const c=spawn(process.execPath,[fileURLToPath(new URL('./course-server.mjs',import.meta.url))],{stdio:['pipe','pipe','pipe']}); - let out='',err='';c.stdout.on('data',x=>out+=x);c.stderr.on('data',x=>err+=x); - c.stdin.end([{jsonrpc:'2.0',id:1,method:'initialize',params:{}},{jsonrpc:'2.0',method:'notifications/initialized'},{jsonrpc:'2.0',id:2,method:'tools/list'},{jsonrpc:'2.0',id:3,method:'tools/call',params:{name:'vision_course_plan',arguments:{}}}].map(JSON.stringify).join('\n')+'\n'); - const code=await new Promise(resolve=>c.on('close',resolve));assert.equal(code,0,err);const rows=out.trim().split('\n').map(JSON.parse);assert.equal(rows.length,3);assert.equal(rows[1].result.tools.length,2);assert.equal(JSON.parse(rows[2].result.content[0].text).totalMinutes,180); -}); diff --git a/plugins/rdk-camera-workshop/mcp/entrypoint.mjs b/plugins/rdk-camera-workshop/mcp/entrypoint.mjs deleted file mode 100644 index 79e6374..0000000 --- a/plugins/rdk-camera-workshop/mcp/entrypoint.mjs +++ /dev/null @@ -1,14 +0,0 @@ -import { realpathSync } from 'node:fs'; -import { relative } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -export function isEntrypoint(meta) { - if (typeof meta.main === 'boolean') return meta.main; - if (!process.argv[1]) return false; - try { - const resolved = name => realpathSync.native(name); - return relative(resolved(process.argv[1]), resolved(fileURLToPath(meta.url))) === ''; - } catch { - return false; - } -} diff --git a/plugins/rdk-camera-workshop/mcp/guide.mjs b/plugins/rdk-camera-workshop/mcp/guide.mjs index 5855895..7c7d718 100644 --- a/plugins/rdk-camera-workshop/mcp/guide.mjs +++ b/plugins/rdk-camera-workshop/mcp/guide.mjs @@ -6,6 +6,7 @@ const issues = { vision_device_transport_failed: { stageId:'connect', message:'X5 未连通。请上电并接上可传数据的 Type-C,或提供可达的局域网地址。', userAction:'接回 X5,或提供板卡的局域网地址。' }, dataset_unconfirmed: { stageId:'data', message:'需要确定数据集版本和划分。', userAction:'选择课堂数据集,或提供本组标注的目录。' }, training_image_unavailable: { stageId:'train', message:'RoboGO 训练镜像不可选。让助教检查兑换码、项目和镜像权限,并在提交截止时分流。' }, + devmachine_unavailable: { stageId:'train', message:'本组开发机入口、权限或数据尚未就绪。保留阻塞记录,先做相机和 ISP,到点按产物分流。' }, training_run_failed: { stageId:'train', message:'原 Run 已失败。保留失败日志,按当前时间和已有产物分流。' }, ptq_image_unavailable: { stageId:'quantize', message:'量化镜像不可选。让助教检查 X5 工具链或课程预跑产物。' }, course_runner_unavailable: { stageId:'deploy', message:'当前 runner 无法加载课程模型。需要匹配三类标签和输出头的 X5 运行入口。' }, @@ -29,6 +30,12 @@ export function presetModelHash(reference) { const validReference = v => typeof v==='string' && v.trim().length>0 && v.length<=300 && !/[\u0000-\u001f\u007f]/u.test(v); const isObject = v => v!==null && typeof v==='object' && !Array.isArray(v); const minuteValid = n => Number.isInteger(n) && n>=0 && n<=180; +export function classroomClock(plan, offset, startOverride) { + const base=typeof startOverride==='string'&&/^\d{1,2}:\d{2}$/.test(startOverride)?startOverride:plan.referenceStart; + const [hour,minute]=base.split(':').map(Number); + const total=(hour*60+minute+offset)%1440; + return String(Math.floor(total/60)).padStart(2,'0')+':'+String(total%60).padStart(2,'0'); +} const runStates = ['submitted','queued','running','completed','artifact_ready','failed']; const inferenceResults=['运行成功','运行失败']; const targetResults=['检出','未检出','未验证']; @@ -38,13 +45,13 @@ export const detectionResults = { inference_result:inferenceResults, target_resu export const guideSchema = { type:'object', properties:{ - evidence:{ type:'object', description:'本工位实际回执引用。已核对的工具回执、Run ID、文件路径或哈希可以作为引用。', + evidence:{ type:'object', description:'本组实际回执引用。已核对的工具回执、Run ID、文件路径或哈希可以作为引用。', properties:Object.fromEntries(Object.keys(labels).map(k=>[k,detectionResults[k]?{type:'string',enum:detectionResults[k]}:evidenceKey])), additionalProperties:false }, blockers:{ type:'object', description:'仍存在的问题及诊断回执。', properties:Object.fromEntries(Object.keys(issues).map(k=>[k,evidenceKey])), additionalProperties:false }, elapsedMinutes:{ type:'integer', minimum:0, maximum:180, description:'实际开场后经过的分钟。彩排可传明确的彩排时钟。' }, camera:{anyOf:[{type:'null'},{type:'object',properties:{experimentId:{type:'string',pattern:cameraIdPattern},runId:{type:'string',pattern:cameraIdPattern}},required:['experimentId'],additionalProperties:false}], description:'与 Camera Workshop 的实际实验和可选 AI Run 绑定。null 解除绑定。'}, - path:{ type:'string', enum:['A','B','C'], description:'本工位已明确选择的完成路径。' }, + path:{ type:'string', enum:['A','B','C'], description:'本组已明确选择的完成路径。' }, run:{ type:'object', description:'RoboGO 已有 Run 的只读状态回执。', properties:{ id:evidenceKey, state:{ type:'string', enum:runStates }, receipt:evidenceKey, name:{type:'string',pattern:'^[a-z0-9](?:[a-z0-9-]{0,118}[a-z0-9])?$',description:'RoboGO 任务名,用于查询并核对原 Run ID。'}, @@ -68,6 +75,25 @@ function task(id, fields=steps[id].fields) { requiredEvidence:fields.map(key=>({key,label:labels[key]})) }; } +export function classroomStep(plan,id,startOverride) { + const cutoff=classroomClock(plan,plan.deadlines.deployAt,startOverride); + const blindStart=classroomClock(plan,plan.breakPolicy.endMinute,startOverride); + const baseOverrides={ + break:{ask:'茶歇期间,助教只查看原 Run,更新状态并给预计超时的实验准备预置产物。'+blindStart+' 开始个人盲选。'}, + await_route:{title:'核对部署准备,等待 '+cutoff+' 分流',ask:'检查模型来源和设备状态,先登记需要的预置模型或演示。'+cutoff+' 开放 A/B/C 选择。'}, + }; + if(plan.training.workflow!=='devmachine') return {...steps[id],...baseOverrides[id]}; + const overrides={ + data:{title:'核对本组开发机与课程数据',ask:'打开开发机连接卡,核对 GPU、数据版本、三类顺序及训练验证划分。'}, + train:{title:'启动一次本组开发机训练',ask:'到点按本组连接卡启动。记下原任务 ID、启动回执和日志位置,回 Studio 继续 ISP。'}, + check_run:{title:'核对本组原训练任务',ask:'查看本组任务的原日志和预计完成时间。更新已有记录,再继续相机步骤。'}, + quantize:{title:'核对本组 ONNX 和 X5 INT8 产物',ask:'从本组连接卡的产物位置取同一次任务的 ONNX、PTQ 回执和 INT8 BIN,核对 SHA-256。'}, + break:{ask:'茶歇期间助教核对各组原任务,并为超时实验准备预置产物。'+blindStart+' 开始个人盲选。'}, + await_route:{title:'核对部署准备,等待 '+cutoff+' 分流',ask:'先核对模型来源和本组相机。'+cutoff+' 开放 A/B/C 选择。'}, + }; + return {...steps[id],...overrides[id]}; +} + export function guideCourse(plan, args={}) { if (!isObject(args) || Object.keys(args).some(k=>!Object.hasOwn(guideSchema.properties,k))) throw new Error('invalid_arguments'); const evidence=references(Object.hasOwn(args,'evidence')?args.evidence:{}, labels); @@ -92,6 +118,9 @@ export function guideCourse(plan, args={}) { evidence.run_id=run.id; } const { submitStart, submitBy, runCheckpoint, deployAt, deliverAt }=plan.deadlines; + const direct=plan.training.workflow==='devmachine'; + const blindStart=classroomClock(plan,plan.breakPolicy.endMinute); + const trainingBlocked=direct?blockers.devmachine_unavailable:blockers.training_image_unavailable; const missing=id=>steps[id].fields.filter(k=>(!evidence[k]|| ['target_result','preset_target_result'].includes(k)&&evidence[k]==='未验证'|| ['inference_result','preset_inference_result'].includes(k)&&evidence[k]==='运行失败')&& @@ -115,20 +144,21 @@ export function guideCourse(plan, args={}) { const boardBlocked=Boolean(blockers.vision_device_transport_failed); const depBlocked=boardBlocked||Boolean(blockers.course_runner_unavailable); const boardReady=done('connect') && !depBlocked; - const passedSubmit=minute!==undefined && minute>=submitBy && !evidence.run_id; + const trained=direct?Boolean(run):Boolean(evidence.run_id); + const passedSubmit=minute!==undefined && minute>=submitBy && !trained; const atDeployment=minute!==undefined && minute>=deployAt; const isBreak=minute!==undefined && minute>=plan.breakPolicy.startMinute && minute=runCheckpoint && run?.etaMinute>deployAt && !ownReady; - const timeToChoose=atDeployment||(minute===undefined&&(missedRun||done('reproduce'))); + const timeToChoose=atDeployment||(!direct&&minute===undefined&&(missedRun||done('reproduce'))); const choices=paths.map(p=>{ - if (p.id==='A') return {...p, available:ownReady&&!depBlocked, reason:!cloudModelReady?'请刷新原 Run,核对平台返回的 X5 INT8 SHA-256 与本组模型一致。':!ownReady?'需要本人训练、验证、ONNX 与 INT8 回执。':depBlocked?'本工位设备或执行入口待恢复。':'本人产物已记录,可以走本人板端验证。'}; - if (p.id==='B') return {...p, available:Boolean(presetModelHash(evidence.preset_model))&&!depBlocked, reason:!presetModelHash(evidence.preset_model)?'请输入预置模型来源及 SHA-256。':depBlocked?'本工位暂时不能运行模型。':'预置产物已记录。'}; + if(direct&&p.id!=='C'&&!boardReady) return {...p,available:false,reason:'请先核对本组相机新帧、板卡连接和原始 ISP 快照。'}; + if (p.id==='A') return {...p, available:ownReady&&!depBlocked, reason:!cloudModelReady?'请刷新原 Run,核对平台返回的 X5 INT8 SHA-256 与本组模型一致。':!ownReady?'需要本人训练、验证、ONNX 与 INT8 回执。':depBlocked?'本组设备或执行入口待恢复。':'本人产物已记录,可以走本人板端验证。'}; + if (p.id==='B') return {...p, available:Boolean(presetModelHash(evidence.preset_model))&&!depBlocked, reason:!presetModelHash(evidence.preset_model)?'请输入预置模型来源及 SHA-256。':depBlocked?'本组暂时不能运行模型。':'预置产物已记录。'}; return {...p, available:true, reason:evidence.demo_reference?'已有演示来源。':'选择后补充讲师演示或录像来源。'}; }); const recommended=choices.find(p=>p.available).id; const actualPath=choices.find(p=>p.id===path); - const trained=Boolean(evidence.run_id); const checkpointDue=minute!==undefined&&minute>=runCheckpoint&&!atDeployment; const needsPreflight=checkpointDue&&!ownReady; const checkedThisCheckpoint=run?.checkedAtMinute>=runCheckpoint; @@ -138,9 +168,14 @@ export function guideCourse(plan, args={}) { preflight:needsPreflight?(likelyLate||missedRun?'prepare_backup':checkedThisCheckpoint?'checked':'due'):null, submitStart, submitBy, checkpointAt:runCheckpoint, deployAt, instruction:trained - ? ownReady?'本人模型可用于板端验证。':isBreak||atDeployment?'查询原 Run 和预计完成时间。按课堂时间分流。':'Run 已记录,继续相机步骤。' - : passedSubmit?'提交窗口已结束,准备预置产物或讲师演示。':'先存基线图,按助教的组序在提交窗口提交一次,保留 Run ID。' }; - const create=id=>task(id,missing(id)); + ? ownReady?'本组模型可用于板端验证。':isBreak||atDeployment?'核对原任务和预计完成时间。按课堂时间分流。':'原任务已登记,继续相机步骤。' + : passedSubmit?'训练启动窗口已结束,准备预置产物或讲师演示。':direct? + '按本组连接卡核对 GPU、课程数据和启动命令。只启动一次,登记原任务 ID 和首行日志。': + '先存基线图,按助教的组序在提交窗口提交一次,保留 Run ID。' }; + const create=(id,fields=missing(id))=>{ + const {title,ask}=classroomStep(plan,id); + return {...task(id,fields),title,instruction:ask}; + }; const reportIssue=code=>({ ...task(issues[code].stageId,[]),kind:'resolve_blocker',instruction:issues[code].message }); const restoreDone=done('restore') || (path==='C' && !evidence.original_snapshot && Boolean(evidence.device_unused)); const pendingCamera=mainCamera.find(id=>!done(id)); @@ -162,7 +197,7 @@ export function guideCourse(plan, args={}) { else if (!restoreDone) nextStep=create('restore'); else if (!done('deliver')) nextStep=create('deliver'); } else if (atDeployment) nextStep={...task('route',[]),kind:'select_path'}; - else if (!trained && !missedRun && !blockers.training_image_unavailable && (minute!==undefined&&minute>=submitStart || minute===undefined&&(done('baseline')||boardBlocked))) { + else if (!trained && !missedRun && !trainingBlocked && (minute!==undefined&&minute>=submitStart || minute===undefined&&(done('baseline')||boardBlocked))) { nextStep=blockers.dataset_unconfirmed?reportIssue('dataset_unconfirmed'):create(done('data')?'train':'data'); } else if (isBreak) { nextStep=create('break'); @@ -170,13 +205,13 @@ export function guideCourse(plan, args={}) { nextStep={...task('route',[]),kind:'select_path'}; } else if (boardBlocked) nextStep=reportIssue('vision_device_transport_failed'); else if (pendingCamera==='blind'&&minute!==undefined&&minuteissues[code].userAction?[{code,instruction:issues[code].userAction}]:[]), evidenceToRecheck:[...recheck], stages:progress, diff --git a/plugins/rdk-camera-workshop/mcp/isp-codec.mjs b/plugins/rdk-camera-workshop/mcp/isp-codec.mjs new file mode 100644 index 0000000..5ff1699 --- /dev/null +++ b/plugins/rdk-camera-workshop/mcp/isp-codec.mjs @@ -0,0 +1,910 @@ +/** + * Zero-dependency pure-JS PNG & Baseline JPEG (SOF0) codec + Gamma LUT + + * vertical before/after comparison composer for portable Vision Workshop MCP. + * Runs in Node >= 22 / Electron without native addons or external packages. + */ +import { deflateSync, inflateSync } from 'node:zlib'; + +// ── Shared helpers ────────────────────────────────────────────────────────── + +const clampByte = (v) => (v <= 0 ? 0 : v >= 255 ? 255 : (v + 0.5) | 0); + +const CRC_TABLE = (() => { + const table = new Uint32Array(256); + for (let n = 0; n < 256; n += 1) { + let c = n; + for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + table[n] = c >>> 0; + } + return table; +})(); + +function crc32(buf) { + let c = 0xffffffff; + for (let i = 0; i < buf.length; i += 1) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} + +// ── PNG Decode / Encode ───────────────────────────────────────────────────── + +const PNG_SIG = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); + +function paeth(a, b, c) { + const p = a + b - c; + const pa = Math.abs(p - a); + const pb = Math.abs(p - b); + const pc = Math.abs(p - c); + return pa <= pb && pa <= pc ? a : pb <= pc ? b : c; +} + +export function decodePng(buf) { + const bytes = Buffer.isBuffer(buf) ? buf : Buffer.from(buf); + if (bytes.length < 33 || !bytes.subarray(0, 8).equals(PNG_SIG)) { + throw new Error('isp_codec_invalid_png'); + } + let width = 0; + let height = 0; + let bitDepth = 0; + let colorType = 0; + const idatChunks = []; + let offset = 8; + while (offset + 12 <= bytes.length) { + const length = bytes.readUInt32BE(offset); + const type = bytes.toString('ascii', offset + 4, offset + 8); + const dataStart = offset + 8; + const dataEnd = dataStart + length; + if (dataEnd + 4 > bytes.length) throw new Error('isp_codec_truncated_png'); + if (type === 'IHDR') { + width = bytes.readUInt32BE(dataStart); + height = bytes.readUInt32BE(dataStart + 4); + bitDepth = bytes[dataStart + 8]; + colorType = bytes[dataStart + 9]; + if (bitDepth !== 8 || (colorType !== 2 && colorType !== 6) || bytes[dataStart + 12] !== 0) { + throw new Error('isp_codec_unsupported_png'); + } + } else if (type === 'IDAT') { + idatChunks.push(bytes.subarray(dataStart, dataEnd)); + } else if (type === 'IEND') { + break; + } + offset = dataEnd + 4; + } + if (!width || !height || !idatChunks.length) throw new Error('isp_codec_invalid_png'); + const bpp = colorType === 6 ? 4 : 3; + const stride = width * bpp; + const raw = inflateSync(Buffer.concat(idatChunks)); + if (raw.length < height * (stride + 1)) throw new Error('isp_codec_truncated_png'); + + const prev = new Uint8Array(stride); + const curr = new Uint8Array(stride); + const rgb = new Uint8Array(width * height * 3); + let src = 0; + let dst = 0; + + for (let y = 0; y < height; y += 1) { + const filter = raw[src++]; + for (let x = 0; x < stride; x += 1) { + const byte = raw[src++]; + const a = x >= bpp ? curr[x - bpp] : 0; + const b = prev[x]; + const c = x >= bpp ? prev[x - bpp] : 0; + let val = byte; + if (filter === 1) val = (byte + a) & 0xff; + else if (filter === 2) val = (byte + b) & 0xff; + else if (filter === 3) val = (byte + ((a + b) >>> 1)) & 0xff; + else if (filter === 4) val = (byte + paeth(a, b, c)) & 0xff; + else if (filter !== 0) throw new Error('isp_codec_invalid_png_filter'); + curr[x] = val; + } + if (bpp === 3) { + rgb.set(curr, dst); + dst += stride; + } else { + for (let x = 0; x < stride; x += 4) { + rgb[dst++] = curr[x]; + rgb[dst++] = curr[x + 1]; + rgb[dst++] = curr[x + 2]; + } + } + prev.set(curr); + } + return { width, height, data: rgb }; +} + +function pngChunk(type, data) { + const out = Buffer.allocUnsafe(12 + data.length); + out.writeUInt32BE(data.length, 0); + out.write(type, 4, 4, 'ascii'); + data.copy(out, 8); + out.writeUInt32BE(crc32(out.subarray(4, 8 + data.length)), 8 + data.length); + return out; +} + +export function encodePng(width, height, rgb) { + const stride = width * 3; + const raw = Buffer.allocUnsafe(height * (stride + 1)); + let pos = 0; + for (let y = 0; y < height; y += 1) { + const rowStart = y * stride; + raw[pos++] = 1; // Sub filter for fast, compact encoding + for (let x = 0; x < stride; x += 1) { + const left = x >= 3 ? rgb[rowStart + x - 3] : 0; + raw[pos++] = (rgb[rowStart + x] - left) & 0xff; + } + } + const ihdr = Buffer.allocUnsafe(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; // bit depth + ihdr[9] = 2; // RGB + ihdr[10] = 0; + ihdr[11] = 0; + ihdr[12] = 0; + const idat = deflateSync(raw, { level: 6 }); + return Buffer.concat([PNG_SIG, pngChunk('IHDR', ihdr), pngChunk('IDAT', idat), pngChunk('IEND', Buffer.alloc(0))]); +} + +// ── Baseline JPEG (SOF0) Decode / Encode ──────────────────────────────────── + +const ZIGZAG = new Uint8Array([ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, +]); + +// Precomputed 8x8 separable DCT / IDCT basis matrices +const DCT_C = new Float64Array(64); +const IDCT_C = new Float64Array(64); +for (let u = 0; u < 8; u += 1) { + const alpha = u === 0 ? Math.SQRT1_2 : 1; + for (let x = 0; x < 8; x += 1) { + const val = 0.5 * alpha * Math.cos(((2 * x + 1) * u * Math.PI) / 16); + DCT_C[u * 8 + x] = val; + IDCT_C[x * 8 + u] = val; + } +} + +function idct8x8(coeff, out) { + const tmp = new Float64Array(64); + for (let r = 0; r < 8; r += 1) { + const row = r * 8; + for (let x = 0; x < 8; x += 1) { + const cRow = x * 8; + let sum = 0; + for (let u = 0; u < 8; u += 1) sum += coeff[row + u] * IDCT_C[cRow + u]; + tmp[row + x] = sum; + } + } + for (let x = 0; x < 8; x += 1) { + for (let y = 0; y < 8; y += 1) { + const cRow = y * 8; + let sum = 0; + for (let v = 0; v < 8; v += 1) sum += tmp[v * 8 + x] * IDCT_C[cRow + v]; + out[y * 8 + x] = clampByte(sum + 128); + } + } +} + +function fdct8x8(pixels, out) { + const tmp = new Float64Array(64); + for (let y = 0; y < 8; y += 1) { + const row = y * 8; + for (let u = 0; u < 8; u += 1) { + const cRow = u * 8; + let sum = 0; + for (let x = 0; x < 8; x += 1) sum += pixels[row + x] * DCT_C[cRow + x]; + tmp[row + u] = sum; + } + } + for (let u = 0; u < 8; u += 1) { + for (let v = 0; v < 8; v += 1) { + const cRow = v * 8; + let sum = 0; + for (let y = 0; y < 8; y += 1) sum += tmp[y * 8 + u] * DCT_C[cRow + y]; + out[v * 8 + u] = sum; + } + } +} + +function buildDecodeHuffTable(counts, symbols) { + const maxCode = new Int32Array(17); + const valOffset = new Int32Array(17); + let code = 0; + let k = 0; + for (let len = 1; len <= 16; len += 1) { + if (counts[len] === 0) { + maxCode[len] = -1; + } else { + valOffset[len] = k - code; + code += counts[len]; + maxCode[len] = code - 1; + k += counts[len]; + } + code <<= 1; + } + return { maxCode, valOffset, symbols }; +} + +export function decodeJpeg(buf) { + const bytes = Buffer.isBuffer(buf) ? buf : Buffer.from(buf); + if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) { + throw new Error('isp_codec_invalid_jpeg'); + } + const quantTables = new Array(4); + const dcTables = new Array(4); + const acTables = new Array(4); + let width = 0; + let height = 0; + let components = []; + let maxH = 1; + let maxV = 1; + let restartInterval = 0; + let pos = 2; + + while (pos < bytes.length) { + if (bytes[pos] !== 0xff) throw new Error('isp_codec_invalid_jpeg_marker'); + while (pos < bytes.length && bytes[pos] === 0xff) pos += 1; + if (pos >= bytes.length) break; + const marker = bytes[pos++]; + if (marker === 0xd9) break; + if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue; + const len = (bytes[pos] << 8) | bytes[pos + 1]; + const segEnd = pos + len; + if (segEnd > bytes.length) throw new Error('isp_codec_truncated_jpeg'); + + if (marker === 0xdb) { + let p = pos + 2; + while (p < segEnd) { + const pqTq = bytes[p++]; + const pq = pqTq >> 4; + const tq = pqTq & 0x0f; + const qt = new Int32Array(64); + for (let i = 0; i < 64; i += 1) { + qt[ZIGZAG[i]] = pq === 0 ? bytes[p++] : (bytes[p++] << 8) | bytes[p++]; + } + quantTables[tq] = qt; + } + } else if (marker === 0xc4) { + let p = pos + 2; + while (p < segEnd) { + const tcTh = bytes[p++]; + const tc = tcTh >> 4; + const th = tcTh & 0x0f; + const counts = new Uint8Array(17); + let total = 0; + for (let i = 1; i <= 16; i += 1) { + counts[i] = bytes[p++]; + total += counts[i]; + } + const symbols = bytes.subarray(p, p + total); + p += total; + const table = buildDecodeHuffTable(counts, symbols); + if (tc === 0) dcTables[th] = table; + else acTables[th] = table; + } + } else if (marker === 0xdd) { + restartInterval = (bytes[pos + 2] << 8) | bytes[pos + 3]; + } else if (marker === 0xc0) { + const precision = bytes[pos + 2]; + if (precision !== 8) throw new Error('isp_codec_unsupported_jpeg_precision'); + height = (bytes[pos + 3] << 8) | bytes[pos + 4]; + width = (bytes[pos + 5] << 8) | bytes[pos + 6]; + const nf = bytes[pos + 7]; + components = []; + maxH = 1; + maxV = 1; + for (let i = 0; i < nf; i += 1) { + const id = bytes[pos + 8 + i * 3]; + const hv = bytes[pos + 9 + i * 3]; + const h = hv >> 4; + const v = hv & 0x0f; + const qId = bytes[pos + 10 + i * 3]; + if (h > maxH) maxH = h; + if (v > maxV) maxV = v; + components.push({ id, h, v, qId, dcId: 0, acId: 0, dcPred: 0 }); + } + } else if (marker === 0xc2) { + throw new Error('isp_codec_progressive_jpeg_unsupported'); + } else if (marker === 0xda) { + const ns = bytes[pos + 2]; + const scanComps = []; + for (let i = 0; i < ns; i += 1) { + const cid = bytes[pos + 3 + i * 2]; + const tdTa = bytes[pos + 4 + i * 2]; + const comp = components.find((c) => c.id === cid); + if (!comp) throw new Error('isp_codec_unknown_component'); + comp.dcId = tdTa >> 4; + comp.acId = tdTa & 0x0f; + scanComps.push(comp); + } + pos = segEnd; + // Entropy decode MCUs + const mcuW = maxH * 8; + const mcuH = maxV * 8; + const mcusX = Math.ceil(width / mcuW); + const mcusY = Math.ceil(height / mcuH); + for (const comp of scanComps) { + comp.planeW = mcusX * comp.h * 8; + comp.planeH = mcusY * comp.v * 8; + comp.plane = new Uint8Array(comp.planeW * comp.planeH); + } + + let bitBuf = 0; + let bitCnt = 0; + const readBit = () => { + if (bitCnt === 0) { + if (pos >= bytes.length) return 0; + let b = bytes[pos++]; + if (b === 0xff) { + const next = bytes[pos++]; + if (next !== 0x00) { + // Marker encountered inside stream; rewind so outer loop or restart handles it + pos -= 2; + b = 0; + } + } + bitBuf = b; + bitCnt = 8; + } + bitCnt -= 1; + return (bitBuf >> bitCnt) & 1; + }; + const readBits = (n) => { + let v = 0; + for (let i = 0; i < n; i += 1) v = (v << 1) | readBit(); + return v; + }; + const extend = (v, n) => (n === 0 ? 0 : v < 1 << (n - 1) ? v - ((1 << n) - 1) : v); + const decodeHuff = (table) => { + let code = 0; + for (let len = 1; len <= 16; len += 1) { + code = (code << 1) | readBit(); + if (code <= table.maxCode[len]) return table.symbols[code + table.valOffset[len]]; + } + throw new Error('isp_codec_huffman_error'); + }; + + const coeff = new Float64Array(64); + const block = new Uint8Array(64); + let mcuDone = 0; + + for (let my = 0; my < mcusY; my += 1) { + for (let mx = 0; mx < mcusX; mx += 1) { + if (restartInterval > 0 && mcuDone > 0 && mcuDone % restartInterval === 0) { + bitBuf = 0; + bitCnt = 0; + if (bytes[pos] === 0xff && bytes[pos + 1] >= 0xd0 && bytes[pos + 1] <= 0xd7) pos += 2; + for (const comp of scanComps) comp.dcPred = 0; + } + for (const comp of scanComps) { + const qt = quantTables[comp.qId]; + const dcT = dcTables[comp.dcId]; + const acT = acTables[comp.acId]; + for (let bv = 0; bv < comp.v; bv += 1) { + for (let bh = 0; bh < comp.h; bh += 1) { + coeff.fill(0); + const dcSize = decodeHuff(dcT); + comp.dcPred += extend(readBits(dcSize), dcSize); + coeff[0] = comp.dcPred * qt[0]; + for (let k = 1; k < 64; ) { + const rs = decodeHuff(acT); + if (rs === 0x00) break; + const run = rs >> 4; + const size = rs & 0x0f; + if (size === 0) { + if (run === 15) k += 16; + else break; + } else { + k += run; + if (k >= 64) break; + const idx = ZIGZAG[k]; + coeff[idx] = extend(readBits(size), size) * qt[idx]; + k += 1; + } + } + idct8x8(coeff, block); + const px0 = (mx * comp.h + bh) * 8; + const py0 = (my * comp.v + bv) * 8; + for (let y = 0; y < 8; y += 1) { + const dstRow = (py0 + y) * comp.planeW + px0; + const srcRow = y * 8; + for (let x = 0; x < 8; x += 1) comp.plane[dstRow + x] = block[srcRow + x]; + } + } + } + } + mcuDone += 1; + } + } + break; + } + pos = segEnd; + } + + if (!width || !height || !components.length) throw new Error('isp_codec_invalid_jpeg'); + const rgb = new Uint8Array(width * height * 3); + if (components.length === 1) { + const c0 = components[0]; + let dst = 0; + for (let y = 0; y < height; y += 1) { + const row = y * c0.planeW; + for (let x = 0; x < width; x += 1) { + const g = c0.plane[row + x]; + rgb[dst++] = g; + rgb[dst++] = g; + rgb[dst++] = g; + } + } + return { width, height, data: rgb }; + } + + const [cY, cCb, cCr] = components; + const cbSx = maxH / cCb.h; + const cbSy = maxV / cCb.v; + const crSx = maxH / cCr.h; + const crSy = maxV / cCr.v; + let dst = 0; + for (let y = 0; y < height; y += 1) { + const yRow = y * cY.planeW; + const cbRow = ((y / cbSy) | 0) * cCb.planeW; + const crRow = ((y / crSy) | 0) * cCr.planeW; + for (let x = 0; x < width; x += 1) { + const Y = cY.plane[yRow + x]; + const Cb = cCb.plane[cbRow + ((x / cbSx) | 0)] - 128; + const Cr = cCr.plane[crRow + ((x / crSx) | 0)] - 128; + rgb[dst++] = clampByte(Y + 1.402 * Cr); + rgb[dst++] = clampByte(Y - 0.344136 * Cb - 0.714136 * Cr); + rgb[dst++] = clampByte(Y + 1.772 * Cb); + } + } + return { width, height, data: rgb }; +} + +// Standard ISO/IEC 10918-1 Annex K quantization & Huffman tables for Baseline JPEG encoding +const STD_Y_QUANT = [ + 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, + 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, + 18, 22, 37, 56, 68, 109, 103, 77, 24, 35, 55, 64, 81, 104, 113, 92, + 49, 64, 78, 87, 103, 121, 120, 101, 72, 92, 95, 98, 112, 100, 103, 99, +]; +const STD_UV_QUANT = [ + 17, 18, 24, 47, 99, 99, 99, 99, 18, 21, 26, 66, 99, 99, 99, 99, + 24, 26, 56, 99, 99, 99, 99, 99, 47, 66, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, +]; + +const STD_DC_Y_BITS = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]; +const STD_DC_Y_VALS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; +const STD_DC_UV_BITS = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]; +const STD_DC_UV_VALS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; +const STD_AC_Y_BITS = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d]; +const STD_AC_Y_VALS = [ + 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, + 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, + 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, + 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, + 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, + 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, + 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, + 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, + 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, + 0xf9, 0xfa, +]; +const STD_AC_UV_BITS = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77]; +const STD_AC_UV_VALS = [ + 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, + 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, + 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, + 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, + 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, + 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, + 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, + 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, + 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, + 0xf9, 0xfa, +]; + +function buildEncodeHuffTable(bits, vals) { + const codes = new Uint32Array(256); + const sizes = new Uint8Array(256); + let k = 0; + let code = 0; + for (let len = 1; len <= 16; len += 1) { + for (let j = 0; j < bits[len]; j += 1) { + const sym = vals[k++]; + codes[sym] = code++; + sizes[sym] = len; + } + code <<= 1; + } + return { codes, sizes }; +} + +const ENC_DC_Y = buildEncodeHuffTable(STD_DC_Y_BITS, STD_DC_Y_VALS); +const ENC_DC_UV = buildEncodeHuffTable(STD_DC_UV_BITS, STD_DC_UV_VALS); +const ENC_AC_Y = buildEncodeHuffTable(STD_AC_Y_BITS, STD_AC_Y_VALS); +const ENC_AC_UV = buildEncodeHuffTable(STD_AC_UV_BITS, STD_AC_UV_VALS); + +function scaleQuant(base, quality) { + const q = Math.max(1, Math.min(100, quality)); + const scale = q < 50 ? Math.floor(5000 / q) : 200 - q * 2; + const out = new Uint8Array(64); + for (let i = 0; i < 64; i += 1) { + out[i] = Math.max(1, Math.min(255, Math.floor((base[i] * scale + 50) / 100))); + } + return out; +} + +function bitCategory(v) { + let abs = v < 0 ? -v : v; + let cat = 0; + while (abs > 0) { + abs >>= 1; + cat += 1; + } + return cat; +} + +export function encodeJpeg(width, height, rgb, quality = 88) { + const yQ = scaleQuant(STD_Y_QUANT, quality); + const uvQ = scaleQuant(STD_UV_QUANT, quality); + + // Header segments + const header = []; + const pushBytes = (...arr) => { for (const b of arr) header.push(b); }; + const pushWord = (w) => { header.push((w >> 8) & 0xff, w & 0xff); }; + + // SOI + JFIF APP0 + pushBytes(0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00); + + // DQT (tables 0 and 1 in zigzag order) + for (const [id, qt] of [[0, yQ], [1, uvQ]]) { + pushBytes(0xff, 0xdb, 0x00, 0x43, id); + for (let i = 0; i < 64; i += 1) header.push(qt[ZIGZAG[i]]); + } + + // SOF0 (4:2:0 YCbCr) + pushBytes(0xff, 0xc0, 0x00, 0x11, 8); + pushWord(height); + pushWord(width); + pushBytes(3, 1, 0x22, 0, 2, 0x11, 1, 3, 0x11, 1); + + // DHT (DC0, AC0, DC1, AC1) + for (const [id, bits, vals] of [ + [0x00, STD_DC_Y_BITS, STD_DC_Y_VALS], + [0x10, STD_AC_Y_BITS, STD_AC_Y_VALS], + [0x01, STD_DC_UV_BITS, STD_DC_UV_VALS], + [0x11, STD_AC_UV_BITS, STD_AC_UV_VALS], + ]) { + pushBytes(0xff, 0xc4); + pushWord(19 + vals.length); + header.push(id); + for (let i = 1; i <= 16; i += 1) header.push(bits[i]); + for (const v of vals) header.push(v); + } + + // SOS + pushBytes(0xff, 0xda, 0x00, 0x0c, 3, 1, 0x00, 2, 0x11, 3, 0x11, 0x00, 0x3f, 0x00); + + // Entropy-coded scan buffer + let scanCap = Math.max(4096, Math.floor((width * height) / 2)); + let scanBuf = Buffer.allocUnsafe(scanCap); + let scanLen = 0; + const emitByte = (b) => { + if (scanLen + 2 >= scanCap) { + scanCap *= 2; + const next = Buffer.allocUnsafe(scanCap); + scanBuf.copy(next, 0, 0, scanLen); + scanBuf = next; + } + scanBuf[scanLen++] = b; + if (b === 0xff) scanBuf[scanLen++] = 0x00; + }; + + let bitBuf = 0; + let bitCnt = 0; + const writeBits = (val, len) => { + bitBuf = (bitBuf << len) | (val & ((1 << len) - 1)); + bitCnt += len; + while (bitCnt >= 8) { + bitCnt -= 8; + emitByte((bitBuf >> bitCnt) & 0xff); + } + }; + + const fdctOut = new Float64Array(64); + const qBlock = new Int32Array(64); + + const encodeBlock = (pixels, qt, dcT, acT, prevDc) => { + fdct8x8(pixels, fdctOut); + for (let i = 0; i < 64; i += 1) { + const idx = ZIGZAG[i]; + const v = fdctOut[idx] / qt[idx]; + qBlock[i] = v >= 0 ? (v + 0.5) | 0 : (v - 0.5) | 0; + } + const dc = qBlock[0]; + const diff = dc - prevDc; + const cat = bitCategory(diff); + writeBits(dcT.codes[cat], dcT.sizes[cat]); + if (cat > 0) writeBits(diff < 0 ? diff + ((1 << cat) - 1) : diff, cat); + + let lastNonZero = 63; + while (lastNonZero > 0 && qBlock[lastNonZero] === 0) lastNonZero -= 1; + let zeroRun = 0; + for (let i = 1; i <= lastNonZero; i += 1) { + const val = qBlock[i]; + if (val === 0) { + zeroRun += 1; + if (zeroRun === 16) { + writeBits(acT.codes[0xf0], acT.sizes[0xf0]); + zeroRun = 0; + } + } else { + const acCat = bitCategory(val); + const sym = (zeroRun << 4) | acCat; + writeBits(acT.codes[sym], acT.sizes[sym]); + writeBits(val < 0 ? val + ((1 << acCat) - 1) : val, acCat); + zeroRun = 0; + } + } + if (lastNonZero < 63) writeBits(acT.codes[0x00], acT.sizes[0x00]); + return dc; + }; + + const yBlocks = [new Float64Array(64), new Float64Array(64), new Float64Array(64), new Float64Array(64)]; + const cbBlock = new Float64Array(64); + const crBlock = new Float64Array(64); + let prevY = 0; + let prevCb = 0; + let prevCr = 0; + + for (let my = 0; my < height; my += 16) { + for (let mx = 0; mx < width; mx += 16) { + cbBlock.fill(0); + crBlock.fill(0); + for (let dy = 0; dy < 16; dy += 1) { + const sy = my + dy < height ? my + dy : height - 1; + const rowOff = sy * width * 3; + const by = dy >> 3; + const iy = (dy & 7) * 8; + const cy = (dy >> 1) * 8; + for (let dx = 0; dx < 16; dx += 1) { + const sx = mx + dx < width ? mx + dx : width - 1; + const p = rowOff + sx * 3; + const r = rgb[p]; + const g = rgb[p + 1]; + const b = rgb[p + 2]; + const Y = 0.299 * r + 0.587 * g + 0.114 * b - 128; + const Cb = -0.168736 * r - 0.331264 * g + 0.5 * b; + const Cr = 0.5 * r - 0.418688 * g - 0.081312 * b; + yBlocks[(by << 1) | (dx >> 3)][iy + (dx & 7)] = Y; + const cIdx = cy + (dx >> 1); + cbBlock[cIdx] += Cb * 0.25; + crBlock[cIdx] += Cr * 0.25; + } + } + for (let i = 0; i < 4; i += 1) prevY = encodeBlock(yBlocks[i], yQ, ENC_DC_Y, ENC_AC_Y, prevY); + prevCb = encodeBlock(cbBlock, uvQ, ENC_DC_UV, ENC_AC_UV, prevCb); + prevCr = encodeBlock(crBlock, uvQ, ENC_DC_UV, ENC_AC_UV, prevCr); + } + } + + // Flush final partial byte padded with 1-bits + if (bitCnt > 0) writeBits((1 << (8 - bitCnt)) - 1, 8 - bitCnt); + + return Buffer.concat([Buffer.from(header), scanBuf.subarray(0, scanLen), Buffer.from([0xff, 0xd9])]); +} + +// ── Gamma Transform & Vertical Compare Banner Composer ────────────────────── + +export function applyGammaRgb(srcRgb, gamma) { + const lut = new Uint8Array(256); + for (let i = 0; i < 256; i += 1) { + lut[i] = clampByte(255 * Math.pow(i / 255, gamma)); + } + const out = new Uint8Array(srcRgb.length); + for (let i = 0; i < srcRgb.length; i += 1) out[i] = lut[srcRgb[i]]; + return out; +} + +// Compact 5x7 ASCII bitmap font for crisp, dependency-free comparison banners +const FONT_5X7 = { + ' ': [0, 0, 0, 0, 0, 0, 0], + '.': [0, 0, 0, 0, 0, 12, 12], + ',': [0, 0, 0, 0, 4, 4, 8], + '-': [0, 0, 0, 31, 0, 0, 0], + '+': [0, 4, 4, 31, 4, 4, 0], + '=': [0, 0, 31, 0, 31, 0, 0], + '_': [0, 0, 0, 0, 0, 0, 31], + ':': [0, 12, 12, 0, 12, 12, 0], + '/': [1, 2, 4, 8, 16, 0, 0], + '|': [4, 4, 4, 4, 4, 4, 4], + '>': [16, 8, 4, 2, 4, 8, 16], + '<': [2, 4, 8, 16, 8, 4, 2], + '%': [25, 26, 4, 4, 11, 19, 0], + '(': [4, 8, 16, 16, 16, 8, 4], + ')': [8, 4, 2, 2, 2, 4, 8], + '0': [14, 17, 19, 21, 25, 17, 14], + '1': [4, 12, 4, 4, 4, 4, 14], + '2': [14, 17, 1, 6, 8, 16, 31], + '3': [14, 17, 1, 6, 1, 17, 14], + '4': [2, 6, 10, 18, 31, 2, 2], + '5': [31, 16, 30, 1, 1, 17, 14], + '6': [6, 8, 16, 30, 17, 17, 14], + '7': [31, 1, 2, 4, 8, 8, 8], + '8': [14, 17, 17, 14, 17, 17, 14], + '9': [14, 17, 17, 15, 1, 2, 12], + A: [14, 17, 17, 31, 17, 17, 17], + B: [30, 17, 17, 30, 17, 17, 30], + C: [14, 17, 16, 16, 16, 17, 14], + D: [28, 18, 17, 17, 17, 18, 28], + E: [31, 16, 16, 30, 16, 16, 31], + F: [31, 16, 16, 30, 16, 16, 16], + G: [14, 17, 16, 23, 17, 17, 15], + H: [17, 17, 17, 31, 17, 17, 17], + I: [14, 4, 4, 4, 4, 4, 14], + J: [1, 1, 1, 1, 17, 17, 14], + K: [17, 18, 20, 24, 20, 18, 17], + L: [16, 16, 16, 16, 16, 16, 31], + M: [17, 27, 21, 21, 17, 17, 17], + N: [17, 25, 21, 19, 17, 17, 17], + O: [14, 17, 17, 17, 17, 17, 14], + P: [30, 17, 17, 30, 16, 16, 16], + Q: [14, 17, 17, 17, 21, 18, 13], + R: [30, 17, 17, 30, 20, 18, 17], + S: [15, 16, 16, 14, 1, 1, 30], + T: [31, 4, 4, 4, 4, 4, 4], + U: [17, 17, 17, 17, 17, 17, 14], + V: [17, 17, 17, 17, 17, 10, 4], + W: [17, 17, 17, 21, 21, 27, 17], + X: [17, 17, 10, 4, 10, 17, 17], + Y: [17, 17, 10, 4, 4, 4, 4], + Z: [31, 1, 2, 4, 8, 16, 31], +}; + +function drawRect(rgb, width, height, x0, y0, w, h, color) { + const xEnd = Math.min(width, x0 + w); + const yEnd = Math.min(height, y0 + h); + for (let y = Math.max(0, y0); y < yEnd; y += 1) { + let off = (y * width + Math.max(0, x0)) * 3; + for (let x = Math.max(0, x0); x < xEnd; x += 1) { + rgb[off++] = color[0]; + rgb[off++] = color[1]; + rgb[off++] = color[2]; + } + } +} + +function drawText(rgb, width, height, text, startX, startY, scale, color) { + const upper = String(text).toUpperCase(); + let cursorX = startX; + for (let i = 0; i < upper.length; i += 1) { + const glyph = FONT_5X7[upper[i]] ?? FONT_5X7[' ']; + for (let row = 0; row < 7; row += 1) { + const bits = glyph[row]; + for (let col = 0; col < 5; col += 1) { + if ((bits >> (4 - col)) & 1) { + drawRect(rgb, width, height, cursorX + col * scale, startY + row * scale, scale, scale, color); + } + } + } + cursorX += 6 * scale; + } +} + +export function composeCompareRgb( + width, + height, + beforeRgb, + afterRgb, + { topLabel, bottomLabel, barHeight, footerLine = '', footerHeight = 28 }, +) { + const hasFooter = Boolean(footerLine); + const footH = hasFooter ? footerHeight : 0; + const totalHeight = barHeight * 2 + height * 2 + footH; + const out = new Uint8Array(width * totalHeight * 3); + const bg = [20, 26, 36]; + const fg = [238, 242, 248]; + const muted = [203, 213, 225]; + const accentBefore = [100, 116, 139]; + const accentAfter = [34, 197, 94]; + + // Top banner + baseline image + drawRect(out, width, totalHeight, 0, 0, width, barHeight, bg); + drawRect(out, width, totalHeight, 0, 0, 6, barHeight, accentBefore); + drawText(out, width, totalHeight, topLabel, 16, Math.floor((barHeight - 14) / 2), 2, fg); + out.set(beforeRgb, barHeight * width * 3); + + // Middle banner + adjusted image + const midY = barHeight + height; + drawRect(out, width, totalHeight, 0, midY, width, barHeight, bg); + drawRect(out, width, totalHeight, 0, midY, 6, barHeight, accentAfter); + drawText(out, width, totalHeight, bottomLabel, 16, midY + Math.floor((barHeight - 14) / 2), 2, fg); + out.set(afterRgb, (midY + barHeight) * width * 3); + + if (hasFooter) { + const footY = midY + barHeight + height; + drawRect(out, width, totalHeight, 0, footY, width, footH, [16, 22, 32]); + const scale = footerLine.length * 12 + 28 <= width ? 2 : 1; + const textH = 7 * scale; + drawText(out, width, totalHeight, footerLine, 14, footY + Math.floor((footH - textH) / 2), scale, muted); + } + + return { width, height: totalHeight, data: out }; +} + +/** Bilinear RGB resizer returning raw RGB Uint8Array (width, height, srcRgb, dstW, dstH). */ +export function resizeRgbBilinear(width, height, srcRgb, dstW, dstH) { + if (dstW <= 0 || dstH <= 0) throw new Error('isp_codec_invalid_resize'); + if (dstW === width && dstH === height) return new Uint8Array(srcRgb); + const out = new Uint8Array(dstW * dstH * 3); + const xRatio = (width - 1) / Math.max(1, dstW - 1); + const yRatio = (height - 1) / Math.max(1, dstH - 1); + for (let y = 0; y < dstH; y++) { + const sy = y * yRatio; + const y0 = Math.floor(sy); + const y1 = Math.min(height - 1, y0 + 1); + const fy = sy - y0; + const row0 = y0 * width; + const row1 = y1 * width; + for (let x = 0; x < dstW; x++) { + const sx = x * xRatio; + const x0 = Math.floor(sx); + const x1 = Math.min(width - 1, x0 + 1); + const fx = sx - x0; + const w00 = (1 - fx) * (1 - fy); + const w10 = fx * (1 - fy); + const w01 = (1 - fx) * fy; + const w11 = fx * fy; + const i00 = (row0 + x0) * 3; + const i10 = (row0 + x1) * 3; + const i01 = (row1 + x0) * 3; + const i11 = (row1 + x1) * 3; + const o = (y * dstW + x) * 3; + out[o] = clampByte(srcRgb[i00] * w00 + srcRgb[i10] * w10 + srcRgb[i01] * w01 + srcRgb[i11] * w11); + out[o + 1] = clampByte(srcRgb[i00 + 1] * w00 + srcRgb[i10 + 1] * w10 + srcRgb[i01 + 1] * w01 + srcRgb[i11 + 1] * w11); + out[o + 2] = clampByte(srcRgb[i00 + 2] * w00 + srcRgb[i10 + 2] * w10 + srcRgb[i01 + 2] * w01 + srcRgb[i11 + 2] * w11); + } + } + return out; +} + +/** Clean bilinear RGB downscaler (even output dimensions, pure JS). */ +export function resizeRgb(rgb, srcW, srcH, maxWidth = 840) { + if (srcW <= maxWidth) return { width: srcW, height: srcH, data: rgb }; + const scale = maxWidth / srcW; + const dstW = Math.max(2, Math.round(srcW * scale) & ~1); + const dstH = Math.max(2, Math.round(srcH * scale) & ~1); + return { width: dstW, height: dstH, data: resizeRgbBilinear(srcW, srcH, rgb, dstW, dstH) }; +} + +/** Decode PNG or Baseline JPEG automatically by magic header bytes or extension hint (pure JS). */ +export function decodeImageBuffer(buf, extHint = '') { + const bytes = Buffer.isBuffer(buf) ? buf : Buffer.from(buf); + if (bytes.length >= 8 && bytes.subarray(0, 8).equals(PNG_SIG)) return decodePng(bytes); + if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xd8) return decodeJpeg(bytes); + const ext = String(extHint).toLowerCase(); + if (ext === '.png' || ext === 'png') return decodePng(bytes); + if (ext === '.jpg' || ext === '.jpeg' || ext === 'jpg' || ext === 'jpeg') return decodeJpeg(bytes); + throw new Error('isp_codec_unsupported_format'); +} + +/** Decode PNG or Baseline JPEG automatically by magic header bytes (pure JS). */ +export function decodeImageAuto(buf) { + const bytes = Buffer.isBuffer(buf) ? buf : Buffer.from(buf); + if (bytes.length >= 8 && bytes.subarray(0, 8).equals(PNG_SIG)) { + return { ...decodePng(bytes), format: 'png' }; + } + if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) { + return { ...decodeJpeg(bytes), format: 'jpeg' }; + } + throw new Error('isp_codec_unsupported_format'); +} diff --git a/plugins/rdk-camera-workshop/mcp/isp-example.mjs b/plugins/rdk-camera-workshop/mcp/isp-example.mjs new file mode 100644 index 0000000..b484b0e --- /dev/null +++ b/plugins/rdk-camera-workshop/mcp/isp-example.mjs @@ -0,0 +1,738 @@ +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { existsSync, lstatSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { basename, dirname, extname, isAbsolute, join } from 'node:path'; +import { + DEFAULT_ISP_PARAMS, + ISP_PARAM_BOUNDS, + ISP_PARAM_KEYS, + analyzeIspImage, + applyIspDelta, + applyIspPipeline, + buildIspDiagnosisNotes, + demosaicBayerRaw, + formatIspParamSummary, + normalizeIspParams, + parseRelativeGoalDelta, + solveAutoIsp, +} from '../web/isp-engine.mjs'; +import { + applyGammaRgb, + composeCompareRgb, + decodeImageAuto, + decodeJpeg, + decodePng, + encodeJpeg, + encodePng, + resizeRgb, +} from './isp-codec.mjs'; + +const sceneCatalog = JSON.parse(readFileSync(new URL('../web/isp-example/scenes.json', import.meta.url), 'utf8')).scenes; +const sceneMap = new Map(sceneCatalog.map(item => [item.id, item])); +export const ISP_EXAMPLE_SCENES = sceneCatalog.map(item => item.id); + +const baselineCache = new Map(); +const renderedCache = new Map(); + +function sceneImageUrl(scene, name) { + const rel = scene.id === 'chart' + ? '../web/isp-example/' + name + '.' + scene.ext + : '../web/isp-example/' + scene.id + '/' + name + '.' + scene.ext; + return new URL(rel, import.meta.url); +} + +function loadBaseline(scene) { + let cached = baselineCache.get(scene.id); + if (cached) return cached; + const raw = readFileSync(sceneImageUrl(scene, 'gamma-20')); + const decoded = scene.ext === 'png' ? decodePng(raw) : decodeJpeg(raw); + cached = { raw, decoded }; + baselineCache.set(scene.id, cached); + return cached; +} + +export function renderIspExampleAsset(pathname) { + if (typeof pathname !== 'string' || pathname.includes('..') || !pathname.startsWith('/isp-example/')) return null; + const match = /^\/isp-example\/(?:([a-z0-9_-]+)\/)?(gamma|compare)-(\d+)\.(png|jpg)$/.exec(pathname); + if (!match) return null; + const [, dirScene, kind, rawIdx, ext] = match; + const sceneId = dirScene ?? 'chart'; + const scene = sceneMap.get(sceneId); + if (!scene || scene.ext !== ext) return null; + const index = Number(rawIdx); + if (!Number.isInteger(index) || index < 11 || index > 29) return null; + if (kind === 'compare' && index === 20) return null; + + const assetUrl = sceneImageUrl(scene, `${kind}-${index}`); + if (existsSync(assetUrl)) { + return [scene.mimeType, readFileSync(assetUrl)]; + } + + const cacheKey = `${scene.id}:${kind}:${index}`; + const hit = renderedCache.get(cacheKey); + if (hit) return [scene.mimeType, hit]; + + const { raw, decoded } = loadBaseline(scene); + let bytes; + if (kind === 'gamma' && index === 20) { + bytes = raw; + } else { + const gamma = index / 20; + const adjusted = applyGammaRgb(decoded.data, gamma); + if (kind === 'gamma') { + bytes = scene.ext === 'png' + ? encodePng(decoded.width, decoded.height, adjusted) + : encodeJpeg(decoded.width, decoded.height, adjusted, 88); + } else { + const barHeight = scene.ext === 'png' ? 36 : 30; + const cmp = composeCompareRgb(decoded.width, decoded.height, decoded.data, adjusted, { + topLabel: 'BASELINE GAMMA 1.00', + bottomLabel: 'CANDIDATE GAMMA ' + gamma.toFixed(2), + barHeight, + }); + bytes = scene.ext === 'png' + ? encodePng(cmp.width, cmp.height, cmp.data) + : encodeJpeg(cmp.width, cmp.height, cmp.data, 86); + } + } + renderedCache.set(cacheKey, bytes); + return [scene.mimeType, bytes]; +} + +export const ISP_EXAMPLE_PRESETS = [ + 'auto', + 'recommended', + 'lowlight_rescue', + 'hdr_backlight', + 'dehaze', + 'cool_wb', + 'warm_wb', + 'sharp_detail', + 'denoise_clean', + 'over_sharpen_demo', + 'reset', +]; + +const NAMED_PRESETS = { + lowlight_rescue: { exposureEv: 0.7, shadows: 52, highlights: -25, gamma: 0.72, brightness: 2, contrast: 1.10, saturation: 1.12, wbShift: 0, denoise: 0.30, sharpness: 0.40 }, + hdr_backlight: { exposureEv: -0.2, shadows: 68, highlights: -75, gamma: 0.80, brightness: 0, contrast: 1.10, saturation: 1.12, wbShift: 0, denoise: 0.20, sharpness: 0.35 }, + dehaze: { exposureEv: -0.1, shadows: 0, highlights: -10, gamma: 1.20, brightness: -18, contrast: 1.55, saturation: 1.45, wbShift: -4, denoise: 0.10, sharpness: 0.50 }, + cool_wb: { exposureEv: 0.1, shadows: 0, highlights: 0, gamma: 0.95, brightness: 0, contrast: 1.05, saturation: 1.10, wbShift: -36, denoise: 0, sharpness: 0.25 }, + warm_wb: { exposureEv: 0, shadows: 0, highlights: 0, gamma: 0.95, brightness: 0, contrast: 1.05, saturation: 1.10, wbShift: 24, denoise: 0, sharpness: 0.20 }, + sharp_detail: { exposureEv: 0, shadows: 0, highlights: 0, gamma: 0.95, brightness: 0, contrast: 1.15, saturation: 1.25, wbShift: 0, denoise: 0.10, sharpness: 1.10 }, + denoise_clean: { exposureEv: 0.2, shadows: 25, highlights: -10, gamma: 0.90, brightness: 0, contrast: 1.06, saturation: 1.08, wbShift: 0, denoise: 0.55, sharpness: 0.25 }, + over_sharpen_demo: { exposureEv: 0, shadows: 0, highlights: 0, gamma: 1.00, brightness: 0, contrast: 1.20, saturation: 1.30, wbShift: 0, denoise: 0, sharpness: 2.00 }, + reset: { ...DEFAULT_ISP_PARAMS }, +}; + +const ALLOWED_KEYS = new Set([ + 'action', 'mode', 'scene', 'imagePath', 'useWorkbenchImage', 'useLatestAttachment', + 'preset', 'goal', 'outputPath', 'inheritCurrent', 'delta', + 'rawWidth', 'rawHeight', 'bayerPattern', 'bitDepth', 'blackLevel', + ...ISP_PARAM_KEYS, +]); + +const LAB_TRIGGER_KEYS = [ + 'action', 'mode', 'imagePath', 'useWorkbenchImage', 'useLatestAttachment', + 'preset', 'goal', 'outputPath', 'inheritCurrent', 'delta', + 'rawWidth', 'rawHeight', 'bayerPattern', 'bitDepth', 'blackLevel', + 'exposureEv', 'shadows', 'highlights', 'brightness', 'contrast', + 'saturation', 'wbShift', 'denoise', 'sharpness', +]; + +const ALLOWED_IMAGE_EXTS = new Set(['.jpg', '.jpeg', '.png', '.webp', '.bmp', '.raw', '.bin']); +const ALLOWED_RAW_EXTS = new Set(['.raw', '.bin']); +const ALLOWED_OUTPUT_EXTS = new Set(['.jpg', '.jpeg', '.png']); +const MAX_LOCAL_IMAGE_BYTES = 32 * 1024 * 1024; + +function withHint(code, hint) { + return Object.assign(new Error(code), { hint }); +} + +function readImage(scene, name, label) { + const url = sceneImageUrl(scene, name); + let bytes; + if (existsSync(url)) { + bytes = readFileSync(url); + } else { + const pathname = scene.id === 'chart' + ? `/isp-example/${name}.${scene.ext}` + : `/isp-example/${scene.id}/${name}.${scene.ext}`; + const rendered = renderIspExampleAsset(pathname); + if (!rendered) throw new Error('isp_example_asset_missing'); + bytes = rendered[1]; + } + return { bytes, sha256: createHash('sha256').update(bytes).digest('hex'), label, mimeType: scene.mimeType }; +} + +/** Optional fallback decoder ONLY for exotic formats (WebP/BMP/Progressive JPEG) not covered by pure-JS SOF0/PNG. */ +function decodeWithPythonFallback(srcPath) { + const script = String.raw` +import io, json, sys +from PIL import Image, ImageOps +im = ImageOps.exif_transpose(Image.open(sys.argv[1])).convert("RGB") +w, h = im.size +if w > 840: + nh = max(2, int(round(h * (840.0 / w))) & ~1) + im = im.resize((840, nh), Image.Resampling.LANCZOS) +buf = io.BytesIO() +im.save(buf, format="PNG") +sys.stdout.buffer.write(buf.getvalue()) +`; + const pngBytes = execFileSync('python3', ['-c', script, srcPath], { + maxBuffer: 20 * 1024 * 1024, + timeout: 15000, + }); + return decodePng(pngBytes); +} + +/** Find newest uploaded image inside RDK Studio chat-attachments directory (within maxAgeMs). */ +export function findLatestChatAttachment( + root = process.env.RDK_VISION_COURSE_CHAT_ATTACHMENTS_DIR ?? join(homedir(), '.rdkstudio', 'chat-attachments'), + maxAgeMs = 60 * 60 * 1000, +) { + if (!root || !existsSync(root)) return null; + let newest = null; + const cutoff = Date.now() - maxAgeMs; + const scan = (dir, depth = 0) => { + if (depth > 3) return; + let entries; + try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; } + for (const ent of entries) { + const full = join(dir, ent.name); + if (ent.isDirectory()) { + scan(full, depth + 1); + } else if (ent.isFile()) { + const ext = extname(ent.name).toLowerCase(); + if (!ALLOWED_IMAGE_EXTS.has(ext)) continue; + try { + const st = statSync(full); + if (st.size > 0 && st.size <= MAX_LOCAL_IMAGE_BYTES && st.mtimeMs >= cutoff) { + if (!newest || st.mtimeMs > newest.mtimeMs) { + newest = { path: full, mtimeMs: st.mtimeMs, size: st.size, name: ent.name }; + } + } + } catch {} + } + } + }; + scan(root, 0); + return newest; +} + +function coerceFiniteNumber(val) { + if (typeof val === 'number') return Number.isFinite(val) ? val : NaN; + if (typeof val === 'string') { + const trimmed = val.trim(); + if (!trimmed) return NaN; + const n = Number(trimmed); + return Number.isFinite(n) ? n : NaN; + } + return NaN; +} + +function validateParamMap(obj, labelPrefix = '') { + for (const key of ISP_PARAM_KEYS) { + if (!Object.hasOwn(obj, key) || obj[key] === undefined || obj[key] === null) { + if (obj[key] === null) delete obj[key]; + continue; + } + const raw = obj[key]; + const val = coerceFiniteNumber(raw); + const [lo, hi] = ISP_PARAM_BOUNDS[key]; + if (!Number.isFinite(val)) { + throw withHint('invalid_arguments', `${labelPrefix}${key} 必须为有限数值(收到 ${typeof raw}: ${JSON.stringify(raw)})。`); + } + if (val < lo || val > hi) { + throw withHint('invalid_arguments', `${labelPrefix}${key} 必须在 [${lo}, ${hi}] 范围内。`); + } + obj[key] = val; + } +} + +function validateDeltaMap(delta) { + if (!delta || typeof delta !== 'object' || Array.isArray(delta)) { + throw withHint('invalid_arguments', 'delta 必须为对象,例如 { wbShift: -10, sharpness: -0.2 }。'); + } + for (const [key, raw] of Object.entries(delta)) { + if (raw === undefined || raw === null) { + delete delta[key]; + continue; + } + if (!ISP_PARAM_KEYS.includes(key)) { + throw withHint('invalid_arguments', `delta 不支持参数 ${key},可用:${ISP_PARAM_KEYS.join(', ')}。`); + } + const val = coerceFiniteNumber(raw); + const [lo, hi] = ISP_PARAM_BOUNDS[key]; + const span = hi - lo; + if (!Number.isFinite(val)) { + throw withHint('invalid_arguments', `delta.${key} 必须为有限数值(收到 ${typeof raw}: ${JSON.stringify(raw)})。`); + } + if (Math.abs(val) > span) { + throw withHint('invalid_arguments', `delta.${key} 增量超出合理跨度(±${span})。`); + } + delta[key] = val; + } +} + +function decodeSourceBuffer({ bytes, ext, filePath, rawMeta }) { + if (ALLOWED_RAW_EXTS.has(ext)) { + if (!rawMeta?.width || !rawMeta?.height) { + throw withHint('invalid_arguments', '处理 Bayer RAW 文件需同时提供 rawWidth 和 rawHeight(及可选 bayerPattern/bitDepth/blackLevel)。'); + } + const demosaiced = demosaicBayerRaw(bytes, rawMeta); + const resized = resizeRgb(demosaiced.data, demosaiced.width, demosaiced.height, 840); + return { ...resized, origWidth: demosaiced.width, origHeight: demosaiced.height, isRaw: true }; + } + let decoded; + try { + decoded = decodeImageAuto(bytes); + } catch { + if (filePath && existsSync(filePath)) { + decoded = decodeWithPythonFallback(filePath); + } else { + throw withHint('isp_decode_failed', '纯 JS 解码器仅直接支持 PNG/Baseline JPEG/Bayer RAW;请检查图片格式或提供本地文件路径。'); + } + } + const resized = resizeRgb(decoded.data, decoded.width, decoded.height, 840); + return { ...resized, origWidth: decoded.width, origHeight: decoded.height, isRaw: false }; +} + +function computeDeltaMetrics(before, after) { + return { + meanLuma: Number((after.meanLuma - before.meanLuma).toFixed(2)), + darkPct: Number((after.darkPct - before.darkPct).toFixed(2)), + clipPct: Number((after.clipPct - before.clipPct).toFixed(2)), + meanSat: Number((after.meanSat - before.meanSat).toFixed(2)), + edgeSharpness: Number((after.edgeSharpness - before.edgeSharpness).toFixed(2)), + noiseEstimate: Number((after.noiseEstimate - before.noiseEstimate).toFixed(2)), + dynamicRange: after.dynamicRange - before.dynamicRange, + wbCastIndex: Number((after.wbCastIndex - before.wbCastIndex).toFixed(1)), + }; +} + +function buildCompareAsciiLabels(params, isAuto) { + const parts = []; + if (Math.abs(params.exposureEv) > 1e-6) parts.push(`EV${params.exposureEv > 0 ? '+' : ''}${params.exposureEv.toFixed(1)}`); + if (Math.abs(params.shadows) >= 1) parts.push(`SH${params.shadows > 0 ? '+' : ''}${Math.round(params.shadows)}`); + if (Math.abs(params.highlights) >= 1) parts.push(`HI${params.highlights > 0 ? '+' : ''}${Math.round(params.highlights)}`); + if (Math.abs(params.gamma - 1) > 1e-6) parts.push(`G${params.gamma.toFixed(2)}`); + if (Math.abs(params.contrast - 1) > 1e-6) parts.push(`C${params.contrast.toFixed(2)}`); + if (Math.abs(params.saturation - 1) > 1e-6) parts.push(`S${params.saturation.toFixed(2)}`); + if (Math.abs(params.wbShift) >= 1) parts.push(`WB${params.wbShift > 0 ? '+' : ''}${Math.round(params.wbShift)}`); + if (params.denoise > 1e-6) parts.push(`NR${params.denoise.toFixed(2)}`); + if (params.sharpness > 1e-6) parts.push(`EE${params.sharpness.toFixed(2)}`); + const tag = parts.length ? parts.slice(0, 6).join(' ') : 'IDENTITY'; + return { + topLabel: 'BEFORE ORIGINAL', + bottomLabel: `${isAuto ? 'AUTO ' : 'TUNED '}${tag}`, + }; +} + +/** + * Pure-JS, Zero-Python 10-Parameter Linear ISP Tuning, 2-Pass Auto-ISP Solver, + * Bayer RAW Demosaic & Multi-Turn Stateful Workbench Sync. + */ +export function ispExample(args = {}, context = {}) { + if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('invalid_arguments'); + for (const key of Object.keys(args)) { + if (!ALLOWED_KEYS.has(key)) throw new Error('invalid_arguments'); + } + + const action = args.action ?? 'tune'; + if (!['tune', 'auto', 'undo', 'inspect'].includes(action)) { + throw withHint('invalid_arguments', 'action 仅支持 tune / auto / undo / inspect。'); + } + + const wbPractice = context.workbenchPractice ?? null; + const wbState = wbPractice?.state ?? null; + + // ── Inspect current bidirectional workbench practice state ── + if (action === 'inspect') { + return { + status: { + mode: 'inspect', + deviceUsed: false, + workbenchOpen: Boolean(wbPractice), + activeScene: wbState?.scene ?? (wbState?.hasCustomImage ? 'custom' : null), + hasCustomImage: Boolean(wbState?.hasCustomImage), + customImageLabel: wbState?.customImageLabel ?? null, + currentParameters: wbState?.params ? normalizeIspParams(wbState.params) : null, + parameterSummary: wbState?.params ? formatIspParamSummary(wbState.params) : null, + historyCount: wbPractice?.historyCount ?? 0, + canUndo: Boolean(wbPractice?.canUndo), + recentHistory: wbPractice?.history ?? [], + availableScenes: sceneCatalog.map(item => ({ + id: item.id, shortTitle: item.shortTitle, title: item.title, badge: item.badge, + })), + }, + images: [], + preview: null, + practiceSync: null, + }; + } + + // ── Undo marker (handled asynchronously by server.mjs via session.undoPractice) ── + if (action === 'undo') { + return { undoRequested: true }; + } + + const hasImagePath = args.imagePath !== undefined; + const hasSceneArg = args.scene !== undefined; + const useWbArg = args.useWorkbenchImage === true; + const useLatestAttArg = args.useLatestAttachment === true; + const explicitSourceCount = [hasSceneArg, hasImagePath, useWbArg, useLatestAttArg].filter(Boolean).length; + if (explicitSourceCount > 1) { + throw withHint('invalid_arguments', 'scene、imagePath、useWorkbenchImage 与 useLatestAttachment 请只传其中一个。'); + } + + // Validate explicit parameters & delta early (work on shallow copy so caller args are not mutated unexpectedly) + const workingArgs = { ...args, ...(args.delta && typeof args.delta === 'object' && !Array.isArray(args.delta) ? { delta: { ...args.delta } } : {}) }; + validateParamMap(workingArgs); + if (workingArgs.delta !== undefined) { + validateDeltaMap(workingArgs.delta); + if (Object.keys(workingArgs.delta).length === 0) delete workingArgs.delta; + } + args = workingArgs; + + // Determine whether to run 10-param linear Lab mode vs exact legacy single-Gamma course mode + const useLabMode = LAB_TRIGGER_KEYS.some(k => args[k] !== undefined); + + // ── Legacy single-Gamma exact mode (100% backward compatible with course & tests) ── + if (!useLabMode) { + const sceneId = args.scene ?? 'chart'; + const scene = sceneMap.get(sceneId); + if (!scene) { + throw withHint('invalid_arguments', '未知示例场景:' + String(sceneId) + '。可用场景:' + ISP_EXAMPLE_SCENES.join('、')); + } + const gamma = args.gamma ?? 1; + if (typeof gamma !== 'number' || !Number.isFinite(gamma) || gamma < 0.55 || gamma > 1.45) { + throw new Error('invalid_arguments'); + } + const index = Math.round(gamma * 20); + if (Math.abs(gamma - index / 20) > 1e-9) throw new Error('invalid_arguments'); + const baseline = readImage(scene, 'gamma-20', scene.shortTitle + ' · 基线 Gamma 1.00'); + const candidate = index === 20 + ? baseline + : readImage(scene, 'gamma-' + index, scene.shortTitle + ' · 候选 Gamma ' + gamma.toFixed(2)); + const preview = index === 20 + ? baseline + : readImage(scene, 'compare-' + index, scene.shortTitle + ' · Gamma 1.00 → ' + gamma.toFixed(2)); + const status = { + source: scene.source, + scene: scene.id, + sceneTitle: scene.title, + shortTitle: scene.shortTitle, + deviceUsed: false, + parameter: 'gamma', + baseline: 1, + gamma: Number(gamma.toFixed(2)), + recommendedGamma: scene.recommendedGamma, + availableScenes: sceneCatalog.map(item => ({ + id: item.id, shortTitle: item.shortTitle, title: item.title, badge: item.badge, + })), + ...(scene.device ? { device: scene.device, date: scene.date, frameId: scene.frameId } : {}), + ...(scene.readbackHash ? { readbackHash: scene.readbackHash } : {}), + note: '仅基于离线示例图生成,不是实时相机采集或板端 ISP 回读。', + }; + return { + status, + images: index === 20 ? [baseline] : [baseline, candidate], + preview, + practiceSync: { mode: 'gamma', scene: scene.id, gamma: Number(gamma.toFixed(2)), source: 'chat' }, + }; + } + + // ── Full 10-Parameter Linear-Light ISP / Auto-ISP / Multi-Turn Delta / Bayer RAW Mode ── + const goal = typeof args.goal === 'string' ? args.goal.replace(/[\u0000-\u001f\u007f]/gu, ' ').trim().slice(0, 240) : ''; + const preset = args.preset; + if (preset !== undefined && (typeof preset !== 'string' || !ISP_EXAMPLE_PRESETS.includes(preset))) { + throw withHint('invalid_arguments', '未知预设:' + String(preset) + '。可用预设:' + ISP_EXAMPLE_PRESETS.join('、')); + } + + // Decide source (explicit -> latest chat attachment -> workbench custom image -> inherited scene -> lowlight default) + let sourceKind = 'scene'; // 'scene' | 'local' | 'workbench' | 'attachment' + let scene = null; + let sourcePath = null; + let sourceBytes = null; + let sourceExt = '.jpg'; + let sourceTitle = ''; + let customLabel = ''; + + const hasExplicitNumericParams = ISP_PARAM_KEYS.some(k => args[k] !== undefined); + const autoInherit = args.inheritCurrent === true || + args.delta !== undefined || + (!hasSceneArg && !hasImagePath && !useWbArg && !useLatestAttArg && wbState && (wbState.hasCustomImage || wbState.scene)); + + if (useLatestAttArg) { + const latest = findLatestChatAttachment(); + if (!latest) { + throw withHint('attachment_not_found', '最近 60 分钟内在 ~/.rdkstudio/chat-attachments 未找到上传图片;请先拖图进对话框或传 imagePath。'); + } + sourceKind = 'attachment'; + sourcePath = latest.path; + sourceExt = extname(latest.path).toLowerCase(); + sourceBytes = readFileSync(latest.path); + customLabel = '聊天附件 · ' + latest.name; + sourceTitle = customLabel; + } else if (useWbArg || (!hasSceneArg && !hasImagePath && autoInherit && wbState?.hasCustomImage && wbPractice?.customImageBase64)) { + if (!wbPractice?.customImageBase64) { + throw withHint('workbench_image_missing', '右侧工作台当前没有已上传的本地图片;请先在工作台点击「导入本地图」,或在对话里传 imagePath。'); + } + sourceKind = 'workbench'; + sourceBytes = Buffer.from(wbPractice.customImageBase64, 'base64'); + sourceExt = wbPractice.customImageMimeType === 'image/png' ? '.png' : '.jpg'; + customLabel = wbPractice.customImageLabel || wbState?.customImageLabel || '工作台图片'; + sourceTitle = customLabel; + } else if (hasImagePath) { + if (typeof args.imagePath !== 'string' || !isAbsolute(args.imagePath)) { + throw withHint('invalid_arguments', 'imagePath 必须是本机图片的绝对路径。'); + } + sourceExt = extname(args.imagePath).toLowerCase(); + if (!ALLOWED_IMAGE_EXTS.has(sourceExt)) { + throw withHint('invalid_arguments', '仅支持 jpg/jpeg/png/webp/bmp/raw/bin 图片格式。'); + } + if (!existsSync(args.imagePath)) throw withHint('image_not_found', '本地图片不存在:' + args.imagePath); + const lst = lstatSync(args.imagePath); + if (lst.isSymbolicLink() || !lst.isFile() || lst.size > MAX_LOCAL_IMAGE_BYTES) { + throw withHint('invalid_arguments', '本地图片不支持符号链接、无效文件或超过 32 MB 限制。'); + } + sourceKind = 'local'; + sourcePath = args.imagePath; + sourceBytes = readFileSync(args.imagePath); + customLabel = '本地图片 · ' + basename(args.imagePath); + sourceTitle = customLabel; + } else { + const inheritedSceneId = autoInherit && wbState?.scene && sceneMap.has(wbState.scene) ? wbState.scene : 'lowlight'; + const sceneId = args.scene ?? inheritedSceneId; + scene = sceneMap.get(sceneId); + if (!scene) { + throw withHint('invalid_arguments', '未知示例场景:' + String(sceneId) + '。可用场景:' + ISP_EXAMPLE_SCENES.join('、')); + } + sourceKind = 'scene'; + sourceExt = '.' + scene.ext; + sourceBytes = readFileSync(sceneImageUrl(scene, 'gamma-20')); + sourceTitle = scene.shortTitle; + } + + // Validate optional outputPath + let outputPath = ''; + if (args.outputPath !== undefined) { + if (typeof args.outputPath !== 'string' || !isAbsolute(args.outputPath)) { + throw withHint('invalid_arguments', 'outputPath 必须是绝对路径(.jpg 或 .png)。'); + } + const outExt = extname(args.outputPath).toLowerCase(); + if (!ALLOWED_OUTPUT_EXTS.has(outExt)) { + throw withHint('invalid_arguments', 'outputPath 仅支持 .jpg/.jpeg/.png。'); + } + if (!existsSync(dirname(args.outputPath))) { + throw withHint('invalid_arguments', 'outputPath 所在目录不存在:' + dirname(args.outputPath)); + } + if (existsSync(args.outputPath) && lstatSync(args.outputPath).isSymbolicLink()) { + throw withHint('invalid_arguments', 'outputPath 不允许覆盖符号链接:' + args.outputPath); + } + outputPath = args.outputPath; + } + + // Decode source image cleanly in pure JS (PNG/JPEG/Bayer RAW; fallback to Python only for WebP/BMP/progressive) + const rawMeta = ALLOWED_RAW_EXTS.has(sourceExt) ? { + width: args.rawWidth, + height: args.rawHeight, + pattern: args.bayerPattern ?? 'RGGB', + bitDepth: args.bitDepth ?? 10, + blackLevel: args.blackLevel ?? 64, + } : null; + const decoded = decodeSourceBuffer({ bytes: sourceBytes, ext: sourceExt, filePath: sourcePath, rawMeta }); + + // Decide whether to run 2-Pass Auto-ISP Solver vs Explicit / Preset / Relative Delta + const sameWorkbenchTarget = Boolean( + wbState?.params && ( + (sourceKind === 'workbench') || + (sourceKind === 'scene' && wbState.scene === scene?.id) || + ((sourceKind === 'local' || sourceKind === 'attachment') && wbState.hasCustomImage && wbState.customImageLabel === customLabel) + ), + ); + const hasExplicitDelta = Boolean(args.delta && Object.keys(args.delta).length > 0); + const shouldInheritParams = Boolean( + sameWorkbenchTarget && + preset !== 'reset' && + preset !== 'recommended' && + preset !== 'auto' && + args.mode !== 'auto' && + (action !== 'auto' || (args.inheritCurrent === true && hasExplicitDelta)) && + (args.inheritCurrent === true || hasExplicitDelta || (!preset && !hasExplicitNumericParams && Boolean(goal))), + ); + + const wantAutoSolve = + !shouldInheritParams && ( + action === 'auto' || + args.mode === 'auto' || + preset === 'auto' || + (!preset && !hasExplicitNumericParams && !hasExplicitDelta && Boolean(goal)) + ); + + let params; + let afterRgb; + let beforeStats; + let afterStats; + let autoMeta = null; + let appliedDelta = null; + + if (wantAutoSolve) { + const solved = solveAutoIsp(decoded.data, decoded.width, decoded.height, goal, 3); + params = solved.params; + afterRgb = solved.outputBytes; + beforeStats = solved.beforeStats; + afterStats = solved.afterStats; + autoMeta = { + iterations: solved.iterations, + diagnosedDefects: solved.diagnosedDefects, + refinements: solved.refinements, + }; + } else { + let base = { ...DEFAULT_ISP_PARAMS }; + if (shouldInheritParams) { + base = normalizeIspParams(wbState.params); + } else if (preset === 'recommended') { + base = normalizeIspParams(scene?.recommendedLab ?? NAMED_PRESETS.lowlight_rescue); + } else if (preset && NAMED_PRESETS[preset]) { + base = normalizeIspParams(NAMED_PRESETS[preset]); + } else if (scene && !hasExplicitNumericParams && !args.delta) { + base = normalizeIspParams(scene.recommendedLab ?? DEFAULT_ISP_PARAMS); + } + + // Apply explicit parameter overrides first + params = normalizeIspParams(args, base); + + // Apply numeric delta and/or relative natural-language delta when inheriting + if (args.delta) { + params = applyIspDelta(params, args.delta); + appliedDelta = args.delta; + } else if (shouldInheritParams && !hasExplicitNumericParams && goal) { + const parsedDelta = parseRelativeGoalDelta(goal); + if (Object.keys(parsedDelta).length > 0) { + params = applyIspDelta(params, parsedDelta); + appliedDelta = parsedDelta; + } + } + + beforeStats = analyzeIspImage(decoded.data, decoded.width, decoded.height, 3); + afterRgb = applyIspPipeline(decoded.data, decoded.width, decoded.height, params, 3); + afterStats = analyzeIspImage(afterRgb, decoded.width, decoded.height, 3); + } + + // Encode tuned JPEG & before/after vertical comparison JPEG in pure JS (zero Python!) + const tunedJpeg = encodeJpeg(decoded.width, decoded.height, afterRgb, 90); + const { topLabel, bottomLabel } = buildCompareAsciiLabels(params, wantAutoSolve); + const cmp = composeCompareRgb(decoded.width, decoded.height, decoded.data, afterRgb, { + topLabel, + bottomLabel, + barHeight: 30, + }); + const compareJpeg = encodeJpeg(cmp.width, cmp.height, cmp.data, 88); + + // Optional export of full-resolution tuned file to outputPath + let savedOutput = null; + if (outputPath) { + const outExt = extname(outputPath).toLowerCase(); + const outBytes = outExt === '.png' + ? encodePng(decoded.width, decoded.height, afterRgb) + : encodeJpeg(decoded.width, decoded.height, afterRgb, 94); + writeFileSync(outputPath, outBytes); + savedOutput = { + path: outputPath, + sha256: createHash('sha256').update(outBytes).digest('hex'), + bytes: outBytes.length, + }; + } + + const summary = formatIspParamSummary(params); + const deltaMetrics = computeDeltaMetrics(beforeStats, afterStats); + const diagnostics = buildIspDiagnosisNotes(beforeStats, afterStats, params, autoMeta); + if (params.sharpness >= 1.55 && !diagnostics.some(m => m.includes('锐度 USM'))) { + diagnostics.unshift(`锐度 USM 已推到 ${params.sharpness.toFixed(2)},黑白高反差边缘会出现明显白边光晕(Overshoot),请用 2.5× 放大镜核查。`); + } + + const compareSha = createHash('sha256').update(compareJpeg).digest('hex'); + const tunedSha = createHash('sha256').update(tunedJpeg).digest('hex'); + + const compareAsset = { + bytes: compareJpeg, + sha256: compareSha, + label: `${sourceTitle} · ${summary}`, + mimeType: 'image/jpeg', + }; + const tunedAsset = { + bytes: tunedJpeg, + sha256: tunedSha, + label: `${sourceTitle} · 调优结果 (${summary})`, + mimeType: 'image/jpeg', + }; + + // Encode custom source preview JPEG for workbench SSE sync when using local/attachment/RAW image + let customPreviewBase64; + if (sourceKind !== 'scene') { + const baseJpeg = encodeJpeg(decoded.width, decoded.height, decoded.data, 88); + customPreviewBase64 = baseJpeg.toString('base64'); + } + + const resolvedSource = decoded.isRaw + ? 'local_bayer_raw_isp_sim' + : sourceKind === 'scene' + ? (scene.source + '_10param_linear_isp') + : 'local_image_7param_isp_sim'; + + const status = { + mode: 'lab', + engine: 'pure_js_linear_10param_isp_v2', + source: resolvedSource, + ...(scene ? { scene: scene.id, sceneTitle: scene.title, shortTitle: scene.shortTitle } : { scene: 'custom', shortTitle: customLabel }), + ...(sourcePath ? { imagePath: sourcePath } : {}), + ...(sourceKind === 'attachment' ? { fromChatAttachment: true } : {}), + ...(sourceKind === 'workbench' ? { fromWorkbenchUpload: true } : {}), + ...(decoded.isRaw ? { bayerRaw: rawMeta } : {}), + deviceUsed: false, + inheritedPreviousParams: shouldInheritParams, + ...(appliedDelta ? { appliedDelta } : {}), + ...(autoMeta ? { autoSolver: autoMeta } : {}), + ...(preset ? { preset } : {}), + ...(goal ? { goal } : {}), + parameters: params, + parameterSummary: summary, + dimensions: { + original: [decoded.origWidth, decoded.origHeight], + rendered: [decoded.width, decoded.height], + }, + metrics: { + before: beforeStats, + after: afterStats, + delta: deltaMetrics, + }, + diagnostics, + ...(savedOutput ? { savedOutput } : {}), + availableScenes: sceneCatalog.map(item => ({ + id: item.id, shortTitle: item.shortTitle, title: item.title, badge: item.badge, + })), + availablePresets: ISP_EXAMPLE_PRESETS, + note: '基于纯 JS 线性 RGB 域 10 参数 ISP 管线实时渲染(零 Python 依赖),不是实时相机硬件寄存器回读;已同步至右侧工作台「示例图练习」可继续微调或撤销。', + }; + + return { + status, + images: [compareAsset, tunedAsset], + preview: compareAsset, + practiceSync: { + mode: 'lab', + source: 'chat', + ...(scene ? { scene: scene.id } : { scene: 'custom' }), + params, + ...(goal ? { goal } : {}), + ...(customPreviewBase64 ? { + customImageBase64: customPreviewBase64, + customImageMimeType: 'image/jpeg', + customImageLabel: customLabel, + } : {}), + }, + }; +} diff --git a/plugins/rdk-camera-workshop/mcp/learner-isp.mjs b/plugins/rdk-camera-workshop/mcp/learner-isp.mjs index aa3bd98..61e18e2 100644 --- a/plugins/rdk-camera-workshop/mcp/learner-isp.mjs +++ b/plugins/rdk-camera-workshop/mcp/learner-isp.mjs @@ -3,7 +3,10 @@ import { isDeepStrictEqual } from 'node:util'; const fields=[ ['exposureUs','曝光时间','曝光','us','exposure','manual_attr.exp_time'], ['gain','模拟增益','增益','×','exposure','manual_attr.again'], + ['brightness','亮度','亮度','','cproc','manual_attr.bright'], ['contrast','对比度','对比度','','cproc','manual_attr.contrast'], + ['saturation','饱和度','饱和度','','cproc','manual_attr.saturation'], + ['hue','色调','色调','°','cproc','manual_attr.hue'], ['sharpness','锐度','锐度',''], ['whiteBalanceTemperature','白平衡 · 色温','白平衡','K'], ['redGain','白平衡 · 红通道增益','白平衡','×','awb','manual_attr.gain.rgain'], @@ -11,7 +14,7 @@ const fields=[ ]; const sharpness=[ - ['edgeAutoFirst','锐度 · AUTO 首段上沿增益','auto_attr.sharp_gain_0_0',0], + ['edgeAutoFirst','锐度 · AUTO(sharp_gain_0_0)','auto_attr.sharp_gain_0_0',0], ['edgeUp','锐度 · 上沿增益','manual_attr.enhancement_attr.sharp_gain.up',1], ['edgeDown','锐度 · 下沿增益','manual_attr.enhancement_attr.sharp_gain.down',1], ['edgeStrength','锐度 · 增强强度','manual_attr.enhancement_attr.strength',1], @@ -34,7 +37,7 @@ export function learnerOptions(config, controls, {nativeSharpness, rules=[]}={}) return [{id,label,group,unit:unit||row.unit||'',location,scale,via:'control', value:row.value,min:row.min,max:row.max,step:row.step, precision:row.nativePrecision??(row.nativeName?.startsWith('hbn_isp_cproc_attr_t.manual_attr.')?'float32':undefined), - linePeriod:row.nativeLinePeriodUs, ...(disabled?{disabled}:{})}]; + linePeriod:row.nativeLinePeriodUs,fixedScale:row.nativeFixedScale,log2GainSteps:row.nativeLog2GainSteps, ...(disabled?{disabled}:{})}]; }); if(native&&!options.some(item=>item.id==='sharpness'&&!item.disabled)) { for(const [id,label,field,mode] of sharpness) { @@ -53,8 +56,9 @@ export function learnerOptions(config, controls, {nativeSharpness, rules=[]}={}) } export function publicLearnerOptions(options) { - return options.map(({id,label,group,unit,value,min,max,step,linePeriod,disabled})=> - ({id,label,group,unit,value,min,max,step,linePeriod,disabled})); + return options.map(({id,label,group,unit,value,min,max,step,linePeriod,fixedScale,log2GainSteps,disabled})=> + ({id,label,group,unit,value,min,max,step,linePeriod, + ...(fixedScale?{fixedScale}:{}),...(log2GainSteps?{log2GainSteps}:{}),disabled})); } export function readValue(config,location) { @@ -64,15 +68,32 @@ export function readValue(config,location) { export function checkedLearnerValue(option, expected, requested) { if(!option||option.disabled) throw new Error('camera_learner_control_unavailable'); if(expected!==option.value) throw new Error('camera_learner_control_changed'); - const {min,max,step,precision,linePeriod}=option; + const {min,max,step,precision,linePeriod,fixedScale,log2GainSteps}=option; const aligned=value=>!step||Math.abs((value-min)/step-Math.round((value-min)/step))<1e-6; if(!Number.isFinite(requested)||requestedmax||!aligned(requested)) { throw new Error('camera_learner_value_out_of_range'); } - const normalized=Number.isFinite(linePeriod)&&linePeriod>0 - ? Math.fround(Math.fround(linePeriod/1e6)*Math.round(requested/linePeriod))*1e6 - : precision==='seconds-float32-us'?Math.fround(requested/1e6)*1e6 + let normalized; + if(Number.isFinite(linePeriod)&&linePeriod>0) { + const lineSec=Math.fround(linePeriod/1e6); + const lines=Math.round(requested/linePeriod); + normalized=Math.fround(lineSec*lines)*1e6; + if(normalized>max) normalized=Math.fround(lineSec*(lines-1))*1e6; + if(normalized=1) { + const idx=Math.round(requested*fixedScale); + normalized=Math.fround(idx/fixedScale); + if(normalized>max) normalized=Math.fround((idx-1)/fixedScale); + if(normalized=1&&requested>0) { + const idx=Math.round(Math.log2(requested)*log2GainSteps); + normalized=Math.fround(Math.pow(2,idx/log2GainSteps)); + if(normalized>max) normalized=Math.fround(Math.pow(2,(idx-1)/log2GainSteps)); + if(normalizedmax||!aligned(normalized)) throw new Error('camera_learner_value_out_of_range'); if(normalized===option.value) throw new Error('camera_learner_value_unchanged'); return normalized; @@ -84,3 +105,175 @@ export function singleFieldMatches(before, after, option, value) { readValue(expected,option.location.slice(0,-1))[field]=value/option.scale; return isDeepStrictEqual(expected,after); } + +export const MULTI_TUNE_FIELDS = Object.freeze([ + 'exposureUs', 'gain', 'redGain', 'blueGain', + 'brightness', 'contrast', 'saturation', 'hue', +]); + +/** + * Safely clamp & quantize any requested numeric value to the exact hardware grid + * (sensor line period, Q3.5 log2 gain, Q2.10 AWB fixed scale, float32 CPROC step). + */ +export function quantizeControlToHardware(row, requested) { + if (!row || !Number.isFinite(requested) || !Number.isFinite(row.min) || !Number.isFinite(row.max)) { + throw new Error('camera_learner_control_unavailable'); + } + const clamped = Math.min(row.max, Math.max(row.min, requested)); + const { min, max, step, nativePrecision: precision, nativeLinePeriodUs: linePeriod, + nativeFixedScale: fixedScale, nativeLog2GainSteps: log2GainSteps } = row; + let normalized = clamped; + if (Number.isFinite(linePeriod) && linePeriod > 0) { + const lineSec = Math.fround(linePeriod / 1e6); + const lines = Math.round(clamped / linePeriod); + normalized = Math.fround(lineSec * lines) * 1e6; + if (normalized > max) normalized = Math.fround(lineSec * (lines - 1)) * 1e6; + if (normalized < min) normalized = Math.fround(lineSec * (lines + 1)) * 1e6; + } else if (Number.isSafeInteger(fixedScale) && fixedScale >= 1) { + const idx = Math.round(clamped * fixedScale); + normalized = Math.fround(idx / fixedScale); + if (normalized > max) normalized = Math.fround((idx - 1) / fixedScale); + if (normalized < min) normalized = Math.fround((idx + 1) / fixedScale); + } else if (Number.isSafeInteger(log2GainSteps) && log2GainSteps >= 1 && clamped > 0) { + const idx = Math.round(Math.log2(clamped) * log2GainSteps); + normalized = Math.fround(Math.pow(2, idx / log2GainSteps)); + if (normalized > max) normalized = Math.fround(Math.pow(2, (idx - 1) / log2GainSteps)); + if (normalized < min) normalized = Math.fround(Math.pow(2, (idx + 1) / log2GainSteps)); + } else if (Number.isFinite(step) && step > 0) { + const steps = Math.round((clamped - min) / step); + normalized = min + steps * step; + if (precision === 'float32' || row.nativeName?.startsWith('hbn_isp_cproc_attr_t.manual_attr.')) { + normalized = Math.fround(normalized); + } else { + normalized = Number(normalized.toFixed(6)); + } + } else if (precision === 'float32' || row.nativeName?.startsWith('hbn_isp_cproc_attr_t.manual_attr.')) { + normalized = Math.fround(clamped); + } + return Math.min(max, Math.max(min, normalized)); +} + +/** + * Translate real X5 frame telemetry + natural-language goal + live sensor controls + * into safe, hardware-quantized multi-parameter X5 register targets. + */ +export function planHardwareIspFromFrame(metrics, controls, goalText = '') { + const goal = String(goalText || '').trim(); + const proposed = {}; + const rationale = []; + const autoModeSwitches = []; + + const wantBrighter = /亮|暗|黑|提亮|救暗|看不清|brighter|dark|lift/i.test(goal); + const wantDarker = /压暗|太亮|过曝|压高光|防过曝|darker|overexpos/i.test(goal); + const wantCooler = /去黄|冷一点|偏黄|偏暖|中性白|白平衡|cooler|yellow|warm cast|wb/i.test(goal); + const wantWarmer = /暖一点|偏蓝|偏冷|warmer|blue cast/i.test(goal); + const wantDehaze = /去雾|去灰|通透|反差|对比|dehaze|contrast/i.test(goal); + const wantVivid = /鲜艳|饱和|生动|vivid|saturat/i.test(goal); + const wantNatural = /自然|淡一点|别太艳|natural/i.test(goal); + + // 1. Exposure & Analog Gain + const expRow = controls?.exposureUs; + const gainRow = controls?.gain; + if (expRow && Number.isFinite(expRow.value) && expRow.min < expRow.max) { + if (metrics.meanLuma < 88 || wantBrighter) { + const factor = metrics.meanLuma < 65 ? 2.1 : metrics.meanLuma < 88 ? 1.55 : 1.35; + const targetExp = quantizeControlToHardware(expRow, expRow.value * factor); + if (Math.abs(targetExp - expRow.value) > 100) { + proposed.exposureUs = targetExp; + rationale.push(`画面均亮 ${metrics.meanLuma} 偏暗,将曝光时间由 ${(expRow.value / 1000).toFixed(1)} ms 提升至 ${(targetExp / 1000).toFixed(1)} ms`); + if (controls.autoExposure?.value === true) autoModeSwitches.push('autoExposure -> false'); + } else if (gainRow && Number.isFinite(gainRow.value) && gainRow.max > gainRow.value) { + const targetGain = quantizeControlToHardware(gainRow, Math.min(gainRow.max, gainRow.value * 1.6)); + if (Math.abs(targetGain - gainRow.value) > 0.05) { + proposed.gain = targetGain; + rationale.push(`曝光时间已接近上限,小幅提高模拟增益 ${gainRow.value.toFixed(2)}× → ${targetGain.toFixed(2)}×`); + if (controls.autoExposure?.value === true) autoModeSwitches.push('autoExposure -> false'); + } + } + } else if (metrics.meanLuma > 180 || metrics.clipPct > 8 || wantDarker) { + const factor = metrics.clipPct > 12 ? 0.55 : 0.72; + const targetExp = quantizeControlToHardware(expRow, expRow.value * factor); + if (Math.abs(targetExp - expRow.value) > 100) { + proposed.exposureUs = targetExp; + rationale.push(`画面偏亮/高光裁切 ${metrics.clipPct}%,将曝光时间由 ${(expRow.value / 1000).toFixed(1)} ms 回调至 ${(targetExp / 1000).toFixed(1)} ms`); + if (controls.autoExposure?.value === true) autoModeSwitches.push('autoExposure -> false'); + } + } + } + + // 2. Hardware AWB (redGain / blueGain) + const rRow = controls?.redGain; + const bRow = controls?.blueGain; + const wbDiff = metrics.wbCastIndex ?? 0; + if (rRow && bRow && Number.isFinite(rRow.value) && Number.isFinite(bRow.value)) { + if (wbDiff > 20 || (wantCooler && wbDiff > 6)) { + const ratio = Math.min(1.65, Math.max(1.12, 1 + (wbDiff / 180))); + const nextR = quantizeControlToHardware(rRow, rRow.value / Math.sqrt(ratio)); + const nextB = quantizeControlToHardware(bRow, bRow.value * ratio); + if (Math.abs(nextR - rRow.value) > 0.02) proposed.redGain = nextR; + if (Math.abs(nextB - bRow.value) > 0.02) proposed.blueGain = nextB; + if (proposed.redGain !== undefined || proposed.blueGain !== undefined) { + rationale.push(`检测到偏暖黄(R-B=${wbDiff}),调整 AWB 增益 R:${rRow.value.toFixed(2)}→${(proposed.redGain ?? rRow.value).toFixed(2)}、B:${bRow.value.toFixed(2)}→${(proposed.blueGain ?? bRow.value).toFixed(2)}`); + if (controls.autoWhiteBalance?.value === true) autoModeSwitches.push('autoWhiteBalance -> false'); + } + } else if (wbDiff < -20 || (wantWarmer && wbDiff < -6)) { + const ratio = Math.min(1.65, Math.max(1.12, 1 + (Math.abs(wbDiff) / 180))); + const nextR = quantizeControlToHardware(rRow, rRow.value * ratio); + const nextB = quantizeControlToHardware(bRow, bRow.value / Math.sqrt(ratio)); + if (Math.abs(nextR - rRow.value) > 0.02) proposed.redGain = nextR; + if (Math.abs(nextB - bRow.value) > 0.02) proposed.blueGain = nextB; + if (proposed.redGain !== undefined || proposed.blueGain !== undefined) { + rationale.push(`检测到偏冷蓝(R-B=${wbDiff}),调整 AWB 增益 R:${rRow.value.toFixed(2)}→${(proposed.redGain ?? rRow.value).toFixed(2)}、B:${bRow.value.toFixed(2)}→${(proposed.blueGain ?? bRow.value).toFixed(2)}`); + if (controls.autoWhiteBalance?.value === true) autoModeSwitches.push('autoWhiteBalance -> false'); + } + } + } + + // 3. Hardware CPROC (contrast / saturation / brightness) + const cRow = controls?.contrast; + const sRow = controls?.saturation; + const brRow = controls?.brightness; + if (cRow && Number.isFinite(cRow.value) && (metrics.hazeScore >= 0.42 || wantDehaze || metrics.contrastStd < 38)) { + const nextC = quantizeControlToHardware(cRow, Math.min(cRow.max, Math.max(cRow.value + 0.18, 1.18))); + if (Math.abs(nextC - cRow.value) > 0.02) { + proposed.contrast = nextC; + rationale.push(`画面反差偏平(标准差 ${metrics.contrastStd}),提升硬件对比度至 ${nextC.toFixed(2)}`); + } + if (brRow && Number.isFinite(brRow.value) && metrics.p05Luma > 34) { + const nextBr = quantizeControlToHardware(brRow, brRow.value - 8); + if (Math.abs(nextBr - brRow.value) >= 1) { + proposed.brightness = nextBr; + rationale.push(`黑位偏高(P05=${metrics.p05Luma}),下压硬件亮度至 ${nextBr}`); + } + } + } + if (sRow && Number.isFinite(sRow.value)) { + if (wantVivid || (metrics.meanSat < 22 && !wantNatural)) { + const nextS = quantizeControlToHardware(sRow, Math.min(sRow.max, Math.max(sRow.value + 0.20, 1.22))); + if (Math.abs(nextS - sRow.value) > 0.02) { + proposed.saturation = nextS; + rationale.push(`色彩偏淡(饱和度 ${metrics.meanSat}),提升硬件饱和度至 ${nextS.toFixed(2)}`); + } + } else if (wantNatural && sRow.value > 1.05) { + const nextS = quantizeControlToHardware(sRow, Math.max(sRow.min, sRow.value - 0.15)); + if (Math.abs(nextS - sRow.value) > 0.02) { + proposed.saturation = nextS; + rationale.push(`按自然色彩偏好回调硬件饱和度至 ${nextS.toFixed(2)}`); + } + } + } + + if (Object.keys(proposed).length === 0 && cRow && Number.isFinite(cRow.value)) { + const nextC = quantizeControlToHardware(cRow, Math.min(cRow.max, cRow.value + 0.1)); + if (Math.abs(nextC - cRow.value) > 0.01) { + proposed.contrast = nextC; + rationale.push(`当前画面基线已较均衡,建议轻度增强对比度至 ${nextC.toFixed(2)} 提升通透感`); + } + } + + return { + proposedValues: proposed, + autoModeSwitches, + rationale, + }; +} diff --git a/plugins/rdk-camera-workshop/mcp/robogo.mjs b/plugins/rdk-camera-workshop/mcp/robogo.mjs index 330a3a2..ecabbc8 100644 --- a/plugins/rdk-camera-workshop/mcp/robogo.mjs +++ b/plugins/rdk-camera-workshop/mcp/robogo.mjs @@ -1,9 +1,14 @@ import {createHash, randomBytes} from 'node:crypto'; import {open} from 'node:fs/promises'; -import {constants} from 'node:fs'; +import {constants, readFileSync} from 'node:fs'; import {homedir} from 'node:os'; import {isAbsolute,join} from 'node:path'; +const pluginVersion=(()=>{ + try { return JSON.parse(readFileSync(new URL('../plugin.json',import.meta.url),'utf8')).version||'0.7.5'; } + catch { return '0.7.5'; } +})(); + const issuer='https://sso.d-robotics.cc'; const oauth=issuer+'/api/userCenterApi/oauth/'; const resource='https://mcp.d-robotics.cc/api'; @@ -113,13 +118,22 @@ export function createRoboGo(send=fetch) { await refreshing; return tokens.access; } - async function rpc(method,params,notification=false) { + async function rpc(method,params,notification=false,{sessionOverride,retried=false}={}) { const id=++sequence; const headers={'Authorization':'Bearer '+await credential(),'Content-Type':'application/json', 'Accept':'application/json, text/event-stream','MCP-Protocol-Version':protocol}; - if(session) headers['Mcp-Session-Id']=session; + const activeSession=sessionOverride??session; + if(activeSession) headers['Mcp-Session-Id']=activeSession; const response=await request(endpoint,{method:'POST',headers,body:JSON.stringify({jsonrpc:'2.0',...(notification?{}:{id}),method,params})}); - if(response.status===401) {tokens=undefined;session=undefined;throw new Error('robogo_login_required');} + if(response.status===401) { + if(!retried&&tokens?.refresh) { + expiresAt=0; + session=undefined; + await credential(); + return rpc(method,params,notification,{sessionOverride,retried:true}); + } + tokens=undefined;session=undefined;throw new Error('robogo_login_required'); + } if(!response.ok) throw new Error('robogo_unavailable'); if(notification) return; const message=await readJson(response); @@ -127,10 +141,12 @@ export function createRoboGo(send=fetch) { return {result:message.result,sessionId:response.headers.get('mcp-session-id')}; } async function connect() { - const {result,sessionId}=await rpc('initialize',{protocolVersion:protocol,capabilities:{},clientInfo:{name:'rdk-vision-workshop',version:'0.7.0'}}); - session=sessionId??''; + const {result,sessionId}=await rpc('initialize',{protocolVersion:protocol,capabilities:{},clientInfo:{name:'rdk-vision-workshop',version:pluginVersion}}); + if(typeof result.protocolVersion!=='string'||!result.protocolVersion) throw new Error('robogo_response_invalid'); + const nextSession=sessionId??''; protocol=result.protocolVersion; - await rpc('notifications/initialized',undefined,true); + await rpc('notifications/initialized',undefined,true,{sessionOverride:nextSession}); + session=nextSession; } async function call(name,args) { await credential(); @@ -165,7 +181,7 @@ export function createRoboGo(send=fetch) { const list=await call('training_jobs',{action:'list',input:{}}); const jobs=list.data?.jobs; if(!Array.isArray(jobs)) throw new Error('robogo_response_invalid'); - lookup=jobName(jobs.find(job=>runId(job?.id??job?.job_id)===id)?.name); + lookup=jobName(jobs.find(job=>runId(job?.id??job?.jobId??job?.job_id)===id)?.name); } if(!lookup) throw new Error('robogo_run_name_required'); const result=await call('training_jobs',{action:'get',input:{name:lookup}}); @@ -220,7 +236,7 @@ export async function trainingProfile(filename=process.env.RDK_VISION_ROBOGO_TRA try { file=await open(filename,constants.O_RDONLY|(constants.O_NOFOLLOW??0)); const info=await file.stat(); - if(!info.isFile()||info.size>65536||process.platform!=='win32'&&info.uid!==process.getuid()) throw new Error('invalid_profile'); + if(!info.isFile()||info.size>65536||process.platform!=='win32'&&(info.uid!==process.getuid()||Boolean(info.mode&0o022))) throw new Error('invalid_profile'); const bytes=await file.readFile(); if(bytes.length>65536) throw new Error('large_profile'); const data=JSON.parse(bytes); diff --git a/plugins/rdk-camera-workshop/mcp/server.mjs b/plugins/rdk-camera-workshop/mcp/server.mjs index 792a1dd..a904720 100644 --- a/plugins/rdk-camera-workshop/mcp/server.mjs +++ b/plugins/rdk-camera-workshop/mcp/server.mjs @@ -1,11 +1,15 @@ #!/usr/bin/env node -import { isEntrypoint } from './entrypoint.mjs'; -import { readFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { existsSync, readFileSync, realpathSync } from 'node:fs'; import { createInterface } from 'node:readline'; +import { pathToFileURL } from 'node:url'; import { plan, guideMarkdown, tuningHandoffMarkdown } from './course.mjs'; import { guideCourse, guideSchema } from './guide.mjs'; import { labels, steps, stepEntries } from './steps.mjs'; -import { workbenchSession } from './workbench-session.mjs'; +import { recomputeCalibrationDemo } from './upstream-calibration.mjs'; +import { calibrationActionSchema, calibrationStatusSchema, validateCalibrationAction, validateCalibrationStatus } from './calibration-chat.mjs'; +import { ISP_EXAMPLE_PRESETS, ISP_EXAMPLE_SCENES, ispExample } from './isp-example.mjs'; +import { publishImage, studioMediaDir, workbenchBuild, workbenchSession } from './workbench-session.mjs'; const plugin=JSON.parse(readFileSync(new URL('../plugin.json',import.meta.url),'utf8')); const emptySchema={type:'object',properties:{},additionalProperties:false}; @@ -16,21 +20,79 @@ const tools=[ { name:'vision_course_stage',description:'查看当前阶段的操作和所需回执。',inputSchema:{type:'object',properties:{stageId:{type:'string',enum:stageIds}},required:['stageId'],additionalProperties:false},annotations:readOnly }, { name:'vision_course_next',description:'按时钟、已有回执和 RoboGO Run 引导下一步,记录 A/B/C 完成路径。只读规划。',inputSchema:guideSchema,annotations:readOnly }, { name:'vision_course_view',description:'启动本机可视化工作台并返回访问地址。Studio 面板需要单独打开。传入保存的 resume 可继续之前的进度。',inputSchema:guideSchema,annotations:readOnly }, - { name:'vision_course_sync',description:'同步当前 Studio 工作台。空参数读取最新进度;有 patch 时把本轮真实工具回执转交给学员界面。本工具只更新工位记录。',inputSchema:{type:'object',properties:{patch:guideSchema,clearBlockers:{type:'array',items:{type:'string'}}},additionalProperties:false},annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:true,openWorldHint:false} }, + { name:'vision_course_sync',description:'同步当前 Studio 工作台。空参数读取最新进度;有 patch 时把本轮真实工具回执转交给学员界面。本工具只更新实验记录。',inputSchema:{type:'object',properties:{patch:guideSchema,clearBlockers:{type:'array',items:{type:'string'}}},additionalProperties:false},annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:true,openWorldHint:false} }, { name:'vision_course_camera',description:'在当前已关联的相机实验里拍照、采集 RAW/ISP/渲染三图或重试渲染。用于「帮我拍张照」「采集基线图」。拍摄异步执行,调用回执仅表示开始。照片、三图和原件下载在返回的工作台,可通过只读 vision_course_camera_status 查询验收状态。',inputSchema:{type:'object',properties:{action:{type:'string',enum:['photo','baseline','retake','render']},scene:{type:'string',minLength:1,maxLength:100}},required:['action'],additionalProperties:false},annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false} }, - { name:'vision_course_camera_status',description:'查看刚才在课堂工位采集的照片或 RAW、ISP、重渲染三张基线。返回逐项进度、产物回执及并排展示的本机工作台地址,无需板端命令。',inputSchema:emptySchema,annotations:readOnly }, - { name:'vision_course_preflight',description:'检查工位相机服务、X5 板端连接、已开启相机流的实时帧。run:true 发起检查,空参数读取本轮状态。仅查询相机,不调参、不启动采流、不重启或烧录。',inputSchema:{type:'object',properties:{run:{type:'boolean'}},additionalProperties:false},annotations:readOnly }, - { name:'vision_course_isp',description:'课堂 Gamma 和单项 ISP。save 保存期初;gamma 执行两轮 Gamma;decision 记录 Gamma 取舍。learner_options 读取本工位可写项;learner_apply 仅接受一个 field、回读 expected 和候选 value;learner_decision 按 trial 记录取舍。revert 恢复原值;restore 恢复并停流。异步受理后查询 vision_course_isp_status。',inputSchema:{type:'object',properties:{action:{type:'string',enum:['save','gamma','decision','reload','revert','restore','learner_options','learner_apply','learner_decision']},goal:{type:'string',minLength:1,maxLength:180},round:{type:'integer',enum:[1,2]},choice:{type:'string',enum:['keep','restore']},reason:{type:'string',minLength:1,maxLength:180},field:{type:'string',pattern:'^[a-zA-Z]{1,40}$'},expected:{type:'number'},value:{type:'number'},trial:{type:'integer',minimum:1}},required:['action'],additionalProperties:false},annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false} }, - { name:'vision_course_isp_status',description:'查询工位原始快照、单项实操、恢复、独立回读与停流进度,返回回执 ID、哈希和工位页面链接。',inputSchema:emptySchema,annotations:readOnly }, + { name:'vision_course_camera_status',description:'查询当前实验的相机实验关联、最近一次预检、已归档照片和三图进度。用户要在 Studio 聊天看本轮照片时,传入拍照回执中的 photoRequestId。photoPreview 为 ready 时 Studio 直接展示已归档照片,pending 时可稍后查询,capture_failed 时检查 capture.errors.photo。空参数只查状态。实验关联以 cameraBinding 为准,baselineRequested 为 false 时尚无三图采集记录。此工具不会重新探测或采集。',inputSchema:{type:'object',properties:{photoRequestId:{type:'string',pattern:'^[a-f0-9-]{36}$'}},additionalProperties:false},annotations:readOnly }, + { name:'vision_course_preflight',description:'检查相机服务、X5 板端连接、已开启相机流的实时帧。run:true 发起检查,空参数读取本轮状态。仅查询相机,不调参、不启动采流、不重启或烧录。',inputSchema:{type:'object',properties:{run:{type:'boolean'}},additionalProperties:false},annotations:readOnly }, + { name:'vision_course_calibration_recompute',description:'用本机配置的 isp-calibration-tool Git 仓库,从固定提交重新运行合成 RAW 离线标定示例并返回实算指标和参数表哈希。只运行合成数据。若工具报告源码未配置,使用 vision_course_calibration_demo 查看课堂参考结果。',inputSchema:emptySchema,annotations:readOnly }, + { name:'vision_course_calibration_demo',description:'查看课堂离线标定示例。返回 GitHub isp-calibration-tool 固定提交对合成 RAW 的实际计算结果、参数文件哈希和预览图。用于「看看亮度和色彩是怎么标定出来的」或「看李乔龙的标定工具课堂示例」。',inputSchema:emptySchema,annotations:readOnly }, + { name:'vision_course_calibration_status',description:'读取当前课堂工作台所关联实验的离线标定引擎(ISPStudio / ispcal-lsc / NumPy)、已归档 RAW、色卡测量资产和任务。空参数读总览;查指定任务传 experimentId 和 taskId,选 task(进度)、result(参数摘要 + Studio 聊天气泡直接渲染 BLC/LSC/CCM/AWB 图表)或 apply_plan(只读 SDK 应用条件与上板工具提示)。',inputSchema:calibrationStatusSchema,annotations:readOnly }, + { name:'vision_course_calibration',description:'仅在学员明确要求时操作当前本组离线标定任务:create_dark(至少3张遮光暗场 RAW 算 BLC,需 darkConfirmed:true)、create_lsc(至少3张平场 RAW + 照度计读数 + 黑电平 + 网格,支持 ispcal-lsc/ispstudio/numpy)、create_awb(至少2组不同光源灰卡 RAW + ROI + 黑电平)、create_ccm(引用已归档色卡测量 assetId)、run(运行离线计算)。不直接写板卡;上板应用需在核对 apply_plan 后用相机插件 vision_calibration_apply。',inputSchema:calibrationActionSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false} }, + { name:'vision_course_isp_example',description:'只读自然语言 10 参数线性域图片 ISP 调试(纯 JS 零 Python 依赖)。支持 7 场景(lowlight/backlight/warm_wb/hazy/macro_detail/colorchecker/chart)、任意本地图或 10/12-bit Bayer RAW(imagePath)、右侧工作台已传图(useWorkbenchImage)或最新聊天图片附件(useLatestAttachment)。支持 2-Pass 自动诊断求解(action:"auto" / preset:"auto" 或仅传 goal)、10 项参数(exposureEv/shadows/highlights/gamma/brightness/contrast/saturation/wbShift/denoise/sharpness)、多轮增量微调(inheritCurrent/delta)、撤销(action:"undo")、查询当前工作台参数(action:"inspect")与成图导出(outputPath);返回真彩前后对照图、量化指标与诊断,并与右侧工作台双向实时同步。仅传 scene/gamma 时保持原版精确 Gamma 曲线。不连相机。',inputSchema:{type:'object',properties:{action:{type:'string',enum:['tune','auto','undo','inspect']},mode:{type:'string',enum:['auto','lab','gamma']},scene:{type:'string',enum:ISP_EXAMPLE_SCENES},imagePath:{type:'string',minLength:1,maxLength:512},useWorkbenchImage:{type:'boolean'},useLatestAttachment:{type:'boolean'},preset:{type:'string',enum:ISP_EXAMPLE_PRESETS},inheritCurrent:{type:'boolean'},delta:{type:'object',properties:{exposureEv:{type:'number'},shadows:{type:'number'},highlights:{type:'number'},gamma:{type:'number'},brightness:{type:'number'},contrast:{type:'number'},saturation:{type:'number'},wbShift:{type:'number'},denoise:{type:'number'},sharpness:{type:'number'}},additionalProperties:false},exposureEv:{type:'number',minimum:-2,maximum:2},shadows:{type:'number',minimum:-100,maximum:100},highlights:{type:'number',minimum:-100,maximum:100},gamma:{type:'number',minimum:0.55,maximum:1.45},brightness:{type:'number',minimum:-60,maximum:60},contrast:{type:'number',minimum:0.5,maximum:1.8},saturation:{type:'number',minimum:0,maximum:2},wbShift:{type:'number',minimum:-50,maximum:50},denoise:{type:'number',minimum:0,maximum:1},sharpness:{type:'number',minimum:0,maximum:2},rawWidth:{type:'integer',minimum:4,maximum:8192},rawHeight:{type:'integer',minimum:4,maximum:8192},bayerPattern:{type:'string',enum:['RGGB','BGGR','GRBG','GBRG']},bitDepth:{type:'integer',enum:[8,10,12,16]},blackLevel:{type:'number',minimum:0,maximum:4095},goal:{type:'string',minLength:1,maxLength:240},outputPath:{type:'string',minLength:1,maxLength:512}},additionalProperties:false},annotations:readOnly }, + { name:'vision_course_isp',description:'真实 X5 相机硬件 ISP 调试。save 保存期初快照(任何调参前必须先保存);auto_plan 只读采帧分析并给出硬件量化后的多参数建议(不写板);multi_apply 安全联调多项硬件参数(values 支持 exposureUs/gain/redGain/blueGain/brightness/contrast/saturation/hue,自动按需切手动 AE/AWB、硬件步进量化、独立回读并拍调前/调后实拍计算客观指标,支持连续多轮迭代);gamma_prepare/gamma_apply/gamma_discard/gamma/decision 用于两轮 Gamma;learner_options/learner_apply/learner_decision 用于课堂单项练习;revert 恢复原值;restore 恢复并停流。异步受理后查询 vision_course_isp_status(传 trial 可在聊天直接展示真机调前/调后对照图)。',inputSchema:{type:'object',properties:{action:{type:'string',enum:['save','gamma','gamma_prepare','gamma_apply','gamma_discard','decision','reload','revert','restore','learner_options','learner_apply','learner_decision','auto_plan','multi_apply']},goal:{type:'string',minLength:1,maxLength:180},round:{type:'integer',enum:[1,2]},choice:{type:'string',enum:['keep','restore']},reason:{type:'string',minLength:1,maxLength:180},field:{type:'string',pattern:'^[a-zA-Z]{1,40}$'},expected:{type:'number'},value:{type:'number'},values:{type:'object',properties:{exposureUs:{type:'number'},gain:{type:'number'},redGain:{type:'number'},blueGain:{type:'number'},brightness:{type:'number'},contrast:{type:'number'},saturation:{type:'number'},hue:{type:'number'}},additionalProperties:false},trial:{type:'integer',minimum:1},candidateId:{type:'string',pattern:'^[a-f0-9-]{36}$'}},required:['action'],additionalProperties:false},annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false} }, + { name:'vision_course_isp_status',description:'查询实验原始快照、单项实操、恢复、独立回读与停流进度。要在聊天显示调前调后实拍,按回执传一个 Gamma round 或单项 trial。ispPreview 为 ready 时已交付对照图。空参数只查状态。',inputSchema:{type:'object',properties:{round:{type:'integer',enum:[1,2]},trial:{type:'integer',minimum:1}},additionalProperties:false},annotations:readOnly }, + { name:'vision_course_detection_status',description:'在 Studio 聊天展示当前实验选定模型最近一张已校验的板端检测归档帧、类别和置信度。只读,不启动检测。持续预览使用返回的工作台地址。',inputSchema:emptySchema,annotations:readOnly }, ]; const content=data=>({content:[{type:'text',text:JSON.stringify(data)}],isError:false}); const reply=(req,body)=>({jsonrpc:'2.0',id:req.id,...body}); const rpcError=(req,code,message)=>reply(req,{error:{code,message}}); -const invalid=(req,error)=>reply(req,{result:{content:[{type:'text',text:JSON.stringify({error:error.message})}],isError:true}}); +const ERROR_HINTS={ + open_workbench_first:'本机课堂工作台尚未打开。先调用 vision_course_view 启动工作台并交给 studio_open_url,再同步记录。', + camera_unconfigured:'尚未配置相机服务连接(~/.config/rdk-camera-workshop/connection.json)。请先在相机插件完成连接设置与自检,再重试。', + camera_credential_missing:'相机连接配置存在,但凭据文件缺失。请先在相机插件重新登录或写入凭据,再重试。', + camera_configuration_invalid:'相机连接配置文件或权限无效(需绝对路径、0600 权限、合法 MCP 地址与凭据)。请运行相机插件自检修复。', + camera_auth_required:'相机服务认证失败(401/403)。请检查 Studio SSO 登录态或管理员令牌,重新登录后重试。', + camera_binding_required:'当前课堂工作台尚未绑定本组相机实验。请打开工作台「相机与预检」关联实验,或通过 vision_course_sync 写入 camera.experimentId。', + camera_binding_invalid:'传入的 experimentId 与工作台当前绑定的相机实验不一致,或当前实验已切换。请先调用 vision_course_camera_status 确认最新绑定。', + camera_isp_stream_required:'相机当前未处于实时采流状态(或 pipeline_validate 未通过)。请先在相机插件启动预览/采流,再执行 ISP 读取或调试。', + camera_isp_snapshot_missing:'尚未保存本实验期初 ISP 快照。请先调用 vision_course_isp({action:"save"}) 保存原始配置,确保随时可一键恢复。', + camera_isp_snapshot_changed:'板端实时 ISP 配置或期初基线与记录不一致(可能有外部修改或重新采流)。请先核对当前配置并按需恢复期初快照。', + camera_recovery_required:'上一次 ISP 写入或恢复尚未确认闭合。严禁继续发起新写入,请先调用 vision_course_isp({action:"revert"}) 或 restore 核对并恢复期初快照。', + camera_capture_busy:'本组相机正在执行另一项操作(预检、采图、ISP 调试或板端检测)。请等待当前操作结束并通过对应 *_status 查询进度后再试。', + vision_device_busy:'板端相机设备正忙(HTTP 429,本次未写入硬件)。请等待数秒待并发请求完成后直接重试,切勿强行重置。', + vision_device_archive_capacity:'当前实验的设备操作归档条数已达上限。先核对 ISP 已恢复且已停流,再在同设备上新建实验继续并保留旧归档。', + vision_device_history_capacity:'当前实验的操作历史已达上限。先核对 ISP 已恢复且已停流,再在同设备上新建实验继续并保留旧归档。', + vision_recovery_recording_failed:'板端 SDK 恢复已确认成功,但服务端写回恢复记录失败。切勿盲目重试写入或覆盖快照,请立即联系助教核对实验记录。', + vision_calibration_illuminant_selection_required:'AWB 多光源标定结果包含多个色温/光源,上板应用时必须传 options: { illuminantId: "<光源ID>" }(可先查标定 result 查看可用光源列表)。', + vision_calibration_roi_bounds_or_bayer_alignment_invalid:'AWB 灰卡 ROI 必须满足 width≥4、height≥4 且 x/y/width/height 均为偶数(2×2 Bayer 对齐),且不能超出图像边界。', + robogo_login_required:'RoboGO OAuth 授权尚未完成或已失效。请在工作台「训练与量化」点击「连接 RoboGO」完成授权后重试。', + board_launcher_locked:'板端检测已有另一任务持有设备锁或上次运行未释放锁。请确认无并发检测运行并核对归档目录后再试。', + camera_archive_quota_full:'当前账号的证据归档存储配额已满。请联系助教清理旧归档或扩容后再试。', +}; +const invalid=(req,error)=>{ + const hint=error.hint??ERROR_HINTS[error.message]; + return reply(req,{result:{content:[{type:'text',text:JSON.stringify({error:error.message,...(hint?{hint}:{})})}],isError:true}}); +}; const session=workbenchSession(process.env.RDK_VISION_COURSE_SESSION_DIR); +async function imageResult(status,images,preview) { + const mediaDir=studioMediaDir(); + if(mediaDir) { + try { + const {bytes,sha256,label,mimeType='image/png'}=preview; + const image=await publishImage(mediaDir,{mimeType,sha256},bytes,label); + return content({...status,__type:'studio_local_preview',ok:true,...image}); + } catch { + // Plain MCP image blocks also work outside Studio. + } + } + const result=content(status); + for(const {bytes,mimeType='image/png'} of images) result.content.push({type:'image',mimeType,data:bytes.toString('base64')}); + return result; +} + +const calibrationDemoRoot=new URL('../web/calibration-demo/',import.meta.url); +function calibrationDemo() { + const status=JSON.parse(readFileSync(new URL('result.json',calibrationDemoRoot),'utf8')); + const bytes=readFileSync(new URL('preview.png',calibrationDemoRoot)); + if(createHash('sha256').update(bytes).digest('hex')!==status.sha256['preview.png']) { + throw new Error('calibration_demo_preview_mismatch'); + } + return {status,preview:{bytes,sha256:status.sha256['preview.png'],label:'标定输入预览 · D65 合成平场'}}; +} + export async function dispatch(req) { if (!req || req.jsonrpc!=='2.0' || typeof req.method!=='string') return rpcError(req??{},-32600,'Invalid request'); if (req.id===undefined) return null; @@ -58,36 +120,82 @@ export async function dispatch(req) { if (name==='vision_course_next') return respond(content(guideCourse(plan,args))); if (name==='vision_course_view') { guideCourse(plan,args); - const url=await session.open(); - if (Object.keys(args).length) await session.sync({patch:args}); - return respond(content({url,title:'视觉 Pipeline · 课堂工作台',scope:'this_computer', - instruction:'返回地址表示课堂服务已就绪。请调用 studio_open_url 让 Studio 显示工作台;工具不可用时给出 Markdown 链接 [打开课堂工作台](返回地址),并提示学员点击。'})); + const allowPrevious=Object.keys(args).length===0; + const url=await session.open({allowPrevious}); + if (!allowPrevious) await session.sync({patch:args}); + const current=await session.sync(undefined,{allowPrevious}); + const legacy=current.workbenchBuild!==workbenchBuild; + const nextStep=guideCourse(plan,current.resume).nextStep; + return respond(content({url,...(legacy?{previousWorkbench:true}:{}),title:'视觉 Pipeline · 课堂工作台',scope:'this_computer', + openInStudio:{url,target:'local'},nextStep,...(current.recentUiEvents?.length?{recentUiEvents:current.recentUiEvents}:{}), + instruction:(legacy?'原实验仍运行旧界面。可继续原实验。需要新版界面时请先导出进度和成果,关闭旧工作台并重启 RDK Studio 后再打开工作台。':'')+'请用 openInStudio 的原始参数调用 studio_open_url。工具不可用时给出可点击的 [打开课堂工作台] 链接。请按 nextStep 给出当前一个动作和验收条件。仅打开课堂时无需连接设备或启动采集。'})); } if (name==='vision_course_sync') { if (Object.keys(args).some(key=>!['patch','clearBlockers'].includes(key))) throw new Error('invalid_arguments'); const body=Object.keys(args).length?{patch:args.patch??{},clearBlockers:args.clearBlockers}:undefined; const updated=await session.sync(body); - return respond(content({...guideCourse(plan,updated.resume),revision:updated.revision})); + return respond(content({...guideCourse(plan,updated.resume),revision:updated.revision, + ...(updated.recentUiEvents?.length?{recentUiEvents:updated.recentUiEvents}:{})})); } if (name==='vision_course_camera') { if (!Object.hasOwn(args,'action')||Object.keys(args).some(key=>!['action','scene'].includes(key))) throw new Error('invalid_arguments'); return respond(content(await session.camera(args))); } if (name==='vision_course_camera_status') { - if (Object.keys(args).length) throw new Error('invalid_arguments'); - return respond(content(await session.camera())); + if (Object.keys(args).some(key=>key!=='photoRequestId')|| + Object.hasOwn(args,'photoRequestId')&&(typeof args.photoRequestId!=='string'||!/^[a-f0-9-]{36}$/.test(args.photoRequestId))) { + throw new Error('invalid_arguments'); + } + return respond(content(await session.cameraStatus(args.photoRequestId))); } if (name==='vision_course_preflight') { if(Object.keys(args).some(k=>k!=='run')||args.run!==undefined&&typeof args.run!=='boolean') throw new Error('invalid_arguments'); return respond(content(await session.preflight(args.run))); } + if(name==='vision_course_calibration_recompute') { + if(Object.keys(args).length) throw new Error('invalid_arguments'); + return respond(content(await recomputeCalibrationDemo())); + } + if(name==='vision_course_calibration_demo') { + if(Object.keys(args).length) throw new Error('invalid_arguments'); + const {status,preview}=calibrationDemo(); + return respond(await imageResult(status,[preview],preview)); + } + if(name==='vision_course_calibration_status') { + return respond(content(await session.calibration(validateCalibrationStatus(args)))); + } + if(name==='vision_course_calibration') { + return respond(content(await session.calibration(validateCalibrationAction(args),true))); + } + if(name==='vision_course_isp_example') { + const needWbImage=args.useWorkbenchImage===true||args.action==='inspect'|| + (!args.scene&&!args.imagePath&&args.useLatestAttachment!==true&&(args.inheritCurrent===true||args.delta!==undefined||args.action==='auto'||args.mode==='auto'||args.preset==='auto'||Boolean(args.goal))); + const workbenchPractice=args.action==='undo'?null:await session.readPractice(needWbImage).catch(()=>null); + const outcome=ispExample(args,{workbenchPractice}); + if(outcome.undoRequested) { + const undone=await session.undoPractice(); + if(!undone?.ok) throw Object.assign(new Error(undone?.error??'practice_undo_unavailable'),{hint:'当前工作台没有可撤销的上一版 ISP 参数记录。'}); + return respond(content({mode:'undo',ok:true,deviceUsed:false,restored:undone.practice})); + } + const {status,images,preview,practiceSync}=outcome; + if(!preview||!images?.length) return respond(content(status)); + const sync=await session.syncPractice(practiceSync).catch(()=>({synced:false})); + return respond(await imageResult({...status,...(sync?.synced?{workbenchSynced:true,historyCount:sync.practice?.historyCount,canUndo:sync.practice?.canUndo}:{})},images,preview)); + } if(name==='vision_course_isp') { - if(!Object.hasOwn(args,'action')||Object.keys(args).some(k=>!['action','goal','round','choice','reason','field','expected','value','trial'].includes(k))) throw new Error('invalid_arguments'); + if(!Object.hasOwn(args,'action')||Object.keys(args).some(k=>!['action','goal','round','choice','reason','field','expected','value','values','trial','candidateId'].includes(k))) throw new Error('invalid_arguments'); return respond(content(await session.isp(args))); } if(name==='vision_course_isp_status') { + const keys=Object.keys(args); + if(keys.length>1||keys.some(key=>key!=='round'&&key!=='trial')|| + Object.hasOwn(args,'round')&&![1,2].includes(args.round)|| + Object.hasOwn(args,'trial')&&(!Number.isSafeInteger(args.trial)||args.trial<1)) throw new Error('invalid_arguments'); + return respond(content(await session.isp(undefined,keys.length?args:undefined))); + } + if(name==='vision_course_detection_status') { if(Object.keys(args).length) throw new Error('invalid_arguments'); - return respond(content(await session.isp())); + return respond(content(await session.detection())); } throw new Error('unknown_tool'); } catch(error) { @@ -95,7 +203,8 @@ export async function dispatch(req) { } } -if (isEntrypoint(import.meta)) { +const entry=process.argv[1]; +if (entry && existsSync(entry) && import.meta.url===pathToFileURL(realpathSync(entry)).href) { const rx=createInterface({input:process.stdin,crlfDelay:Infinity}); rx.on('line',async line=>{ let input; diff --git a/plugins/rdk-camera-workshop/mcp/setup.mjs b/plugins/rdk-camera-workshop/mcp/setup.mjs index 0afe131..5901cf8 100644 --- a/plugins/rdk-camera-workshop/mcp/setup.mjs +++ b/plugins/rdk-camera-workshop/mcp/setup.mjs @@ -1,6 +1,5 @@ #!/usr/bin/env node /** Local onboarding. No token arguments, host-settings edits or camera writes. */ -import { isEntrypoint } from './entrypoint.mjs'; import { mkdir, mkdtemp, writeFile, rm, link, realpath } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import path from 'node:path'; @@ -16,7 +15,8 @@ export async function configure({ url, auth, credentialFile, config = resolveCon const scratch = await mkdtemp(path.join(tmpdir(), 'camera-setup-')); const temporary = path.join(scratch, 'connection.json'); try { - const content = JSON.stringify({ url, auth: { type: auth, credentialFile: await realpath(credentialFile) } }, null, 2) + '\n'; + const credentialPath = await realpath(credentialFile).catch(() => { throw new Error('camera_bridge_credential_unavailable'); }); + const content = JSON.stringify({ url, auth: { type: auth, credentialFile: credentialPath } }, null, 2) + '\n'; await writeFile(temporary, content, { mode: 0o600, flag: 'wx' }); await validateConfiguration(temporary); await mkdir(path.dirname(config), { recursive: true, mode: 0o700 }); @@ -40,6 +40,7 @@ const CAPABILITY_CHAINS = { core: ['vision_workshop_runtime_status', 'vision_experiment_create', 'vision_experiment_list', 'vision_experiment_get', 'vision_camera_readiness'], knowledge: ['vision_camera_knowledge_search', 'vision_camera_knowledge_get'], bringup: ['vision_camera_probe', 'vision_pipeline_validate', 'vision_camera_bringup', 'vision_camera_capture_frame', 'vision_camera_controls_get'], + preview: ['vision_camera_preview_start', 'vision_camera_preview_frame', 'vision_camera_preview_stop'], aiDebug: ['vision_ai_debug_start', 'vision_ai_debug_status', 'vision_ai_debug_cancel', 'vision_ai_debug_restore_original'], isp: ['vision_raw_capture', 'vision_isp_generate', 'vision_isp_process_raw', 'vision_isp_apply', 'vision_isp_restore', 'vision_isp_tuning_get', 'vision_isp_tuning_load'], calibration: ['vision_calibration_task_create', 'vision_calibration_task_run', 'vision_calibration_task_result', 'vision_calibration_apply_plan', 'vision_calibration_apply'], @@ -55,10 +56,28 @@ export function chainReadiness(names) { } const connectedNext = chains => { const base = '在宿主中读取 runtime_status,选择实际登记的设备;连接成功不代表相机已点亮。'; - const delivery = chains?.delivery; - return delivery?.status === 'ready' ? base - : base + '服务端缺少交付/验收工具:' + (delivery?.missing ?? []).join('、') + ';workshop 交付与验收前先升级服务端。'; + const missing = Object.entries(chains).filter(([, chain]) => chain.status === 'missing'); + return missing.length ? base + '服务端缺少工作流工具:' + missing.map(([name, chain]) => name + '(' + chain.missing.join('、') + ')').join(';') + ';使用这些工作流前先升级服务端。' : base; }; +// Check the documented runtime contract, not merely an MCP envelope. Never return its private body. +function runtimeSummary(result) { + if (!result || result.isError) throw new Error('camera_setup_runtime_unavailable'); + const content = result.content; + if (!Array.isArray(content) || content.length !== 1 || content[0]?.type !== 'text' || typeof content[0].text !== 'string') throw new Error('camera_setup_runtime_invalid'); + let payload; + try { payload = JSON.parse(content[0].text); } catch { throw new Error('camera_setup_runtime_invalid'); } + const record = value => value !== null && typeof value === 'object' && !Array.isArray(value); + if (!record(payload) || payload.ok !== true) throw new Error('camera_setup_runtime_invalid'); + let data = payload; + if (Object.hasOwn(payload, 'data')) { + if (!Number.isInteger(payload.status) || payload.status < 200 || payload.status >= 300) throw new Error('camera_setup_runtime_invalid'); + data = payload.data; + } + if (!record(data) || data.ok !== true || data.contract !== 'rdk.vision-workshop.v1' || typeof data.modelEnabled !== 'boolean' + || !record(data.aiDebug) || !['available', 'unavailable'].includes(data.aiDebug.status) || !Array.isArray(data.deviceAdapters) + || !data.deviceAdapters.every(record)) throw new Error('camera_setup_runtime_invalid'); + return { contract: data.contract, modelEnabled: data.modelEnabled, aiDebug: data.aiDebug.status, configuredDeviceAdapters: data.deviceAdapters.length }; +} async function probe(config) { return new Promise((resolve, reject) => { const child = spawn(process.execPath, [path.join(here, 'bridge.mjs')], { @@ -84,13 +103,14 @@ async function probe(config) { const names = message.result.tools.map(tool => tool.name); if (!names.some(name => name !== 'vision_connection_status')) return finish(new Error('camera_setup_no_remote_tools')); toolCount = names.length; chains = chainReadiness(names); - if (!names.includes('vision_workshop_runtime_status')) return finish(null, { status: 'tools_available', toolCount: names.length, runtime: 'unverified', hardware: 'unverified', chains }); + if (!names.includes('vision_workshop_runtime_status')) return finish(new Error('camera_setup_runtime_tool_missing')); child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'vision_workshop_runtime_status', arguments: {} } }) + '\n'); } if (message.id === 2) { // Do not echo upstream bodies: they may contain device addresses or private runtime details. - if (message.result?.isError || !message.result || !Array.isArray(message.result.content)) return finish(new Error('camera_setup_runtime_unavailable')); - finish(null, { status: 'connected', toolCount, runtime: 'responded', hardware: 'unverified', chains, next: connectedNext(chains) }); + let capabilities; + try { capabilities = runtimeSummary(message.result); } catch (error) { return finish(error); } + finish(null, { status: 'connected', toolCount, runtime: 'validated', capabilities, hardware: 'unverified', chainVerification: 'tool-directory-only', chains, next: connectedNext(chains) }); } } }); @@ -124,7 +144,7 @@ export async function main(argv = process.argv.slice(2)) { ], notes: 'configure 不覆盖已有配置,不接收 token;client-config 仅打印本机绝对路径配置,不修改宿主设置。' }; throw new Error('camera_setup_arguments_invalid'); } -if (isEntrypoint(import.meta)) { +if (process.argv[1] && await realpath(process.argv[1]).catch(() => '') === fileURLToPath(import.meta.url)) { main().then(result => process.stdout.write(JSON.stringify(result, null, 2) + '\n')).catch(error => { // Only locally defined error codes; never print paths, URLs, secrets or raw OS errors. const code = /^camera_(?:bridge|setup)_[a-z0-9_]+$/.test(error.message) ? error.message : error.code === 'EEXIST' ? 'camera_setup_config_exists' : 'camera_setup_failed'; diff --git a/plugins/rdk-camera-workshop/mcp/setup.test.mjs b/plugins/rdk-camera-workshop/mcp/setup.test.mjs deleted file mode 100644 index b77249e..0000000 --- a/plugins/rdk-camera-workshop/mcp/setup.test.mjs +++ /dev/null @@ -1,118 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { mkdtemp, writeFile, readFile, chmod, rm, stat } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import path from 'node:path'; -import { createServer } from 'node:http'; -import { spawnSync } from 'node:child_process'; -import { configure, doctor, clientConfig, wireErrorCode, chainReadiness } from './setup.mjs'; - -async function fixture(fn) { - const directory = await mkdtemp(path.join(tmpdir(), 'camera-onboarding-')); - const credentialFile = path.join(directory, 'credential'); const config = path.join(directory, 'connection.json'); - await writeFile(credentialFile, 'private-fixture-token', { mode: 0o600 }); - try { await fn({ directory, credentialFile, config }); } finally { await rm(directory, { recursive: true, force: true }); } -} -test('configure creates private validated config without overwriting existing files', async () => fixture(async ({ credentialFile, config }) => { - const input = { url: 'http://127.0.0.1:9/api/ops/vision-workshop/mcp', auth: 'sso', credentialFile, config }; - assert.equal((await configure(input)).status, 'configured'); - assert.equal((await stat(config)).mode & 0o777, 0o600); - const before = await readFile(config, 'utf8'); assert.equal(JSON.parse(before).auth.type, 'sso'); - await assert.rejects(configure({ ...input, auth: 'admin' }), { code: 'EEXIST' }); - assert.equal(await readFile(config, 'utf8'), before); -})); -test('invalid URL and public credential permissions cannot create a config', async () => fixture(async ({ credentialFile, config }) => { - for (const url of ['http://external.invalid/api/ops/vision-workshop/mcp', 'https://example.invalid/wrong', 'https://example.invalid/api/ops/vision-workshop/mcp?secret=x']) { - await assert.rejects(configure({ url, auth: 'sso', credentialFile, config }), /camera_bridge_url_invalid/); - await assert.rejects(stat(config), { code: 'ENOENT' }); - } - await chmod(credentialFile, 0o644); - await assert.rejects(configure({ url: 'https://example.invalid/api/ops/vision-workshop/mcp', auth: 'admin', credentialFile, config }), /permissions_invalid/); -})); -test('doctor traverses actual stdio bridge and only calls read-only runtime status', async () => fixture(async ({ credentialFile, config }) => { - const calls = []; - const server = createServer(async (request, response) => { - assert.equal(request.headers['x-rdk-sso-session'], 'private-fixture-token'); - let body = ''; for await (const part of request) body += part; - const message = JSON.parse(body); calls.push(message); - const result = message.method === 'tools/list' ? { tools: [{ name: 'vision_workshop_runtime_status', description: 'Runtime fixture', inputSchema: { type: 'object' } }] } : { content: [{ type: 'text', text: 'fixture-private-device-state' }], isError: false }; - response.setHeader('content-type', 'application/json'); response.end(JSON.stringify({ jsonrpc: '2.0', id: message.id, result })); - }); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - try { - await configure({ url: 'http://127.0.0.1:' + server.address().port + '/api/ops/vision-workshop/mcp', auth: 'sso', credentialFile, config }); - const result = await doctor(config); - assert.equal(result.status, 'connected'); assert.equal(result.hardware, 'unverified'); assert.equal(result.toolCount, 1); - assert.deepEqual(calls.map(call => call.method), ['tools/list', 'tools/call']); - assert.equal(calls[1].params.name, 'vision_workshop_runtime_status'); - assert.ok(!JSON.stringify(result).includes('fixture-private')); - } finally { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); } -})); -test('doctor distinguishes unconfigured, service refusal and tool execution errors', async () => fixture(async ({ credentialFile, config }) => { - await assert.rejects(doctor(config), /unconfigured/); - const server = createServer((_request, response) => { response.writeHead(403); response.end('private error'); }); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - try { - await configure({ url: 'http://127.0.0.1:' + server.address().port + '/api/ops/vision-workshop/mcp', auth: 'sso', credentialFile, config }); - await assert.rejects(doctor(config), /camera_bridge_remote_http_403/); - } finally { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); } -})); -test('fallback configuration uses executable and bridge absolute paths independent of cwd', () => { - const config = clientConfig().mcpServers['rdk-camera-workshop']; - assert.ok(path.isAbsolute(config.command)); assert.ok(path.isAbsolute(config.args[0])); - const result = spawnSync(config.command, config.args, { cwd: tmpdir(), input: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05' } }) + '\n', encoding: 'utf8' }); - assert.equal(result.status, 0); assert.equal(JSON.parse(result.stdout).result.protocolVersion, '2024-11-05'); -}); - -test('wire messages with appended hints normalize to the bare CLI error code', () => { - assert.equal(wireErrorCode('camera_bridge_remote_transport_failed: 无法访问相机服务,请检查服务运行状态、地址和网络。'), 'camera_bridge_remote_transport_failed'); - assert.equal(wireErrorCode('camera_bridge_unconfigured'), 'camera_bridge_unconfigured'); - assert.equal(wireErrorCode('camera_bridge_remote_http_403: 认证失效,请在原服务更新凭据后重试。'), 'camera_bridge_remote_http_403'); - assert.equal(wireErrorCode('Unexpected token < in JSON'), 'camera_setup_response_invalid'); - assert.equal(wireErrorCode(undefined), 'camera_setup_response_invalid'); -}); - -test('chainReadiness names the missing typed tools per workflow without inventing a fallback', () => { - const chains = chainReadiness(['vision_workshop_runtime_status', 'vision_camera_probe', 'vision_workshop_delivery']); - assert.equal(chains.core.status, 'missing'); - assert.deepEqual(chains.core.missing, ['vision_experiment_create', 'vision_experiment_list', 'vision_experiment_get', 'vision_camera_readiness']); - assert.equal(chains.bringup.status, 'missing'); - assert.ok(chains.bringup.missing.includes('vision_pipeline_validate')); - assert.equal(chains.delivery.status, 'missing'); - assert.ok(chains.delivery.missing.includes('vision_acceptance_record')); - const ready = chainReadiness(['vision_workshop_delivery', 'vision_delivery_target_select', 'vision_acceptance_plan_save', 'vision_acceptance_record', 'vision_workshop_export']); - assert.equal(ready.delivery.status, 'ready'); - assert.ok(!('missing' in ready.delivery)); -}); - -test('doctor reports per-chain readiness from the actual remote tools directory', async () => fixture(async ({ credentialFile, config }) => { - const remoteTools = ['vision_workshop_runtime_status', 'vision_experiment_create', 'vision_experiment_list', 'vision_experiment_get', 'vision_camera_readiness', - 'vision_camera_knowledge_search', 'vision_camera_knowledge_get', - 'vision_camera_probe', 'vision_pipeline_validate', 'vision_camera_bringup', 'vision_camera_capture_frame', 'vision_camera_controls_get', - 'vision_ai_debug_start', 'vision_ai_debug_status', 'vision_ai_debug_cancel', 'vision_ai_debug_restore_original', - 'vision_raw_capture', 'vision_isp_generate', 'vision_isp_process_raw', 'vision_isp_apply', 'vision_isp_restore', 'vision_isp_tuning_get', 'vision_isp_tuning_load', - 'vision_calibration_task_create', 'vision_calibration_task_run', 'vision_calibration_task_result', 'vision_calibration_apply_plan', 'vision_calibration_apply', - 'vision_workshop_delivery', 'vision_workshop_export']; - const server = createServer(async (request, response) => { - let body = ''; for await (const part of request) body += part; - const message = JSON.parse(body); - const result = message.method === 'tools/list' - ? { tools: remoteTools.map(name => ({ name, description: 'fixture', inputSchema: { type: 'object' } })) } - : { content: [{ type: 'text', text: 'fixture-runtime-ok' }], isError: false }; - response.setHeader('content-type', 'application/json'); response.end(JSON.stringify({ jsonrpc: '2.0', id: message.id, result })); - }); - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); - try { - await configure({ url: 'http://127.0.0.1:' + server.address().port + '/api/ops/vision-workshop/mcp', auth: 'sso', credentialFile, config }); - const result = await doctor(config); - assert.equal(result.chains.core.status, 'ready'); - assert.equal(result.chains.knowledge.status, 'ready'); - assert.equal(result.chains.bringup.status, 'ready'); - assert.equal(result.chains.aiDebug.status, 'ready'); - assert.equal(result.chains.isp.status, 'ready'); - assert.equal(result.chains.calibration.status, 'ready'); - assert.equal(result.chains.delivery.status, 'missing'); - assert.deepEqual(result.chains.delivery.missing, ['vision_delivery_target_select', 'vision_acceptance_plan_save', 'vision_acceptance_record']); - assert.ok(result.next.includes('升级服务端')); - } finally { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); } -})); diff --git a/plugins/rdk-camera-workshop/mcp/steps.mjs b/plugins/rdk-camera-workshop/mcp/steps.mjs index 4c8eae9..ae81425 100644 --- a/plugins/rdk-camera-workshop/mcp/steps.mjs +++ b/plugins/rdk-camera-workshop/mcp/steps.mjs @@ -13,7 +13,7 @@ export const stepEntries={ gamma_trial:{section:'camera-isp',label:'打开第 2 轮自主'}, blind:{section:'comparison',label:'打开盲选'}, reproduce:{section:'camera-isp',label:'打开 ISP 版本与回读'}, - deploy:{section:'board',label:'核对本组板端回执'}, + deploy:{section:'board',label:'打开本组模型检测'}, live:{section:'board',label:'查看板端检测证据'}, preset_deploy:{section:'board',label:'核对预置模型板端结果'}, restore:{section:'camera-isp',label:'打开恢复与停流'}, @@ -22,16 +22,16 @@ export const stepEntries={ // Evidence field labels double as short pass conditions in the workbench. export const labels = { - group_and_target_identified: '本人工位、设备和一句观察目标', + group_and_target_identified: '本人实验、设备和一句观察目标', plugin_tools_available: '相机工具连接结果', - current_device_identity: '本工位 X5、IMX415 与实际模式', + current_device_identity: '本组 X5、IMX415 与实际模式', fresh_camera_image: '本轮相机新图', original_snapshot: '可恢复的原始 ISP 快照', baseline_images: '固定场景的基线图与素材来源', baseline_raw: '本人相机的 Bayer RAW 文件与采集回执', - baseline_raw_sample: 'RAW 样例来源与本工位实采未完成原因', - baseline_isp: '本工位的 ISP 显示图', - baseline_render: '本工位的渲染图', + baseline_raw_sample: 'RAW 样例来源与本组实采未完成原因', + baseline_isp: '本组的 ISP 显示图', + baseline_render: '本组的渲染图', label_schema: '数据集类别顺序', grouped_split: '训练与验证划分', dataset_version: '数据集版本或清单', @@ -77,7 +77,7 @@ export const labels = { preset_target_result: '预置模型目标检出结果', preset_detection_receipt: '预置检测回执文件哈希', restoration_and_release: '原始配置回读、停止采集与释放', - device_unused: '本工位没有启动相机或写参数的记录', + device_unused: '本组没有启动相机或写参数的记录', camera_and_model_manifest: '个人成果包与模型、参数来源', remaining_work: '未完成事项或完整完成记录', package_opened: '下载、解压和打开文件的核对记录', @@ -87,25 +87,25 @@ export const labels = { }; export const steps = { - intro: { title:'写下一个观察目标', ask:'选一个想看得更清楚的区域,写一句目标并核对工位。', fields:['group_and_target_identified'] }, - connect: { title:'让本工位相机出图', ask:'关联相机实验并运行连接预检。没有画面时从相机插件点亮,回到这里重新检查。', actions:['选本工位设备,核对相机服务、X5 和实时画面。','通过后,在照片卡保存一张本轮新图。','保存原始 ISP,确认已取得可恢复版本。'], tool:'vision_course_preflight → vision_course_camera → vision_course_isp', fields:['plugin_tools_available','current_device_identity','fresh_camera_image','original_snapshot'] }, - baseline: { title:'固定机位,保存三种基线图', ask:'固定机位、目标和光照。打开三图采集,核对 RAW、ISP 显示图和同组 RAW 的渲染图。', actions:['关联本工位相机实验。','填写固定场景,启动三图采集。','检查每张图的归档状态和原件。遇到渲染前提缺失时保留已采图,按提示补齐。'], tool:'vision_course_camera → vision_course_camera_status', fields:['baseline_images','baseline_raw','baseline_isp','baseline_render'] }, + intro: { title:'写下一个观察目标', ask:'选一个想看得更清楚的区域,写一句目标并核对实验。', fields:['group_and_target_identified'] }, + connect: { title:'让本组相机出图', ask:'关联相机实验并运行连接预检。没有画面时从相机插件点亮,回到这里重新检查。', actions:['选本组设备,核对相机服务、X5 和实时画面。','通过后,在照片卡保存一张本轮新图。','保存原始 ISP,确认已取得可恢复版本。'], tool:'vision_course_preflight → vision_course_camera → vision_course_isp', fields:['plugin_tools_available','current_device_identity','fresh_camera_image','original_snapshot'] }, + baseline: { title:'固定机位,保存三种基线图', ask:'固定机位、目标和光照。打开三图采集,核对 RAW、ISP 显示图和同组 RAW 的渲染图。', actions:['关联本组相机实验。','填写固定场景,启动三图采集。','检查每张图的归档状态和原件。遇到渲染前提缺失时保留已采图,按提示补齐。'], tool:'vision_course_camera → vision_course_camera_status', fields:['baseline_images','baseline_raw','baseline_isp','baseline_render'] }, data: { title:'核对预置数据集', ask:'在 RoboGO 核对本组使用的课程数据集。确认 park、qrcode、obstacle 顺序与训练、验证划分。', fields:['label_schema','grouped_split','dataset_version'] }, train: { title:'在 RoboGO 提交训练', ask:'用组织方提供的兑换码,在 RoboGO 确认 YOLOv8s、640、100 轮。提交一次,立即把 Run ID 和已受理回执带回;随后继续相机步骤。', fields:['run_id'] }, formats: { title:'辨认三种图像格式', ask:'打开基线记录,辨认 Bayer RAW、ISP 显示图和渲染图。分别写下来源、用途和你在画面里看到的一处问题。', fields:['format_observation'] }, - gamma_demo: { title:'跟做一次有界 Gamma 调整', ask:'在 Gamma 面板选一个观察目标,保持机位和光照固定。', actions:['先保存原始 ISP。','让模型给出一个候选。工位校验当前生效的 Gamma 曲线后才写入。','核对候选独立回读和前后新图,记录保留或恢复的理由。'], tool:'vision_course_isp → vision_course_isp_status', fields:['gamma_readback','gamma_fresh_frame','gamma_decision'] }, + gamma_demo: { title:'跟做一次有界 Gamma 调整', ask:'在 Gamma 面板选一个观察目标,保持机位和光照固定。', actions:['先保存原始 ISP。','让模型给出一个候选。实验校验当前生效的 Gamma 曲线后才写入。','核对候选独立回读和前后新图,记录保留或恢复的理由。'], tool:'vision_course_isp → vision_course_isp_status', fields:['gamma_readback','gamma_fresh_frame','gamma_decision'] }, gamma_trial: { title:'第 2 轮自主 Gamma 对照', ask:'写自己的观察目标,保持机位和光照。核对两张新实拍与独立回读,再保存取舍。', actions:['先独立确认已恢复期初 ISP。','写本轮的观察目标,应用一次合格候选。','核对本轮前后实拍及回读,再写下保留或恢复的理由。'], tool:'vision_course_isp → vision_course_isp_status', fields:['trial_readback','trial_fresh_frame','trial_decision'] }, - break: { title:'助教核对各组训练进度', ask:'茶歇期间,助教只查看原 Run,更新状态并给预计超时的工位准备预置产物。11:20 开始个人盲选。', fields:[] }, + break: { title:'助教核对各组训练进度', ask:'茶歇期间,助教只查看原 Run,更新状态并给预计超时的实验准备预置产物。11:20 开始个人盲选。', fields:[] }, blind: { title:'隐藏标签,先看图再选', ask:'对着同一观察区域比较两张图,选一张或记录差异不明显,先写理由再揭晓。', fields:['blind_review'] }, reproduce: { title:'重载自己的 tuning', ask:'先恢复原值保持采流,再重载这次选定的 Gamma 候选。核对独立回读、加载后新图和原始恢复步骤。其他效果库走相机插件的已验证版本。', tool:'vision_course_isp → vision_course_isp_status', fields:['selected_tuning','independent_readback','tuning_reload_frame'] }, check_run: { title:'查询原 RoboGO Run', ask:'只读查询现有 Run。保留状态、验证结果和权重来源;后台训练期间可以继续下一项 ISP 操作。', fields:[] }, quantize: { title:'取回自己的 X5 INT8 产物', ask:'查询原任务权重。导出 opset 11 ONNX,并在兼容工具链用训练图校准生成 Bayes-e NV12 .bin。现场优先取云端预跑产物。', fields:['completed_checkpoint','validation_prediction','onnx_contract','checker_report','calibration_manifest','x5_model_hash'] }, - route: { title:'选择本工位完成路径', ask:'根据已核对的产物和设备状态选择 A、B 或 C。记录来源,再继续对应步骤。', fields:[] }, + route: { title:'选择本组完成路径', ask:'根据已核对的产物和设备状态选择 A、B 或 C。记录来源,再继续对应步骤。', fields:[] }, await_route: { title:'核对部署准备,等待 11:40 分流', ask:'检查模型来源和设备状态,先登记需要的预置模型或演示。11:40 开放 A/B/C 选择。', fields:[] }, - deploy: { title:'下发本人模型并验证 BPU', ask:'核对 X5 上实际加载的模型 SHA-256。用三类 YOLOv8 执行入口在静态图上跑一次实际 BPU 推理,并核对输出头、标签和前后处理。', fields:['board_model_hash','actual_bpu_inference','matching_pre_postprocess'] }, - live: { title:'用本人相机运行实时检测', ask:'用 Studio 在本工位启动课程检测,使用本组模型和选定 ISP。', actions:['确认实际检测画面来自本工位,核对检测流的 ISP 回读。','看到「实时更新」后移动观察目标,核对本轮带框实拍。','检测完成后点「采用回执并留证」,再记录本帧目标结果。'], fields:['exclusive_camera_owner','tuning_in_detection_pipeline','fresh_frames','inference_result','target_result','live_detections'] }, + deploy: { title:'加载本组模型并验证 BPU', ask:'打开模型检测。先确认要用的 ISP,启动后核对本组模型 SHA-256 和三类模型的 BPU 静态推理。', fields:['board_model_hash','actual_bpu_inference','matching_pre_postprocess'] }, + live: { title:'用本人相机运行实时检测', ask:'用 Studio 在本组启动课程检测,使用本组模型和选定 ISP。', actions:['确认实际检测画面来自本组,核对检测流的 ISP 回读。','看到「实时更新」后移动观察目标,核对本轮带框实拍。','检测完成后点「采用回执并留证」,再记录本帧目标结果。'], fields:['exclusive_camera_owner','tuning_in_detection_pipeline','fresh_frames','inference_result','target_result','live_detections'] }, preset_deploy: { title:'用预置模型完成实机操作', ask:'记录预置模型来源和哈希,实际加载并保存板端推理回执。个人记录标为 B 路径。', fields:['preset_model','preset_board_model_hash','preset_bpu_inference','preset_stream_isp','preset_live_frame','preset_inference_result','preset_target_result','preset_live_detections'] }, demo: { title:'观看演示并记下实际完成项', ask:'看讲师现场演示或已有录像,记录来源和观察。个人板端实操保持待完成。', fields:['demo_reference','demo_viewed'] }, - restore: { title:'恢复原始 ISP 并释放设备', ask:'按本工位原始快照恢复,独立回读并停流。若本工位没有启动相机或写参数,记录该事实。', tool:'vision_course_isp → vision_course_isp_status', fields:['restoration_and_release'] }, + restore: { title:'恢复原始 ISP 并释放设备', ask:'按本组原始快照恢复,独立回读并停流。若本组没有启动相机或写参数,记录该事实。', tool:'vision_course_isp → vision_course_isp_status', fields:['restoration_and_release'] }, deliver: { title:'下载并打开个人成果包', ask:'打包 tuning、过程手册、训练与模型来源、检测证据和恢复记录,下载后解压核对。', fields:['camera_and_model_manifest','remaining_work','package_opened'] }, }; diff --git a/plugins/rdk-camera-workshop/mcp/studio-config.mjs b/plugins/rdk-camera-workshop/mcp/studio-config.mjs index e9b07de..2a037b2 100644 --- a/plugins/rdk-camera-workshop/mcp/studio-config.mjs +++ b/plugins/rdk-camera-workshop/mcp/studio-config.mjs @@ -1,24 +1,41 @@ #!/usr/bin/env node -// Print configuration for the two MCP entries present in this installed package. -import { isEntrypoint } from './entrypoint.mjs'; -import { readFileSync } from 'node:fs'; -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; +// Emit (do not save) an explicit native-Moss MCP configuration for this installed copy. +import { existsSync, readFileSync, realpathSync } from 'node:fs'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const serverName = 'rdk-vision-workshop'; +const configKeys = [ + 'RDK_CAMERA_WORKSHOP_CONFIG', + 'RDK_VISION_COURSE_TRAINING_RECEIPT', + 'RDK_VISION_COURSE_BOARD_ARCHIVE', + 'RDK_VISION_COURSE_PRESET_BOARD_ARCHIVE', + 'RDK_VISION_ROBOGO_TRAINING_PROFILE', + 'RDK_VISION_COURSE_DEVMACHINE_PROFILE', + 'RDK_VISION_COURSE_ISPCAL_REPOSITORY', + 'RDK_VISION_COURSE_SESSION_DIR', + 'RDK_VISION_COURSE_PREVIOUS_SESSION', + 'RDK_VISION_COURSE_STUDIO_MEDIA_DIR', + 'RDK_VISION_COURSE_BOARD_LAUNCHER', +]; -const root = fileURLToPath(new URL('../', import.meta.url)); export function studioConfig(node = process.execPath) { - const {mcpServers} = JSON.parse(readFileSync(path.join(root, '.mcp.json'), 'utf8')); - const names = ['RDK_CAMERA_WORKSHOP_CONFIG', 'RDK_VISION_COURSE_TRAINING_RECEIPT', 'RDK_VISION_COURSE_BOARD_ARCHIVE', - 'RDK_VISION_COURSE_PRESET_BOARD_ARCHIVE', 'RDK_VISION_ROBOGO_TRAINING_PROFILE', 'RDK_VISION_COURSE_SESSION_DIR', 'RDK_VISION_COURSE_PREVIOUS_SESSION']; - const paths = Object.fromEntries(names.filter(key => process.env[key]).map(key => [key, process.env[key]])); - for (const entry of Object.values(mcpServers)) { - entry.command = node; - entry.args = [path.resolve(root, entry.args[0])]; - entry.env = {...entry.env, ...paths}; - if (process.versions.electron) entry.env.ELECTRON_RUN_AS_NODE = '1'; - } - return {mcpServers}; + const { mcpServers } = JSON.parse(readFileSync(new URL('../.mcp.json', import.meta.url), 'utf8')); + const { env: declaredEnv, ...declaration } = mcpServers[serverName]; + const env = { + ...declaredEnv, + ...Object.fromEntries(configKeys.filter(key => process.env[key]).map(key => [key, process.env[key]])), + }; + if (process.versions.electron) env.ELECTRON_RUN_AS_NODE = '1'; + const config = { + ...declaration, + command: node, + args: [fileURLToPath(new URL('./server.mjs', import.meta.url))], + ...(Object.keys(env).length ? { env } : {}), + }; + return { mcpServers: { [serverName]: config } }; } -if (isEntrypoint(import.meta)) { + +const entry = process.argv[1]; +if (entry && existsSync(entry) && import.meta.url === pathToFileURL(realpathSync(entry)).href) { console.log(JSON.stringify(studioConfig(), null, 2)); } diff --git a/plugins/rdk-camera-workshop/mcp/upstream-calibration.mjs b/plugins/rdk-camera-workshop/mcp/upstream-calibration.mjs new file mode 100644 index 0000000..33a22ed --- /dev/null +++ b/plugins/rdk-camera-workshop/mcp/upstream-calibration.mjs @@ -0,0 +1,45 @@ +import { execFile } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { isAbsolute, join } from 'node:path'; +import { promisify } from 'node:util'; + +const run=promisify(execFile); +const commit='889d1a02e8a4eaca16b4df44cc54b24ab7a100f0'; +const runOptions={timeout:30000,maxBuffer:4*1024*1024}; +const hash=bytes=>createHash('sha256').update(bytes).digest('hex'); + +export async function recomputeCalibrationDemo() { + const source=process.env.RDK_VISION_COURSE_ISPCAL_REPOSITORY; + if(!source||!isAbsolute(source)) throw new Error('camera_calibration_source_unconfigured'); + const staging=await mkdtemp(join(tmpdir(),'rdk-course-calibration-')); + try { + // Only the pinned algorithm source and fixed upstream demo are executable here. + const archive=join(staging,'ispcal.tar'); + let snapshot; + try { + snapshot=await run('git',['-C',source,'archive','--format=tar',commit,'ispcal'],{...runOptions,encoding:'buffer'}); + } catch {throw new Error('camera_calibration_source_unavailable');} + await writeFile(archive,snapshot.stdout); + await run('tar',['-xf',archive,'-C',staging],runOptions); + const output=join(staging,'result'); + let receipt; + try { + receipt=await run('python3',['-EB','-m','ispcal','demo','--output',output],{...runOptions,cwd:staging}); + } catch {throw new Error('camera_calibration_upstream_execution_failed');} + const lines=receipt.stdout.trim().split('\n'); + const metrics=Object.fromEntries(lines.map(line=>{ + const [key,value]=line.split(': '); + return [key,Number(value)]; + })); + if(Object.keys(metrics).length!==9||Object.values(metrics).some(value=>!Number.isFinite(value))) { + throw new Error('camera_calibration_upstream_receipt_invalid'); + } + const result=await readFile(join(output,'static_calibrations.json')); + return {status:'computed',commit,input:'upstream_synthetic_raw_demo',deviceUsed:false,metrics, + parameterTableSha256:hash(result)}; + } finally { + await rm(staging,{recursive:true,force:true}); + } +} diff --git a/plugins/rdk-camera-workshop/mcp/workbench-session.mjs b/plugins/rdk-camera-workshop/mcp/workbench-session.mjs index 55d4968..85256df 100644 --- a/plugins/rdk-camera-workshop/mcp/workbench-session.mjs +++ b/plugins/rdk-camera-workshop/mcp/workbench-session.mjs @@ -1,35 +1,119 @@ -import { isEntrypoint } from './entrypoint.mjs'; import { spawn } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'; +import { createHash, randomUUID } from 'node:crypto'; +import { existsSync } from 'node:fs'; +import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'; import { homedir } from 'node:os'; -import { dirname,join } from 'node:path'; +import { dirname,isAbsolute,join } from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; -import { fileURLToPath } from 'node:url'; -import { startWorkbench } from './workbench.mjs'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { startWorkbench, workbenchBuild } from './workbench.mjs'; +import { plan } from './course.mjs'; import { readWorkbenchState,writeWorkbenchState } from './workbench-state.mjs'; +import { summarizeCalibration, summarizeCalibrationTask } from './calibration-chat.mjs'; +import { renderCalibrationResultPng } from './calibration-visual.mjs'; const worker=fileURLToPath(import.meta.url); const sessionUrl=/^http:\/\/127\.0\.0\.1:\d{1,5}\/#[-a-f0-9]{36}$/; const idleMs=8*60*60*1000; const launchTimeoutMs=8000; +const photoMimeExtensions=new Map([['image/jpeg','jpg'],['image/png','png'],['image/webp','webp']]); +const photoPreviewLimit=24*1024*1024; +export { workbenchBuild }; +const upgradeBlocked=()=>Object.assign(new Error('workbench_previous_version_running'),{ + hint:'本实验的旧版课堂工作台仍在运行。用不带参数的「打开课堂工作台」返回旧窗口,完成或恢复未结束的操作并下载进度与成果;若需切换到新版界面,请先关闭旧工作台并重新打开 RDK Studio 后再进入同一实验。', +}); -async function request(url,body,route='/session') { +export function studioMediaDir() { + const directory=process.env.RDK_VISION_COURSE_STUDIO_MEDIA_DIR; + return directory&&isAbsolute(directory)?directory:undefined; +} + +async function readArchivedImage(url,route,asset) { + if(!photoMimeExtensions.has(asset.mimeType)||!/^[a-f0-9]{64}$/.test(asset.sha256)) throw new Error('camera_photo_preview_unavailable'); + const address=new URL(url); + const response=await fetch(new URL(route,address),{ + headers:{'X-Workshop-Session':address.hash.slice(1)},redirect:'error',signal:AbortSignal.timeout(18000), + }); + if(!response.ok||response.headers.get('content-type')!==asset.mimeType) { + await response.body?.cancel(); + throw new Error('camera_photo_preview_unavailable'); + } + const chunks=[]; + let size=0; + for await(const chunk of response.body) { + size+=chunk.length; + if(size>photoPreviewLimit) throw new Error('camera_photo_preview_unavailable'); + chunks.push(chunk); + } + const bytes=Buffer.concat(chunks,size); + if(!size||asset.byteLength!==undefined&&size!==asset.byteLength||createHash('sha256').update(bytes).digest('hex')!==asset.sha256) { + throw new Error('camera_frame_integrity_failed'); + } + return bytes; +} + +export async function publishImage(mediaDir,asset,bytes,label) { + const extension=photoMimeExtensions.get(asset.mimeType); + const fileName='workshop-photo-'+asset.sha256+'.'+extension; + const temporary=join(mediaDir,'.workshop-photo-'+randomUUID()+'.tmp'); + await mkdir(mediaDir,{recursive:true,mode:0o700}); + try { + await writeFile(temporary,bytes,{mode:0o600,flag:'wx'}); + await rename(temporary,join(mediaDir,fileName)); + } finally { + await rm(temporary,{force:true}); + } + return {fileName:label,imageUrl:'/api/local-files/'+fileName}; +} + +async function request(url,body,route='/session',timeout=1500) { const address=new URL(url); const headers={'X-Workshop-Session':address.hash.slice(1)}; if (body) headers['Content-Type']='application/json'; const response=await fetch(new URL(route,address),{ - method:body?'POST':'GET',headers,body:body&&JSON.stringify(body),redirect:'error',signal:AbortSignal.timeout(1500), + method:body?'POST':'GET',headers,body:body&&JSON.stringify(body),redirect:'error',signal:AbortSignal.timeout(timeout), }); if ([400,409,422].includes(response.status)) throw new Error((await response.json()).error); if (!response.ok) throw new Error('workbench_unavailable'); return response.json(); } +async function registeredUrl(registry) { + try { + const value=await readFile(registry,'utf8'); + if(sessionUrl.test(value)) return value; + } catch(error) { + if(error.code!=='ENOENT') throw error; + } +} + +async function runningStation(registry,{allowPrevious=false,checkRetirement=false}={}) { + const url=await registeredUrl(registry); + if(!url) return; + try { + // The public course probe does not refresh the idle deadline of a detached instance. + const response=await fetch(new URL('/course.json',url),{redirect:'error',signal:AbortSignal.timeout(1500)}); + if(response.status===404) return; + if(!response.ok) throw new Error('workbench_status_unconfirmed'); + const data=await response.json(); + if(data.plan?.schema!==plan.schema) throw new Error('workbench_status_unconfirmed'); + const previous=data.workbenchBuild!==workbenchBuild; + const canRetire=data.workbenchRetirement===1; + if(previous&&!allowPrevious&&!(checkRetirement&&canRetire)) throw upgradeBlocked(); + const session=await request(url); + if(session.workbenchBuild!==data.workbenchBuild) throw new Error('workbench_status_unconfirmed'); + return {url,session,previous,canRetire}; + } catch(error) { + if(error.cause?.code==='ECONNREFUSED') return; + if(['workbench_previous_version_running','workbench_status_unconfirmed'].includes(error.message)) throw error; + throw new Error('workbench_status_unconfirmed',{cause:error}); + } +} + async function active(registry) { try { - const url=await readFile(registry,'utf8'); - if (sessionUrl.test(url)) { + const url=await registeredUrl(registry); + if (url) { await request(url); return url; } @@ -38,76 +122,313 @@ async function active(registry) { } } -export function workbenchSession(root=join(homedir(),'.rdk-vision-workshop')) { - const scope=createHash('sha256').update(worker+'|persistent-workbench').digest('hex').slice(0,32); - const directory=join(root,scope); +const stationIdPattern=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; +const sessionVersion=plan.classroomId?'v7-'+plan.classroomId:'v6'; +const registryFor=(base,id)=>join(id?join(base,'stations',id):base,'session-learner-isp-'+sessionVersion); +const pointerFor=base=>join(base,'active-station'); +const lastStationFor=base=>join(base,'last-new-station'); +const stateFor=(base,id)=>join(dirname(registryFor(base,id)),'workbench-state-learner-isp-'+sessionVersion+'.json'); +async function lastNewStation(base) { + const id=await readFile(lastStationFor(base),'utf8').catch(()=>undefined); + return stationIdPattern.test(id)?id:undefined; +} +async function selectedStation(base) { + try { + const id=await readFile(pointerFor(base),'utf8'); + if(id==='original') return ''; + if(stationIdPattern.test(id)) return id; + throw new Error('workbench_station_invalid'); + } catch(error) { + if(error.code==='ENOENT') return ''; + throw error; + } +} + +async function openStation(base,id,{allowPrevious=false}={}) { // An older detached workbench can still be listening after an in-place import. - const registry=join(directory,'session-classroom-v6'); - const lock=join(directory,'starting-classroom-v6'); - async function open() { - await mkdir(directory,{recursive:true,mode:0o700}); - const deadline=Date.now()+launchTimeoutMs; - while (Date.now(){if(err.code!=='ENOENT') throw err;}); - if (info&&Date.now()-info.mtimeMs>launchTimeoutMs*2) await rm(lock,{recursive:true,force:true}); - await delay(80); - continue; - } - try { - const existing=await active(registry); - if (existing) return existing; - const child=spawn(process.execPath,[worker,'--serve',registry],{detached:true,stdio:'ignore',windowsHide:true}); - let failure; - child.once('error',error=>{failure=error;}); - child.once('exit',()=>{failure??=new Error('workbench_start_failed');}); - child.unref(); - while (Date.now(){if(err.code!=='ENOENT') throw err;}); + if(info&&Date.now()-info.mtimeMs>launchTimeoutMs*2) await rm(lock,{recursive:true,force:true}); + await delay(80); + continue; + } + try { + const existing=await runningStation(registry,options); + if(existing) { + if(!existing.previous||!existing.canRetire) return existing.url; + try { + const retirement=await request(existing.url,{},'/session/retire'); + if(retirement.retiring!==true) throw new Error('workbench_status_unconfirmed'); + } catch(error) { + if(error.message!=='station_busy') throw error; + if(allowPrevious) return existing.url; + throw upgradeBlocked(); + } + while(Date.now()=deadline) throw new Error('workbench_status_unconfirmed'); } + const child=spawn(process.execPath,[worker,'--serve',base,id],{detached:true,stdio:'ignore',windowsHide:true}); + let failure; + child.once('error',error=>{failure=error;}); + child.once('exit',()=>{failure??=new Error('workbench_start_failed');}); + child.unref(); + while(Date.now()openStation(directory,await selectedStation(directory),options); + return {open,async sync(body,{allowPrevious=false}={}) { + const current=await runningStation(registryFor(directory,await selectedStation(directory)),{allowPrevious:!body&&allowPrevious}); + if (!current) throw new Error('open_workbench_first'); + if(!body) return current.session; + return request(current.url,body); },async camera(body) { const url=await open(); const target=new URL(url); target.searchParams.set('panel','capture'); - return {url:target.href,...await request(url,body,'/camera/capture')}; + const result=await request(url,body,'/camera/capture'); + await notifyFocus(url,'camera-capture'); + return {url:target.href,...result}; + },async cameraStatus(photoRequestId) { + const url=await open(); + for (let attempt=0;attempt<2;attempt++) { + const [{resume,revision},captureResult,{preflight}]=await Promise.all([ + request(url),request(url,undefined,'/camera/capture'),request(url,undefined,'/camera/preflight'), + ]); + const experimentId=resume.camera?.experimentId??null; + if (revision!==captureResult.recordingRevision|| + captureResult.capture&&captureResult.capture.experimentId!==experimentId|| + preflight&&preflight.experimentId!==experimentId) continue; + const target=new URL(url); + target.searchParams.set('panel','capture'); + const status={url:target.href,...captureResult, + cameraBinding:{source:'workbench',status:experimentId?'bound':'unbound',experimentId}, + baselineRequested:Boolean(captureResult.capture?.scene),latestPreflight:preflight??null}; + if(!photoRequestId) return status; + const capture=captureResult.capture; + if(capture?.photoRequestId!==photoRequestId) return {...status,photoPreview:'request_changed'}; + if(!capture.assets.photo) return {...status,photoPreview:capture.errors.photo||capture.recording?'capture_failed':'pending'}; + const mediaDir=studioMediaDir(); + if(!mediaDir) return {...status,photoPreview:'studio_media_unavailable'}; + try { + const photo=capture.assets.photo; + const bytes=await readArchivedImage(url,'/camera/capture/file/photo?id='+encodeURIComponent(photo.id),photo); + const preview=await publishImage(mediaDir,photo,bytes,'相机实拍.'+photoMimeExtensions.get(photo.mimeType)); + return {...status,__type:'studio_local_preview',ok:true,...preview,photoPreview:'ready'}; + } catch { + return {...status,photoPreview:'preview_unavailable'}; + } + } + throw new Error('camera_status_changed'); },async preflight(run) { const url=await open(); const target=new URL(url); target.searchParams.set('panel','preflight'); - return {url:target.href,...await request(url,run?{}:undefined,'/camera/preflight')}; - },async isp(body) { + const result=await request(url,run?{}:undefined,'/camera/preflight'); + if(run) await notifyFocus(url,'camera-preflight'); + return {url:target.href,...result}; + },async calibration(args,mutating=false) { + const url=await open(); + const target=new URL(url); + target.searchParams.set('panel','calibration'); + const {resume,calibrationChat,calibrationView,stationActive}=await request(url); + const experimentId=resume.camera?.experimentId??null; + const cameraBinding={source:'workbench',status:experimentId?'bound':'unbound',experimentId}; + const view={url:target.href,cameraBinding,...(calibrationView!==2?{previousWorkbench:true}:{})}; + if(stationActive===false||args.experimentId!==undefined&&args.experimentId!==experimentId) { + throw new Error('camera_binding_invalid'); + } + if(calibrationChat!==true) return {...view,status:'workbench_update_required'}; + if(!experimentId) return {...view,status:'camera_binding_required'}; + const {action,taskId,experimentId:reqExp,...rest}=args; + if(!mutating) { + const query=new URLSearchParams({action,experimentId,...(taskId&&{taskId})}); + const data=await request(url,undefined,'/calibration?'+query,20000); + if(action!=='overview') await notifyFocus(url,'calibration-workbench'); + const summarized={...view,...summarizeCalibration(action,data,experimentId)}; + if(action==='result'&&data?.result) { + const mediaDir=studioMediaDir(); + if(mediaDir) { + try { + const visual=renderCalibrationResultPng(data.result); + if(visual) { + const image=await publishImage(mediaDir,{mimeType:'image/png',sha256:visual.sha256},visual.bytes,visual.label); + return {...summarized,__type:'studio_local_preview',ok:true,...image,calibrationPreview:'ready'}; + } + } catch {} + } + } + return summarized; + } + const body=action==='run'?{action:'run_async',experimentId,taskId}:{action,experimentId,input:rest}; + let data; + try { data=await request(url,body,'/calibration',20000); } + catch(error) { + if(['TimeoutError','AbortError'].includes(error.name)) throw new Error('camera_calibration_submission_unconfirmed'); + throw error; + } + await notifyFocus(url,'calibration-workbench'); + return {...view,task:summarizeCalibrationTask(data.task),reused:data.reused, + ...(data.pendingRequest&&{pendingRequest:data.pendingRequest})}; + },async detection() { + const workbenchUrl=await open(); + const target=new URL(workbenchUrl); + target.searchParams.set('panel','board'); + const url=target.href; + let receipt; + try { + receipt=await request(url,undefined,'/board/receipt'); + } catch (error) { + if(!/^board_[a-z_]+$/.test(error.message)) throw error; + return {url,detectionPreview:'archive_unavailable',error:error.message}; + } + const frame=receipt.latestDetection; + const status={url,runId:receipt.runId,modelSha256:receipt.modelSha256,boardStatus:receipt.status, + targetObservation:receipt.targetObservation,receiptSha256:receipt.receiptSha256,frame}; + if(!frame) return {...status,detectionPreview:'no_verified_frame'}; + const mediaDir=studioMediaDir(); + if(!mediaDir) return {...status,detectionPreview:'studio_media_unavailable'}; + try { + const asset={...frame,mimeType:'image/jpeg'}; + const bytes=await readArchivedImage(url,'/board/file/'+encodeURIComponent(frame.file)+ + '?receipt='+encodeURIComponent(receipt.receiptSha256),asset); + const boxes=Object.entries(frame.counts).filter(([,count])=>count>0).map(([label,count])=>{ + const score=frame.maxScores?.[label]; + return label+' × '+count+(Number.isFinite(score)?'(最高 '+(score*100).toFixed(1)+'%)':''); + }); + const label='板端检测归档帧 · '+(boxes.length?boxes.join(' · '):'本帧无检测框'); + const preview=await publishImage(mediaDir,asset,bytes,label); + await notifyFocus(workbenchUrl,'board'); + return {...status,__type:'studio_local_preview',ok:true,...preview,detectionPreview:'ready'}; + } catch { + return {...status,detectionPreview:'preview_unavailable'}; + } + },async isp(body,selection) { const url=await open(); const target=new URL(url); target.searchParams.set('panel','isp'); - return {url:target.href,...await request(url,body,'/camera/isp')}; + const result=await request(url,body,'/camera/isp'); + const proposal=result.isp?.gammaProposal; + const round=proposal??result.isp?.rounds?.findLast(item=>item.before&&item.after); + if(round) target.searchParams.set('round',String(round.number)); + if(body||selection) { + if(selection?.trial!==undefined) await notifyFocus(url,'isp-learner'); + else await notifyFocus(url,'camera-isp',selection?.round??round?.number); + } + const status={url:target.href,...result,presentation:{panel:'isp', + ...(round?{round:round.number}:{}),...(proposal?{candidatePending:true}:{}), + archivedFrames:['before','after','restored'].filter(name=>round?.[name])}}; + if(!selection) return status; + const {round:roundNumber,trial}=selection; + if(roundNumber!==undefined) target.searchParams.set('round',String(roundNumber)); + else target.searchParams.delete('round'); + status.url=target.href; + const item=trial===undefined?result.isp?.rounds?.find(value=>value.number===roundNumber): + result.isp?.adjustments?.find(value=>value.number===trial); + const afterReadback=trial===undefined?item?.gammaReadback:item?.afterReadback; + if(!item?.before||!item.after||!item.beforeReadback?.hash||!afterReadback?.hash|| + item.before.tuningHash!==item.beforeReadback.hash||item.after.tuningHash!==afterReadback.hash) { + return {...status,ispPreview:result.isp?.running?'pending':'no_verified_pair'}; + } + const mediaDir=studioMediaDir(); + if(!mediaDir) return {...status,ispPreview:'studio_media_unavailable'}; + try { + const route=trial===undefined?{round:String(roundNumber)}:{scope:'learner',trial:String(trial)}; + const pair=await Promise.all(['before','after'].map(async phase=>{ + const asset=item[phase]; + const query=new URLSearchParams({...route,file:phase,sha256:asset.sha256}); + return {asset,bytes:await readArchivedImage(url,'/camera/isp?'+query,asset)}; + })); + const [before,after]=await Promise.all(pair.map(({asset,bytes},index)=> + publishImage(mediaDir,asset,bytes,index===0?'调前实拍':'调后实拍'))); + const adjustment=trial===undefined?('第 '+roundNumber+' 轮 Gamma'+ + (item.curveChange?.changed?' · '+item.curveChange.changed+' 个曲线节点变化':'')): + item.kind==='multi'?(item.label+' · '+Object.entries(item.appliedValues??item.afterValues??{}).map(([k,v])=>`${k}=${v}`).join(' ')): + item.label+' '+item.beforeValue+' → '+item.afterValue+(item.unit?' '+item.unit:''); + const caption=adjustment+' · 板端独立回读 '+afterReadback.hash.slice(0,12); + return {...status,__type:'studio_local_preview',ok:true,...before, + comparison:{...after,caption},ispPreview:'ready'}; + } catch { + return {...status,ispPreview:'preview_unavailable'}; + } + },async readPractice(includeImage=false) { + if(!existsSync(directory)) return null; + try { + const current=await runningStation(registryFor(directory,await selectedStation(directory))); + if(!current) return null; + return await request(current.url,undefined,'/practice/state'+(includeImage?'?includeImage=1':''),2000); + } catch { + return null; + } + },async undoPractice() { + if(!existsSync(directory)) return {ok:false,error:'workbench_not_running'}; + try { + const current=await runningStation(registryFor(directory,await selectedStation(directory))); + if(!current) return {ok:false,error:'workbench_not_running'}; + return await request(current.url,{},'/practice/undo',2000); + } catch(error) { + return {ok:false,error:error.message}; + } + },async syncPractice(payload) { + if(!payload||!existsSync(directory)) return {synced:false}; + try { + const current=await runningStation(registryFor(directory,await selectedStation(directory))); + if(!current) return {synced:false}; + const res=await request(current.url,payload,'/practice/sync',2500); + return {synced:true,url:current.url,practice:res?.practice}; + } catch { + return {synced:false}; + } }}; } -async function serve(registry) { +async function serve(base,id) { + if(id&&!stationIdPattern.test(id)) throw new Error('workbench_station_invalid'); + const registry=registryFor(base,id); const temporary=registry+'.'+process.pid; - const stateFile=join(dirname(registry),'workbench-state-classroom-v6.json'); + const stateFile=stateFor(base,id); const previous=process.env.RDK_VISION_COURSE_PREVIOUS_SESSION; - if(!readWorkbenchState(stateFile)) { + const previousPlanState=plan.classroomId&&!readWorkbenchState(stateFile)? + readWorkbenchState(join(dirname(registry),'workbench-state-learner-isp-v6.json')):undefined; + if(previousPlanState) writeWorkbenchState(stateFile,previousPlanState); + if(!id&&!readWorkbenchState(stateFile)) { const legacy=readWorkbenchState(join(dirname(registry),'workbench-state-learner-isp-v5.json'))?? readWorkbenchState(join(dirname(registry),'workbench-state-isp-rounds-v4.json'))?? readWorkbenchState(join(dirname(registry),'workbench-state-capture-v3.json'))?? @@ -124,7 +445,36 @@ async function serve(registry) { } } } - const view=await startWorkbench({},0,undefined,{idleMs,stateFile}); + const stationActions=async action=>{ + if(action==='active') return openStation(base,await selectedStation(base)); + const nextId=action==='new'?randomUUID():action==='latest'?await lastNewStation(base):''; + if(nextId===undefined) throw new Error('workbench_station_invalid'); + const url=await openStation(base,nextId); + const draft=pointerFor(base)+'.'+randomUUID(); + try { + await writeFile(draft,nextId||'original',{mode:0o600,flag:'wx'}); + if(action==='new') await writeFile(lastStationFor(base),nextId,{mode:0o600}); + await rename(draft,pointerFor(base)); + } finally {await rm(draft,{force:true});} + return url; + }; + const priorTraining=async()=>{ + const children=await readdir(join(base,'stations')).catch(error=>{ + if(error.code==='ENOENT') return []; + throw error; + }); + for(const other of ['',...children.filter(name=>stationIdPattern.test(name))]) { + if(other===id) continue; + const previous=readWorkbenchState(stateFor(base,other)); + const run=previous?.lockedRun??previous?.resume.run; + if(previous?.submission==='pending'||run?.source==='robogo') { + return {runId:run?.id,uncertain:previous.submission==='pending'}; + } + } + }; + const view=await startWorkbench({},0,undefined,{idleMs,stateFile,stationActions, + isActiveStation:async()=>await selectedStation(base).catch(()=>undefined)===id, + stationKind:id?'fresh':'original',lastStation:async()=>Boolean(await lastNewStation(base)),priorTraining}); try { await writeFile(temporary,view.url,{mode:0o600,flag:'wx'}); await rename(temporary,registry); @@ -135,6 +485,6 @@ async function serve(registry) { } } -if (isEntrypoint(import.meta)&&process.argv[2]==='--serve') { - await serve(process.argv[3]); +if (process.argv[1]&&pathToFileURL(process.argv[1]).href===import.meta.url&&process.argv[2]==='--serve') { + await serve(process.argv[3],process.argv[4]??''); } diff --git a/plugins/rdk-camera-workshop/mcp/workbench-state.mjs b/plugins/rdk-camera-workshop/mcp/workbench-state.mjs index c46e6c3..af4bfc1 100644 --- a/plugins/rdk-camera-workshop/mcp/workbench-state.mjs +++ b/plugins/rdk-camera-workshop/mcp/workbench-state.mjs @@ -11,6 +11,10 @@ export function readWorkbenchState(file) { return state; } catch (error) { if (error.code==='ENOENT') return undefined; + if (error instanceof SyntaxError || error.message==='workbench_state_invalid') { + try { renameSync(file,file+'.corrupt-'+Date.now()); } catch {} + return undefined; + } throw error; } } diff --git a/plugins/rdk-camera-workshop/mcp/workbench.mjs b/plugins/rdk-camera-workshop/mcp/workbench.mjs index e3ffeb6..5eb260f 100644 --- a/plugins/rdk-camera-workshop/mcp/workbench.mjs +++ b/plugins/rdk-camera-workshop/mcp/workbench.mjs @@ -1,21 +1,39 @@ #!/usr/bin/env node import { createServer } from 'node:http'; -import { readFileSync, realpathSync, existsSync } from 'node:fs'; +import { readFileSync, readdirSync, realpathSync, existsSync, lstatSync } from 'node:fs'; import { pathToFileURL } from 'node:url'; -import { randomUUID } from 'node:crypto'; -import { plan } from './course.mjs'; +import { isAbsolute, join } from 'node:path'; +import { homedir } from 'node:os'; +import { createHash, randomUUID } from 'node:crypto'; +import { isDeepStrictEqual } from 'node:util'; +import { plan as defaultPlan } from './course.mjs'; import { guideCourse, guideSchema, normalizedModelHash, presetModelHash } from './guide.mjs'; import { createCameraSource } from './camera-source.mjs'; +import { awbTaskInput, ccmTaskInput, darkTaskInput, lscTaskInput, matchingDarkTask, validateCalibrationAction } from './calibration-chat.mjs'; import { boardEvidence, externalTrainingReceipt } from './course-evidence.mjs'; +import { createBoardLauncher } from './board-launcher.mjs'; import { createRoboGo, trainingProfile } from './robogo.mjs'; import { readWorkbenchState, writeWorkbenchState } from './workbench-state.mjs'; +import { renderIspExampleAsset } from './isp-example.mjs'; -const cameraErrors=new Set(['camera_unconfigured','camera_configuration_invalid','camera_service_unreachable','camera_auth_required', +const buildFiles=['../plugin.json','../skills/rdk-vision-workshop/assets/course-plan.json', + ...['./','../web/'].flatMap(directory=>readdirSync(new URL(directory,import.meta.url),{withFileTypes:true}) + .filter(file=>file.isFile()&&/\.(?:mjs|html|css)$/.test(file.name)&&!file.name.endsWith('.test.mjs')) + .map(file=>directory+file.name).sort())]; +export const workbenchBuild=createHash('sha256').update(JSON.stringify(buildFiles.map(path=> + [path,createHash('sha256').update(readFileSync(new URL(path,import.meta.url))).digest('hex')]))).digest('hex'); +const cameraErrors=new Set(['camera_unconfigured','camera_credential_missing','camera_configuration_invalid','camera_service_unreachable','camera_auth_required', 'camera_archive_missing','camera_response_invalid','camera_service_error','camera_frame_integrity_failed','camera_binding_invalid']); const captureActions=new Set(['photo','baseline','retake','render']); +const rawReplayCaptureMetadataRequired='vision_raw_replay_capture_metadata_required'; const unconfirmedCapture=new Set(['camera_capture_unconfirmed','vision_device_transport_failed']); const evidenceErrors=new Set(['training_receipt_unconfigured','training_receipt_invalid','board_archive_unconfigured','board_receipt_pending', - 'board_model_mismatch','board_receipt_changed','board_asset_missing','board_asset_integrity_failed','evidence_file_invalid']); + 'board_model_mismatch','board_receipt_changed','board_asset_missing','board_asset_integrity_failed','evidence_file_invalid', + 'board_comparison_unavailable','board_comparison_region_invalid','training_receipt_task_unverified']); +const focusPanels=new Set(['camera','camera-preflight','camera-capture','camera-isp','isp-learner','calibration-workbench','calibration-demo','training','comparison','board','delivery']); +const uiEventTypes=new Set(['stage_view','evidence_saved','camera_bound','camera_unbound','preflight_started','capture_started','isp_decision','blind_revealed','route_selected','export_downloaded','station_switched','prompt_copied']); +const maxSseClients=16; +const maxUiEvents=12; function gammaCurveChange(before,after) { const original=before?.config?.modules?.gamma; @@ -37,34 +55,99 @@ function gammaCurveChange(before,after) { before:source.slice(selected,selected+64),after:target.slice(selected,selected+64)}; } +function comparisonEligible(before,after) { + if(!gammaCurveChange(before,after)) return false; + const withoutCurve=({config})=>{ + const gamma={...config.modules.gamma}; + delete gamma[gamma.mode===0?'auto_attr.curve':'manual_attr.curve']; + return {...config,modules:{...config.modules,gamma}}; + }; + return isDeepStrictEqual(withoutCurve(before),withoutCurve(after)); +} + const routes = new Map([ ['/', ['text/html', '../web/index.html']], ['/style.css', ['text/css', '../web/style.css']], ['/app.mjs', ['text/javascript', '../web/app.mjs']], + ['/calibration-exercise.mjs', ['text/javascript', '../web/calibration-exercise.mjs']], + ['/calibration-panel.mjs', ['text/javascript', '../web/calibration-panel.mjs']], ['/camera-panel.mjs', ['text/javascript', '../web/camera-panel.mjs']], ['/capture-panel.mjs', ['text/javascript', '../web/capture-panel.mjs']], ['/preflight-panel.mjs', ['text/javascript', '../web/preflight-panel.mjs']], ['/isp-panel.mjs', ['text/javascript', '../web/isp-panel.mjs']], ['/isp-demo.mjs', ['text/javascript', '../web/isp-demo.mjs']], + ['/isp-engine.mjs', ['text/javascript', '../web/isp-engine.mjs']], + ['/image-compare.mjs', ['text/javascript', '../web/image-compare.mjs']], ['/isp-demo/manifest.json', ['application/json', '../web/isp-demo/manifest.json']], ['/board-panel.mjs', ['text/javascript', '../web/board-panel.mjs']], ['/zip.mjs', ['text/javascript', '../web/zip.mjs']], ['/guide.mjs', ['text/javascript', './guide.mjs']], ['/steps.mjs', ['text/javascript', './steps.mjs']], ]); -for(const name of ['exposure','gain','contrast','sharpness','white-balance']) { +const demoManifest=JSON.parse(readFileSync(new URL('../web/isp-demo/manifest.json',import.meta.url),'utf8')); +for(const sample of demoManifest.samples) { for(const phase of ['before','after']) { - const asset='/isp-demo/'+name+'-'+phase+'.jpg'; - routes.set(asset,['image/jpeg','../web'+asset]); + const file=sample[phase]?.image; + if(file) routes.set('/isp-demo/'+file,['image/jpeg','../web/isp-demo/'+file]); } } +routes.set('/isp-example/scenes.json',['application/json','../web/isp-example/scenes.json']); +const exampleScenes=JSON.parse(readFileSync(new URL('../web/isp-example/scenes.json',import.meta.url),'utf8')).scenes; +for(const scene of exampleScenes) { + const asset=scene.prefix+'gamma-20.'+scene.ext; + routes.set(asset,[scene.mimeType,'../web'+asset]); +} +for(const [name,type] of [['result.json','application/json'],['preview.png','image/png'], + ['static-calibrations.json','application/json'],['exercise.json','application/json'], + ['flat-before.png','image/png'],['flat-after.png','image/png']]) { + const path='/calibration-demo/'+name; + routes.set(path,[type,'../web'+path]); +} const files = new Map([...routes].map(([path,[type,name]])=>[path,[type,readFileSync(new URL(name,import.meta.url))]])); -export async function startWorkbench(input={}, port=0, cameraSource=createCameraSource(), {idleMs,roboGo=createRoboGo(),stateFile,practiceReturnUrl}={}) { +function readDeveloperMachineProfile(file=process.env.RDK_VISION_COURSE_DEVMACHINE_PROFILE) { + if(!file) return {status:'unconfigured'}; + try { + if(!isAbsolute(file)) throw new Error(); + const stat=lstatSync(file); + if(!stat.isFile()||stat.size>8192||process.platform!=='win32'&&(stat.uid!==process.getuid()||stat.mode&0o022)) throw new Error(); + const document=JSON.parse(readFileSync(file,'utf8')); + const fields=['connection','dataset','startCommand','logPath','artifactPath']; + if(!document||Object.keys(document).length!==fields.length||!fields.every(key=> + typeof document[key]==='string'&&document[key].trim().length>0&&document[key].length<=1000&&!/[\u0000-\u001f\u007f]/.test(document[key]))) throw new Error(); + return {status:'ready',...document}; + } catch {return {status:'invalid'};} +} + +function readActiveQuickstartRuntime() { + const file=process.env.RDK_VISION_COURSE_QUICKSTART_RUNTIME!==undefined + ? process.env.RDK_VISION_COURSE_QUICKSTART_RUNTIME + : join(homedir(),'.config','rdk-vision-workshop','quickstart','runtime.json'); + if(!file||!isAbsolute(file)||!existsSync(file)) return; + try { + const info=lstatSync(file); + const posixPrivate=process.platform==='win32'||((info.mode&0o777)===0o600&&info.uid===process.getuid?.()); + if(!info.isFile()||info.isSymbolicLink()||info.size>32768||!posixPrivate) return; + const data=JSON.parse(readFileSync(file,'utf8')); + if(typeof data?.experimentId!=='string'||!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(data.experimentId)) return; + if(!Number.isSafeInteger(data.workbenchPid)||data.workbenchPid<=0) return; + process.kill(data.workbenchPid,0); + return data; + } catch {return;} +} + +export async function startWorkbench(input={}, port=0, cameraSource, { + idleMs,roboGo=createRoboGo(),stateFile,practiceReturnUrl,stationActions,isActiveStation,stationKind,lastStation,priorTraining, + classroomPlan:plan=defaultPlan,workbenchBuild:reportedBuild=workbenchBuild,onPracticeMirror +}={}) { + const quickstart=cameraSource===undefined?readActiveQuickstartRuntime():undefined; + cameraSource??=createCameraSource(); + const direct=plan.training.workflow==='devmachine'; const stored=readWorkbenchState(stateFile); let verifiedRun=stored?.verifiedRun; let lockedRun=stored?.lockedRun; const initial={...(stored?.resume??input)}; + if(quickstart&&initial.camera===undefined&&!stored?.resume) initial.camera={experimentId:quickstart.experimentId}; if(initial.run?.modelSha256!==undefined&&(initial.run.id!==verifiedRun?.id||initial.run.modelSha256!==verifiedRun?.modelSha256)) { initial.run={...initial.run};delete initial.run.modelSha256; } @@ -89,15 +172,292 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera cameraCapture={...saved,errors:{...saved.errors,[running]:'camera_capture_unconfirmed'}}; } let cameraJob=false; + let creatingDarkTask=false; + let calibrationSnapshot; + function recordCalibrationSnapshot(experimentId,catalog) { + if(!experimentId||!Array.isArray(catalog?.engines)||!Array.isArray(catalog?.tasks)||!Array.isArray(catalog?.samples)) return; + calibrationSnapshot={ + experimentId, + readyEngines:catalog.engines.filter(e=>e?.available).map(e=>e.id), + completedOps:[...new Set(catalog.tasks.filter(t=>t?.status==='completed').map(t=>t.operation))], + taskCount:catalog.tasks.length, + rawCount:catalog.samples.length, + }; + } + const calibrationRequests=new Map(); + const calibrationErrorCode=error=>/^(camera|vision)_[a-z0-9_]{1,90}$/.test(error.message)? + error.message:'camera_calibration_invalid'; const board=boardEvidence(); const presetBoard=process.env.RDK_VISION_COURSE_PRESET_BOARD_ARCHIVE?boardEvidence(process.env.RDK_VISION_COURSE_PRESET_BOARD_ARCHIVE):board; - const selectedBoard=()=>resume.path==='B'?presetBoard:board; + const boardLauncherFile=process.env.RDK_VISION_COURSE_BOARD_LAUNCHER??quickstart?.launcherPath; + const boardLauncher=createBoardLauncher(boardLauncherFile,{onChange:()=>emitEvent('board')}); let lastRoboGoCheck, checkingRoboGo; let preparedTraining, submittingTraining=false, authorizationRound=0, submission=stored?.submission??'idle'; + let focusSeq=0, focusTarget=null; + let practiceSyncSeq=0, practiceSyncState=null, practiceSyncPayload=null, practiceCustomImage=null; + const practiceHistory=[]; + const maxPracticeHistory=20; + const uiEvents=[]; + const sseClients=new Set(); + const sseHeartbeat=setInterval(()=>{ + for(const client of sseClients) { + try { client.write(': ping\n\n'); } catch { sseClients.delete(client); } + } + },25000); + sseHeartbeat.unref(); + function emitEvent(topic, detail={}) { + if(!sseClients.size) return; + const payload='event: update\ndata: '+JSON.stringify({topic,revision,focusSeq,at:new Date().toISOString(),...detail})+'\n\n'; + for(const client of sseClients) { + try { client.write(payload); } catch { sseClients.delete(client); } + } + } + function closeSseClients() { + clearInterval(sseHeartbeat); + for(const client of sseClients) { + try { client.end(); } catch {} + } + sseClients.clear(); + } + const PRACTICE_PARAM_BOUNDS=[ + ['exposureEv',[-2,2]],['shadows',[-100,100]],['highlights',[-100,100]], + ['gamma',[0.55,1.45]],['brightness',[-60,60]],['contrast',[0.5,1.8]], + ['saturation',[0,2]],['wbShift',[-50,50]],['denoise',[0,1]],['sharpness',[0,2]], + ]; + function practiceSnapshotPublic(includeImage=false) { + return { + state:practiceSyncState, + historyCount:practiceHistory.length, + canUndo:practiceHistory.length>1, + history:practiceHistory.slice(-8).map(h=>({ + seq:h.seq,at:h.at,source:h.source,mode:h.mode, + ...(h.scene?{scene:h.scene}:{}), + ...(h.hasCustomImage?{hasCustomImage:true,customImageLabel:h.customImageLabel}:{}), + ...(h.goal?{goal:h.goal}:{}), + ...(h.params?{params:h.params}:{}), + })), + ...(includeImage&&practiceCustomImage?{ + customImageBase64:practiceCustomImage.bytes.toString('base64'), + customImageMimeType:practiceCustomImage.mimeType, + customImageLabel:practiceCustomImage.label, + }:{}), + }; + } + function applyPracticeSync(input) { + if(!input||typeof input!=='object'||Array.isArray(input)) throw new Error('invalid_practice_sync'); + const mode=input.mode==='gamma'?'gamma':'lab'; + const source=input.source==='ui'?'ui':'chat'; + const scene=typeof input.scene==='string'&&/^[a-z0-9_-]{1,40}$/.test(input.scene)?input.scene:undefined; + const gamma=typeof input.gamma==='number'&&Number.isFinite(input.gamma)?Math.min(1.45,Math.max(0.55,input.gamma)):undefined; + const goal=typeof input.goal==='string'?input.goal.replace(/[\u0000-\u001f\u007f]/gu,' ').trim().slice(0,180):undefined; + let params; + if(input.params&&typeof input.params==='object'&&!Array.isArray(input.params)) { + const clean={}; + for(const [k,bounds] of PRACTICE_PARAM_BOUNDS) { + const v=input.params[k]; + if(typeof v==='number'&&Number.isFinite(v)) clean[k]=Math.min(bounds[1],Math.max(bounds[0],v)); + } + params=clean; + } + let hasCustomImage=Boolean(practiceCustomImage); + let customImageLabel=practiceCustomImage?.label; + if(typeof input.customImageBase64==='string'&&input.customImageBase64.length>0) { + const bytes=Buffer.from(input.customImageBase64,'base64'); + if(bytes.length>6*1024*1024) throw new Error('practice_image_too_large'); + const mime=input.customImageMimeType==='image/png'?'image/png':'image/jpeg'; + customImageLabel=typeof input.customImageLabel==='string'?input.customImageLabel.slice(0,120):'本地图片'; + practiceCustomImage={bytes,mimeType:mime,label:customImageLabel}; + hasCustomImage=true; + } else if(scene&&scene!=='custom') { + practiceCustomImage=null; + hasCustomImage=false; + customImageLabel=undefined; + } + practiceSyncSeq++; + const nextState={ + seq:practiceSyncSeq,mode,source,at:new Date().toISOString(), + ...(scene?{scene}:{}), + ...(gamma!==undefined?{gamma}:{}), + ...(params?{params}:{}), + ...(goal?{goal}:{}), + ...(hasCustomImage?{hasCustomImage:true,customImageLabel}:{}), + }; + practiceSyncState=nextState; + practiceSyncPayload={...input,_mirrored:undefined}; + if(input.pushHistory!==false) { + const last=practiceHistory.at(-1); + const sameKey=input.coalesce===true&&last&&source==='ui'&&last.source==='ui'&&last.scene===nextState.scene&& + Boolean(last.hasCustomImage)===Boolean(nextState.hasCustomImage)&&Date.now()-Date.parse(last.at)<2500; + if(sameKey) practiceHistory[practiceHistory.length-1]=nextState; + else { + practiceHistory.push(nextState); + while(practiceHistory.length>maxPracticeHistory) practiceHistory.shift(); + } + } + const enriched={...nextState,historyCount:practiceHistory.length,canUndo:practiceHistory.length>1}; + practiceSyncState=enriched; + if(source!=='ui'||input._broadcastUi===true) { + emitEvent('practice',{practice:enriched}); + } + if(!input._mirrored) { + const mirrorPayload={...input,_mirrored:true}; + if(practice) void practice.then(view=>{try{view.syncPractice(mirrorPayload);}catch{}},()=>{}); + if(onPracticeMirror) {try{onPracticeMirror(mirrorPayload);}catch{}} + } + return enriched; + } + function undoPracticeSync(input={}) { + if(practiceHistory.length<=1) throw new Error('practice_undo_unavailable'); + practiceHistory.pop(); + const prev=practiceHistory.at(-1); + practiceSyncSeq++; + const restored={ + ...prev, + seq:practiceSyncSeq, + source:'undo', + at:new Date().toISOString(), + historyCount:practiceHistory.length, + canUndo:practiceHistory.length>1, + }; + practiceSyncState=restored; + practiceSyncPayload={ + mode:restored.mode,scene:restored.scene,gamma:restored.gamma,params:restored.params,goal:restored.goal, + ...(practiceCustomImage&&restored.hasCustomImage?{ + customImageBase64:practiceCustomImage.bytes.toString('base64'), + customImageMimeType:practiceCustomImage.mimeType, + customImageLabel:practiceCustomImage.label, + }:{}), + }; + emitEvent('practice',{practice:restored}); + if(!input._mirrored) { + if(practice) void practice.then(view=>{try{view.undoPractice({_mirrored:true});}catch{}},()=>{}); + if(onPracticeMirror) {try{onPracticeMirror({...practiceSyncPayload,pushHistory:false,_mirrored:true});}catch{}} + } + return restored; + } + function requestFocus(panel, round) { + if(typeof panel!=='string'||!focusPanels.has(panel)) throw new Error('invalid_focus_panel'); + if(round!==undefined&&(!Number.isSafeInteger(round)||round<1||round>10)) throw new Error('invalid_focus_panel'); + focusSeq++; + focusTarget={seq:focusSeq,panel,...(round!==undefined?{round}:{}),at:new Date().toISOString()}; + emitEvent('focus',{focus:focusTarget}); + return focusTarget; + } + function recordUiEvent(type, summary, stageId) { + if(typeof type!=='string'||!uiEventTypes.has(type)) throw new Error('invalid_ui_event'); + const cleanSummary=typeof summary==='string'?summary.replace(/[\u0000-\u001f\u007f]/gu,' ').trim().slice(0,180):''; + if(!cleanSummary) throw new Error('invalid_ui_event'); + const cleanStage=typeof stageId==='string'&&/^[a-z0-9_]{1,40}$/.test(stageId)?stageId:undefined; + const now=Date.now(); + const prev=uiEvents.at(-1); + if(prev&&prev.type===type&&prev.summary===cleanSummary&&now-Date.parse(prev.at)<3000) return prev; + const entry={at:new Date(now).toISOString(),type,summary:cleanSummary,...(cleanStage?{stageId:cleanStage}:{})}; + uiEvents.push(entry); + if(uiEvents.length>maxUiEvents) uiEvents.splice(0,uiEvents.length-maxUiEvents); + return entry; + } + function cameraConfigHealth() { + const file=process.env.RDK_CAMERA_WORKSHOP_CONFIG??join(homedir(),'.config','rdk-camera-workshop','connection.json'); + try { + if(!isAbsolute(file)) return 'invalid'; + const resolved=realpathSync(file); + const st=lstatSync(resolved); + if(!st.isFile()||st.size>65536) return 'invalid'; + if(process.platform!=='win32'&&(st.uid!==process.getuid()||(st.mode&0o777)!==0o600)) return 'invalid'; + const parsed=JSON.parse(readFileSync(resolved,'utf8')); + const url=new URL(parsed?.url); + if(url.username||url.password||url.search||url.hash||!url.pathname.endsWith('/api/ops/vision-workshop/mcp')|| + !(url.protocol==='https:'||url.protocol==='http:'&&['localhost','127.0.0.1','[::1]'].includes(url.hostname))|| + !['admin','sso'].includes(parsed?.auth?.type)||typeof parsed?.auth?.credentialFile!=='string'||!isAbsolute(parsed.auth.credentialFile)) { + return 'invalid'; + } + let credPath; + try { credPath=realpathSync(parsed.auth.credentialFile); } + catch(err) { return err?.code==='ENOENT'?'credential_missing':'invalid'; } + const cst=lstatSync(credPath); + if(!cst.isFile()||cst.size===0||cst.size>16384) return 'invalid'; + if(process.platform!=='win32'&&(cst.uid!==process.getuid()||(cst.mode&0o777)!==0o600)) return 'invalid'; + return readFileSync(credPath,'utf8').trim()?'configured':'invalid'; + } catch(error) { + return error?.code==='ENOENT'?'unconfigured':'invalid'; + } + } + function stationHealth() { + const mediaDir=process.env.RDK_VISION_COURSE_STUDIO_MEDIA_DIR; + const mediaDirConfigured=Boolean(mediaDir&&isAbsolute(mediaDir)); + if(practiceReturnUrl) { + return {practice:true,studio:{mediaDirConfigured,liveEvents:true}}; + } + const pf=readPreflight(); + const pfChecks=pf?.checks?Object.values(pf.checks):[]; + const preflightStatus=pf?.running?'running':pfChecks.length&&pfChecks.every(c=>c.status==='passed')?'passed': + pfChecks.some(c=>c.status==='blocked')?'blocked':'idle'; + const isp=storedIsp(); + const cal=calibrationSnapshot&&resume.camera?.experimentId&&calibrationSnapshot.experimentId===resume.camera.experimentId?calibrationSnapshot:null; + const devMachine=direct?readDeveloperMachineProfile():undefined; + const launcher=boardLauncher.status(boardSelection()); + return { + camera:{ + configStatus:cameraConfigHealth(), + bound:Boolean(resume.camera?.experimentId), + experimentId:resume.camera?.experimentId??null, + title:inspected?.experiment?.title??null, + sensorModel:inspected?.experiment?.sensorModel??null, + preflightStatus, + preflightCode:pf?.checks?.service?.code??pf?.checks?.board?.code??pf?.checks?.frame?.code??null, + }, + isp:{ + hasOriginal:Boolean(isp?.original), + roundsCompleted:isp?.rounds?.length??0, + recoveryPending:Boolean(isp?.recoveryPending), + changesActive:Boolean(isp?.changesActive), + }, + calibration:{ + known:Boolean(cal), + readyEngines:cal?cal.readyEngines:[], + completedOps:cal?cal.completedOps:[], + taskCount:cal?cal.taskCount:0, + rawCount:cal?cal.rawCount:0, + }, + training:direct?{ + mode:'devmachine', + profileStatus:devMachine.status, + runId:resume.run?.id??null, + runState:resume.run?.state??null, + }:{ + mode:'robogo', + connected:Boolean(roboGo.connected?.()), + runId:resume.run?.id??null, + runState:resume.run?.state??null, + }, + board:{ + path:resume.path??null, + launcherReady:launcher.ready, + launcherReason:launcher.reason??null, + hasBoardArchive:Boolean(process.env.RDK_VISION_COURSE_BOARD_ARCHIVE), + hasPresetArchive:Boolean(process.env.RDK_VISION_COURSE_PRESET_BOARD_ARCHIVE), + }, + studio:{ + mediaDirConfigured, + liveEvents:true, + }, + }; + } const persist=(next=resume)=>writeWorkbenchState(stateFile,{resume:next,submission,verifiedRun,lockedRun,cameraCapture,cameraIsp}); const selectedModelHash=()=>resume.path==='B'?presetModelHash(resume.evidence.preset_model) :resume.path==='C'||resume.run?.source==='robogo'&&resume.run.modelSha256!==normalizedModelHash(resume.evidence.x5_model_hash) ?undefined:normalizedModelHash(resume.evidence.x5_model_hash); + const boardBinding=()=>({path:resume.path,modelHash:selectedModelHash(),experimentId:resume.camera?.experimentId}); + function boardSelection() { + const isp=storedIsp(); + const readback=isp?.reloadReadback??isp?.rounds?.findLast(round=>round.decision?.choice==='keep')?.gammaReadback; + const approvedIsp=readback?.config&&isp?.original?.config&&readback.hash!==isp.original.hash? + {config:readback.config,hash:readback.hash,originalConfig:isp.original.config,originalHash:isp.original.hash}:undefined; + return {...boardBinding(),approvedIsp,comparisonEligible:Boolean(approvedIsp&&comparisonEligible(isp.original,readback)), + available:guideCourse(plan,resume).routing.choices.some(choice=>choice.id===resume.path&&choice.available), + cameraBusy:cameraJob||ispBusy||preflightRunning||cameraIsp?.recoveryPending||cameraIsp?.changesActive}; + } + const selectedBoard=()=>boardLauncher.evidence(boardBinding())??(resume.path==='B'?presetBoard:board); function checkTrainingWindow() { if(!stateFile) throw new Error('robogo_state_required'); if(resume.run||resume.evidence.run_id) throw new Error('robogo_run_exists'); @@ -109,10 +469,12 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera } async function prepareTraining() { checkTrainingWindow(); + if(await priorTraining?.()) throw new Error('robogo_other_station_run'); const round=authorizationRound; const profile=await trainingProfile(); const ref=await roboGo.prepare(profile.input); checkTrainingWindow(); + if(switchingStation||isActiveStation&&!await isActiveStation()) throw new Error('robogo_plan_changed'); if(round!==authorizationRound) throw new Error('robogo_plan_changed'); if(resume.blockers.training_image_unavailable) update({},['training_image_unavailable']); const confirmationId=randomUUID(); @@ -127,6 +489,8 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera submittingTraining=true; preparedTraining=undefined; try { + if(await priorTraining?.()) throw new Error('robogo_other_station_run'); + if(switchingStation||isActiveStation&&!await isActiveStation()) throw new Error('robogo_plan_changed'); submission='pending'; persist(); const run=await roboGo.submit(prepared.ref); @@ -134,16 +498,17 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera submission='accepted'; verifiedRun=run; return update({run:{...run,checkedAtMinute:resume.elapsedMinutes}}); - } catch { + } catch(error) { + if(submission==='idle') throw error; if(!lockedRun) submission='pending'; throw new Error('robogo_submit_unconfirmed'); } finally {submittingTraining=false;} } - async function refreshRoboGo() { + async function refreshRoboGo(force=false) { const run=resume.run; if(run?.source!=='robogo') throw new Error('robogo_run_required'); if(checkingRoboGo?.id===run.id) return checkingRoboGo.promise; - if(lastRoboGoCheck?.id===run.id&&Date.now()-lastRoboGoCheck.time<15000) return read(); + if(!force&&lastRoboGoCheck?.id===run.id&&Date.now()-lastRoboGoCheck.time<15000) return read(); const promise=(async()=>{ const result=await roboGo.refresh(run.id,{name:run.name,receipt:run.receipt}); if(resume.run?.source!=='robogo'||resume.run.id!==result.id) throw new Error('run_receipt_mismatch'); @@ -171,10 +536,12 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera checks:{service:{status:'checking'},board:{status:'waiting'},frame:{status:'waiting'}}}; preflight=result; preflightRunning=true; + emitEvent('preflight',{running:true}); void (async()=>{ try { await cameraSource.preflight(binding,(layer,receipt)=>{ result.checks[layer]={...receipt,checkedAt:new Date().toISOString()}; + emitEvent('preflight',{layer,status:receipt.status}); }); if(binding?.experimentId&&binding.experimentId===resume.camera?.experimentId&& Object.values(result.checks).every(check=>check.status==='passed')) { @@ -189,6 +556,7 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera result.running=false; result.completedAt=new Date().toISOString(); preflightRunning=false; + emitEvent('preflight',{running:false}); } })(); return result; @@ -228,16 +596,22 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera function saveIsp(value) { const previous=cameraIsp; cameraIsp=value; - try {persist();} + try {persist();emitEvent('isp');} catch(error) {cameraIsp=previous;throw error;} } - function queueIsp(action,goal,{round,choice,reason,field,expected,value,trial}={}) { + function queueIsp(action,goal,{round,choice,reason,field,expected,value,trial,candidateId,values}={}) { const validText=(input,max)=>typeof input==='string'&&input.trim().length>0&&input.trim().length<=max&&!/[\u0000-\u001f\u007f]/u.test(input); const isChoice=['keep','restore'].includes(choice)&&validText(reason,180); - if(!['save','gamma','decision','reload','revert','restore','exposure','learner_options','learner_apply','learner_decision'].includes(action)|| - (action==='gamma'&&!validText(goal,180))|| + const validMultiValues=values&&typeof values==='object'&&!Array.isArray(values)&& + Object.keys(values).length>=1&&Object.keys(values).length<=8&& + Object.entries(values).every(([k,v])=>['exposureUs','gain','redGain','blueGain','brightness','contrast','saturation','hue'].includes(k)&&typeof v==='number'&&Number.isFinite(v)); + if(!['save','gamma','gamma_prepare','gamma_apply','gamma_discard','decision','reload','revert','restore','exposure','learner_options','learner_apply','learner_decision','auto_plan','multi_apply'].includes(action)|| + (['gamma','gamma_prepare'].includes(action)&&!validText(goal,180))|| + (action==='gamma_apply'&&!/^[a-f0-9-]{36}$/u.test(candidateId??''))|| + (['learner_apply','auto_plan','multi_apply'].includes(action)&&(goal!==undefined&&!validText(goal,180)||reason!==undefined&&!validText(reason,180)))|| (action==='decision'&&(![1,2].includes(round)||!isChoice))|| (action==='learner_apply'&&(!/^[a-zA-Z]{1,40}$/.test(field??'')||typeof field!=='string'||!Number.isFinite(expected)||!Number.isFinite(value)))|| + (action==='multi_apply'&&!validMultiValues)|| (action==='learner_decision'&&(!Number.isSafeInteger(trial)||!isChoice))) { throw new Error('camera_isp_action_invalid'); } @@ -249,22 +623,33 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera if(action==='save'&¤t?.original) return ispStatus(); if(action!=='save'&&!current?.original) throw new Error('camera_isp_snapshot_missing'); if((action==='restore'||action==='revert')&¤t.stop) return ispStatus(); - if(['gamma','reload','exposure','learner_apply','learner_options'].includes(action)&&(current.recoveryPending||current.changesActive||current.stop)) throw new Error('camera_recovery_required'); + if(['gamma','gamma_prepare','gamma_apply','reload','exposure','learner_apply','learner_options'].includes(action)&&(current.recoveryPending||current.changesActive||current.stop)) throw new Error('camera_recovery_required'); + if(['auto_plan','multi_apply'].includes(action)&&(current.recoveryPending||current.stop)) throw new Error('camera_recovery_required'); const rounds=current?.rounds??[]; const nextRound=rounds.length+1; const selected=rounds.at(-1); const adjustments=current?.adjustments??[]; const active=adjustments.find(item=>item.number===current?.activeAdjustment); if(action==='learner_apply'&&selected&&!selected.decision) throw new Error('camera_gamma_round_locked'); + if(action==='learner_apply'&¤t.gammaProposal) throw new Error('camera_gamma_proposal_pending'); if(action==='learner_apply'&&!current.learnerOptions?.some(item=>item.id===field&&!item.disabled&&item.value===expected)) { throw new Error('camera_learner_control_changed'); } if(action==='learner_decision'&&(!active||trial!==active.number||active.decision||!active.after|| !current.changesActive||current.recoveryPending||current.stop)) throw new Error('camera_learner_trial_locked'); if(action==='exposure'&&selected&&!selected.decision) throw new Error('camera_gamma_round_locked'); - if(action==='gamma'&&(nextRound>2||selected&&!selected.decision||round!==undefined&&round!==nextRound)) { + if(['gamma','gamma_prepare','gamma_apply'].includes(action)&&(nextRound>2||selected&&!selected.decision||round!==undefined&&round!==nextRound)) { throw new Error('camera_gamma_round_locked'); } + if(action==='gamma_apply'&&(!current.gammaProposal||current.gammaProposal.candidateId!==candidateId|| + current.gammaProposal.number!==nextRound)) throw new Error('camera_gamma_proposal_changed'); + if(action==='gamma_discard') { + const next={...current,stage:'saved'}; + delete next.gammaProposal; + delete next.error; + saveIsp(next); + return ispStatus(); + } if(action==='decision'&&(round!==selected?.number||selected.decision||current.stop||choice==='keep'&& (!current.changesActive||current.recoveryPending||current.stage==='gamma_reloaded'))) throw new Error('camera_gamma_round_locked'); if(action==='reload'&&(!current.gamma?.candidateId||!current.gammaReadback||!current.restored)) { @@ -274,8 +659,11 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera stage:action==='save'?'snapshot':'checking', recoveryPending:['restore','revert'].includes(action)||['decision','learner_decision'].includes(action)&&choice==='restore'||current?.recoveryPending===true}; delete status.error; - if(action==='learner_options') delete status.learnerOptions; - if(!['learner_options','learner_apply'].includes(action)) delete status.learnerOptions; + if(!['gamma_apply','learner_options'].includes(action)) delete status.gammaProposal; + if(action!=='learner_apply') { + delete status.learnerOptions; + delete status.learnerOptionsReadAt; + } saveIsp(status); ispBusy=true; void (async()=>{ @@ -287,11 +675,38 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera update({evidence:{original_snapshot:status.original.baselineId+' · sha256:'+status.original.hash}}); } else if(action==='learner_options') { status.learnerOptions=await cameraSource.getLearnerOptions(binding,status.original); - status.stage='learner_ready'; + status.learnerOptionsReadAt=new Date().toISOString(); + status.stage=status.gammaProposal?'gamma_proposed':'learner_ready'; + } else if(action==='auto_plan') { + status.autoPlan=await cameraSource.autoPlanHardwareIsp(binding,status.original,goal?.trim()??''); + status.stage='auto_planned'; + } else if(action==='multi_apply') { + delete status.learnerOptions; + delete status.learnerOptionsReadAt; + const number=(adjustments.at(-1)?.number??0)+1; + let record={number,kind:'multi',entry:'ai_multi_tune', + ...(goal?{goal:goal.trim()}:{}),...(reason?{reason:reason.trim()}:{})}; + await cameraSource.multiHardwareTrial(binding,status.original,{values,goal:goal?.trim(),reason:reason?.trim()},(stage,progress,writing)=>{ + status.stage=stage; + if(progress) { + record={...record,...progress}; + status.adjustments=[...adjustments,record]; + } + if(writing) { + status.activeAdjustment=number; + status.recoveryPending=true; + delete status.readback; + delete status.stopPending; + } + saveIsp({...status}); + }); + Object.assign(status,{stage:'multi_saved',recoveryPending:false,changesActive:true}); } else if(action==='learner_apply') { delete status.learnerOptions; + delete status.learnerOptionsReadAt; const number=(adjustments.at(-1)?.number??0)+1; - let record={number,field}; + let record={number,field,...(goal?{goal:goal.trim()}:{}),...(reason?{reason:reason.trim()}:{}), + entry:goal||reason?'guided':'manual'}; await cameraSource.learnerTrial(binding,status.original,{field,expected,value},(stage,progress,writing)=>{ status.stage=stage; if(progress) { @@ -343,22 +758,33 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera status.recoveryPending=false; status.stage=status.exposure.error?'exposure_incomplete':'exposure_restored'; } - } else if(action==='gamma') { + } else if(action==='gamma_prepare'||action==='gamma'||action==='gamma_apply') { delete status.pendingGamma; - const result=await cameraSource.gammaTrial(binding,status.original,goal.trim(),(stage,progress,applyStarted)=>{ + const onPhase=(stage,progress,applyStarted)=>{ status.stage=stage; if(progress) status.pendingGamma={...status.pendingGamma,...progress}; if(applyStarted) { status.recoveryPending=true; + delete status.gammaProposal; delete status.readback; delete status.stopPending; delete status.gammaReadback; } saveIsp({...status}); - }); + }; + const proposal=action==='gamma_apply'?status.gammaProposal:{ + ...await cameraSource.prepareGamma(binding,status.original,goal.trim(),onPhase), + number:nextRound,goal:goal.trim()}; + if(action==='gamma_prepare') { + Object.assign(status,{gammaProposal:proposal,stage:'gamma_proposed'}); + delete status.pendingGamma; + return; + } + const result=await cameraSource.applyPreparedGamma(binding,status.original,proposal,onPhase); status.gamma={before:result.before,after:result.after,candidateId:result.candidateId}; status.gammaReadback=result.readback; - status.rounds=[...rounds,{number:nextRound,goal:goal.trim(),...status.gamma,beforeReadback:result.beforeReadback, + status.rounds=[...rounds,{number:nextRound,goal:proposal.goal,model:proposal.model,modelReasons:proposal.reasons, + ...status.gamma,beforeReadback:result.beforeReadback, gammaReadback:result.readback}]; delete status.pendingGamma; delete status.restored; @@ -405,6 +831,7 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera }, }); delete status.comparisonIssue; + delete status.gammaProposal; Object.assign(status,result,{stage:action==='restore'?'stopped':'reverted',recoveryPending:false,changesActive:false,stopPending:false}); if(exposureRecovery) status.exposure={...status.exposure,restorationReadback:result.readback,recoveryPending:false}; if(active) { @@ -426,6 +853,11 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera update({evidence},['recovery_unconfirmed']); } } catch(error) { + if(action==='gamma_apply'&&!status.recoveryPending&&error.message==='camera_isp_snapshot_changed') { + delete status.gammaProposal; + status.error='camera_gamma_baseline_moved'; + return; + } if(['decision','learner_decision'].includes(action)&&choice==='keep'&&error.message==='camera_isp_snapshot_changed') status.recoveryPending=true; status.error=/^(vision|camera)_[a-z0-9_]{1,90}$/.test(error.message)?error.message:'camera_isp_recording_failed'; if(status.recoveryPending) { @@ -445,7 +877,7 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera function saveCapture(value) { const previous=cameraCapture; cameraCapture=value; - try {persist();} + try {persist();emitEvent('capture');} catch(error) {cameraCapture=previous;throw error;} } function recordCapture(action,value) { @@ -492,7 +924,11 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera const binding=resume.camera; const previous=captureStatus()??{experimentId:binding.experimentId,assets:{},errors:{}}; const next=structuredClone(previous); - if(action==='photo') {delete next.assets.photo;delete next.errors.photo;} + if(action==='photo') { + next.photoRequestId=randomUUID(); + delete next.assets.photo; + delete next.errors.photo; + } else if(action==='retake'||!previous.scene) { for(const kind of ['raw','isp','render']) {delete next.assets[kind];delete next.errors[kind];} next.scene=scene?.trim(); @@ -500,6 +936,9 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera if(action==='render'&&(!next.assets.raw||next.assets.render)) throw new Error('camera_render_raw_required'); if(action==='baseline'&&next.scene!==scene.trim()) throw new Error('camera_scene_changed'); if(action==='baseline'&&next.assets.raw&&next.assets.isp&&next.assets.render&&!next.recording) return previous; + if((action==='baseline'||action==='render')&&next.errors.render===rawReplayCaptureMetadataRequired) { + throw new Error(next.errors.render); + } if(action==='baseline'&&['raw','isp','render'].some(kind=>unconfirmedCapture.has(next.errors[kind]))|| action==='render'&&unconfirmedCapture.has(next.errors.render)) throw new Error('camera_capture_unconfirmed'); delete next.recording; @@ -530,6 +969,10 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera throw new Error('invalid_session_update'); } const candidate={...current,...patch,evidence:{...current.evidence,...patch.evidence},blockers}; + if(direct&&resume.run?.source==='external') { + if(incomingId&&incomingId!==resume.run.id||candidate.run&&candidate.run.source!=='external') throw new Error('run_receipt_mismatch'); + candidate.run??=resume.run; + } if(lockedRun) { if((incomingId&&incomingId!==lockedRun.id)||(candidate.run&&candidate.run.source!=='robogo')) throw new Error('run_receipt_mismatch'); candidate.run??=lockedRun; @@ -543,46 +986,114 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera const verified=run.source==='robogo'&&run.id===verifiedRun?.id?verifiedRun.modelSha256:undefined; candidate.run={...run,...(verified?{modelSha256:verified}:{})}; } - if (!replace&&patch.path&&patch.path!==current.path&&candidate.elapsedMinutes!==undefined&&candidate.elapsedMinutesserver.close(),idleMs); idle.unref(); } - const server=createServer(async (req,res)=>{ - const host='127.0.0.1:'+server.address().port; + const server=createServer((req,res)=>{ + const mutating=req.method==='POST'||req.url?.startsWith('/robogo/callback'); + if(mutating) mutatingRequests++; + void handleRequest(req,res,mutating).catch(error=>res.destroy(error)).finally(()=>{ + if(mutating) mutatingRequests--; + }); + }); + const isJsonContent=req=>(req.headers['content-type']??'').split(';',1)[0].trim().toLowerCase()==='application/json'; + async function handleRequest(req,res,mutating) { + const portNumber=server.address().port; + const host='127.0.0.1:'+portNumber; res.setHeader('Cache-Control','no-store'); res.setHeader('X-Content-Type-Options','nosniff'); res.setHeader('Referrer-Policy','no-referrer'); res.setHeader('Content-Security-Policy',"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' blob: data:; base-uri 'none'; form-action 'none'"); - if (req.headers.host!==host) { res.writeHead(404).end(); return; } + if (req.headers.host!==host) { + if (req.headers.host==='localhost:'+portNumber) { + res.setHeader('Content-Type','text/plain; charset=utf-8'); + res.writeHead(400).end('请使用本机回环地址 http://'+host+'(保留 # 后的会话片段)打开课堂工作台。'); + return; + } + res.writeHead(404).end(); return; + } const url=new URL(req.url,'http://'+host); - if (req.headers['x-workshop-session']===key||url.pathname==='/course.json'&&url.searchParams.get('view')===key) keepAlive(); + if(url.pathname==='/session/retire') { + if(!reportedBuild||req.method!=='POST'||req.headers['x-workshop-session']!==key|| + req.headers.origin&&req.headers.origin!=='http://'+host) {res.writeHead(404).end();return;} + res.setHeader('Content-Type','application/json; charset=utf-8'); + if(retiring||mutatingRequests>1||switchingStation||cameraJob||preflightRunning||ispBusy|| + cameraIsp?.recoveryPending||cameraIsp?.changesActive||boardLauncher.running()|| + submittingTraining||submission==='pending'||checkingRoboGo||creatingDarkTask|| + [...calibrationRequests.values()].some(item=>item.status==='submitting')) { + res.writeHead(409).end(JSON.stringify({error:'station_busy'}));return; + } + retiring=true; + req.resume(); + closeSseClients(); + res.setHeader('Connection','close'); + res.end(JSON.stringify({retiring:true}),()=>server.close()); + return; + } + if(retiring&&mutating) { + res.writeHead(409,{'Content-Type':'application/json; charset=utf-8'}).end(JSON.stringify({error:'station_retiring'})); + return; + } + if ((req.headers['x-workshop-session']===key||url.pathname==='/course.json'&&url.searchParams.get('view')===key)&&req.headers['x-workshop-poll']!=='1'&&url.pathname!=='/events') keepAlive(); + if(req.method==='POST'&&req.headers['x-workshop-session']===key&&isActiveStation&& + (!await isActiveStation()||switchingStation)) { + res.writeHead(409,{'Content-Type':'application/json'}).end(JSON.stringify({error:'station_inactive'})); + return; + } + if(['/station/new','/station/original','/station/latest','/station/active'].includes(url.pathname)) { + const action=url.pathname.slice('/station/'.length); + if(!stationActions||req.method!==(action==='active'?'GET':'POST')||req.headers['x-workshop-session']!==key|| + req.headers.origin&&req.headers.origin!=='http://'+host) {res.writeHead(404).end();return;} + if(action!=='active'&&(switchingStation||cameraJob||preflightRunning||ispBusy||cameraIsp?.recoveryPending||cameraIsp?.changesActive|| + boardLauncher.running()||submittingTraining||submission==='pending')) { + res.writeHead(409,{'Content-Type':'application/json'}).end(JSON.stringify({error:'station_busy'}));return; + } + if(action!=='active') switchingStation=true; + res.setHeader('Content-Type','application/json; charset=utf-8'); + try { + const next=await stationActions(action); + res.end(JSON.stringify({url:next})); + } catch { + res.writeHead(503).end(JSON.stringify({error:'station_unavailable'})); + } finally {if(action!=='active') switchingStation=false;} + return; + } if (url.pathname==='/practice') { if (practiceReturnUrl||req.headers['x-workshop-session']!==key) { res.writeHead(404).end(); return; } if (req.method!=='POST'||req.headers.origin&&req.headers.origin!=='http://'+host) { res.writeHead(405).end(); return; } res.setHeader('Content-Type','application/json; charset=utf-8'); try { - practice??=startWorkbench({},0,undefined,{idleMs:idleMs??8*60*60*1000,practiceReturnUrl:'http://'+host+'/#'+key}).then(view=>{ + practice??=startWorkbench({},0,undefined,{ + idleMs:idleMs??8*60*60*1000,classroomPlan:plan,practiceReturnUrl:'http://'+host+'/#'+key, + onPracticeMirror:payload=>{try{applyPracticeSync(payload);}catch{}}, + }).then(view=>{ view.server.once('close',()=>{practice=undefined;}); + if(practiceSyncPayload) {try{view.syncPractice({...practiceSyncPayload,_mirrored:true});}catch{}} return view; }); const view=await practice; @@ -593,14 +1104,18 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera } return; } - if (practiceReturnUrl && /^\/(?:camera|robogo|board|training)(?:\/|$)/.test(url.pathname)) { res.writeHead(404).end(); return; } + if (practiceReturnUrl && /^\/(?:calibration|camera|robogo|board|training)(?:\/|$)/.test(url.pathname)) { res.writeHead(404).end(); return; } if(url.pathname==='/robogo/callback'&&req.method==='GET') { - res.setHeader('Content-Type','text/plain; charset=utf-8'); try { + if(isActiveStation&&(!await isActiveStation()||switchingStation)) throw new Error('station_inactive'); await roboGo.callback(url.searchParams); authorizationRound++;preparedTraining=undefined; - res.writeHead(303,{Location:'/#'+key}).end(); + emitEvent('robogo',{connected:true}); + res.setHeader('Content-Type','text/html; charset=utf-8'); + res.setHeader('Content-Security-Policy',"default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"); + res.writeHead(200).end('RoboGO 授权完成

RoboGO 授权已完成

请返回原课堂工作台窗口继续查询或提交训练任务,本页面可安全关闭。

'); } catch { + res.setHeader('Content-Type','text/plain; charset=utf-8'); res.writeHead(400).end('RoboGO 授权未完成。请回课堂工作台重新连接。'); } return; @@ -611,18 +1126,29 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera } res.setHeader('Content-Type','application/json; charset=utf-8'); try { + if(direct&&(['/robogo/prepare','/robogo/submit'].includes(url.pathname)|| + url.pathname==='/robogo/connect'&&resume.run?.source!=='robogo')) throw new Error('robogo_devmachine_classroom'); if(req.method==='GET'&&url.pathname==='/robogo/state') { const profile=stateFile?await trainingProfile().then(()=>({profileConfigured:true}), error=>({profileConfigured:false,profileIssue:error.message})): {profileConfigured:false,profileIssue:'robogo_state_required'}; - return res.end(JSON.stringify({connected:roboGo.connected(),...profile,uncertainTraining:submission==='pending'})); + return res.end(JSON.stringify({connected:roboGo.connected(),...profile,uncertainTraining:submission==='pending', + otherStationTraining:await priorTraining?.()})); } if(req.method!=='POST') {res.writeHead(405).end();return;} if(url.pathname==='/robogo/connect') { authorizationRound++;preparedTraining=undefined; return res.end(JSON.stringify(await roboGo.authorize('http://'+host))); } - if(url.pathname==='/robogo/refresh') return res.end(JSON.stringify(await refreshRoboGo())); + if(url.pathname==='/robogo/refresh') { + let force=url.searchParams.get('force')==='1'; + if(!force&&isJsonContent(req)) { + const chunks=[];let size=0; + for await(const chunk of req) { if((size+=chunk.length)<=1024) chunks.push(chunk); } + try { force=JSON.parse(Buffer.concat(chunks).toString('utf8'))?.force===true; } catch {} + } + return res.end(JSON.stringify(await refreshRoboGo(force))); + } if(url.pathname==='/robogo/prepare') return res.end(JSON.stringify(await prepareTraining())); if(url.pathname==='/robogo/submit') { const id=req.headers['x-workshop-confirmation']; @@ -630,11 +1156,58 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera } res.writeHead(405).end(); } catch(error) { - const code=/^robogo_[a-z_]+$/.test(error.message)?error.message:'robogo_unavailable'; + const code=/^robogo_[a-z_]+$/.test(error.message)||error.message==='run_receipt_mismatch'?error.message:'robogo_unavailable'; res.writeHead(code==='robogo_login_required'?401:422).end(JSON.stringify({error:code})); } return; } + if(url.pathname==='/board/launch') { + if(req.headers['x-workshop-session']!==key||req.headers.origin&&req.headers.origin!=='http://'+host) { + res.writeHead(404).end();return; + } + res.setHeader('Content-Type','application/json; charset=utf-8'); + try { + if(req.method==='GET') return res.end(JSON.stringify(boardLauncher.status(boardSelection()))); + if(req.method==='POST') { + if(req.headers['x-workshop-isp-mode']==='comparison'&&req.headers['x-workshop-fixed-scene']!=='1') { + throw new Error('board_launcher_comparison_scene_unconfirmed'); + } + const job=boardLauncher.start(boardSelection(),req.headers['x-workshop-isp-mode']); + emitEvent('board'); + return res.writeHead(202).end(JSON.stringify(job)); + } + res.writeHead(405).end(); + } catch(error) { + const code=/^board_launcher_[a-z_]+$/.test(error.message)?error.message:'board_launcher_start_failed'; + res.writeHead(409).end(JSON.stringify({error:code})); + } + return; + } + if(url.pathname==='/board/score') { + if(req.method!=='POST'||req.headers['x-workshop-session']!==key||!isJsonContent(req)|| + req.headers.origin&&req.headers.origin!=='http://'+host) {res.writeHead(404).end();return;} + res.setHeader('Content-Type','application/json; charset=utf-8'); + try { + let body=''; + for await(const chunk of req) { + body+=chunk; + if(body.length>1024) throw new Error('board_comparison_region_invalid'); + } + const request=JSON.parse(body); + if(!request||typeof request!=='object'||Array.isArray(request)) throw new Error('board_comparison_region_invalid'); + const recorded=await selectedBoard().score(selectedModelHash(),request); + res.end(JSON.stringify(recorded)); + } catch(error) { + const code=evidenceErrors.has(error.message)?error.message:'board_comparison_region_invalid'; + res.writeHead(422).end(JSON.stringify({error:code})); + } + return; + } + if(req.method==='POST'&&url.pathname.startsWith('/camera/')&&boardLauncher.running()&& + req.headers['x-workshop-session']===key) { + res.setHeader('Content-Type','application/json; charset=utf-8'); + res.writeHead(409).end(JSON.stringify({error:'camera_capture_busy'}));return; + } if(url.pathname==='/training/receipt'||url.pathname==='/board/receipt'||url.pathname==='/board/preview'||url.pathname.startsWith('/board/file/')) { if(req.method!=='GET'||req.headers['x-workshop-session']!==key) {res.writeHead(404).end();return;} try { @@ -643,7 +1216,10 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera res.setHeader('Content-Type',result.type);res.end(result.bytes);return; } const result=url.pathname==='/training/receipt'?await externalTrainingReceipt():url.pathname==='/board/preview'? - await selectedBoard().preview(selectedModelHash(),url.searchParams.get('known')):(await selectedBoard().get(selectedModelHash())).view; + await selectedBoard().preview(selectedModelHash(),url.searchParams.get('known'),url.searchParams.get('batch')==='1'): + (await selectedBoard().get(selectedModelHash())).view; + if(direct&&url.pathname==='/training/receipt'&& + (resume.run?.source!=='external'||result.runId!==resume.run.id)) throw new Error('training_receipt_task_unverified'); res.setHeader('Content-Type','application/json; charset=utf-8');res.end(JSON.stringify(result)); } catch(error) { const code=evidenceErrors.has(error.message)?error.message:'evidence_file_invalid'; @@ -651,6 +1227,98 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera } return; } + if(url.pathname==='/calibration') { + if(req.headers['x-workshop-session']!==key||req.headers.origin&&req.headers.origin!=='http://'+host) { + res.writeHead(404).end();return; + } + res.setHeader('Content-Type','application/json; charset=utf-8'); + try { + const binding=resume.camera; + let data; + if(req.method==='GET') { + if([...url.searchParams.keys()].some(key=>!['experimentId','action','taskId'].includes(key))) { + throw new Error('camera_calibration_invalid'); + } + data=Object.fromEntries(url.searchParams); + if(!['overview','task','result','apply_plan'].includes(data.action)) throw new Error('camera_calibration_invalid'); + } else if(req.method==='POST'&&isJsonContent(req)) { + const chunks=[];let length=0; + for await(const chunk of req) { + if((length+=chunk.length)>1024*1024) throw new Error('camera_calibration_file_too_large'); + chunks.push(chunk); + } + try { data=JSON.parse(Buffer.concat(chunks)); } catch { throw new Error('camera_calibration_invalid'); } + if(!data||typeof data!=='object'||Array.isArray(data)|| + Object.keys(data).some(key=>!['experimentId','action','input','taskId'].includes(key))|| + !['create','run','import_measurement','create_dark','create_lsc','create_awb','create_ccm','run_async'].includes(data.action)) throw new Error('camera_calibration_invalid'); + } else {res.writeHead(405).end();return;} + async function assertBinding() { + if(!binding||data.experimentId!==binding.experimentId|| + isActiveStation&&(switchingStation||!await isActiveStation())|| + resume.camera?.experimentId!==binding.experimentId) throw new Error('camera_binding_invalid'); + } + await assertBinding(); + const requestId=binding.experimentId+'/'+data.taskId; + const guidedBuilders={create_dark:darkTaskInput,create_lsc:lscTaskInput,create_awb:awbTaskInput,create_ccm:ccmTaskInput}; + let result; + if(Object.hasOwn(guidedBuilders,data.action)) { + const args=validateCalibrationAction({...data.input,action:data.action,experimentId:data.experimentId}); + if(creatingDarkTask) throw new Error('camera_calibration_busy'); + creatingDarkTask=true; + try { + const catalog=await cameraSource.calibration(binding,'overview'); + recordCalibrationSnapshot(binding.experimentId,catalog); + const input=guidedBuilders[data.action](args,catalog); + const existing=catalog.tasks.find(task=>matchingDarkTask(task,input)); + await assertBinding(); + result=existing?{task:existing,reused:true}:await cameraSource.calibration(binding,'create',input); + if(!existing&&result?.task) { + recordCalibrationSnapshot(binding.experimentId,{...catalog,tasks:[...catalog.tasks,result.task]}); + } + } finally {creatingDarkTask=false;} + } else if(data.action==='run_async') { + validateCalibrationAction({action:'run',experimentId:data.experimentId,taskId:data.taskId}); + const {task}=await cameraSource.calibration(binding,'task',undefined,data.taskId); + await assertBinding(); + if(task.id!==data.taskId||!['ispstudio','ispcal-lsc','numpy'].includes(task.engine)) { + throw new Error('camera_calibration_invalid'); + } + if(task.engine==='ispstudio'&&!/^[a-f0-9]{64}$/.test(task.engineSourceSha256)) { + throw new Error('vision_calibration_ispstudio_unavailable'); + } + if(task.engine==='ispcal-lsc'&&!/^[a-f0-9]{64}$/.test(task.engineSourceSha256)) { + throw new Error('vision_calibration_ispcal_lsc_unavailable'); + } + const pending=calibrationRequests.get(requestId); + if(!['queued','failed','interrupted'].includes(task.status)||pending?.status==='submitting') { + result={task,pendingRequest:pending?.status==='submitting'?pending:undefined}; + } else { + const submitting={status:'submitting'}; + for(const [request,entry] of calibrationRequests) { + if(calibrationRequests.size<128) break; + if(entry.status!=='submitting') calibrationRequests.delete(request); + } + if(calibrationRequests.size>=128) throw new Error('camera_calibration_busy'); + calibrationRequests.set(requestId,submitting); + void cameraSource.calibration(binding,'run',undefined,data.taskId) + .then(()=>{calibrationRequests.delete(requestId);emitEvent('calibration');}) + .catch(error=>{calibrationRequests.set(requestId,{status:'request_failed',error:calibrationErrorCode(error)});emitEvent('calibration');}); + result={task,pendingRequest:submitting}; + } + } else { + result=await cameraSource.calibration(binding,data.action,data.input,data.taskId); + if(data.action==='overview') recordCalibrationSnapshot(binding.experimentId,result); + if(data.action==='task') result={...result,pendingRequest:calibrationRequests.get(requestId)}; + } + await assertBinding(); + if(req.method==='POST') emitEvent('calibration'); + res.end(JSON.stringify(result)); + } catch(error) { + const code=calibrationErrorCode(error); + res.writeHead(422).end(JSON.stringify({error:code})); + } + return; + } if(url.pathname==='/camera/isp') { if(req.headers['x-workshop-session']!==key||req.headers.origin&&req.headers.origin!=='http://'+host) { res.writeHead(404).end();return; @@ -666,6 +1334,7 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera const trial=url.searchParams.get('trial'); const source=()=>{ const status=storedIsp(); + if(scope==='gamma-proposal') return round===null?status?.gammaProposal:undefined; if(exposure) return round===null?status?.exposure:undefined; if(learner) return round===null?status?.adjustments?.find(item=>String(item.number)===trial):undefined; if(scope!==null||trial!==null) return; @@ -693,16 +1362,16 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera } res.end(JSON.stringify({isp:ispStatus()}));return; } - if(req.method!=='POST'||req.headers['content-type']!=='application/json') {res.writeHead(405).end();return;} + if(req.method!=='POST'||!isJsonContent(req)) {res.writeHead(405).end();return;} try { const chunks=[]; let size=0; for await(const chunk of req) { - if((size+=chunk.length)>1024) {res.writeHead(413).end();return;} + if((size+=chunk.length)>4096) {res.writeHead(413).end();return;} chunks.push(chunk); } const body=JSON.parse(Buffer.concat(chunks)); - if(!body||Array.isArray(body)||Object.keys(body).some(k=>!['action','goal','round','choice','reason','field','expected','value','trial'].includes(k))) throw new Error('camera_isp_action_invalid'); + if(!body||Array.isArray(body)||Object.keys(body).some(k=>!['action','goal','round','choice','reason','field','expected','value','trial','candidateId','values'].includes(k))) throw new Error('camera_isp_action_invalid'); const result=queueIsp(body.action,body.goal,body); res.writeHead(202).end(JSON.stringify({isp:result})); } catch(error) { @@ -717,7 +1386,7 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera } res.setHeader('Content-Type','application/json; charset=utf-8'); if(req.method==='GET') {res.end(JSON.stringify({preflight:readPreflight()}));return;} - if(req.method!=='POST'||req.headers['content-type']!=='application/json') {res.writeHead(405).end();return;} + if(req.method!=='POST'||!isJsonContent(req)) {res.writeHead(405).end();return;} try { const result=queuePreflight(); res.writeHead(202).end(JSON.stringify({preflight:result})); @@ -740,8 +1409,8 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera } if(url.pathname!=='/camera/capture') {res.writeHead(405).end();return;} res.setHeader('Content-Type','application/json; charset=utf-8'); - if(req.method==='GET') {res.end(JSON.stringify({capture:captureStatus(),recordingRevision:revision}));return;} - if(req.method!=='POST'||req.headers['content-type']!=='application/json') {res.writeHead(405).end();return;} + if(req.method==='GET') {res.end(JSON.stringify({experimentId:resume.camera?.experimentId??null,capture:captureStatus(),recordingRevision:revision}));return;} + if(req.method!=='POST'||!isJsonContent(req)) {res.writeHead(405).end();return;} const chunks=[]; let size=0; for await(const chunk of req) { @@ -754,7 +1423,7 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera const capture=queueCapture(body.action,body.scene); res.writeHead(202).end(JSON.stringify({capture})); } catch(error) { - const code=/^camera_[a-z0-9_]{1,90}$/.test(error.message)?error.message:'camera_service_error'; + const code=error.message===rawReplayCaptureMetadataRequired||/^camera_[a-z0-9_]{1,90}$/.test(error.message)?error.message:'camera_service_error'; res.setHeader('Content-Type','application/json; charset=utf-8'); res.writeHead(code==='camera_archive_missing'?404:code==='camera_capture_busy'?409:422).end(JSON.stringify({error:code})); } @@ -784,11 +1453,123 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera } return; } + if (url.pathname==='/events') { + if (req.method!=='GET'||req.headers['x-workshop-session']!==key|| + req.headers.origin&&req.headers.origin!=='http://'+host) { res.writeHead(404).end(); return; } + res.writeHead(200,{ + 'Content-Type':'text/event-stream; charset=utf-8', + 'Cache-Control':'no-store', + 'Connection':'keep-alive', + 'X-Accel-Buffering':'no', + }); + if(sseClients.size>=maxSseClients) { + const oldest=sseClients.values().next().value; + sseClients.delete(oldest); + try { oldest.end(); } catch {} + } + sseClients.add(res); + res.write(': connected\n\n'); + res.write('event: ready\ndata: '+JSON.stringify({revision,focusSeq,...(focusTarget?{focus:focusTarget}:{}),...(practiceSyncState?{practice:practiceSyncState}:{})})+'\n\n'); + req.on('close',()=>{ sseClients.delete(res); }); + return; + } + if (url.pathname==='/practice/state') { + if (req.method!=='GET'||req.headers['x-workshop-session']!==key|| + req.headers.origin&&req.headers.origin!=='http://'+host) { res.writeHead(404).end(); return; } + res.setHeader('Content-Type','application/json; charset=utf-8'); + res.setHeader('Cache-Control','no-store'); + res.end(JSON.stringify(practiceSnapshotPublic(url.searchParams.get('includeImage')==='1'))); + return; + } + if (url.pathname==='/practice/undo') { + if (req.method!=='POST'||req.headers['x-workshop-session']!==key|| + req.headers.origin&&req.headers.origin!=='http://'+host) { res.writeHead(404).end(); return; } + res.setHeader('Content-Type','application/json; charset=utf-8'); + try { + const restored=undoPracticeSync(); + res.end(JSON.stringify({ok:true,practice:restored})); + } catch(error) { res.writeHead(409).end(JSON.stringify({error:error.message})); } + return; + } + if (url.pathname==='/practice/sync') { + if (req.method!=='POST'||req.headers['x-workshop-session']!==key||!isJsonContent(req)|| + req.headers.origin&&req.headers.origin!=='http://'+host) { res.writeHead(404).end(); return; } + res.setHeader('Content-Type','application/json; charset=utf-8'); + try { + let size=0; + const chunks=[]; + for await (const chunk of req) { + if((size+=chunk.length)>9*1024*1024) { res.writeHead(413).end(); return; } + chunks.push(chunk); + } + const body=JSON.parse(Buffer.concat(chunks).toString('utf8')); + const state=applyPracticeSync(body); + res.end(JSON.stringify({ok:true,practice:state})); + } catch(error) { res.writeHead(400).end(JSON.stringify({error:error.message})); } + return; + } + if (url.pathname==='/practice/custom-image') { + if (req.method!=='GET'||req.headers['x-workshop-session']!==key|| + req.headers.origin&&req.headers.origin!=='http://'+host) { res.writeHead(404).end(); return; } + if (!practiceCustomImage) { res.writeHead(404).end(); return; } + res.setHeader('Content-Type',practiceCustomImage.mimeType); + res.setHeader('Cache-Control','no-store'); + res.end(practiceCustomImage.bytes); + return; + } + if (url.pathname==='/health') { + if (req.method!=='GET'||req.headers['x-workshop-session']!==key|| + req.headers.origin&&req.headers.origin!=='http://'+host) { res.writeHead(404).end(); return; } + res.setHeader('Content-Type','application/json; charset=utf-8'); + res.end(JSON.stringify(stationHealth())); + return; + } + if (url.pathname==='/session/focus') { + if (req.method!=='POST'||req.headers['x-workshop-session']!==key||!isJsonContent(req)|| + req.headers.origin&&req.headers.origin!=='http://'+host) { res.writeHead(404).end(); return; } + res.setHeader('Content-Type','application/json; charset=utf-8'); + try { + let size=0; + const chunks=[]; + for await (const chunk of req) { + if((size+=chunk.length)>2048) { res.writeHead(413).end(); return; } + chunks.push(chunk); + } + const body=JSON.parse(Buffer.concat(chunks).toString('utf8')); + const focus=requestFocus(body?.panel,body?.round); + res.end(JSON.stringify({ok:true,focus})); + } catch(error) { res.writeHead(400).end(JSON.stringify({error:error.message})); } + return; + } + if (url.pathname==='/session/ui-event') { + if (req.method!=='POST'||req.headers['x-workshop-session']!==key||!isJsonContent(req)|| + req.headers.origin&&req.headers.origin!=='http://'+host) { res.writeHead(404).end(); return; } + res.setHeader('Content-Type','application/json; charset=utf-8'); + try { + let size=0; + const chunks=[]; + for await (const chunk of req) { + if((size+=chunk.length)>4096) { res.writeHead(413).end(); return; } + chunks.push(chunk); + } + const body=JSON.parse(Buffer.concat(chunks).toString('utf8')); + const entry=recordUiEvent(body?.type,body?.summary,body?.stageId); + res.end(JSON.stringify({ok:true,event:entry})); + } catch(error) { res.writeHead(400).end(JSON.stringify({error:error.message})); } + return; + } if (url.pathname==='/session') { if (req.headers['x-workshop-session']!==key) { res.writeHead(404).end(); return; } res.setHeader('Content-Type','application/json; charset=utf-8'); - if (req.method==='GET') { res.end(JSON.stringify(read())); return; } - if (req.method!=='POST'||req.headers['content-type']!=='application/json' || + if (req.method==='GET') { + res.end(JSON.stringify({...read(),workbenchUi:2,calibrationWorkbench:true,calibrationChat:true,calibrationView:2,workbenchBuild:reportedBuild, + ...(focusTarget?{focus:focusTarget}:{}), + ...(practiceSyncState?{practice:practiceSyncState}:{}), + ...(uiEvents.length?{recentUiEvents:uiEvents.slice(-5)}:{}), + ...(isActiveStation?{stationActive:await isActiveStation()}:{})})); + return; + } + if (req.method!=='POST'||!isJsonContent(req) || req.headers.origin&&req.headers.origin!=='http://'+host) { res.writeHead(405).end(); return; } try { let size=0; @@ -799,31 +1580,49 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera chunks.push(chunk); } const input=JSON.parse(Buffer.concat(chunks).toString('utf8')); - res.end(JSON.stringify(update(input.patch,input.clearBlockers,input.replace===true))); + const prevCamera=resume.camera?.experimentId??null; + const prevPath=resume.path??null; + const updated=update(input.patch,input.clearBlockers,input.replace===true); + if(req.headers['x-workshop-source']==='ui') { + const nextCamera=resume.camera?.experimentId??null; + if(nextCamera!==prevCamera) { + recordUiEvent(nextCamera?'camera_bound':'camera_unbound',nextCamera?'绑定相机实验 '+nextCamera.slice(0,8):'解除相机实验绑定'); + } else if(resume.path&&resume.path!==prevPath) { + recordUiEvent('route_selected','选择完成路径 '+resume.path,'route'); + } else if(input.patch?.evidence&&Object.keys(input.patch.evidence).length) { + recordUiEvent('evidence_saved','更新记录:'+Object.keys(input.patch.evidence).slice(0,3).join(', ')); + } + } + res.end(JSON.stringify({...updated,...(uiEvents.length?{recentUiEvents:uiEvents.slice(-5)}:{})})); } catch(error) { res.writeHead(400).end(JSON.stringify({error:error.message})); } return; } if (req.method!=='GET') { res.writeHead(404).end(); return; } if (url.pathname==='/course.json') { res.setHeader('Content-Type','application/json; charset=utf-8'); - res.end(JSON.stringify({plan, ...(url.searchParams.get('view')===key?{...read(), ...(practiceReturnUrl?{practiceReturnUrl}:{})}:{})})); + const local=url.searchParams.get('view')===key; + const station=local&&stationKind?{stationKind,lastStation:await lastStation(),stationActive:await isActiveStation()}:{}; + res.end(JSON.stringify({plan,workbenchBuild:reportedBuild,...(reportedBuild?{workbenchRetirement:1}:{}),...station,...(local?{...read(),...(practiceSyncState?{practice:practiceSyncState}:{}),...(practiceReturnUrl?{practiceReturnUrl}:direct? + {developerMachine:readDeveloperMachineProfile()}:{} )}:{})})); return; } - const file=files.get(url.pathname); + if(url.pathname==='/favicon.ico') { res.writeHead(204).end(); return; } + const file=files.get(url.pathname) ?? renderIspExampleAsset(url.pathname); if (!file) { res.writeHead(404).end(); return; } - res.setHeader('Content-Type',file[0]+'; charset=utf-8'); + res.setHeader('Content-Type',file[0].startsWith('image/')?file[0]:file[0]+'; charset=utf-8'); res.end(file[1]); - }); + } await new Promise((resolve,reject)=>{ server.once('error',reject); server.listen(port,'127.0.0.1',resolve); }); server.once('close',()=>{ clearTimeout(idle); + closeSseClients(); if (practice) void practice.then(view=>view.server.close(),()=>{}); }); keepAlive(); - return {server, read, update, url:'http://127.0.0.1:'+server.address().port+'/#'+key}; + return {server, read, update, syncPractice: applyPracticeSync, undoPractice: undoPracticeSync, readPractice: practiceSnapshotPublic, url:'http://127.0.0.1:'+server.address().port+'/#'+key}; } const entry=process.argv[1]; diff --git a/plugins/rdk-camera-workshop/plugin.json b/plugins/rdk-camera-workshop/plugin.json index aaf34cd..ba6153f 100644 --- a/plugins/rdk-camera-workshop/plugin.json +++ b/plugins/rdk-camera-workshop/plugin.json @@ -1,8 +1,8 @@ { "name": "rdk-camera-workshop", "displayName": "RDK Camera AI", - "version": "1.5.7", - "description": "日常相机调试:拍照、点亮、采流诊断、AI 看图调 ISP、读回与恢复。180 分钟视觉 Workshop:三图采集、RoboGO 提交与原 Run 跟踪、ISP、A/B/C 分流、X5 检测和成果留证。", + "version": "1.5.14", + "description": "RDK Camera AI 日常相机调试与 180 分钟视觉 Workshop。支持点亮、采流诊断、10 参数线性域 ISP、2-Pass 自动诊断、Bayer RAW、离线标定、X5 检测与成果留证;新增一键确定性点亮建基线、真机 AI 调优前后对比图内联展示与原尺寸锐度/噪点遥测。", "author": { "name": "D-Robotics" }, diff --git a/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/SKILL.md b/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/SKILL.md index ae87dbf..a4df3cf 100644 --- a/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/SKILL.md +++ b/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/SKILL.md @@ -12,177 +12,89 @@ enabled: true # 相机点亮与 ISP 调优 -## Studio 拍照和课程基线 - -- 查询插件能做什么时,从本轮工具目录加载 `vision_workshop_runtime_status`;有已绑定实验才读取 `vision_camera_workflow`。按目录、适配器和实际回执回答。连接失败时用 `vision_connection_status` 说明配置缺口。 -- 合并版工位拍照用 `vision_course_camera` 的 `photo`。展示已拍照片或基线图时用只读的 `vision_course_camera_status` 打开工作台结果。只有用户明确要求重拍才新采图。 -- 独立相机版使用实际绑定实验的 `vision_camera_capture_frame`,从相机服务的归档入口查看、下载原件。能力缺失时给出未完成项,禁止改用板端脚本猜路径、下载整段命令输出或临时切换 ISP 模式。只读请求保持只读。 - -## 能力与操作范围 - -使用当前运行中发现的 `vision_*` 工具;Studio 原生桥的名称前缀为 -`mcp__rdk-camera-workshop__`。安装插件不安装 Sensor 驱动或原生 ISP adapter。 -先检索接入知识,再读取当前设备能力,不以“资料已核对”推断相机已点亮。 -知识摘要返回 sections 时,按需用 knowledge_get 的 section 读取完整分节;操作目录可 search 过滤并按 nextOffset 翻页。 -通用知识的 not_admitted 不是当前实验的准入结论。controls_set 与原生 ISP apply_tuning 是不同写通道; -前者缺失不能推导后者不可用。先读取本实验 readiness.aiDebug.canStart,再由真实 probe 的数值规则、 -恢复和执行回执限定范围;不能由资料或配置自行宣称准入。 - -用户要接入新型号、把全流程交给 AI,或继续一次跨接线/版本/模式/画质的调试时, -先读 [新 Sensor 的 AI 工作流与证据状态机](references/new-sensor-ai-workflow.md)。 -它将资料与驱动开发、真实原子能力、同场景看图、恢复和交付分开推进; -已有成功证据可复用,但不能越过本次模式、采集和恢复的缺口。 +## 0. 双插件意图分流与防误调矩阵(优先核对) -X5 / 亚博 IMX415 的版本兼容、接口与 lane、旧 SDK、开流失败、恢复或 USB 网络问题, -先读 [兼容性与失败恢复](references/imx415-compatibility-and-recovery.md)。 -其中实机记录是历史证据;本次状态仍取当前 probe、getter、新帧和恢复回执。 +| 用户意图 | 正确工具通道 | 禁止误调(反例) | +|---|---|---| +| 免接相机图片/本地照片/RAW 模拟调优、180 分钟课堂课表与工作台 | `rdk-vision-workshop` 的 `vision_course_isp_example` / `vision_course_next` / `vision_course_view` | 勿调 `vision_camera_probe` 或 `vision_ai_debug_start` | +| 课堂三图基线采集、课堂单项/多参数联调、课堂恢复 | `rdk-vision-workshop` 的 `vision_course_camera` / `vision_course_isp` | 勿绕过课堂工位私自创建新实验写硬件 | +| 新 Sensor 适配、点亮、采流诊断、实机多轮 AI 看图调试、效果库导出/重载、交付验收 | 本插件 `rdk-camera-workshop` 的 `vision_camera_*` / `vision_ai_debug_*` / `vision_isp_*` / `vision_workshop_delivery` | 勿用示例图模拟替代真机实拍或跳过 `probe`/`readiness` | +| 离线标定(BLC/LSC/CCM/AWB)计算与查看 | 课堂工位内优先 `vision_course_calibration*`;独立相机实验用 `vision_calibration_*` | 上板应用唯一入口为 `vision_calibration_apply`(AWB 必传 `options.illuminantId`) | -系统调曝光、空间/时域降噪、锐化或组合选优时,读取[系统调试与组合复验流程](references/systematic-isp-search.md)。只对白平衡有收益不能关闭更广的调试目标;无收益项也须有实际对照。单消费者采流助手已保留为源码,宿主未接入时不宣称MCP能力已上线。 +### 高频场景端到端工具链速查(按顺序执行,禁跳步) -偶发彩条、长时采集才出现的 RAW 校验失败,也先读该流程中的失败快照、首像素帧号注入与 Sensor 内置图案诊断。将采集误报、真实行状变化和画质验收分别取证;数字图案不代替真实暗场,未查清的成像端问题不靠扩大参数穷举掩盖。 +| 高频任务 | 标准原子工具链 | 关键验收与退出门禁 | +|---|---|---| +| 新 Sensor 适配缺口评估 | `vision_camera_knowledge_search/get` → `vision_workshop_runtime_status` → `vision_experiment_create`(无匹配 adapter 时省略 `targetId`)→ `vision_camera_workflow` | 仅报真实 `missingAdaptation` 与工程任务,不借用他型号 `targetId` | +| X5 / IMX415 点亮开流 | 优先一键 `vision_camera_bringup_flow(experimentId)`(内部按安全顺序串联 `probe` 恢复围栏检查 → `bringup` → `pipeline_validate` → `capture_frame` → `controls_get` 并附首帧预览);若需分步排查则依次调用单步原子工具 | 核对每阶段回执、首帧哈希与可写参数清单;遇恢复围栏立即停止先恢复 | +| 实机有界 AI 看图调优 | `vision_camera_readiness` → `vision_camera_controls_get` → `vision_ai_debug_start(goal,maxRounds)` → 轮询 `vision_ai_debug_status` → `vision_ai_debug_preview(experimentId,runId)` 在聊天展示前后对比图 | 核对 `adjustmentCount`、原尺寸锐度/噪点遥测、独立回读与终态新帧;退化则 `vision_ai_debug_restore_original` | +| 离线标定到安全上板 | `vision_calibration_engines` → `vision_calibration_task_create/run` → `vision_calibration_task_result` → `vision_calibration_apply_plan` → 授权后 `vision_calibration_apply` | 先查 `apply_plan` 且用户确认后再写设备;上板后必拍新帧并保留原快照 | +| 异常恢复与交付验收 | `vision_camera_readiness` → `vision_isp_restore(baselineId)` 或 `vision_ai_debug_restore_original` → `vision_camera_capture_frame` → `vision_workshop_delivery` | 确认 `recovery.status` 闭环与新帧校验通过,缺终态证据即报未确认 | -## 团队经验与阶段规划 - -涉及快速点亮、USB 最小闭环、相机选型/供货、未点亮素材、专家步骤沉淀、旧版本 I²C/tuning 故障、雾感/彩噪或对外演示时,先读 [点亮与 ISP 现场操作指引](references/bringup-and-isp-field-playbook.md)。知识详情中的 `teamExperience` 同步提供可检索的经验、来源和证据要求。 - -按目标和已有证据选择 USB 基础闭环、Studio 真实 MIPI、原生 ISP 与场景验收阶段。用户已指定阶段时从缺口继续,不强迫重跑已通过步骤。先确认目标板上的初始状态,不把供应商既有驱动的复用当 AI 从零适配。优先读取准确版本的 Datasheet/Tuning guide,避免盲目扩大调参次数。 +## Studio 拍照和课程基线 -历史版本、供货、全志对标和画质改善案例标为用户报告,需本次核实;不是官方最低版本、现有库存或本平台成功回执。标定文件缺失 warning 只有在匹配版本的默认/回退效果库和实际出图均得到证据时才可判为不阻塞。专家流程没有实际操作记录时列为待采集,不臆造自动化步骤。 +- 启动/继续 Workshop 或核对板卡绑定时,先查合并版 `vision_course_camera_status`(读 `cameraBinding` 与 `latestPreflight`;旧版用 `vision_course_sync` 的 `resume.camera` 与 `vision_course_preflight({})`)。`device_boundary` 仅描述聊天通用设备范围;工位关联、SSH 可达与实时出图各有独立回执。预检受阻时报具体阶段和错误;遇到 `vision_device_archive_capacity`(兼容旧码 `vision_device_history_capacity`)时先核对 ISP 恢复与停流,再换同设备新实验并保留旧归档。 +- 日常拍照按回执回答;仅在课程基线阶段或用户要求采三图时列 RAW/ISP/重渲染(`baselineRequested:false` 表示未采三图)。 +- 查询能力时调用 `vision_workshop_runtime_status`,有已绑定实验再查 `vision_camera_workflow`;连接失败用 `vision_connection_status` 说明配置缺口。 +- 合并版拍照用 `vision_course_camera(action:"photo")`,展示已拍/基线图用只读 `vision_course_camera_status`(仅明确要求重拍才新采);独立相机版用 `vision_camera_capture_frame`。能力缺失时说明缺项,禁改用板端脚本猜路径或私切 ISP 模式,只读请求保持只读。 -## 任务范围与面向用户的结论 +## 能力与操作范围 -`bringup` 使用已适配的驱动和采集模式启动相机,不生成新 Sensor 驱动、设备树或寄存器初始化代码,也不自动编译部署。用户要求接入尚未支持的新相机时,先核对资料、电气兼容性和缺口,明确当前未覆盖的驱动开发步骤。 +使用当前运行中发现的 `vision_*` 工具;Studio 原生桥的名称前缀为 +`mcp__rdk-camera-workshop__`。安装插件不安装 Sensor 驱动或原生 ISP adapter。 +先检索知识再读设备能力,不以资料推断已点亮;知识带 `sections` 时按需用 `knowledge_get(section)` 读取,目录可 `search` + `nextOffset` 翻页。 +通用知识的 `not_admitted` 非当前实验准入结论;`controls_set` 与原生 `apply_tuning` 为不同写通道,互不推导。先查 `readiness.aiDebug.canStart`,由真实 `probe` 规则、恢复和执行回执限定范围。 -无驱动时仍可由 AI 形成工程任务并在用户授权的宿主开发工具中完成真实源码补丁、 -匹配 SDK 构建与隔离测试,再接入适配器并实机验证。当前没有通用驱动生成/发布 API; -不自造 MCP 名称,不把私有 SSH helper 打包,也不用任意 shell 绕过设备原子接口。 +按场景先读对应参考(历史实机记录仅作参考,本次状态取当前 probe/getter/新帧/恢复回执): +- 新型号接入 / 全流程 AI / 跨接线或模式调试:[新 Sensor 的 AI 工作流与证据状态机](references/new-sensor-ai-workflow.md) +- X5 / 亚博 IMX415 兼容、lane、旧 SDK、开流失败、恢复或 USB 网络:[兼容性与失败恢复](references/imx415-compatibility-and-recovery.md) +- 系统调曝光/降噪/锐化、组合复验、偶发彩条/RAW 校验失败/内置图案与 30fps 接收策略:[系统调试与组合复验流程](references/systematic-isp-search.md)(单消费者采流助手与离线只读观察/候选脚本源码见该文档,未接入宿主时不宣称 MCP 已上线) +- 快速点亮、USB 最小闭环、选型供货、雾感彩噪或演示:[点亮与 ISP 现场操作指引](references/bringup-and-isp-field-playbook.md)(知识 `teamExperience` 同步提供) +- ISPStudio 源码标定引擎接入与验收:[源码标定引擎与真实验收](references/ispstudio-calibration.md) -先说明本次能做什么、卡在哪里及具体下一步;能力配置不表示设备在线。结束时先报告目标是否达到、当前实际参数是否确认、终态新帧和噪点/细节/颜色/曝光退化,再按需展示历史推荐与回读哈希。恢复错误优先于旧成功状态;缺少终态证据时报告未确认。 +## 任务边界与阶段规划 +- 按目标与已有证据选择 USB 闭环、Studio MIPI、原生 ISP 或场景验收阶段,从缺口续跑;不把供应商既有驱动复用当 AI 从零适配。用户报告的历史版本、供货或画质案例须本次核实;标定缺失 warning 须匹配版本的默认/回退库与实际出图均取证后才判不阻塞。 +- `bringup` 仅启动已适配驱动/模式,不自动生成、编译或部署新驱动。无驱动时先核对资料与缺口,形成工程任务交用户授权的宿主开发工具补丁、构建、隔离测试并接入适配器;不自造 MCP 名称、不打包私有 SSH helper、不用任意 shell 绕过原子接口。 +- 开场先说明当前能做什么、卡点与下一步;结束时先报目标达成度、当前实际参数、终态新帧及噪点/细节/颜色/曝光退化,再按需列历史推荐与哈希。恢复错误优先于旧成功状态,缺终态证据报未确认。 ## 先确认本次可以执行什么 -1. 用 `vision_camera_knowledge_search/get` 检索用户给定板型和型号。 - X5 亚博 IMX415 的知识 ID 为 `x5-yahboom-imx415`;RDK S100 / IMX219 的知识 ID 为 `s100-imx219-mipi`(仅文档核对,无实机证据,且平台尚无 S100 adapter)。来源事实与实机证据分开报告。 -2. 读取真实 `/capabilities`:有 `vision_workshop_runtime_status` 时直接调用;否则先用 - `vision_workshop_capabilities` 发现目录,再通过 `vision_workshop_execute` 执行目录中的 GET。 - 前者是运行状态,后者是操作目录,二者不能混用。 -3. 只选择当前登记且板型、Sensor、接口、SDK、模式匹配的 targetId。 - 缺少原生适配器、接线或实际模式时,说明缺口并停止对应硬件操作。 - 不能以 S100/UVC 成功记录覆盖 X5 MIPI、Bayer RAW 或原生 ISP。 -4. 列出或读取当前身份实验。有 typed `vision_experiment_list/get/create` 则使用;否则 - 用当前目录中的 GET/POST 经 `vision_workshop_execute` 执行。已有匹配 adapter 时绑定它; - 新型号尚无 adapter 时,可省略 targetId,以 title、goal 和真实已知相机信息创建未绑定实验, - 用 workflow 读取 missingAdaptation 并推进资料/工程规划。该分支不操作设备, - 不借用其他 Sensor 的 targetId;硬件执行前才必须绑定真正匹配的 adapter。 - 不自行构造主机、shell、下载地址、SDK 索引或凭据。 -5. 目录提供 `vision_camera_workflow({experimentId})` 时读取保存的阶段诊断与 nextActions, - 按实际缺口选原子工具。它不探测设备,历史阶段不证明当前连接或画质。 - `vision_camera_stream_analyze({experimentId,runIds?,expectedFps?,tolerancePercent?,minimumDurationSeconds?})` - 只分析本身份已归档的 SDK 帧证据;需要新的连续采集时另用已支持的相机工具取得新证据。 - 目录提供 `vision_camera_response_analyze` 时,用同实验A1/B/A2各3–8张归档PNG帧ID和可选ROI - 核对多帧输出变化。它读取实际字节与配置/场景/时序,只作观察;亮度降低、A2区间回归 - 均不代表文字改善、物理曝光标定或完整SDK恢复,不用客户端“改善分数”替代图像。 +1. 用 `vision_camera_knowledge_search/get` 检索板型与型号(X5 亚博 IMX415:`x5-yahboom-imx415`;RDK S100 / IMX219:`s100-imx219-mipi`,仅文档核对无实机证据且无 S100 adapter),文档事实与实机证据分开汇报。 +2. 读取真实 `/capabilities`:有 `vision_workshop_runtime_status` 时直接调用;否则先用 `vision_workshop_capabilities` 发现目录,再通过 `vision_workshop_execute` 执行目录中的 GET(运行状态与操作目录不可混用)。 +3. 只选择当前登记且板型、Sensor、接口、SDK、模式匹配的 `targetId`;缺原生适配器/接线/模式时说明缺口并停止对应硬件操作,不得以 S100/UVC 记录覆盖 X5 MIPI / Bayer RAW / 原生 ISP。 +4. 列出或读取当前身份实验。有 typed `vision_experiment_list/get/create` 则使用,否则经 `vision_workshop_execute` 执行。已有匹配 adapter 时绑定;新型号尚无 adapter 时省略 `targetId` 创建未绑定实验,用 `vision_camera_workflow` 读 `missingAdaptation` 推进工程规划(不借用其他 Sensor 的 `targetId`,硬件执行前才绑定真实 adapter)。不自行构造主机、shell、下载地址、SDK 索引或凭据。 +5. 用 `vision_camera_workflow({experimentId})` 读阶段诊断与 `nextActions`(不探测设备);用 `vision_camera_stream_analyze` 分析已归档 SDK 帧;用 `vision_camera_response_analyze` 对同实验 A1/B/A2 各 3–8 张归档 PNG 及可选 ROI 做像素输出观察(亮度降低或 A2 回归不代表文字清晰、物理标定或完整恢复,不用分数替代看图)。 ## 自然语言点亮与调优 -- 用户要求点亮时,调用 `vision_camera_probe`、`vision_pipeline_validate` 和 - `vision_camera_bringup`;逐项读真实失败/成功检查。再启动预览并采集当前新帧。 - 保存尺寸、时间、配置哈希与图像来源;没有可辨识现场图像不能报告画面正常。 -- X5 HBN 首版采用 probe → bringup → pipeline_validate 新帧的顺序。 - 开流前 `actual_stream_required` 是待点亮状态;获得本次点亮/调优授权后执行 bringup, - 再校验实际帧。probe 不初始化 Sensor;先点亮并取得原始快照,再提交 AI 调优 Run。 -- 用户要求画面控制调优时,先核对 `controls_get` 的支持范围、可写/active 状态, - 原始配置与恢复能力。实际配置和模型具备所需能力时,用 `vision_ai_debug_start` 提交目标, - 用 status 轮询真实 Run。模型看原始、最佳与当前实际图像,不在技能中写死参数序列。 - 探索预算由 `maxRounds` 显式声明(1–6,默认 4);限时演示、课堂或受控场景按授权压缩到 1–2, - 并在目标中写明允许的调整上限,不依赖模型自行收敛。status 的 `adjustmentCount` 是实际写入轮数。 -- 原生 ISP AI 路径要求实际 probe.baseline 为本次声明 scope 的完整 `x5-hbn-isp-v2` 快照、真实允许 rules, - 且适配器支持 apply_tuning。模型的 adjust 只返回 `patches:[{path,value,reason}]`, - 每轮最多三个已列入规则的数值叶子;执行器将补丁合入完整快照后应用、独立回读和采新帧。 - UVC/普通控制路径仍用 `values`,两条路径不能混用。AUTO 下只写被实际规则开放的活动表叶子, - 不以保存的 manual_attr、效果库数值或其他型号经验扩大范围、切换模式或开放 AE/AWB。 -- 用户要求原生 ISP 时,先核对实际 SDK tuning schema、应用、回读和恢复; - 需要 RAW 采集/回灌的目标再核对实际 Bayer RAW 能力。 - 使用实际支持的 `vision_raw_capture`、`vision_isp_generate/process_raw/apply/restore`。 - `process_raw` 需先确认 SDK 回灌支持;允许数值路径来自真实基线,不编造厂商字段。 - 基线导入可用 typed `vision_tuning_baseline_import` 或目录中的 baseline 操作。 -- IR-CUT 与手动调焦若未提供软件原子接口,按知识前提交给实际操作员处理。 - 标定算法计算、SDK 参数应用与光学/画质验收分别记录,缺少实际测量不能互相替代。 -- 先读 probe;X5 原生路径须先成功开流并取得新帧,再读取 typed controls 与保存原始快照, - 不在开流失败后硬试 getter/setter。以当前 SDK 回执确认 AE/AWB、CPROC、模块和模式支持。 - 新版原生格式 `x5-hbn-isp-v2` 需要匹配的 ABI 2 库;已有 ABI 1 只支持 MANUAL CPROC。 - 缺库时只进行只读预检,配置声明不代表相机、库或全部模块已验收。 -- 读取每轮新帧、真实回读、停止原因、最终版本及恢复回执。模型 improved/done、 - 全图变暗或统计变化不等于画质通过,不代填人工评分。 - 写入回读正确也不证明像素响应或目标改善;构图变化、自动算法未稳定、只有平面/单帧时, - 分别保留比较限制,不编造 SNR。目标细节、噪点、颜色或曝光明显回退时否决候选。 +- **点亮与开流**:工具列表含 `vision_camera_bringup_flow` 时优先一键调用(自动完成 `probe` 恢复围栏检查 → `bringup` → `pipeline_validate` → 首帧 `capture_frame` + Studio 内联看图 → `controls_get` 可调清单);需单步排查时依次调用 `vision_camera_probe` → `vision_pipeline_validate` → `vision_camera_bringup`(X5 HBN 首版按 `probe → bringup → pipeline_validate` 顺序,开流前 `actual_stream_required` 为待点亮;先点亮、采新帧并保存原始快照再调优),保存尺寸、时间、配置哈希与来源,无可辨识新帧不报正常。单帧查看可用只读 `vision_camera_frame_preview`。 +- **有界 AI 调优**:先核对 `controls_get` 支持范围/可写态与恢复能力,再用 `vision_ai_debug_start` 提交目标(`maxRounds` 1–6 默认 4,课堂/限时压缩到 1–2 并在目标写明上限)并轮询 `status`(`adjustmentCount` 为实写轮数)。调试完成或阶段性检视时调用只读 `vision_ai_debug_preview` 把真实相机原始帧与最优/终态帧合成为带亮度/暗部/高光/原尺寸锐度与噪点差值的对照图内联展示给用户。模型看原始/最佳/当前实图,不在技能写死参数序列。 +- **原生 ISP AI 路径**:要求 `probe.baseline` 为完整 `x5-hbn-isp-v2`(需 ABI 2 库;ABI 1 仅支持 MANUAL CPROC,缺库保持只读)及真实允许 `rules`,且支持 `apply_tuning`/`tuning_export`。数值调整用 `patches:[{path,value,reason}]`(每轮 ≤3 规则叶子);具 SDK 模式读回资格的布尔开关可用 `values` 单独切换(模式与数值不可混写,切后先 `tuning_get` 建该模式新基线再于下轮调值;AUTO 旧锚点不可写 MANUAL;完整原始快照独立保留)。UVC/普通路径按实际 `controls` 用 `values`;AUTO 下不把 `manual_attr` 当生效值。 +- **RAW 与手动前提**:原生 ISP / RAW 仅在适配器声明支持时调用 `vision_raw_capture`、`vision_isp_generate/process_raw/apply/restore`;允许路径取自真实基线,不编造厂商字段。基线导入可用 typed `vision_tuning_baseline_import` 或目录中的 baseline 操作。IR-CUT 与手动调焦无软件接口时交操作员处理。 +- **诚实评价**:核对每轮新帧、真实回读、停止原因与恢复回执;模型 `improved/done`、全图变暗或统计变化不等同画质通过,不代填人工评分、不编造 SNR;构图变化或自动算法未稳时保留比较限制,目标退化时否决候选。 ## 原生 ISP 与标定 -选定实际实验后先读取 `vision_camera_readiness`。它只投影保存的阶段证据、缺少的操作和恢复状态,不探测当前设备。`recovery.status=unconfirmed` 时先显式恢复并核对实际回读和新帧,恢复确认后才启动新调试;历史 `observed` 不证明当前在线或画质达标。 - -用 `vision_isp_tuning_get/export` 保存实际 SDK getter 快照、支持范围及版本; -完整效果库与公开模块快照是不同读回范围。`vision_isp_tuning_load` 优先提交 experimentId 和本实验 -已导出并归档的 artifactId,由服务端重读文件并验哈希;外部文件导入仍可提交 contentBase64 和 sha256, -两种输入互斥,不传文件路径或 shell,不让模型复制整段大文件。较大的工具回执带 -`projection: bounded_mcp_receipt`,只表示文本摘要;真实原始配置保存在实验基线,原生 REST 响应保留完整值。 -摘要中的恢复状态、错误、图像与参数哈希仍按实际回执判断,不能将字段摘要当成完整 SDK 数组。写后必须有独立 SDK -getter/效果库回读、输入哈希及恢复证据;unknown mode、缺 SDK、未接相机或不一致保持 -未就绪/未确认。候选按已声明的 float32 或 seconds-float32-us 精度量化并复查范围。 - -用 `vision_calibration_asset_import/list` 归档真实测量与原资产哈希, -`vision_calibration_task_create/list/get/run/result` 执行和读取 BLC/LSC/CCM/AWB 离线任务。 -软件算法结果不能宣称光学标定或画质真机验收。先用 `vision_calibration_apply_plan` -检查 trusted result 的 SDK 映射和前提,再在授权与适配器支持内使用 -`vision_calibration_apply`,只传 taskId 和 options,服务读取可信结果,不能提交模型伪造参数。 - -RAW 回灌仅在适配器声明支持时使用 `vision_isp_process_raw`。核对 RAW/tuning 哈希、 -独立读回、匹配回灌输出的帧 ID/提交时间、AE/AWB manual 与 live 恢复。 -旧 live 帧不能证明回灌成功,提交时间回显不能宣称 sensor 时基。 +- **准入与快照**:先查 `vision_camera_readiness`(仅投影保存证据,不探测设备);`recovery.status=unconfirmed` 时先恢复并核对回读与新帧再开新调试。手动编排写入前必先 `vision_isp_tuning_get` 独立保存本轮 `baselineId` 与哈希(`bringup` 不更新基线;模式切换后 `tuning_get` 得到的 MANUAL 基线不覆盖原始恢复版本),恢复时显式传原始 `baselineId` 并核对 `appliedHash/readbackHash`。 +- **效果库与回执边界**:完整效果库与公开模块快照范围不同。`vision_isp_tuning_load` 优先传已导出归档 `artifactId`(与外部 `contentBase64`+`sha256` 互斥,不传文件路径或复制大文件)。带 `projection: bounded_mcp_receipt` 仅为摘要,完整值在实验基线/REST。写后必做独立 SDK 回读与恢复取证;候选按 float32 / seconds-float32-us 精度量化复查。 +- **RAW 回灌与离线标定**:X5 RAW 回放要求 RAW 元数据含正曝光/增益且目标 AE/AWB 为 MANUAL 并严格匹配(不可补造旧元数据);`raw_replay_preflight` / `writeOutcome:not_attempted` 表示未写 SDK,按缺口修正前提;`vision_isp_process_raw` 须核对哈希、回读、匹配输出帧 ID/提交时间及 live 恢复。标定用 `vision_calibration_asset_import/list`、`vision_calibration_engines`、`vision_calibration_task_create/list/get/run/result`(ISPStudio 显式 `engine:"ispstudio"`);先查 `vision_calibration_apply_plan` 再经授权调用 `vision_calibration_apply(taskId,options)`(服务读可信结果,禁伪造参数);算法结果不等于光学/画质真机验收。 ## 禁止事项 -- 写工具包括 controls_set、AI debug start/restore、ISP apply/restore/tuning_load、 - calibration_asset_import、task_create/run 和 calibration_apply;保持实际宿主审批边界。 -- 不伪造硬件验证、标定、独立 readback 或恢复成功;按当前证据分别报告成熟度。 -- 不用板端 shell、任意路径、寄存器写入或 I²C 扫描绕过平台原子能力和授权。 +- 写工具(`controls_set`、`ai_debug_start/restore`、`isp_apply/restore/tuning_load`、`calibration_asset_import/task_create/task_run/apply`)严格保持宿主审批边界。 +- 不伪造硬件验证、标定、独立 readback 或恢复成功;按证据分别报告成熟度。 +- 不用板端 shell、任意路径、寄存器写入或 I²C 扫描绕过平台原子能力与授权。 ## 失败、取消与交付 -写操作继续遵循宿主已有权限与审批边界;本技能不授予权限,也不增加逐步审批。 -超时或断连可能已经写入:先查实验 `deviceRuns` 与实际控制,禁止盲目重放。 -取消后轮询到真实恢复回执;无法确认恢复时报告 unknown/failed。 -配置离线恢复与恢复后的开流/新帧分别核对;配置 hash 匹配而取帧失败时保留流恢复未确认, -不清除 recovery fence,不以恢复命令返回成功或关闭句柄冒充终态画面已验证。 -导出实验制品、原始与最终参数哈希、来源和未验证项。 -普通 ROS `image_raw`、JPEG/PNG、NV12/YUYV 与 UVC 控制不能作为 Bayer RAW 或 X5 原生 ISP 证据。 - +- 超时或断连可能已写入:先查 `deviceRuns` 与实际控制,禁止盲目重放。取消后轮询至真实恢复回执,无法确认报 `unknown/failed`。 +- 离线配置恢复与恢复后开流/新帧分别核对;hash 匹配但取帧失败时保留流恢复未确认,不清除 recovery fence。普通 ROS `image_raw`、JPEG/PNG、NV12/YUYV 与 UVC 控制不可冒充 Bayer RAW 或 X5 原生 ISP 证据。 ## Workshop 交付与验收 -先发现实际工具目录。新版 `vision_workshop_delivery` 读取本实验交付缺口、参数目标、验收标准和记录;无设备可先用 `vision_acceptance_plan_save` 保存场景、照明、必验项目、测量方法/单位及阈值。用 `vision_delivery_target_select` 显式选择目录返回的交付版本;保存观察记录不会暗中改选版本。 - -`vision_acceptance_record` 仅经明确授权记录操作者实际提供的观察或外部测量报告,并绑定本实验图像与参数哈希。不能替用户编造测量值、视觉通过意见或人工评分。模型判断、PNG 输出统计和外部录入的校准测量分别标注;`recorded_pass` 仅说明保存记录满足项目阈值,不能写成独立画质认证。 - -厂商候选库必须有匹配真实 SDK、模式、原模板和模块的服务端字段绑定,完整覆盖已修改字段。原归档效果库、私有快照控制配置和新生成厂商 JSON 分别说明。导出返回 vendorArtifact.id 时,优先用 `vision_isp_tuning_load` 的 artifactId 加载,服务端限定为当前身份、当前实验的已归档厂商候选。导入外部字节时用 `artifactRole: vendor_effect_library_candidate` 显式加载;缺生成回执、绑定或字节校验时停止。仅指定角色不构成通过。 - -核对独立 SDK 回读、本轮新帧、必要的新 SDK 会话重载及原始参数恢复。`fresh_session_reload_recorded` 仅是匹配 profile 下的 SDK 会话重载记录,不保证任意新系统/板卡无需配置。交付 ZIP 包应有 delivery.json、调优手册、实际图像与版本证据,生成的厂商候选另归档为 vendor-tuning/.json;无候选不伪造文件。 - -受控弱信号RAW往返对照的归档复算使用[相位序列助手](scripts/controlled_raw_phase_series.py),输入/限制见[系统性ISP搜索](references/systematic-isp-search.md);它只读归档,不授予正式RAW、标定或最佳ISP资格。 - -macOS 宿主可选用[只读文字识别助手](scripts/text_ocr_observation.swift)复核已归档文字局部;按[系统性ISP搜索](references/systematic-isp-search.md)保留原图/裁剪哈希、ROI和全部识别结果。它不操作相机、不提供新MCP工具,也不把文字识别正确等同于光学清晰度或全部ISP验收。 - -Gamma/WDR的归档A/B/A可用[固定区域色调助手](scripts/tone_region_observation.py)复算,限制见[系统性ISP搜索](references/systematic-isp-search.md);它记录亮度/区域对比,不能自动判定文字变清或光学光晕修复。 - -文字模糊但锐化无收益时,用[RAW/ISP笔画对照助手](scripts/raw_isp_edge_observation.py)复核归档源图与处理图的局部码值边缘,使用条件见[系统性ISP搜索](references/systematic-isp-search.md);不把它当MTF或镜头故障诊断。 - -白纸偏色复验可用[白纸颜色观察脚本](scripts/wb_paper_observation.py),输入、依赖和限制见[系统性ISP搜索](references/systematic-isp-search.md)。它校验归档PNG哈希、固定纸面mask及图像几何,记录B/G、R/G和截断;不连接相机,不执行调参,不把纸面颜色或注册结果当作AWB标定、物理照明控制或MCP工具已上线。 - -文字对比受限时,可用[只读Gamma带状候选构造器](scripts/x5_gamma_band_candidate.py)生成当前已观测X5布局的有界候选,详见[系统性ISP搜索](references/systematic-isp-search.md)。它不写相机,不替代当前曲线回读、AUTO AE复验或厂商完整效果库导出。 - -生成厂商Gamma文件时,使用[只读模板映射器](scripts/x5_gamma_vendor_candidate.py),核对非HDR表与当前完整活动曲线/增益网格后再渲染。它不导出其它模块的当前态,也不证明加载后画质;实际加载要检查降噪等副作用和原厂/关闭重开恢复,详见[系统性ISP搜索](references/systematic-isp-search.md)。 - -正式适配器的完整 Gamma AUTO 表可用[完整配置候选构造器](scripts/x5_gamma_tuning_candidate.py)处理;保留实际 snapshot/layout 和其它模块,经现有 `apply_tuning` 执行。模型自动搜索使用适配器显式声明的 `x5-common-auto-gamma-band-v1` 数值规则:模型只选有界强度,平台按绑定的原始曲线生成完整表,不让模型直接填写数组。新型号、不同 ISO 曲线或未经观察的 SDK 不继承该规则。启动采图先按 profile 绑定的稳定观测策略排除明显 AE/AWB 收敛期,实际当前曲线、新帧、恢复与画质分别验收;详见系统性搜索说明。 - -声明30fps时仍须连续测实际帧率。已审查驱动的CSI2接收兼容路径可使用私有 `receiverCompatibility` 策略及可选原生ABI扩展,须先核对驱动指纹、实际SDK、安全设置和独占硬件;它不自动为新模组换驱动或选择时钟。策略/驱动哈希绑定快照,跨配置不得复用。当前30fps实机范围与连续行异常观察方法见[系统性ISP搜索](references/systematic-isp-search.md),不能将明亮文字场景无明显彩条当作暗光根因已解决。 +- 用 `vision_workshop_delivery` 查交付缺口、目标与记录;无设备可先 `vision_acceptance_plan_save` 存验收计划;用 `vision_delivery_target_select` 显式选定交付版本。 +- `vision_acceptance_record` 仅经明确授权录入操作者实测或观察并绑定图像与参数哈希,不代填分数;模型判断、PNG 统计与外部测量分别标注,`recorded_pass` 非独立画质认证。 +- 厂商候选库须具匹配真实 SDK/模式/模板/模块的服务端字段绑定并完整覆盖改动字段;导出返回 `vendorArtifact.id` 时优先按 `artifactId` 加载,导入外部字节须显式 `artifactRole: vendor_effect_library_candidate`,缺回执或校验即停。 +- 交付 ZIP 须含 `delivery.json`、调优手册、实拍与版本证据(有候选才归档 `vendor-tuning/.json`),核对独立回读、新帧、新会话重载(`fresh_session_reload_recorded` 仅限匹配 profile)与原值恢复。 +- **离线诊断脚本与 30fps 接收策略**:归档相位/色调/笔画/白纸偏色/macOS OCR/X5 Gamma 候选构造等 8 份只读离线脚本,以及 `x5-common-auto-gamma-band-v1` 与 `receiverCompatibility` 30fps 实测口径,均详见 [系统调试与组合复验流程](references/systematic-isp-search.md)(脚本仅读本地归档,不注册 MCP 工具、不授予正式 RAW/标定/画质通过资格)。 diff --git a/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/references/imx415-compatibility-and-recovery.md b/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/references/imx415-compatibility-and-recovery.md index 13d1f40..71c32ea 100644 --- a/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/references/imx415-compatibility-and-recovery.md +++ b/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/references/imx415-compatibility-and-recovery.md @@ -1,5 +1,17 @@ # X5 / IMX415 兼容性与失败恢复 +## 0. 症状 → 根因 → 原子动作快速决策树 + +| 现场症状 / 错误码 | 优先排查根因 | 推荐动作顺序 | +|---|---|---| +| `camera_isp_stream_required` / `actual_stream_required` / `vision_device_checks_failed` | X5 相机服务冷启动未开流,或板端检测刚重启服务 | 先 `vision_camera_probe` → `vision_camera_bringup` → `vision_pipeline_validate`;切勿直接重试 ISP 写 | +| `vision_device_busy` (`429`) | 另一项采集/调试占用互斥锁(未写硬件) | 等待进行中任务结束再重试;**不要**误触恢复流程 | +| `isp_write_unconfirmed_restore_required` / `cleanupRequired: true` | 上次写后读回/取帧中断,`isp-write.json` 处于恢复围栏 | 严禁新写入;先 `vision_camera_readiness` 查原快照 → `vision_isp_restore(baselineId)` 或 `vision_ai_debug_restore_original` → 验证新帧 | +| `isp_control_float32_required` / `isp_module_field_quantization_required` / `-5 (-EIO)` | 曝光未按行周期整数行、模拟增益未按 Q3.5 (`log2Steps=32`) 或 AWB 增益未按 Q2.10 (`fixedScale=1024`) 对齐 | 读取 `controls_get` / `baseline.rules` 的量化元数据,经服务端/插件量化函数对齐后再写 | +| `vision_device_archive_capacity` / `quota_exceeded` | 单实验归档或回执达上限 | 先确认原配置恢复并停流,再以同 `targetId` 新建实验继续(保留旧归档) | +| 画面全黑、彩条、偶发丢帧或 30fps 不稳 | MIPI lane / INCK / 接收器时钟兼容或驱动未适配 | 核对 `vision_camera_stream_analyze` 连续帧窗口与下文 30fps / 接收器兼容实测边界;勿把未测物理 INCK 当已认证 | +| 画面发糊、雾感或局部过曝反光 | 物理手动对焦失焦、IR-CUT 状态或镜面强反射 | 先核对物理对焦/IR-CUT/布光;数字锐化无法救回失焦,勿用强降亮度伪造改善 | + ## 截至2026-10-16的最新实机结论与阅读入口 先读[最新实机结果与R3](#2026-10-16-新原sdk基线固定aeawb的cproc负结果及r3)和[源码审计及下一步](#2026-10-16-只读sensor源码审计收口与下一步);下方早期`documentation_preflight_only`等表述保留当时的历史范围。 diff --git a/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/references/ispstudio-calibration.md b/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/references/ispstudio-calibration.md new file mode 100644 index 0000000..5cf6696 --- /dev/null +++ b/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/references/ispstudio-calibration.md @@ -0,0 +1,180 @@ +# ISPStudio 离线标定接入 + +先用 `vision_calibration_engines`(experimentId)检查实际服务依赖,再创建任务: +`vision_calibration_task_create` 传 `engine: "ispstudio"`、operation、已有 inputs 和 options。 +不传 engine 继续使用 NumPy。服务器保存引擎与适配器源码的合成哈希;依赖变化必须重新建任务, +不能把失败偷偷回退为 NumPy,也不能用本地目录、命令或 Arm 固件 JSON 作为任务参数。 + +按 BLC → LSC → CCM → AWB 推进,每阶段先检查素材与数值,再走 apply-plan、实际适配器 +`vision_calibration_apply`、新帧和完整恢复。计算成功、SDK 映射成功、画质通过分别记录。 +缺少当前模式的 SDK binding、真实采集条件或物理标定材料时保留未验证状态。 + +先显式 `vision_camera_probe`,再读 `vision_camera_readiness.calibrationMapping` 中的 BLC/LSC/CCM/AWB +逐项状态。`declared` 仅表示保存的探测回执声明了该绑定,仍需 SDK 实际应用及画质验收; +`saved_sdk_binding_missing` 表示该次探测没有绑定此项。没有该字段的旧回执、失败或模式不匹配的 +最近探测保持 unknown,不用较早成功记录替代。探测是显式操作,规划和 readiness 不连接设备。 +`vision_calibration_apply_plan.runtimeMapping` 返回同一证据来源、probeRunId 和时间; +接口总体声明 `calibration_apply` 不能替代具体标定绑定。配置更新后重新探测,再核对应用前提。 + +| operation | 源码入口与平台适配 | 材料与限制 | +|---|---|---| +| blc | full-frame Bayer mean,跨帧取中位数,输出 R/Gr/Gb/B 码值 | 至少三帧实际遮光暗场,匹配曝光/增益/温度;不是照片中随意找黑块 | +| lsc | 每个 Bayer 平面调用 calc_mesh_gainmap,跨帧中位数 | 至少三帧均匀平场、四通道黑电平、独立照度计网格;网格至少6×6。输出是边界外推节点而非单元中心 | +| ccm | calibrate_ccm,明确参考色值、固定单位 WB/曝光、只拟合训练块 | 至少18个有彩度训练块,另至少3个留出块;记录 D65 白点及光源。先前 BLC/LSC/WB 必须固定且记录。拒绝未收敛和过大留出误差 | +| awb | 实际灰卡 ROI 的 grey_patch_stats,反比得到增益 | 至少两个记录光源、每组至少三帧、明确 CCT/ROI/黑电平。仅静态白平衡增益,不是完整 Arm AWB 光源分类/网格 | + +LSC 是四平面适配变体,CCM 锁定预处理并使用平台参考与留出集;不可称为原版完整工作流等价。 +保留源函数、源码哈希、screeningMethod、SDK 单位/范围/量化与实际输入输出哈希。 +离线预览不能代替板端真实 ISP 输出,色差统计不能代替合格测试卡的实测验收。 + +## 服务安装 + +服务管理员单独安装 ISPStudio Python 包及其 NumPy/Pillow/SciPy 等实际依赖,配置可信环境变量 +`RDK_VISION_ISPSTUDIO_ROOT`(含 ispstudio/ 的绝对路径)和 `RDK_VISION_CALIBRATION_PYTHON` +(匹配环境的 Python 可执行文件)。本地 workbench 私有配置也支持 +`calibration: {ispstudioRoot, pythonExecutable}`。部署路径不进入工具参数或共享回执。 +建议固定一份经过验证的源码快照;插件只分发平台适配器,不自动复制第三方原始源码、模型或运行库。 + +## 用李乔龙的工具计算本组 LSC + +通过 `vision_calibration_engines` 检查 `ispcal-lsc` 是否可用。该引擎只支持镜头阴影校正,使用 +`isp-calibration-tool` 固定提交 `889d1a02e8a4eaca16b4df44cc54b24ab7a100f0` 的网格计算函数。 +服务侧配置 `RDK_VISION_ISPCAL_REPOSITORY` 指向包含该提交的本机 Git 仓库,本地工作台也可用 +`calibration.ispcalRepository` 配置。工具参数只接收本组样本和采集条件。 + +用至少三张同照明、同模式及同曝光增益的均匀平场 RAW,提供独立照度计读数、四通道黑电平和 +至少 6×6 的网格。创建任务选 `operation: "lsc"` 和 `engine: "ispcal-lsc"`,再运行计算。 +结果包含固定提交和源码摘要,应按该摘要匹配 X5 的 LSC 几何和 SDK 处理条件,再应用并独立回读。 +用同机位与固定曝光验证四角对中心的亮度比,恢复后的新帧也纳入比较。 + +无界面检查 `python tools/vision-x5-calibration.py --engines`。可用仅代表依赖导入成功, +不能据此声称当前采集、上板或画质已验收。相关执行器固定最长120秒,客户端错误只返回静态代码。 + +## SDK 数值与恢复 + +新计算结果的 `inputProfile` 纳入原始 `outputSha256`:RAW 保留实际输入字节绑定的布局、码值域和 +记录的采集条件;CCM 保留线性测量空间、预处理与参考编码。平台独立对照原任务/测量资产, +不能靠重算一个自洽哈希替换这些信息。旧归档缺字段时仍可读取和导出,显示 `legacy-unavailable`, +不自动补造位深或模式。SDK 请求携带原结果对象,不修改其哈希覆盖内容。 + +可信私有 binding 可设置 `inputProfile`,RAW 使用 `{kind:"raw-sample",metadata:{width,height,bitDepth, +bayer,packing,stride,blackLevel,whiteLevel},capture:{source,preprocessing,sensorMode,...}}`;CCM 使用 +`{kind:"measurement",measurement:{measurementSpace,preprocessing,referenceEncoding,referenceWhitePoint, +imageWidth,imageHeight,...}}`。每份输入都必须匹配,缺字段或不同模式在 SDK 写入前拒绝。 +另设 `sdkProfile` 时必须同时设置输入 profile;schema 为 `rdk.x5-calibration-sdk-profile.v1`, +包含 `sdkVersion/sensorConfig/cameraMode/csiPort` 和 `nativeSha256/libvpfSha256/librarySha256`。 +它核对实际二进制及私有归档效果库来源,不充当 BLC 全字段 getter 或物理画质证明。 +不要把诊断用 `synthetic-fixture` profile 当真实标定绑定;实际资格还需采集条件、增益策略、 +分数码值量化、几何与留出图像分别验证。 + +板端在调用 setter/效果库加载前拒绝映射时,错误回执带 `phase:calibration_mapping` 与 +`writeOutcome:not_attempted`,平台保留相同阶段与未写入证据。只有明确的该阶段回执才使用此分类; +实际写入后的读回失败、断连或缺回执仍为 unconfirmed。不要为一次未写入请求清除以前的恢复限制, +也不要为真正未确认的写入自动重放。 + +SDK 功能探测与标定任务分别留证。`diagnostics/qualify_calibration.py` 必须由正常 daemon +账号独占运行、保留完整原始值并恢复;LSC/CCM/AWB 的小幅试写通过不构成标定结果。 +当前已检查的 X5 SDK 白平衡增益按正 float32 的 Q10 格点向下取整。匹配版本及实际 +libvpf 哈希后,可在可信 AWB binding 中设置 `gainQuantization`,字段为 +`kind: x5-hbn-awb-q10-floor-v1`、`sdkVersion`、`libvpfSha256`、`evidenceRef`。 +映射在下发前对齐,回执保留请求与编码值;SDK 严格独立回读比较继续生效。 +不匹配 SDK 的配置应失败,不能用浮点容差掩盖已发生的量化写入。 + +LSC 从 AUTO 切到 MANUAL 时,归一化快照中的 inactive `x_size/y_size` 为零,不能把这些零 +写入手动模块。适配器只对匹配的 4×33×33、32/16 段描述符,从同一私有 SDK 快照原样带入 +网格尺寸;调用者不能修改这些只读值。物理网格位置与平场标定仍需单独取得资格。 +标定结果必须先带有合法的 `outputSha256`,再进入任何 SDK 写入。 + +匹配 SDK 的可选 `MODULE_CONTROL_GETTER=initialized-v0` 原生构建用于修复未初始化版本 +选择器的 vendor getter;其双哨兵检查和范围限制不能替代真实恢复验证。遇到旧日志包含 +无效 module mask,保留旧日志并明确恢复试验前归档配置,不能自动把当前值认作原始值。 +详细构建和独占诊断说明见包内 `tools/vision-x5-native/README.md`。 +对有效消息头却完全保留哨兵的空读回,最多重新读取三组;每组仍要求两次完整且相同的独立 +读回。其他协议异常立即失败,写入不重试。不要把“SDK 返回成功”直接当作字段已有有效值。 + +LSC 大网格的 MCP result/apply-plan 会明确标为 `bounded_calibration_mcp_receipt`:保留完整输出、 +输入 profile、系数表的哈希及绑定/未验收状态,网格只返回形状、数值范围和元素数。 +`coefficientsIncluded=false` 时不能把摘要作为系数或重算结果哈希。需要全表时使用返回的 +`completeRecordUrl` 经原有身份鉴权读取;应用仍直接传本实验 `taskId`,由平台读取并校验完整结果。 +REST、实验导出与实际 SDK 输入都保持全量。小结果仍返回完整值,旧归档缺 profile 仍保持未知。 + +需要绑定源 LSC 时,可选的 `lscGeometryProfile` 同时校验 SDK 私有快照的 32/16 段尺寸、 +输入尺寸、声明的半区布局、目标节点位置、源网格定义及源算法身份。它还校验明确声明的 +`inputBlackLevels` 和 `moduleControl={mask,value}`;这些是计算域条件,不能用错误黑电平 +或另一条前处理流程的结果替代。绑定匹配仍标记硬件网格插值未验收,不自动获得物理镜头资格。 +RAW 输入绑定可选择同时匹配遮光状态、光源 ID、色温和 Bayer 对齐 ROI,类型与边界均须合法。 +大 SDK 应用回执的 MCP 摘要保留这些校验结论、输出身份和未验收状态,完整 SDK 回执仍按哈希追溯。 + +LSC 可选的 `pipelinePreparation` 为匹配 SDK 声明 `dpcc-auto-factory-then-bypass-ge-dpcc`: +先从归档的 ADPCC 工厂表构造完整 AUTO 请求、严格写入与回读,再用真实新快照关闭 GE/DPCC 并应用 +源网格;全程保留最初原始版本和恢复日志。已处于 AUTO 时不重复写工厂表。 +处理声明通过 `calibrationPreparations.lsc` 进入 probe、readiness、apply-plan 和 MCP; +`qualification=declared-not-qualified` 只表示配置声明。平台自动携带最近同设备/SDK 探测的 +`pipelinePreparationSha256`;缺失、过期或已移除的声明在写入前拒绝,重新探测后再核对应用前提。 +兼容组件的编译、私有字段和身份要求见分发的 native README。不要把诊断绑定复制到普通配置。 +合成 RAW 的真实 SDK 对照只能证明功能链,不能证明现场镜头、黑电平、颜色或光学画质合格。 + +`vision_device_history_capacity` 表示本实验操作账本已满,SDK 尚未执行;先恢复原始版本并停止相机, +再新建实验继续,不删除验收记录、不提高上限、不自动重放先前写入。普通账本上限 128 条,恢复留证保留至 144 条。 +即使恢复留证额度用尽或平台存储不可写,显式 `vision_isp_restore` / `vision_camera_preview_stop` +仍可在账号归属、设备独占和实际 SDK 校验通过后执行;不能因此跳过这些检查。 +若返回 `vision_recovery_recording_failed`,分别读取 `recovery.status` 与 `recording`: +`readback_verified` 仅表示所选参数的实际哈希回读匹配,`stopped` 表示设备返回 `running:false`; +二者均不证明画质合格。`recording.status:unconfirmed` 表示本次回执保存未确认,不是 SDK 未执行;写入后的同步也可能失败,先核对已有记录。 +不要自动重试设备操作,不要将响应哈希或旧实验链接当成本次已保存记录;先恢复存储空间或新建实验, +再探测并重新留证。校验失败仍按实际 SDK 错误处理,不能套用“恢复已完成”。 + +开始 AI 前读取 `vision_camera_readiness`:`aiDebug.maxRoundsAvailable` 按保存记录与服务配置配额给出可选上限, +`aiDebug.archiveCapacity.rounds` 说明各轮数需要的图像、操作记录及拒绝原因。页面、路线与执行器使用同一检查。 +`vision_ai_debug_history_capacity` 表示剩余账本不足以完成所选轮数;`vision_ai_debug_archive_capacity` +表示图像数量、元数据或配置存储额度不足。先减少轮数或恢复可用额度;必要时核对恢复、停止后新建续调实验。 +续调只带入设备与目标,不复制旧样本、候选或验收状态;重新探测、保存基线并留证。 +这些是读取时的配额评估,不是磁盘预分配、当前在线或画质证明,开始执行前还会重新核对。 + +CCM/AWB 私有绑定可通过 `processingProfile` 固定实际 SDK 的 WB、LSC、模块开关、CCM 偏移等计算域。 +它要求同时匹配输入域和 SDK 身份;大网格可声明 SDK 元素数及精确数组哈希,避免复制系数。 +实际处理状态不符时写前拒绝,不自动切换模式或接受当前值。回执中的 +`processingProfileVerification=matched_declared_sdk_processing_state` 仅证明本次 SDK 状态匹配声明, +不证明测量条件或物理色卡真实合格。错误后核对采集条件和应用前提,不能自动重试写入。 + +匹配的 X5 CCM `configMode` 与 AE/AWB 枚举不同:0 才选择 MANUAL,1 选择 AUTO。 +AUTO 下手动矩阵能被缓存及回读,却可能不参与图像处理。经过真实库身份绑定的 +`modeProfile.kind=x5-hbn-ccm-manual-zero-v1` 要求 `modeField=configMode, modeValue=0`, +并校验实际 device/engine/CCM 算法库;不把这个数值泛化到其他 SDK。SDK 同 RAW 响应、矩阵方向和恢复 +须另有实测,模式声明或系数读回不能替代。未配置真实标定绑定的普通相机仍保持缺项。 + +此匹配 SDK 手动 AWB 增益范围为1到3.996。源灰卡计算的相对增益可能小于1,不能原样下发,也不能 +逐通道截断。可显式配置 `gainNormalization.kind=x5-hbn-awb-minimum-unity-v1`,先用共同倍率 +`max(1,1/min(R,G,B))` 保留颜色比例,再按已绑定的 Q10 floor 编码。仍超范围则写前拒绝。 +回执保留源增益、编码值、`commonExposureScale` 和亮度未验收状态;共同倍率可能提高亮度,须验曝光/截断。 +平台 registry 也必须显式注册已实现的 `calibration_apply`,然后按最近 probe 的逐项绑定判断可用; +注册接口不能替代具体绑定,普通配置绑定为空时仍不可标定应用。 + +源 CCM 为1/256网格并保留行和,此匹配 SDK 实际使用 signed12 / fractional7。 +可显式声明 `coefficientQuantization`,包含实际 libcommon 哈希与证据;同时需要输入、SDK、处理状态和 +MANUAL0身份。`x5-hbn-ccm-s0507-nearest-away-v1` 复现 SDK 独立舍入; +`x5-hbn-ccm-s0507-row-sum-v1` 在可表示行和约束下,以最小系数误差调整整数码值,不使用色块数据选系数。 +回执保留源矩阵、编码矩阵、每项码值修正及行和;不要把原浮点 getter 或编码误差当画质认证。 +全零编码矩阵在此算法中会被跳过,必须写前拒绝;编码后超出算法范围的端点也拒绝,不截断凑成功。 + +板端长期运行用独立系统服务管理 daemon,避免依附某次 SSH 会话。插件包提供 +`tools/vision-camera-systemd.py`:传入普通用户、已安装脚本和私有配置的绝对路径,只输出待审查 unit, +不安装、不提权、不重启。先用目标板 `systemd-analyze verify` 验证,再在无 AI、无写入、恢复已确认、 +相机空闲且仅有一个已核对的 owner 时交接。配置仍保持0600,SDK 与标定绑定不变。 +`rdk-camera-workshop.service` 的异常退出自动重启不等于 ISP 已恢复;重连后仍须核对恢复日志、实际回读和新帧。 +达到启动限流时先查故障和恢复状态,不循环 reset/start。维护诊断需先 `systemctl stop rdk-camera-workshop`, +结束后显式 start;停止服务不会自动重启,不能另起第二个 daemon。 + +普通 NV12 预览在慢客户端或 PNG 编码期间可能积压旧帧。只在点亮时丢帧不能覆盖后续成图。 +匹配实机可由管理员配置 `previewQueueDrainProfile`,kind 为 +`imx415-host2-nv12-six-buffer-discard-v1`,固定 SDK/模式/host2、native/libvpf/driver 哈希、 +`discardFrames:5` 和独立证据引用;不允许由模型填写或绕过二进制身份检查。 +普通预览和归档图的 `evidence.queueDrain` 记录实际启用的有界排空策略及哈希,缺项不补造资格。 +SDK 时间戳递增只说明不是重复返回同一时间戳,不等于没有队列积压;时钟原点未核对时,不能直接 +用 `tv_timeval` 减主机 monotonic 宣称显示延迟。恢复、新图与实际画质仍各自验收。 + +普通成图的完整 ISP 配置在取帧前后分别回读,帧哈希绑定该次已验证的配置;编码期间后来变化的 +设备状态不能覆盖旧帧的参数标签。正常预览和归档均保留完整尺寸与无损 RGB;预览可用较快的 +PNG压缩,归档保留原压缩方式,超限只对同一帧重新编码并继续执行大小限制。 +`evidence.encoding` 是编码回执,不代表画质优化。平台预览的 `receivedAt`/`receivedAtSource` +表示实际校验后接收时刻;`capturedAt` 仍保留设备原值,设备时钟未同步时不能把它当绝对采集时间。 diff --git a/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/references/systematic-isp-search.md b/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/references/systematic-isp-search.md index 6b3242a..1a7c2d7 100644 --- a/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/references/systematic-isp-search.md +++ b/plugins/rdk-camera-workshop/skills/rdk-camera-workshop/references/systematic-isp-search.md @@ -1,5 +1,15 @@ # 系统性 ISP 调试:由新图到可复验的组合配置 +## 0. 调试目标 → 通道选择 → 验收门槛速查树 + +| 调试目标 | 优先通道与顺序 | 必须守住的验收门槛 | +|---|---|---| +| 暗光发黑 / 整体过曝 | 先确认 `autoExposure` 模式;手动调曝光行周期 (`exposureUs` / `manual_attr.exp_time`) 与 Q3.5 增益 (`gain` / `manual_attr.again`) | 每轮对照 ORIGINAL/BEST 实拍图与 `visualTelemetry` 码值差,防亮部剪切与高增益噪点恶化 | +| 偏黄 / 偏蓝白平衡纠偏 | 固定目标照明与 IR-CUT 状态;手动调 Q2.10 `redGain`/`blueGain` 或离线 AWB 多光源标定(上板必传 `illuminantId`) | 必须有中性参考物或色卡,禁止无参考物时仅凭 RGB 均值判色偏 | +| 画面发灰 / 对比度与色彩 | 优先 `cproc`(亮度/对比度/饱和度)或有界 Gamma 带状曲线(`x5-common-auto-gamma-band-v1` 只压暗不提亮) | 检查暗部文字与亮部细节同步保留,避免单纯压暗冒充对比度提升 | +| 细节柔和 / 锐度与降噪 | 先固定 AE/AWB,再单项双向粗调 EE/NR 并配对 3 帧新图 + A2 恢复回测 | 严查文字边缘白边光晕与背景颗粒噪点;若 `regressions` 非空必须否决 | +| 暗场 BLC / 平场 LSC / 24 色卡 CCM | 确认物理光学遮挡(新拍 RAW/PNG 无残留场景)→ 登记离线标定任务 → `apply_plan` 核对映射后由 `vision_calibration_apply` 上板 | `userReportedCovered=true` 不替代光学遮挡实检;AWB ROI 须满足 2×2 Bayer 偶数对齐且宽高 ≥ 4 | + 用于“曝光、降噪、锐化都调一遍”“别只改白平衡就算完成”“做到当前现场最佳”。这是已实机执行的方法;参数范围与结论必须重新绑定本次 Sensor、模式、SDK、库及现场,不能把 IMX415 的数值套给新型号。 1. **先列完整验收范围。** 分开记录曝光、空间降噪、时域降噪、锐化、色彩和必要的对比度。参数生效、当前画质选优、全场景标定、插件上线是不同结论。只完成白平衡不能关闭更广的系统调试目标。 diff --git a/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/SKILL.md b/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/SKILL.md index 27287e7..7aa84aa 100644 --- a/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/SKILL.md +++ b/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/SKILL.md @@ -1,8 +1,8 @@ --- name: rdk-vision-workshop description: 在 Studio 按 180 分钟方案带学员完成 X5 + IMX415 点亮、Gamma 调优、RoboGO 异步训练、A/B/C 分流、实时检测和个人成果打包。 -version: 0.7.4 -trigger: 视觉 Workshop,视觉 Pipeline,相机与 BPU 工作坊,继续视觉任务,相机训练部署全流程,采集基线图,三张基线图,展示基线图 +version: 0.8.1 +trigger: 视觉 Workshop,视觉 Pipeline,课堂工作台,打开工作台,相机与 BPU 工作坊,继续视觉任务,相机训练部署全流程,采集基线图,三张基线图,展示基线图,ISP 示例图,ISP 调参,自然语言调图,图片调优,提亮暗部,白平衡校正,去雾去灰,真机 ISP 联调,Bayer RAW 调参,课程测试卡,示例图调 Gamma,本组离线标定,本组黑电平标定,本组 ISPStudio 标定,镜头阴影标定,色彩矩阵标定,白平衡标定,ispcal-lsc risk: medium requires_board: false permissions: network @@ -12,17 +12,71 @@ enabled: true # 视觉 Pipeline · 180 分钟 Workshop -本课程依据 [180 分钟课程安排](assets/course-plan.json)。课程执行方法见 [操作稿](references/course-runbook.md),实机交接见 [检测交接](references/tuning-handoff.md)。 +本课程依据 [飞书方案](https://horizonrobotics.feishu.cn/docx/UdhhdVXYXoPLgfxmZ32cJBSAnRb)。课程执行方法见 [操作稿](references/course-runbook.md),实机交接见 [检测交接](references/tuning-handoff.md)。 -1. 用户要开始或继续时调用 `vision_course_next`。带回已有 `resume`,并更新当前实际回执。如果知道课堂开始时间,传入实际经过的 `elapsedMinutes`。用户明确彩排时可以使用彩排时钟,标注模拟时间。展示工作台时调用 `vision_course_view`,把返回的本机地址交给 `studio_open_url`,等待宿主显示加载状态。网页工具不可用时,给出可点击的 Markdown 链接「打开课堂工作台」。仅取得本机地址时告诉学员链接已准备好。用户看总课表时调用 `vision_course_plan`。 +0. **工具发现(Studio 延迟挂载)**:调用任何 `vision_course_*` 或 `vision_*` 工具前,若当前轮次工具列表中尚未出现目标工具,先调用对应 MCP 服务的按需检索元工具 `mcp__rdk-vision-workshop__search`(涉及真机底层控制、AI 自动调试或标定上板时一并调用 `mcp__rdk-camera-workshop__search`)。**切勿**把插件 MCP 服务名传给内置 `tool_search(group)`(它只接受 Studio 内置工具组名),也不要绕过 MCP 用 `exec` 拼命令;若宿主本轮未挂载插件 MCP 服务,如实告知用户并在提问中附带 `mcp__rdk-vision-workshop__vision_course_view` 即可触发宿主挂载。 + +## 双插件意图分流与防误调矩阵 + +| 用户意图 / 场景 | 首选插件与工具 | 禁止误调 / 边界说明 | +| :--- | :--- | :--- | +| 180 分钟课堂引导、打开可视化工作台、查阶段要求与同步回执 | `rdk-vision-workshop`:`vision_course_next` / `vision_course_stage` / `vision_course_view` / `vision_course_sync` | 仅打开课堂或规划时严禁连接设备或改动板端 ISP | +| 离线自然语言调图、本地 JPG/PNG/10-bit Bayer RAW 调参、示例图 10 参数模拟与撤销 | `rdk-vision-workshop`:`vision_course_isp_example`(纯 JS 零 Python,支持 `action:"auto"` / `inheritCurrent` / `undo` / `inspect`) | 不连接相机,严禁把离线模拟表述为真机硬件回读 | +| 课堂拍照、三张基线图(RAW/ISP/重渲染)、三层预检、板端检测归档帧 | `rdk-vision-workshop`:`vision_course_camera` / `vision_course_camera_status` / `vision_course_preflight` / `vision_course_detection_status` | 查看已归档图保持只读,禁止擅自改 AE/AWB 或烧录 | +| 课堂真机 X5 ISP(保存期初快照、自动规划、多参数联调、两轮 Gamma、单项练习、恢复停流) | `rdk-vision-workshop`:`vision_course_isp`(`save` → `auto_plan`/`multi_apply`/`gamma_prepare`/`gamma_apply`/`gamma_discard`/`decision`/`revert`/`restore`)+ `vision_course_isp_status` | 任何写入前必须先 `save`;若恢复未确认严禁叠加新写入 | +| 本组离线标定(BLC / LSC / CCM / AWB 创建、运行、查图表与 `apply_plan`) | `rdk-vision-workshop`:`vision_course_calibration_status` / `vision_course_calibration` | 本工具永不直接写板卡;上板须核对 `apply_plan` 后切 `rdk-camera-workshop` 的 `vision_calibration_apply`(AWB 必带 `options:{illuminantId}`) | +| 底层 X5/S100 设备注册、点亮/开流、直接 AI 多轮自动调优、原始寄存器读写、标定上板与紧急恢复 | `rdk-camera-workshop`:`vision_device_run` / `vision_ai_debug_start` / `vision_calibration_apply` / `vision_experiment_*` | 需先用 `mcp__rdk-camera-workshop__search` 加载 `rdk-camera-workshop`;写设备操作按权限确认 | + +1. 用户要开始或继续时调用 `vision_course_next`;想看某一具体阶段的操作步骤与所需回执字段时调用 `vision_course_stage`。带回已有 `resume`,并更新当前实际回执。如果知道课堂开始时间,传入实际经过的 `elapsedMinutes`。用户明确彩排时可以使用彩排时钟,标注模拟时间。展示工作台时调用 `vision_course_view`,把返回的本机地址交给 `studio_open_url`,等待宿主显示加载状态。网页工具不可用时,给出可点击的 Markdown 链接「打开课堂工作台」。仅取得本机地址时告诉学员链接已准备好。用户看总课表时调用 `vision_course_plan`。 2. 工作台打开后,用 `vision_course_sync` 的空参数读取当前记录。完成实际工具操作后,用 `{patch:{evidence:{...}}}` 把本轮实际回执引用同步到工作台;确实解决的阻塞放入 `clearBlockers`。根据宿主对本地记录更新的权限执行。每轮只给学员当前一步,说明完成条件和证据。宿主有可用且已授权的工具时,从相机、GPU 或板端工具执行当前一步。实际工具缺失时指出哪项配置或操作需要用户或助教处理。不要把课程工具的规划回执当成执行回执。 3. 相机工具返回实际实验 ID 后,把 `camera:{experimentId}` 写入 `vision_course_sync` 的 `patch`。有实际相机 AI Run 后同步 `{camera:{experimentId,runId}}`。提示学员在工作台核对这轮新帧、实际回读和采集时间,再附入成果包。 4. 开场第 35–45 分钟采三种基线,第 45–50 分钟按组提交 RoboGO。收到已有 Run ID 后只查询原 Run。茶歇由助教核对,第 110 分钟个人盲选,第 120 分钟助教预检,第 130 分钟按实际产物与设备状态做 A/B/C 选择。 5. A 使用本人训练和量化产物。B 记录预置模型来源,完成本人板端操作。C 只归档已观看的演示记录。切换路径保留原 Run 和实际来源。板端模型需核对三类输出与实际 SHA-256。检测流须读取实际生效的 ISP 配置和本轮新帧。 6. 操作相机前保存原始配置。ISP 未恢复时按相机插件的恢复状态继续处理。交付时保存个人手册、tuning、媒体、实际模型来源、待完成项及终态恢复记录,并打开 ZIP 核对。传给用户的文件从真实制品取,未完成的路径保留说明。 -学员要开场、接回板卡或确认相机可用时,先打开原工位,读取实际实验绑定,调用 `vision_course_preflight({run:true})`。空参数查询进度。工具逐项回报服务、板卡和两帧推进。未绑定时打开工位关联,相机未开流时由学员在相机实验点亮后重试。预检通过后才报告实时画面有本轮证据;本机记录时间和 SDK 帧时间分别读取。 +学员要开场、继续 Workshop、接回板卡或确认相机可用时,先打开原实验,用 `vision_course_camera_status` 读取 `cameraBinding` 和 `latestPreflight`。旧版可用 `vision_course_sync` 的 `resume.camera` 和 `vision_course_preflight({})`。实验关联以实际实验记录为准,`device_boundary` 只表示聊天的通用设备工具范围。需要检查实时相机时调用 `vision_course_preflight({run:true})`,随后用空参数查询进度。工具逐项回报服务、板卡和两帧推进。实验未关联时打开实验关联,相机未开流时由学员在相机实验点亮后重试。`vision_device_archive_capacity` / `vision_device_history_capacity` 表示当前实验操作归档记录已满,先核对 ISP 恢复和停流,再用同设备的新实验继续并保留旧归档。预检通过后才报告实时画面有本轮证据;本机记录时间和 SDK 帧时间分别读取。 + +学员用自然语言提出调图需求——无论说纯人话(如「帮我把这张暗光图救亮但别过曝」「去黄还原中性白」「把右侧刚上传的图去雾提清晰」「再冷一点、锐度降一点」「撤销上一步」)、拖入聊天图片附件、指定本地 JPEG/PNG/10-bit Bayer RAW(`imagePath`),还是在 7 套典型场景中练习——都优先调用 `vision_course_isp_example`(纯 JS 零 Python 依赖,线性 RGB 域 10 参数:`exposureEv / shadows / highlights / gamma / brightness / contrast / saturation / wbShift / denoise / sharpness`): +- **纯人话自动诊断求解**:不猜参数,直接传 `action:"auto"`(或 `preset:"auto"`)与用户原话 `goal`,工具会执行 2-Pass 像素闭环诊断与防过曝/白平衡阻尼校验并同步到工作台; +- **多轮增量微调 & 撤销**:用户追问「再冷一点、锐度降一点」时传 `inheritCurrent:true`(配 `delta` 或直接传相对目标 `goal`),不会冲掉上一轮已调好的其他参数;说「撤销/恢复上一版」时传 `action:"undo"`;想看右侧工作台当前图与参数时传 `action:"inspect"`; +- **双向图源打通**:用户把图上传到了右侧工作台时传 `useWorkbenchImage:true`;用户把图片拖进聊天框发送时传 `useLatestAttachment:true`(或直接传附件绝对路径 `imagePath`);支持直接读取 10/12-bit Bayer RAW(配 `rawWidth`/`rawHeight`/`bayerPattern`/`bitDepth`/`blackLevel`)。不要把离线模拟称为真机硬件回读。 + +学员要求用自然语言直接调试**真实 X5 相机硬件 ISP**(如「帮我看看真实相机画面太暗偏黄怎么调」「一次性把曝光和白平衡都调好」)时: +1. 先确认已调用 `vision_course_isp({action:"save"})` 保存期初快照(确保随时可一键恢复); +2. 先调用只读 `vision_course_isp({action:"auto_plan", goal:"..."})` 采一帧真实 X5 画面分析并产出经过硬件步进量化的多参数建议(不写板卡); +3. 经学员确认后调用 `vision_course_isp({action:"multi_apply", values:{exposureUs, gain, redGain, blueGain, brightness, contrast, saturation, hue}, goal:"..."})`,自动安全切手动 AE/AWB、批量下发、独立回读并拍调前/调后实拍计算客观指标提升,支持连续多轮微调;随后用 `vision_course_isp_status({trial})` 在聊天直接渲染真机调前/调后对比图;结束前按授权调用 `revert` 或 `restore` 恢复原状。 + +课堂 Gamma 使用实验 ISP 工具。先 `vision_course_isp` 的 `save` 保存原始版本,再按已确认的学员观察目标执行 `gamma`。使用 `vision_course_isp_status` 查看实际应用、回读和前后图;学员记录保留或恢复理由。先 `revert` 取得恢复后新图,再用 `reload` 验证同一个候选。最后按课堂授权调用 `restore` 恢复并停流。候选不符合单模块要求时按失败回执说明缺项;恢复结果不明确时继续核对同一个原始快照。 + +拍照和基线图先读取 `vision_course_camera_status`。用户明确要拍照时,用 `vision_course_camera` 的 `photo`。要在 Studio 聊天看到照片时,把返回的 `capture.photoRequestId` 传给 `vision_course_camera_status`。`photoPreview:pending` 时稍后继续查询同一个 ID;`ready` 时图片已作为工具结果交给 Studio,直接报告拍照完成。`capture_failed` 时按回执说明拍摄失败,`request_changed` 时说明实验照片请求已变化。`studio_media_unavailable` 或 `preview_unavailable` 时报告内联不可用,并给出工作台链接;旧设备未返回请求 ID 时也提供工作台入口。 + +要在聊天看 ISP 调前调后图,先查询 `vision_course_isp_status`,再用已完成的 Gamma `round` 或单项 `trial` 查询指定一轮。`ispPreview:ready` 时 Studio 显示两张实拍和回读摘要。若两图或独立回读未齐,按状态说明缺项;需要查看曲线或原件时给出实验链接。 + +要在聊天看带框图,调用 `vision_course_detection_status`。`detectionPreview:ready` 时显示当前模型最近一张已校验的归档帧,并以帧回执为准说明类别和最高置信度。要看连续画面,打开返回的 Studio 工作台入口。查看归档不会启动检测。 + +用户说「看基线图」「这几张展示给我看」时,打开工具返回的工作台链接,展示当前实验已归档的图,保持只读。进入课堂基线阶段或用户要求采三图时,用 `baseline` 并传学员确认的固定场景;场景变更用 `retake`。`baselineRequested:false` 表示尚无三图采集记录。需要实验绑定时先打开工作台关联本组。操作后查询原状态,确定哪一项成功,再展示带原件下载的入口。工具不可用时指出缺失工具和工作台入口,禁止改用批量终端命令或自动改 AE/AWB。只读排查禁止调用烧录、写设备或修改 ISP 的工具。 + + +学员用自然语言描述暗部问题并希望先看建议时,调用 `vision_course_isp` 的 `gamma_prepare`,带上本轮号和学员原话。轮询 `vision_course_isp_status` 到候选就绪,使用返回地址打开 Studio 的 ISP 面板。候选仅表示 AI 建议。学员授权试调时,用当前候选的 ID 调用 `gamma_apply`;若学员不满意当前提案或想换观察目标,先调用 `gamma_discard` 放弃未下发的候选再重新生成;等待调后实拍和独立回读,再让学员描述观察与取舍。不要将模型理由写成画质结论。 + +学员要求从对话调节曝光、增益、对比度、锐度或白平衡时,先读当前实验 ISP 状态和 learner_options。只使用当前返回且可写的一个字段,不自行切换自动模式。将学员目标与选择理由附在 learner_apply;expected 取本次读回,候选值遵守步进及范围。没有实际图像时将理由明确表述为参数原理和待验证假设。 + + +## 离线标定示例与本组数据 + +学员说「看离线标定示例」时,调用 `vision_course_calibration_demo` 展示上游固定提交对合成 RAW 的计算记录和预览。课堂工作台「ISP 原理与五参数 → 离线标定示例」提供 BLC/LSC/CCM/AWB 四合一交互演练,以及参数表和计算记录下载。合成参数仅用于讲解。 + +学员要检查或计算本组标定时,先调用空参数的 `vision_course_calibration_status`,读取工作台实际关联的实验、可用离线引擎(ISPStudio / ispcal-lsc / NumPy)、已归档 RAW、色卡测量资产和已有任务。实验尚未关联时,给出工作台入口。引擎不可用或素材缺失时说明实际缺项。合成示例的上游提交与本组计算的服务端引擎哈希分别保留。 + +学员明确要求登记离线标定任务时,使用 `vision_course_calibration`: +- 黑电平(BLC):`create_dark`,传入实际归档的 `sampleIds`、真实采集模式 `sensorMode` 与 `darkConfirmed:true`(可选 `engine`: `ispstudio`/`numpy`); +- 镜头阴影(LSC):`create_lsc`,传入平场 `sampleIds`、`sensorMode`、`illuminantId`、`blackLevels`、`grid`、`luxSamples`(默认优先选 `ispcal-lsc`,也可指定 `ispstudio`/`numpy`); +- 色彩矩阵(CCM):`create_ccm`,传入已归档色卡测量资产 `assetId`(可在工作台下载 24 色卡模板 JSON 并上传归档); +- 多光源白平衡(AWB):`create_awb`,传入 `sensorMode`、`blackLevels` 与 ≥2 组不同色温光源的灰卡 `groups`(含 `illuminantId`、`colorTemperatureK`、`roi`(`width/height ≥ 4` 且 `x/y/width/height` 为 2×2 Bayer 偶数对齐)、`sampleIds`)。 +曝光和增益均从归档元数据核对。学员明确要求计算某个已有任务时,用 `vision_course_calibration` 的 `run`,传实验 ID 和任务 ID。收到 `pendingRequest` 后,查询同一任务的 `task` 状态,服务端报告 `completed` 才告知计算完成;提交回执不确定时先核对原任务状态避免重复发起。 + +用户查看结果时用 `vision_course_calibration_status` 的 `result`,确认来源、输出哈希、参数摘要和验证状态;在 Studio 环境会自动生成 BLC/LSC/CCM/AWB 标定结果预览图内嵌展示。用户想看能否应用到设备上时用同工具的 `apply_plan` 读 SDK 映射和前提:当 `runtimeMapping.status === 'declared'` 且返回 `nextDeviceTool` 时,经学员明确确认后由相机插件 `vision_calibration_apply` 执行上板、回读与实拍验证(注意 **AWB 标定必带 `options: { illuminantId: "<色温/光源ID>" }`**,否则服务端会返回 `vision_calibration_illuminant_selection_required`);`vision_course_calibration` 本身永不直接写设备。 -课堂 Gamma 使用工位 ISP 工具。先 `vision_course_isp` 的 `save` 保存原始版本,再按已确认的学员观察目标执行 `gamma`。使用 `vision_course_isp_status` 查看实际应用、回读和前后图;学员记录保留或恢复理由。先 `revert` 取得恢复后新图,再用 `reload` 验证同一个候选。最后按课堂授权调用 `restore` 恢复并停流。候选不符合单模块要求时按失败回执说明缺项;恢复结果不明确时继续核对同一个原始快照。 +学员也可在「ISP 原理与五参数 → 本组离线标定」通过四步流水线(BLC → LSC → CCM → AWB)选择引擎、一键填入已算 BLC、下载色卡模板、查看热图/矩阵/曲线、一键复制上板应用指令给 Studio 助手并跳转拍照对比画质。 -拍照和基线图先读取 `vision_course_camera_status`。用户说「看基线图」「这几张展示给我看」时,打开工具返回的工作台链接,展示当前工位已归档的图,保持只读。用户明确要拍照时,用 `vision_course_camera` 的 `photo`。采三图用 `baseline`,传学员确认的固定场景;场景变更用 `retake`。需要实验绑定时先打开工作台关联本工位。操作后查询原状态,确定哪一项成功,再展示带原件下载的入口。工具不可用时指出缺失工具和工作台入口,禁止改用批量终端命令或自动改 AE/AWB。只读排查禁止调用烧录、写设备或修改 ISP 的工具。 +用户明确想重新计算课堂示例时,用 `vision_course_calibration_recompute`。该工具从启动环境的 `RDK_VISION_COURSE_ISPCAL_REPOSITORY` 指定的已安装 Git 仓库提取固定提交,在临时目录运行上游 CLI。它需要本机 Git、tar、Python 及上游依赖。源码路径由宿主配置,工具调用不接受路径参数。未配置时用 `vision_course_calibration_demo` 读取原先计算的参考结果。 diff --git a/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/assets/course-plan.json b/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/assets/course-plan.json index b340b48..ad5ab52 100644 --- a/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/assets/course-plan.json +++ b/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/assets/course-plan.json @@ -4,7 +4,7 @@ "course": "AI Native 工作坊 —— 视觉 Pipeline 开发", "totalMinutes": 180, "referenceStart": "09:30", - "source": "视觉 Pipeline AI Native 开发 Workshop 180 分钟课程方案", + "source": "https://horizonrobotics.feishu.cn/docx/UdhhdVXYXoPLgfxmZ32cJBSAnRb", "sourceRevision": "195", "kit": "RDK X5 + Sony IMX415", "classSize": 30, diff --git a/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/assets/ddc-2026-12-06.json b/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/assets/ddc-2026-12-06.json new file mode 100644 index 0000000..e3c90d6 --- /dev/null +++ b/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/assets/ddc-2026-12-06.json @@ -0,0 +1,172 @@ +{ + "schema": "rdk.vision-workshop-course.v2", + "executionStatus": "planning_only", + "course": "AI Native 工作坊 —— 视觉 Pipeline 开发", + "totalMinutes": 180, + "referenceStart": "09:30", + "source": "https://horizonrobotics.feishu.cn/docx/UdhhdVXYXoPLgfxmZ32cJBSAnRb", + "sourceRevision": "ddc-12-06-draft", + "kit": "RDK X5 + Sony IMX415", + "classSize": 30, + "deadlines": { + "submitBy": 45, + "runCheckpoint": 120, + "deployAt": 135, + "deliverAt": 160, + "perBoardMinutes": 2, + "submitStart": 40 + }, + "breakPolicy": { + "startMinute": 105, + "endMinute": 115 + }, + "training": { + "platform": "直连开发机", + "dataset": "课堂固定数据集,以本组连接卡为准", + "model": "YOLOv8s", + "classes": [ + "park", + "qrcode", + "obstacle" + ], + "imgsz": 640, + "epochs": 100, + "opset": 11, + "target": "X5 Bayes-e", + "input": "NV12", + "workflow": "devmachine" + }, + "schedule": [ + { + "id": "intro", + "topic": "开场与目标", + "start": 0, + "end": 10, + "minutes": 10, + "lane": "class", + "executionStatus": "not_executed" + }, + { + "id": "connect", + "topic": "连接与点亮", + "start": 10, + "end": 30, + "minutes": 20, + "lane": "camera", + "executionStatus": "not_executed" + }, + { + "id": "baseline", + "topic": "三张基线与启动训练", + "start": 30, + "end": 45, + "minutes": 15, + "lane": "camera", + "executionStatus": "not_executed" + }, + { + "id": "formats", + "topic": "ISP 原理与五参数", + "start": 45, + "end": 70, + "minutes": 25, + "lane": "camera", + "executionStatus": "not_executed" + }, + { + "id": "gamma_demo", + "topic": "第 1 轮跟做 Gamma", + "start": 70, + "end": 90, + "minutes": 20, + "lane": "camera", + "executionStatus": "not_executed" + }, + { + "id": "gamma_trial", + "topic": "第 2 轮自主 Gamma", + "start": 90, + "end": 105, + "minutes": 15, + "lane": "camera", + "executionStatus": "not_executed" + }, + { + "id": "break", + "topic": "茶歇与助教核对任务", + "start": 105, + "end": 115, + "minutes": 10, + "lane": "class", + "executionStatus": "not_executed" + }, + { + "id": "blind", + "topic": "盲选与记录偏好", + "start": 115, + "end": 120, + "minutes": 5, + "lane": "camera", + "executionStatus": "not_executed" + }, + { + "id": "reproduce", + "topic": "保存与个人复现", + "start": 120, + "end": 135, + "minutes": 15, + "lane": "camera", + "executionStatus": "not_executed" + }, + { + "id": "deploy", + "topic": "11:45 分流与模型部署", + "start": 135, + "end": 160, + "minutes": 25, + "lane": "model", + "executionStatus": "not_executed" + }, + { + "id": "deliver", + "topic": "恢复、分享与打包", + "start": 160, + "end": 180, + "minutes": 20, + "lane": "class", + "executionStatus": "not_executed" + } + ], + "parallel": [ + { + "id": "train", + "topic": "核对数据集并启动本组开发机任务", + "start": 30, + "end": 45, + "minutes": 15, + "lane": "model", + "executionStatus": "not_executed" + }, + { + "id": "wait_run", + "topic": "后台训练与助教核对", + "start": 40, + "end": 135, + "minutes": 95, + "lane": "model", + "executionStatus": "not_executed" + } + ], + "limitations": [ + "课程进度引用由学员、助教或宿主提供。真实设备和算力操作由各自执行工具完成。" + ], + "groupCount": 15, + "classroomId": "ddc-2026-12-06-shanghai", + "date": "2026-12-06", + "instructor": { + "intro": 45, + "expertStart": 55, + "expertEnd": 65, + "practiceReady": 70 + } +} diff --git a/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/references/course-runbook.md b/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/references/course-runbook.md index d867007..21146be 100644 --- a/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/references/course-runbook.md +++ b/plugins/rdk-camera-workshop/skills/rdk-vision-workshop/references/course-runbook.md @@ -1,22 +1,22 @@ # 180 分钟课程操作稿 -课程来源为 [视觉 Pipeline AI Native 开发 Workshop 方案](../assets/course-plan.json)。以下时刻以 09:30 开场为例,可按实际开场平移。 +课程来源为 [视觉 Pipeline AI Native 开发 Workshop 方案](https://horizonrobotics.feishu.cn/docx/UdhhdVXYXoPLgfxmZ32cJBSAnRb)。以下时刻以 09:30 开场为例,可按实际开场平移。 | 时间 | 学员当前一步 | 完成后留存 | |---|---|---| -| 09:30–09:45 | 确定观察目标、区域与工位 | 一句观察目标 | +| 09:30–09:45 | 确定观察目标、区域与实验 | 一句观察目标 | | 09:45–10:05 | 核对 X5 + IMX415,启动已适配模式 | 第一张新图、设备模式、原始 ISP | | 10:05–10:20 | 固定场景,10:10–10:15 分别保存 RAW、ISP 显示、渲染图。10:15–10:20 分批提交 RoboGO | 三种基线图的来源、采集条件、原 Run ID 和受理回执 | | 10:20–10:35 | 用样例辨认 Bayer RAW、ISP 显示图与渲染图 | 格式辨认记录 | | 10:35–10:55 | 第 1 轮跟做有界 Gamma,随后第 2 轮自主 | 实际参数回读、新图、亮度对照和取舍 | | 10:55–11:10 | 从暗部文字或整体明暗选一项,自主对照 | 观察依据与保留或恢复理由。保留原值也可完成 | -| 11:10–11:20 | 茶歇,助教核对原 Run 预计完成时间 | 原 Run 状态、超时工位的预置分支准备 | +| 11:10–11:20 | 茶歇,助教核对原 Run 预计完成时间 | 原 Run 状态、超时实验的预置分支准备 | | 11:20–11:25 | 用已有图做盲选,先写理由再揭晓 | 本人偏好和理由 | | 11:25–11:40 | 导出选定 tuning、先恢复原值、再个人重载 | 版本身份、独立回读、重载后新图、恢复步骤 | | 11:40–12:10 | 核对本人 Run 和预跑的 X5 产物,按 A/B/C 分流并完成相应验证 | 本人产物、预置产物或演示的来源,实际板端画面及是否检出 | | 12:10–12:30 | 恢复原始配置、停止采集,下载并解压个人包 | 原始配置回读、手册、tuning、图像、检测记录、实际待办 | -训练默认使用组织方预置数据集、YOLOv8s、park / qrcode / obstacle 三类、640 输入、100 轮。ONNX 为 opset 11,PTQ 在 X5 Bayes-e 工具链用训练图校准并生成 NV12 制品。课堂量化尽量云端预跑,板端下发与检测按工位分批,11:30 再预检原 Run,11:40 切分流,目标单台两分钟。 +训练默认使用组织方预置数据集、YOLOv8s、park / qrcode / obstacle 三类、640 输入、100 轮。ONNX 为 opset 11,PTQ 在 X5 Bayes-e 工具链用训练图校准并生成 NV12 制品。课堂量化尽量云端预跑,板端下发与检测按实验分批,11:30 再预检原 Run,11:40 切分流,目标单台两分钟。 - A 使用本人训练和量化产物。核对三类标签、前后处理和实际板端模型哈希。 - B 使用来源可核对的预置产物。个人训练与量化保持未完成,实机操作按实际回执记录。 diff --git a/plugins/rdk-camera-workshop/web/app.mjs b/plugins/rdk-camera-workshop/web/app.mjs index dbcd408..9bb98a3 100644 --- a/plugins/rdk-camera-workshop/web/app.mjs +++ b/plugins/rdk-camera-workshop/web/app.mjs @@ -1,11 +1,21 @@ -import { detectionResults, guideCourse, guideSchema, normalizedModelHash, presetModelHash } from '/guide.mjs'; -import { labels, steps } from '/steps.mjs'; +import { classroomClock, classroomStep, detectionResults, guideCourse, guideSchema, normalizedModelHash, presetModelHash } from '/guide.mjs'; +import { labels, stepEntries, steps } from '/steps.mjs'; import { storedZip } from '/zip.mjs'; +import { createCalibrationPanel } from '/calibration-panel.mjs'; +import { setupCalibrationExercise } from '/calibration-exercise.mjs'; import { createCameraPanel } from '/camera-panel.mjs'; import { createCapturePanel } from '/capture-panel.mjs'; import { createPreflightPanel } from '/preflight-panel.mjs'; import { createIspPanel } from '/isp-panel.mjs'; import { renderIspDemo } from '/isp-demo.mjs'; +import { createCompareStage, drawToneCurve } from '/image-compare.mjs'; +import { + DEFAULT_ISP_PARAMS, + applyIspPipeline as runLinearIsp, + formatIspParamSummary, + normalizeIspParams, + solveAutoIsp, +} from '/isp-engine.mjs'; import { createBoardPanel } from '/board-panel.mjs'; const $=id=>document.getElementById(id); @@ -41,23 +51,58 @@ function field(key,title,{value='',type='text',options=[],required=true,max=300, input.required=required; input.placeholder=placeholder; if(type==='number') {input.min='0';input.max=String(max);input.step='1';} - else input.maxLength=max; + else if(type!=='time') input.maxLength=max; label.append(input); return label; } const key=location.hash.slice(1); +window.addEventListener('hashchange',()=>location.reload()); const storageKey='rdk-vision-classroom-v2:'+key; -const response=await fetch('/course.json?view='+encodeURIComponent(key)); -if (!response.ok) throw new Error('课程数据无法读取'); -const {plan,resume,revision=0,practiceReturnUrl}=await response.json(); +function startupIssue(title, detail, retry=false) { + const card=element('section','','box'); + card.setAttribute('role','alert'); + card.append(element('h1',title),element('p',detail,'action-copy')); + if(retry) card.append(button('重新读取',()=>location.reload(),'primary')); + document.querySelector('main').replaceChildren(card); + document.querySelector('.top-actions').remove(); +} +async function loadCourse() { + if(!key) { + startupIssue('课堂链接缺少实验会话','回到 RDK Studio,在当前学员对话重新打开课堂工作台。复制到浏览器时,请复制包含 # 后面内容的完整链接。'); + return; + } + try { + const response=await fetch('/course.json?view='+encodeURIComponent(key),{signal:AbortSignal.timeout(10000)}); + if(!response.ok) throw new Error('course_unavailable'); + const course=await response.json(); + if(!Array.isArray(course.plan?.schedule)||!Array.isArray(course.plan?.parallel)) throw new Error('course_invalid'); + if(!course.resume) { + startupIssue('实验链接已失效','回到 RDK Studio,从当前学员对话重新打开课堂工作台,使用新打开的地址。'); + return; + } + return course; + } catch { + startupIssue('课堂数据暂时无法读取','确认 RDK Studio 仍在运行,再点“重新读取”。如果仍打不开,请从学员对话重新打开课堂工作台。',true); + } +} +const course=await loadCourse(); +if(course) startClassroom(course); + +function startClassroom({plan,resume,revision=0,practiceReturnUrl,practice:initialPractice,stationKind,lastStation,stationActive,developerMachine}) { +const direct=plan.training.workflow==='devmachine'; const stages=new Map([...plan.schedule,...plan.parallel].map(stage=>[stage.id,stage])); +const mainStageIds=new Set(plan.schedule.map(stage=>stage.id)); +const parallelStageIds=new Set(plan.parallel.map(stage=>stage.id)); const runStatus={not_submitted:'待提交',submitted:'已受理',queued:'排队中',running:'后台训练',completed:'训练完成',artifact_ready:'INT8 已就绪',failed:'训练失败',missed:'提交窗口已结束'}; -let state={resume:resume??{},anchor:null,manual:false}; +let state={resume:resume??{},anchor:null,manual:false,startClock:null}; let files=[]; let report, updateDialog, timer, lastMinute; +let viewedStage; +const timelineItems=new Map(); let sessionRevision=revision; let updates=0; let updateQueue=Promise.resolve(); +let importingProgress=false; let photoSlot; let photos={}; let blindOrder; @@ -65,27 +110,85 @@ let revealed=false; let routeExpanded=false; let trainingEvidence, boardProof; let comparisonReadback; -let roboGoStatus={}, roboGoBusy=false, roboGoNote='', lastRoboGoCall=0; +let roboGoStatus={}, roboGoBusy=false, roboGoNote='', lastRoboGoCall=0, lastRoboGoStateCall=0; +let activeToolTab=''; +let stationHealthData=null, sseConnected=false, lastFocusSeq=0; const attachedCameraEvidence=new Map(); -const toolPanels=Array.from($('tool-panels').children); +const toolPanels=Array.from($('tool-panels').children).filter(panel=>!practiceReturnUrl||panel.id!=='isp-demo'); const activePanels={ connect:['camera-preflight','camera'], baseline:['camera-capture'],formats:['camera-capture'], + await_route:['training'], deploy:['board'],live:['board'],preset_deploy:['board'], }; + +const timelineDetails=$('timeline').closest('details'); const wide=matchMedia('(min-width: 1000px)'); -function syncTimeline() { $('timeline').parentElement.open=wide.matches; } +let lastWide=null; +function syncTimeline() { + if(wide.matches) { + timelineDetails.open=true; + lastWide=true; + return; + } + if(lastWide!==false) { + timelineDetails.open=false; + lastWide=false; + } +} +timelineDetails.addEventListener('toggle',()=>{ + if(wide.matches&&!timelineDetails.open) timelineDetails.open=true; +}); wide.addEventListener('change',syncTimeline); +window.addEventListener('resize',syncTimeline); syncTimeline(); -function showPanel(id) { + +function renderToolTabs() { + const tabs=$('tool-tabs'); + const panels=Array.from($('tool-panels').children).filter(panel=>!panel.hidden); + tabs.replaceChildren(); + if(!panels.length) { + $('station-tools').hidden=true; + return; + } + $('station-tools').hidden=false; + if(!panels.some(panel=>panel.id===activeToolTab)) activeToolTab=panels[0].id; + for(const panel of panels) { + const selected=panel.id===activeToolTab; + panel.dataset.tabHidden=selected?'false':'true'; + const tab=element('button',panel.dataset.toolLabel||panel.id,'tool-tab'); + tab.type='button'; + tab.role='tab'; + tab.setAttribute('aria-selected',String(selected)); + tab.setAttribute('aria-controls',panel.id); + tab.onclick=()=>{ + activeToolTab=panel.id; + if(panel.tagName==='DETAILS') panel.open=true; + renderToolTabs(); + }; + tabs.append(tab); + } +} + +function showPanel(id, focusId=id) { const panel=$(id); - if(panel.hidden) {notify('此操作还缺本步所需的产物或回执。');return;} - if($('tool-panels').contains(panel)) $('station-tools').open=true; - const title=panel.querySelector('h2,summary')??panel; + if(!panel||panel.hidden) {notify('此操作还缺本步所需的产物或记录。');return;} + if($('tool-panels').contains(panel)) { + activeToolTab=panel.id; + $('station-tools').open=true; + if(panel.tagName==='DETAILS') panel.open=true; + renderToolTabs(); + } else if(panel.tagName==='DETAILS') { + panel.open=true; + } + const target=$(focusId)??panel; + const title=target.querySelector('h2,h3,summary')??target; title.tabIndex=-1; title.focus({preventScroll:true}); - panel.scrollIntoView({block:'start'}); + target.scrollIntoView({block:'start'}); } + +let modalStage=null; function compareFrames(frames) { const controls=['frame-scale','frame-x','frame-y'].map($); [controls[0].value,controls[1].value,controls[2].value]=['1','50','50']; @@ -107,10 +210,49 @@ function compareFrames(frames) { }; for(const control of controls) control.oninput=zoom; zoom(); + + const modeBar=$('frame-dialog-mode'); + const stageWrap=$('frame-dialog-stage'); + const zoomImages=$('frame-dialog-images'); + const zoomControls=$('frame-dialog-controls'); + const setModalMode=next=>{ + const curtain=next==='curtain'&&frames.length===2; + stageWrap.hidden=!curtain; + zoomImages.hidden=curtain; + zoomControls.hidden=curtain; + $('frame-mode-curtain').className='isp-seg-btn'+(curtain?' active':''); + $('frame-mode-curtain').setAttribute('aria-pressed',String(curtain)); + $('frame-mode-zoom').className='isp-seg-btn'+(!curtain?' active':''); + $('frame-mode-zoom').setAttribute('aria-pressed',String(!curtain)); + }; + if(frames.length===2) { + modeBar.hidden=false; + if(!modalStage) { + modalStage=createCompareStage({element,button,defaultMode:'split',showHistogram:true,showLoupe:true}); + stageWrap.replaceChildren(modalStage.root); + } + modalStage.setImages({ + beforeSrc:frames[0].src,afterSrc:frames[1].src, + beforeLabel:frames[0].label,afterLabel:frames[1].label, + beforeAlt:frames[0].label,afterAlt:frames[1].label, + }); + modalStage.setPosition(50); + $('frame-mode-curtain').onclick=()=>setModalMode('curtain'); + $('frame-mode-zoom').onclick=()=>setModalMode('zoom'); + setModalMode('curtain'); + } else { + modeBar.hidden=true; + setModalMode('zoom'); + } $('frame-dialog').showModal(); + if(frames.length===2&&modalStage) requestAnimationFrame(()=>modalStage.refreshScope()); } + +const pageParams=new URLSearchParams(location.search); +const initialPanel=pageParams.get('panel'); const ispPanel=createIspPanel({key,$,element,button,openDialog,field,notify,getBinding:()=>report?.resume.camera, - compareFrames,onEvidenceChange:renderDeliveryChecklist, + showCamera:()=>showPanel('camera'), + compareFrames,onEvidenceChange:renderDeliveryChecklist,initialRound:initialPanel==='isp'?Number(pageParams.get('round')):null, pick:(pair,readback)=>{ for(const photo of Object.values(photos)) URL.revokeObjectURL(photo.url); photos=Object.fromEntries(pair.map((file,index)=>[index?'candidate':'original',{file,url:URL.createObjectURL(file)}])); @@ -118,16 +260,27 @@ const ispPanel=createIspPanel({key,$,element,button,openDialog,field,notify,getB resetBlindOrder();render();showPanel('comparison'); }, }); -const preflightPanel=createPreflightPanel({key,$,element,button,notify,showCamera:()=>showPanel('camera'),getBinding:()=>report?.resume.camera}); +const preflightPanel=createPreflightPanel({key,$,element,button,notify,showCamera:()=>showPanel('camera'), + isCameraVisible:()=>$('step-workspace').contains($('camera')), + getBinding:()=>report?.resume.camera}); const capturePanel=createCapturePanel({key,$,element,button,field,openDialog,notify, getBinding:()=>report?.resume.camera, + canRefresh:()=>updates===0, attach:entries=>{addCameraFiles(entries);render();notify('已附入相机原件与回执。');}, }); +function openCalibrationPanel(id) { + $(id).open=true; + showPanel(id); +} +const calibrationPanel=createCalibrationPanel({key,$,element,button,notify,getBinding:()=>report?.resume.camera, + showCamera:()=>showPanel('camera'),showCapture:()=>showPanel('camera-capture'), + showExample:()=>openCalibrationPanel('calibration-demo'), + isExampleOpen:()=>$('step-workspace').contains($('calibration-demo'))&&$('calibration-demo').open}); const cameraPanel=createCameraPanel({key,$,element,button,field,openDialog,notify, getBinding:()=>report?.resume.camera, - bind:camera=>save({camera},camera?'已关联本工位相机实验。':'已解除关联。'), + bind:camera=>save({camera},camera?'已关联本组相机实验。':'已解除关联。'), canRefresh:()=>updates===0, - attach:entries=>{addCameraFiles(entries);render();notify('已附入本工位成果包。');}, + attach:entries=>{addCameraFiles(entries);render();notify('已附入本实验成果包。');}, compare:entries=>{ addCameraFiles(entries); for(const photo of Object.values(photos)) URL.revokeObjectURL(photo.url); @@ -158,34 +311,92 @@ const boardPanel=createBoardPanel({key,$,element,button,notify,getReport:()=>rep resetBlindOrder();render();showPanel('comparison'); }, }); + try { const saved=JSON.parse(localStorage.getItem(storageKey)); - if(saved) {guideCourse(plan,saved.resume);state={...saved,resume:resume??saved.resume};} + if(saved) { + guideCourse(plan,saved.resume); + state={...state,...saved,resume:resume??saved.resume}; + } } catch {} + const minute=()=>state.anchor!==null?Math.min(180,Math.max(0,Math.floor((Date.now()-state.anchor)/60000))):state.resume.elapsedMinutes; -let entryDismissed=false; +const formatted=n=>classroomClock(plan,n,state.startClock); + function renderEntryChoice() { const choice=$('entry-choice'); const time=minute(); const {camera,evidence,run,path}=report.resume; const hasProgress=time!==undefined||camera||run||path||Object.keys(evidence).length>0; - choice.hidden=!practiceReturnUrl&&(entryDismissed||!hasProgress); + + // Keep header station control updated without cluttering above-the-fold with a giant banner. + const topStation=$('top-new-station'); + topStation.hidden=Boolean(practiceReturnUrl)||!stationKind||stationActive===false||(stationKind==='original'&&!hasProgress); + topStation.textContent=stationKind==='fresh'?'返回原实验':'新建实验'; + + // Only show the banner when switching context is genuinely needed (practice return, inactive station, or secondary station switcher). + const needsBanner=Boolean(practiceReturnUrl)||stationActive===false||stationKind==='fresh'||Boolean(lastStation&&stationKind==='original'); + choice.hidden=!needsBanner; if(choice.hidden) return; - $('entry-title').textContent=practiceReturnUrl?'独立练习':'已有课堂工位'; - $('entry-summary').textContent=practiceReturnUrl?'从开场记录观察目标,也可打开 ISP 标准案例。此练习独立记录,真机和训练入口已关闭。': - '当前步骤 · '+(report.nextStep?.title??'核对成果包')+'。新练习从开场开始,原工位进度会保留。'; - $('entry-continue').textContent=practiceReturnUrl?'返回原工位':'继续工位'+(time===undefined?'':' · '+formatted(time)); - $('entry-practice').textContent=practiceReturnUrl?'看 ISP 标准案例':'开始新练习'; + $('entry-title').textContent=practiceReturnUrl?'ISP 图像调试实验室': + stationActive===false?'当前页面不是活跃实验': + stationKind==='fresh'?'当前在新建实验':'已有其他实验记录'; + $('entry-summary').textContent=practiceReturnUrl?'可在 7 套典型 ISP 病灶与标板场景(或导入本地图)间自由切换,支持 10 项线性 ISP 实时模拟、AI 自动诊断、卷帘对比、2.5× 放大镜与双向实时同步。': + stationActive===false?'此页面仅用于查看历史记录。要继续操作设备或保存进度,请切回当前实验。': + stationKind==='fresh'?'此实验从第一步独立记录,原有实验数据已保留。': + '本机已有另一份新建实验,可直接切换,或继续当前实验。'; + $('entry-continue').hidden=!practiceReturnUrl&&stationActive!==false; + $('entry-continue').textContent=practiceReturnUrl?'返回原实验':'打开当前实验'; + $('entry-station').hidden=Boolean(practiceReturnUrl)||stationActive===false||stationKind!=='fresh'; + $('entry-station').textContent='返回原实验'; + $('entry-last-station').hidden=Boolean(practiceReturnUrl)||!lastStation||stationKind!=='original'||stationActive===false; + $('entry-practice').hidden=true; } + $('entry-continue').onclick=()=>{ if(practiceReturnUrl) {location.assign(practiceReturnUrl);return;} - entryDismissed=true; - renderEntryChoice(); - showPanel('step-title'); + if(stationActive===false) {void changeStation('active',$('entry-continue'));return;} +}; +async function changeStation(action,control) { + control.disabled=true; + try { + const response=await fetch('/station/'+action,{method:action==='active'?'GET':'POST',headers:{'X-Workshop-Session':key}}); + const data=await response.json(); + if(!response.ok) throw new Error(data.error); + location.assign(data.url); + } catch(error) { + notify(error.message==='station_busy'?'请等训练提交确认,完成检测或相机恢复后再切换。': + '实验暂时无法切换,请刷新后重试。原有记录已保留。'); + control.disabled=false; + } +} +function handleStationSwitch(control) { + if(stationKind==='fresh') {void changeStation('original',control);return;} + openDialog('新建实验',[ + element('p','课堂计时、实验记录和训练绑定从第一步开始。原实验记录可随时回看。同组已有训练任务时,请在新实验记录原 Run。'), + ],()=>{void changeStation('new',control);},'新建实验'); +} +$('entry-station').onclick=()=>handleStationSwitch($('entry-station')); +$('top-new-station').onclick=()=>handleStationSwitch($('top-new-station')); +$('entry-last-station').onclick=()=>void changeStation('latest',$('entry-last-station')); +const stationLink=$('station-link'); +stationLink.hidden=!key||Boolean(practiceReturnUrl); +stationLink.onclick=()=>{ + const link=new URL('/',location.href); + link.hash=location.hash; + const addressField=element('label','本机浏览器地址','field'); + const address=element('input'); + address.type='url'; + address.value=link.href; + address.readOnly=true; + addressField.append(address); + const tip=element('p','复制完整地址,在这台电脑的浏览器粘贴打开。'); + openDialog('当前实验链接',[tip,addressField],()=>{},'完成'); + address.focus(); + address.select(); }; -$('entry-practice').onclick=async()=>{ - if(practiceReturnUrl) { $('isp-demo').open=true;showPanel('isp-demo');return; } - const control=$('entry-practice'); +async function openIspPractice(event) { + const control=event.currentTarget; control.disabled=true; try { const result=await fetch('/practice',{method:'POST',headers:{'X-Workshop-Session':key}}); @@ -193,14 +404,13 @@ $('entry-practice').onclick=async()=>{ const {url}=await result.json(); location.assign(url); } catch { - notify('独立练习暂时打不开。可重试,或继续原工位。'); + notify('独立练习暂时打不开。可重试,或继续原实验。'); control.disabled=false; } -}; -const formatted=n=>{ - const total=570+n; - return String(Math.floor(total/60)).padStart(2,'0')+':'+String(total%60).padStart(2,'0'); -}; +} +$('top-practice').onclick=openIspPractice; +$('entry-practice').onclick=openIspPractice; + function notify(message) { $('notice').textContent=message; $('notice').hidden=false; clearTimeout(timer); timer=setTimeout(()=>$('notice').hidden=true,5000); @@ -219,17 +429,161 @@ function applySession(result) { storeState(); render(); } -function publish(patch, clearBlockers=[], replace=false) { +async function writeSession(patch,clearBlockers,replace=false,signal) { + const reply=await fetch('/session',{method:'POST',headers:{'Content-Type':'application/json','X-Workshop-Session':key,'X-Workshop-Source':'ui'}, + body:JSON.stringify({patch,clearBlockers,replace}),signal}); + const result=await reply.json(); + if(!reply.ok) throw new Error(result.error??'session_update_failed'); + return result; +} +function reportUiEvent(type,summary,stageId) { + if(!key||practiceReturnUrl) return; + void fetch('/session/ui-event',{ + method:'POST', + headers:{'Content-Type':'application/json','X-Workshop-Session':key}, + body:JSON.stringify({type,summary,...(stageId?{stageId}:{})}), + }).catch(()=>{}); +} +function updateSyncBadge(connected) { + sseConnected=connected; + const badge=$('live-sync-badge'); + if(!badge) return; + badge.className='live-sync'+(connected?' connected':''); + const label=badge.querySelector('span'); + if(label) label.textContent=connected?'实时联动':'轮询同步'; +} +function healthPill(label,tone,onClick) { + const node=element('button','','health-pill'+(tone?' '+tone:'')); + node.type='button'; + node.append(element('i'),element('span',label)); + node.addEventListener('click',onClick); + return node; +} +function renderStationHealth() { + const bar=$('station-health'); + if(!bar||practiceReturnUrl) return; + bar.hidden=false; + const pills=$('station-health-pills'); + pills.replaceChildren(); + const h=stationHealthData; + if(!h||h.practice) { + pills.append(healthPill('工位检查中…','',()=>void refreshStationHealth(true))); + return; + } + const camCfg=h.camera?.configStatus; + const camCfgLabel=camCfg==='configured'?'相机服务已配':camCfg==='credential_missing'?'缺少相机凭据':camCfg==='invalid'?'相机配置异常':'相机服务未配'; + const camCfgTone=camCfg==='configured'?'ok':camCfg==='unconfigured'?'warn':'blocked'; + pills.append(healthPill(camCfgLabel,camCfgTone,()=>openHealthDiagnostics())); + + const bound=Boolean(h.camera?.bound); + const pf=h.camera?.preflightStatus; + const bindLabel=!bound?'未关联实验':pf==='passed'?'实时流预检通过':pf==='running'?'预检进行中':pf==='blocked'?'相机预检受阻': + '已关联 · '+(h.camera?.title?h.camera.title.slice(0,12):'待预检'); + const bindTone=!bound?'warn':pf==='passed'?'ok':pf==='blocked'?'blocked':''; + pills.append(healthPill(bindLabel,bindTone,()=>showPanel(bound?'camera-preflight':'camera'))); + + const tr=h.training; + const trLabel=tr?.runId?'训练已登记':tr?.mode==='devmachine'? + (tr.profileStatus==='ready'?'开发机卡就绪':tr.profileStatus==='invalid'?'开发机卡异常':'开发机待配置'): + (tr?.connected?'RoboGO 已授权':'RoboGO 待授权'); + const trTone=tr?.runId||tr?.profileStatus==='ready'||tr?.connected?'ok':tr?.profileStatus==='invalid'?'blocked':'warn'; + pills.append(healthPill(trLabel,trTone,()=>showPanel('training'))); + + const bd=h.board; + const bdLabel=bd?.path==='C'?'路径 C(演示)':bd?.launcherReady?'板端执行器就绪': + (bd?.hasBoardArchive||bd?.hasPresetArchive)?'板端归档可用':'板端检测待配'; + const bdTone=bd?.launcherReady||bd?.hasBoardArchive||bd?.hasPresetArchive?'ok':''; + pills.append(healthPill(bdLabel,bdTone,()=>showPanel($('board').hidden?'delivery':'board'))); + + const cal=h.calibration; + const calLabel=!bound?'标定待关联':!cal?.known?'标定就绪':cal.completedOps?.length?'标定 '+cal.completedOps.length+'/4': + cal.readyEngines?.length?'标定引擎 '+cal.readyEngines.length+' 个':'标定引擎待查'; + const calTone=!bound?'':cal?.completedOps?.length||cal?.readyEngines?.length?'ok':'warn'; + pills.append(healthPill(calLabel,calTone,()=>openCalibrationPanel('calibration-workbench'))); +} +function openHealthDiagnostics() { + const h=stationHealthData; + const list=element('div','','health-diag-list'); + const rows=h?[ + ['相机服务连接',h.camera?.configStatus==='configured'?'已配置':'待处理', + h.camera?.configStatus==='configured'?'已检测到本机相机连接配置与凭据文件。若查询失败,请在终端执行 node mcp/setup.mjs doctor 核对服务可达性。': + '尚未配置 ~/.config/rdk-camera-workshop/connection.json(或 RDK_CAMERA_WORKSHOP_CONFIG)。请按相机插件 README 运行 node mcp/setup.mjs configure 配置服务与凭据,或先使用顶部「示例图练习」。'], + ['相机实验与实时流',h.camera?.bound?(h.camera.preflightStatus==='passed'?'已通过':'待预检'):'未关联', + h.camera?.bound?'已绑定实验 '+(h.camera.title||h.camera.experimentId.slice(0,8))+(h.camera.sensorModel?' · '+h.camera.sensorModel:'')+'。点击「设备预检」核对板卡在线与两帧推进;若尚未开流,请先在 Studio 对话里让相机插件点亮相机。': + '请点「相机实验 → 关联相机实验」绑定本组实验;若还没有实验,可直接在左侧 Studio 对话里说「用 RDK Camera AI 点亮相机」。'], + ['离线标定引擎',h.calibration?.known?(h.calibration.readyEngines?.length?'已就绪':'待检查'):(h.camera?.bound?'展开核对':'未关联'), + h.calibration?.known?'可用引擎:'+(h.calibration.readyEngines?.length?h.calibration.readyEngines.join(' / '):'无')+' · 已完成 '+(h.calibration.completedOps?.length??0)+'/4 步(BLC/LSC/CCM/AWB)· 本组 RAW '+h.calibration.rawCount+' 张。': + '支持 BLC/LSC/CCM/AWB 四步离线标定(ISPStudio / ispcal-lsc / NumPy)。展开「本组离线标定」后自动探测服务端可用引擎;未连相机也可使用「离线标定示例」四合一演练。'], + ['训练通道',h.training?.runId?'已记录 Run':h.training?.mode==='devmachine'?(h.training.profileStatus==='ready'?'开发机就绪':'待配置'):(h.training?.connected?'已授权':'待授权'), + h.training?.mode==='devmachine'?'本场使用开发机连接卡(RDK_VISION_COURSE_DEVMACHINE_PROFILE)。未配置时向助教报组号,可先做相机和 ISP 步骤。': + '本场使用 RoboGO 异步训练。在「训练与量化」面板点击「连接 RoboGO」授权后即可查询或提交原 Run。'], + ['板端检测与 Studio 联动',h.board?.launcherReady?'就绪':h.studio?.mediaDirConfigured?'Studio 预览已接通':'部分待配', + 'Studio 聊天内嵌出图通道:'+(h.studio?.mediaDirConfigured?'已接通(RDK_VISION_COURSE_STUDIO_MEDIA_DIR)':'未检测到 Studio 媒体目录(外部浏览器模式正常)')+';工作台实时推送:'+(sseConnected?'SSE 实时联动已连接':'自动轮询同步')+'。'], + ]:[['工位状态','读取中','正在获取本机工位配置状态…']]; + for(const [title,tag,desc] of rows) { + const item=element('div','','health-diag-item'); + const head=element('div','','health-diag-head'); + head.append(element('strong',title),element('span',tag,'status-tag'+(tag.includes('已')||tag==='就绪'?' ok':''))); + item.append(head,element('p',desc)); + list.append(item); + } + openDialog('本组工位能力体检',[list],()=>void refreshStationHealth(true),'重新检查'); +} +async function refreshStationHealth(force=false) { + if(!key||practiceReturnUrl||(!force&&document.hidden)) return; + try { + const res=await fetch('/health',{headers:{'X-Workshop-Session':key,...(!force?{'X-Workshop-Poll':'1'}:{})}}); + if(!res.ok) return; + stationHealthData=await res.json(); + renderStationHealth(); + } catch {} +} +function applyPanelQuery(search,roundOverride) { + const params=new URLSearchParams(search||''); + const panel=params.get('panel'); + const round=roundOverride??(panel==='isp'&¶ms.get('round')?Number(params.get('round')):undefined); + const map={capture:'camera-capture',preflight:'camera-preflight',isp:'camera-isp',calibration:'calibration-workbench',board:'board',camera:'camera',training:'training',comparison:'comparison',delivery:'delivery'}; + const targetId=map[panel]??panel; + if(!targetId) return false; + if(targetId==='calibration-workbench') $('calibration-workbench').open=true; + if(targetId==='board'&&$('board').hidden) return false; + showPanel(targetId); + if(targetId==='camera-isp'&&Number.isSafeInteger(round)) { + const card=document.getElementById('isp-gamma-round-'+round)??document.querySelector(`[data-isp-round="${round}"]`); + if(card) card.scrollIntoView({block:'nearest'}); + } + return true; +} +function handleRemoteFocus(focus) { + if(!focus||!Number.isSafeInteger(focus.seq)||focus.seq<=lastFocusSeq) return; + lastFocusSeq=focus.seq; + if(focus.panel==='calibration-workbench') $('calibration-workbench').open=true; + if(focus.panel==='board'&&$('board').hidden) return; + if(focus.panel==='isp-learner') { + showPanel('camera-isp'); + const learner=$('isp-learner'); + if(learner&&!learner.hidden) learner.scrollIntoView({block:'nearest'}); + return; + } + showPanel(focus.panel); + if(focus.panel==='camera-isp'&&Number.isSafeInteger(focus.round)) { + const card=document.getElementById('isp-gamma-round-'+focus.round)??document.querySelector(`[data-isp-round="${focus.round}"]`); + if(card) card.scrollIntoView({block:'nearest'}); + } +} +function publish(patch, clearBlockers=[]) { if (!resume) return; updates++; updateQueue=updateQueue.then(async()=>{ - const reply=await fetch('/session',{method:'POST',headers:{'Content-Type':'application/json','X-Workshop-Session':key}, - body:JSON.stringify({patch,clearBlockers,replace})}); - if (!reply.ok) throw new Error('session_update_failed'); - applySession(await reply.json()); - }).catch(()=>notify('进度暂存在此窗口。同步失败,可下载进度留存。')).finally(()=>{updates--;cameraPanel.syncBinding();}); + applySession(await writeSession(patch,clearBlockers)); + }).catch(()=>notify('进度暂存在此窗口。同步失败,可保存进度 JSON 留存。')).finally(()=>{updates--;cameraPanel.syncBinding();capturePanel.syncBinding();}); } function save(patch,message='已保存') { + if(importingProgress) { + const error=new Error('正在导入进度,请等待操作结果。'); + notify(error.message); + throw error; + } try { const previous=state.resume; const time=minute(); @@ -238,8 +592,8 @@ function save(patch,message='已保存') { state.resume=next.resume; storeState(); const changes={...update}; - for (const field of ['evidence','blockers']) { - if (changes[field]) changes[field]=Object.fromEntries(Object.entries(changes[field]).filter(([k,v])=>previous[field]?.[k]!==v)); + for (const item of ['evidence','blockers']) { + if (changes[item]) changes[item]=Object.fromEntries(Object.entries(changes[item]).filter(([k,v])=>previous[item]?.[k]!==v)); } const clearBlockers=patch.blockers?Object.keys(previous.blockers??{}).filter(k=>!Object.hasOwn(patch.blockers,k)):[]; publish(changes,clearBlockers); @@ -265,43 +619,56 @@ $('dialog-form').onsubmit=event=>{ catch {} }; function editEvidence(title,keys,required=true) { - openDialog(title,keys.map(k=>field(k,labels[k],{value:report.resume.evidence[k],required:required&&k!=='misses_false_positives',placeholder:'回执 ID、文件名、链接或哈希', + openDialog(title,keys.map(k=>field(k,labels[k],{value:report.resume.evidence[k],required:required&&k!=='misses_false_positives', + placeholder:k==='group_and_target_identified'?'例如:第 3 组,想看清右侧暗部二维码和路锥边缘':'填写实际记录、编号、文件名或哈希', ...(detectionResults[k]?{options:[['','请选择实际结果'],...detectionResults[k].map(value=>[value,value])]}:{})})),data=>{ save({evidence:{...report.resume.evidence,...Object.fromEntries(Object.entries(data).filter(([,v])=>v.trim()))}}); }); } function editRun() { const old=report.resume.run??{}; + const source=old.source??(direct?'external':'robogo'); openDialog('记录原训练任务',[ - field('source','任务来源',{value:old.source??'robogo',options:[['robogo','RoboGO 原 Run'],['external','外部训练']]}), - field('id','原 Run ID',{value:report.training.id??'',placeholder:'从 RoboGO 的任务详情复制'}), + ...(!direct?[field('source','任务来源',{value:source,options:[['robogo','RoboGO 原 Run'],['external','外部训练']]})]:[]), + field('id','原任务 ID',{value:report.training.id??'',placeholder:direct?'从本组任务回执或启动日志复制':'从 RoboGO 的任务详情复制'}), field('state','实际状态',{value:old.state??'submitted',options:[['submitted','已受理'],['queued','排队中'],['running','运行中'],['completed','训练完成'],['artifact_ready','INT8 已就绪'],['failed','失败']]}), field('receipt','状态回执',{value:old.receipt,placeholder:'Run 链接或对应记录'}), field('eta','预计完成于开场后第几分钟(可选)',{type:'number',max:1440,value:old.etaMinute,required:false}), - ],data=>save({run:{id:data.id.trim(),source:data.source,state:data.state,receipt:data.receipt.trim(), + ],data=>save({run:{id:data.id.trim(),source:data.source??source,state:data.state,receipt:data.receipt.trim(), ...(minute()!==undefined?{checkedAtMinute:minute()}:{}),...(data.eta!==''?{etaMinute:Number(data.eta)}:{})}})); } -const roboGoErrors={ - robogo_login_required:'RoboGO 授权已失效,请重新连接。原 Run 和已保存状态仍在。', - robogo_profile_required:'本工位没有配置课程训练镜像和算力。可打开 RoboGO 的训练页提交,随后绑定原 Run。', - robogo_profile_invalid:'课程训练配置格式不正确,请助教检查。', - robogo_tool_rejected:'RoboGO 拒绝了本次请求,请核对任务 ID、镜像、算力和本组权限。', - robogo_run_name_required:'无法用原 Run ID 找到任务名称。请在「更新原任务状态」中保存 RoboGO 任务详情链接。', - robogo_run_receipt_invalid:'RoboGO 没有返回可核对的原 Run 状态,保留了上一次记录。', - robogo_submit_unconfirmed:'暂时无法确认提交结果,请先到 RoboGO 任务列表核对,避免重复提交。', - robogo_submit_window:'本组提交窗口是 10:15–10:20。请核对课堂进度。', - robogo_training_step_required:'请先核对并记录课程数据集。', - robogo_plan_expired:'本次提交预检已过期,请重新核对课程任务。', - robogo_plan_changed:'该确认页对应的计划已更新,请重新核对后提交。', - robogo_state_required:'请从 Studio 打开工位,让插件保存提交状态后再提交。', -}; -async function roboGo(action,method='POST',confirmationId) { +function roboGoErrorText(code) { + const map={ + robogo_login_required:'RoboGO 授权已失效,请重新连接。原 Run 和已保存状态仍在。', + robogo_profile_required:'本组没有配置课程训练镜像和算力。可在 RoboGO 核对已有任务并绑定原 Run。', + robogo_other_station_run:'这台电脑的另一实验已有 RoboGO 提交记录。请找回原 Run 并在此绑定。', + robogo_profile_invalid:'课程训练配置格式不正确,请助教检查。', + robogo_tool_rejected:'RoboGO 拒绝了本次请求,请核对任务 ID、镜像、算力和本组权限。', + robogo_run_name_required:'无法用原 Run ID 找到任务名称。请在「更新原任务状态」中保存 RoboGO 任务详情链接。', + robogo_run_receipt_invalid:'RoboGO 没有返回可核对的原 Run 状态,保留了上一次记录。', + robogo_submit_unconfirmed:'暂时无法确认提交结果,请先到 RoboGO 任务列表核对,避免重复提交。', + robogo_submit_window:'本组提交窗口是 '+formatted(plan.deadlines.submitStart)+'–'+formatted(plan.deadlines.submitBy)+'。请核对课堂进度。', + robogo_training_step_required:'请先核对并记录课程数据集。', + robogo_plan_expired:'本次提交预检已过期,请重新核对课程任务。', + robogo_plan_changed:'该确认页对应的计划已更新,请重新核对后提交。', + robogo_state_required:'请从 Studio 打开实验,让插件保存提交状态后再提交。', + robogo_devmachine_classroom:'本场课堂使用开发机直连模式,不在此处发起新的 RoboGO 提交。', + robogo_run_exists:'当前实验已绑定原训练任务,请直接核对或刷新原 Run,避免重复提交。', + robogo_run_required:'当前实验尚未绑定 RoboGO 原 Run,请先登记或提交训练任务。', + robogo_run_id_invalid:'原 Run ID 格式不合法,请从 RoboGO 任务详情页重新复制。', + robogo_oauth_registration_failed:'RoboGO OAuth 客户端注册失败,请检查网络连接后重试。', + run_receipt_mismatch:'RoboGO 返回的 Run ID 与本组已记录任务不一致,已保留原记录,请核对任务详情。', + }; + return map[code]??'暂时无法读取 RoboGO。已保存的状态仍在。'; +} +async function roboGo(action,method='POST',confirmationId,background=false) { const response=await fetch('/robogo/'+action,{method,headers:{'X-Workshop-Session':key, + ...(background?{'X-Workshop-Poll':'1'}:{}), ...(confirmationId?{'X-Workshop-Confirmation':confirmationId}:{})}}); const result=await response.json(); if(!response.ok) { if(result.error==='robogo_login_required') roboGoStatus.connected=false; - throw new Error(roboGoErrors[result.error]??'暂时无法读取 RoboGO。已保存的状态仍在。'); + throw new Error(roboGoErrorText(result.error)); } return result; } @@ -313,20 +680,24 @@ async function connectRoboGo() { catch(error) {popup.close();notify(error.message);} } async function pollRoboGo(force=false) { - if(!key||roboGoBusy||updates) return; + if(!key||roboGoBusy||updates||(!force&&document.hidden)) return; + const run=report?.resume.run; + const activeRun=run?.source==='robogo'&&run.state!=='failed'&&!run.modelSha256; + const minStateGap=activeRun?4000:15000; + if(!force&&Date.now()-lastRoboGoStateCallsessionRevision) applySession(result); - roboGoNote='已自动核对原 Run · '+new Date().toLocaleTimeString('zh-CN'); + roboGoNote=(force?'已手动核对原 Run · ':'已自动核对原 Run · ')+new Date().toLocaleTimeString('zh-CN'); } catch(error) {roboGoNote=error.message;} finally {roboGoBusy=false;renderRoboGo();renderParallelTraining();} } @@ -340,12 +711,17 @@ async function prepareRoboGo() { } catch(error) {notify(error.message);} } async function submitRoboGo(confirmationId) { + let submitted=false; try { const result=await roboGo('submit','POST',confirmationId); if(!updates) applySession(result); roboGoNote='RoboGO 已返回原 Run 回执,等待时可继续 ISP。'; + submitted=true; } catch(error) {roboGoNote=error.message;notify(error.message);} - finally {void pollRoboGo();} + finally { + if(submitted) { renderRoboGo(); renderParallelTraining(); } + else void pollRoboGo(true); + } } function renderRoboGo() { const run=report?.resume.run; @@ -354,11 +730,33 @@ function renderRoboGo() { actions.replaceChildren(); const note=$('robogo-note'); const checks=$('training-readiness'); - note.textContent=ownExternal?'当前工位已使用外部训练回执。':roboGoNote|| + $('training-title').textContent=direct?'本组开发机与模型产物':'训练与量化进度'; + if(direct) { + checks.replaceChildren(); + const ready=developerMachine?.status==='ready'; + note.textContent=run?'继续核对原任务日志与产物。': + ready?'按本组连接卡准备。到 '+formatted(plan.deadlines.submitStart)+' 只启动一次。': + '本组开发机连接卡'+(developerMachine?.status==='invalid'?'格式有误':'尚未配置')+'。请向助教报组号,先做相机和 ISP。'; + if(ready) { + for(const [label,prop] of [['连接方式','connection'],['课程数据','dataset'],['启动命令','startCommand'], + ['训练日志','logPath'],['ONNX/INT8 位置','artifactPath']]) { + const card=element('div','','preflight-check'); + card.append(element('h3',label),element('code',developerMachine[prop],'station-command')); + checks.append(card); + } + } + if(run?.source==='robogo') { + actions.append(roboGoLink(run.receipt)); + if(roboGoStatus.connected) actions.append(button('刷新原 RoboGO Run',()=>pollRoboGo(true))); + else actions.append(button('授权查询原 RoboGO Run',connectRoboGo)); + } + return; + } + note.textContent=ownExternal?'当前实验已使用外部训练回执。':roboGoNote|| (roboGoStatus.connected?'RoboGO 已授权。登记原 Run 后自动查询状态。':'授权后可在工作台查询原 Run。'); checks.replaceChildren(); if(ownExternal) return; - const datasetReady=steps.data.fields.every(field=>report?.resume.evidence[field]); + const datasetReady=steps.data.fields.every(item=>report?.resume.evidence[item]); for(const [label,value,ready] of [ ['课堂数据',datasetReady?'类别、划分与版本已记录':'核对类别顺序、训练与验证划分',datasetReady], ['RoboGO',roboGoStatus.connected?'账号已授权':'等待本组授权',roboGoStatus.connected], @@ -374,6 +772,13 @@ function renderRoboGo() { if(roboGoStatus.connected) actions.append(button('刷新原 Run',()=>pollRoboGo(true))); actions.append(roboGoLink(run.name?'https://robogo.d-robotics.cc/train-job/detail/'+run.name:run.receipt)); } + if(!run&&roboGoStatus.otherStationTraining) { + const previous=roboGoStatus.otherStationTraining; + note.textContent=previous.runId?'另一实验已有原 Run '+previous.runId+'。请登记该任务继续。': + '另一实验的训练提交待确认。请在 RoboGO 找到原任务,再登记 Run。'; + actions.append(button('登记原 Run',editRun,'primary'),roboGoLink(undefined)); + return; + } const elapsed=report?.resume.elapsedMinutes; const insideWindow=elapsed>=plan.deadlines.submitStart&&elapsed - field(k,map[k],{required:false,value:report.resume.blockers[k],placeholder:'填写当前回执;已解决则留空'})), + openDialog('更新异常排查记录',Object.keys(guideSchema.properties.blockers.properties).map(k=> + field(k,map[k],{required:false,value:report.resume.blockers[k],placeholder:'填写当前情况;已解决则留空'})), data=>save({blockers:Object.fromEntries(Object.entries(data).filter(([,v])=>v.trim()))})); } + +function loadPhotosIntoComparison(pair, readback) { + for(const photo of Object.values(photos)) URL.revokeObjectURL(photo.url); + photos=Object.fromEntries(pair.map((file,index)=>[index?'candidate':'original',{file,url:URL.createObjectURL(file)}])); + comparisonReadback=readback&&{label:'候选独立 ISP 回读',hash:readback.hash}; + resetBlindOrder(); + render(); +} + function renderComparison() { - const stage=report.nextStep?.stageId; + const stage=viewedStage??report.nextStep?.stageId; const visible=['gamma_demo','gamma_trial','blind','reproduce'].includes(stage)||Object.keys(photos).length>0; $('comparison').hidden=!visible; if (!visible) return; - const blind=stage==='blind'&&!revealed; + const inBlindStage=stage==='blind'; + const blind=inBlindStage&&!revealed; const slots=blind&&blindOrder?blindOrder:['original','candidate']; - const labels={original:'原始画面',candidate:'调整后的新图'}; + const slotLabels={original:'原始画面',candidate:'调整后的新图'}; const content=$('comparison-images'); const actions=$('comparison-actions'); const ready=Boolean(photos.original&&photos.candidate); content.replaceChildren();actions.replaceChildren(); - $('comparison-state').textContent=blind&&ready?'盲选中':ready?'两张图已添加':'等待现场图片'; - $('comparison-help').textContent=blind&&ready?'先选一张并说明理由,再揭晓前后。': - '从相机工具保存两张现场图。选定同一观察区域,核对实际回读后再判断变化。'; + $('comparison-title').textContent=inBlindStage?'盲选对照 · 先看图再揭晓':'Gamma 实拍对照'; + $('comparison-state').textContent=blind&&ready?'盲选中 · 标签已隐藏':inBlindStage&&revealed?'已揭晓前后':ready?'两张图已就绪':'等待放图'; + $('comparison-state').className='status-tag'+(revealed||ready&&!blind?' ok':''); + $('comparison-help').textContent=blind&&ready?'两张图的顺序已随机打乱并隐藏标签。比较同一观察区域,选出更符合目标的一张并写理由,再揭晓前后。': + inBlindStage&&!ready?'放入调前、调后两张图后,系统会自动打乱顺序并隐藏标签,进入盲选。': + '放入同一场景的调前与调后实拍,可同步放大同一区域核对细节变化。'; + + if(inBlindStage&&!ready) { + const latest=ispPanel.latestBlindPair(); + if(latest) { + actions.append(button('载入第 '+latest.round+' 轮 Gamma 实拍进入盲选',()=>{ + loadPhotosIntoComparison(latest.pair,latest.readback); + notify('已载入第 '+latest.round+' 轮实拍并隐藏标签。'); + },'primary')); + } + } + for (const [index,slot] of slots.entries()) { - const title=blind&&ready?`画面 ${index+1}`:labels[slot]; + const title=blind&&ready?`画面 ${index+1}`:(inBlindStage&&!ready?`待放图片 ${index+1}(${slotLabels[slot]})`:slotLabels[slot]); const figure=element('figure','','comparison-frame'); if (photos[slot]) { const image=element('img');image.src=photos[slot].url;image.alt=title;figure.append(image); - } else figure.append(element('div','等待取图','comparison-placeholder')); + } else figure.append(element('div','点击右侧按钮导入图片','comparison-placeholder')); const caption=element('figcaption',title); if (!blind||!ready) caption.append(button(photos[slot]?'更换':'添加图片',()=>{ photoSlot=slot;$('comparison-file').click(); @@ -443,7 +874,7 @@ function renderComparison() { figure.append(caption);content.append(figure); } if(ready) actions.append(button('放大同一区域',()=>compareFrames(slots.map((slot,index)=>({ - src:photos[slot].url,label:blind?`画面 ${index+1}`:labels[slot], + src:photos[slot].url,label:blind?`画面 ${index+1}`:slotLabels[slot], }))),'ghost')); if(ready&&!blind) { if(comparisonReadback) { @@ -452,14 +883,22 @@ function renderComparison() { actions.append(proof); } else actions.append(element('small','当前图片未关联同次 ISP 回读。可从相机实验或板端回执重新打开配对实拍。','comparison-readback')); } - if (blind&&ready) actions.append(button('记录选择并揭晓',()=>openDialog('这两张图,你更偏好哪张?',[ - field('choice','画面',{options:[['first','画面 1'],['second','画面 2'],['same','差异不明显']]}), - field('reason','你看的区域和理由',{placeholder:'例如暗处轮廓更清楚,亮处细节还在',max:210}), - ],data=>{ - const preference=data.choice==='same'?'差异不明显':labels[blindOrder[data.choice==='first'?0:1]]; - revealed=true; - save({evidence:{...report.resume.evidence,blind_review:preference+' · '+data.reason.trim()}},'已记录盲选。两张图的身份已揭晓。'); - },'保存并揭晓'),'primary')); + // Allow recording blind selection whenever in blind view with both photos ready (never deadlock on earlier missing stages). + if (blind&&ready) { + actions.prepend(button('记录选择并揭晓',()=>openDialog('这两张图,你更偏好哪张?',[ + field('choice','你更偏好的画面',{options:[['first','画面 1'],['second','画面 2'],['same','差异不明显']]}), + field('reason','观察区域和理由',{placeholder:'例如暗处轮廓更清楚,亮处细节还在',max:210}), + ],data=>{ + const preference=data.choice==='same'?'差异不明显':slotLabels[blindOrder[data.choice==='first'?0:1]]; + revealed=true; + save({evidence:{...report.resume.evidence,blind_review:preference+' · '+data.reason.trim()}},'已记录盲选。两张图的身份已揭晓。'); + reportUiEvent('blind_revealed','盲选揭晓:'+preference,'blind'); + },'保存并揭晓'),'primary')); + actions.append(button('重新选图',()=>{ + for(const photo of Object.values(photos)) URL.revokeObjectURL(photo.url); + photos={};blindOrder=undefined;revealed=false;comparisonReadback=undefined;render(); + },'plain')); + } } function resetBlindOrder() { blindOrder=crypto.getRandomValues(new Uint8Array(1))[0]%2?['candidate','original']:['original','candidate']; @@ -502,13 +941,13 @@ function renderDetection() { const visible=['live','preset_deploy'].includes(stage)||(path==='A'||path==='B')&&Boolean(evidence[runtime]); $('detection').hidden=!visible; if (!visible) return; - $('detection-summary').replaceChildren(...[[path+' · '+(own?'本人模型':'预置模型'),'模型来源'], + $('detection-summary').replaceChildren(...[[path+' · '+(own?'本组':'预置'),'模型来源'], [evidence[runtime]??'待回执','推理是否运行'],[evidence[target]??'待观察','目标是否检出']].map(([value,label])=>{ const card=element('div');card.append(element('span',label),element('strong',value));return card; })); const fields=own?['board_model_hash','tuning_in_detection_pipeline','fresh_frames','live_detections']: ['preset_board_model_hash','preset_stream_isp','preset_live_frame','preset_live_detections']; - $('detection-evidence').replaceChildren(...fields.map(key=>element('li',`${labels[key]} · ${evidence[key]??'等待本轮回执'}`))); + $('detection-evidence').replaceChildren(...fields.map(item=>element('li',`${labels[item]} · ${evidence[item]??'等待本轮回执'}`))); if(evidence[target]&&evidence[target]!=='未验证'&&evidence.misses_false_positives) { $('detection-evidence').append(element('li','现场观察 · '+evidence.misses_false_positives)); } @@ -530,12 +969,30 @@ function renderDetection() { }),'primary')]:evidence[runtime]? [button('复核检测结果',()=>editEvidence('本次检测结果',[runtime,target,'misses_false_positives']),'plain')]:[])); } + function renderRoutes() { const area=$('route'); + const banner=$('route-ready-banner'); area.replaceChildren(); - if (!report.routing.eligible && report.nextStep?.stageId!=='route') return; + const modulePreview=viewedStage==='deploy'; + const canChoose=report.routing.eligible||report.nextStep?.stageId==='route'; + const isRouteContext=modulePreview||(!viewedStage&&( + report.nextStep?.stageId==='route'|| + (Boolean(report.routing.selected)&&['deploy','live','preset_deploy','demo','restore','deliver'].includes(report.nextStep?.stageId)) + )); + + // If routing is open by clock, never inject A/B/C cards into unrelated earlier steps; show a dedicated banner instead. + const showBanner=!practiceReturnUrl&&!isRouteContext&&canChoose&&!report.routing.selected; + banner.hidden=!showBanner; + if(showBanner) { + const rec=report.routing.choices.find(item=>item.id===report.routing.recommended); + $('route-ready-title').textContent='已到 '+formatted(report.routing.decisionAt)+' 分流时间'; + $('route-ready-detail').textContent='当前建议路径:'+rec.id+' · '+rec.name+'。可先补完当前步骤,或直接前往选择部署路径。'; + } + if (!isRouteContext) return; + if (!canChoose) area.append(element('p','课堂分流在 '+formatted(report.routing.decisionAt)+' 开放。可以先了解各路径需要的模型和设备。','action-copy')); const chosen=report.routing.choices.find(path=>path.id===report.routing.selected); - const chooser=report.nextStep?.stageId==='route'||!chosen?area:element('details','','proof-details route-review'); + const chooser=report.nextStep?.stageId==='route'||!chosen||modulePreview?area:element('details','','proof-details route-review'); if(chooser!==area) { chooser.open=routeExpanded; chooser.ontoggle=()=>{if(chooser.isConnected) routeExpanded=chooser.open;}; @@ -550,29 +1007,116 @@ function renderRoutes() { save({path:p.id},'已选择 '+p.id+' 路径'); },''); box.className='route-card'+(active?' active':''); - box.disabled=!p.available; + box.disabled=!canChoose||!p.available; box.setAttribute('aria-pressed',String(active)); box.append(element('strong',p.id+' · '+p.name),element('small',p.description), element('small',p.reason)); - if(active||report.routing.recommended===p.id) box.append(element('span',active?'已选择':'当前建议','status-tag')); + if(active) box.append(element('span','已选择','status-tag ok')); + else if(canChoose&&report.routing.recommended===p.id) box.append(element('span','当前建议','status-tag')); + else if(!canChoose||!p.available) box.append(element('span',!canChoose?'未到时间':'条件未齐','status-tag')); group.append(box); } - chooser.append(group,backupButton()); + chooser.append(group); + if(canChoose) chooser.append(backupButton()); } +$('route-ready-open').onclick=()=>selectStage('deploy'); + function backupButton() { return button('登记预置模型或演示',()=>editEvidence('登记备用来源',['preset_model','demo_reference'],false)); } +function selectStage(id) { + viewedStage=id; + reportUiEvent('stage_view',id?'切换到自由查看:'+(stages.get(id)?.topic??id):'回到当前建议步骤',id); + const example=$('calibration-demo'); + if(id==='formats'&&!example.dataset.visited) { + example.open=true; + example.dataset.visited='true'; + } + renderWorkspace(); + renderTimeline(); + renderStep(); + renderComparison(); + preflightPanel.render(); + calibrationPanel.syncBinding(); + renderToolTabs(); + const title=$('step-title'); + if(!wide.matches) { + timelineDetails.open=false; + title.tabIndex=-1; + title.focus({preventScroll:true}); + } + const bounds=title.getBoundingClientRect(); + if(!wide.matches||bounds.top<0||bounds.bottom>innerHeight) title.scrollIntoView({block:'start'}); +} +function viewedStep() { + const id={deploy:'route',wait_run:'check_run'}[viewedStage]??viewedStage; + const {title,ask,tool,actions,fields}=classroomStep(plan,id,state.startClock); + return {stageId:id,title,instruction:ask,tool,actions,entry:stepEntries[id], + requiredEvidence:fields.map(item=>({key:item,label:labels[item]}))}; +} +function renderTimeline() { + const mainList=$('timeline'); + const parallelList=$('timeline-parallel'); + const allVisible=report.stages.filter(stage=>stages.has(stage.id)); + const mainStages=allVisible.filter(stage=>mainStageIds.has(stage.id)).sort((a,b)=>a.start-b.start); + const parallelStages=allVisible.filter(stage=>parallelStageIds.has(stage.id)).sort((a,b)=>a.start-b.start); + const current=allVisible.find(stage=>stage.status==='current'); + const selected=viewedStage??current?.id; + const completedMain=mainStages.filter(stage=>stage.status==='evidence_recorded').length; + $('timeline-progress').textContent=`${completedMain} / ${mainStages.length}`; + $('timeline-bar-fill').style.setProperty('--progress',Math.round(completedMain/Math.max(1,mainStages.length)*100)+'%'); + $('timeline-parallel-wrap').hidden=!parallelStages.length; + + function renderList(listNode, items) { + for(const {id,topic,start,end,status} of items) { + if(!timelineItems.has(id)) { + const row=element('li'); + const control=button('',()=>{ + const recommended=report.stages.some(stage=>stage.id===id&&stage.status==='current'); + selectStage(recommended?undefined:id); + },''); + control.className='stage-button'; + control.setAttribute('aria-controls','classroom-step'); + const marker=element('span','','marker'); + marker.setAttribute('aria-hidden','true'); + const copy=element('span'),time=element('span','','stage-time'); + copy.append(element('span',topic,'stage-name'),time); + control.append(marker,copy); + row.append(control); + listNode.append(row); + timelineItems.set(id,{row,control,time}); + } + const {row,control,time}=timelineItems.get(id); + row.className='state-'+status; + if(id===selected) control.setAttribute('aria-current','location'); + else control.removeAttribute('aria-current'); + time.textContent=formatted(start)+'–'+formatted(end)+ + (status==='current'?' · 当前建议':status==='evidence_recorded'?' · 已完成':status==='blocked'?' · 待处理':''); + } + } + renderList(mainList,mainStages); + renderList(parallelList,parallelStages); +} function renderStep() { - const next=report.nextStep; - $('step-title').textContent=next?.title??(report.completion.lessonEvidenceComplete?'本工位记录已齐备':'当前记录可交接'); - $('step-help').textContent=next?.instruction??'查看成果包和未完成事项,保留本工位的实际记录。'; - $('step-tag').textContent=next?.kind==='resolve_blocker'?'需要处理':next?.kind==='recovery'?'先恢复设备':next?.kind==='select_path'?'等待选择':next?'进行中':'本轮结果'; - $('step-tag').className='status-tag'+(['resolve_blocker','recovery'].includes(next?.kind)?' blocked':''); + const browsing=Boolean(viewedStage); + const next=browsing?viewedStep():report.nextStep; + const localized=next?classroomStep(plan,next.stageId,state.startClock):null; + const displayTitle=browsing?next.title: + (next?.stageId==='await_route'?localized.title:next?.title)??(report.completion.lessonEvidenceComplete?'本实验记录已齐备':'当前记录可交接'); + const displayHelp=browsing?next.instruction: + (next?.stageId==='break'||next?.stageId==='await_route'?localized.ask:next?.instruction)??'查看成果包和未完成事项,保留本组的实际记录。'; + $('step-context').textContent=browsing?'自由查看 · '+stages.get(viewedStage).topic:'当前建议步骤'; + $('step-title').textContent=displayTitle; + $('step-help').textContent=displayHelp; + $('step-tag').hidden=false; + $('step-tag').textContent=browsing?'自由查看':next?.kind==='resolve_blocker'?'需要处理':next?.kind==='recovery'?'先恢复设备':next?.kind==='select_path'?'等待选择':next?'进行中':'本轮结果'; + $('step-tag').className='status-tag'+(!browsing&&['resolve_blocker','recovery'].includes(next?.kind)?' blocked':''); + $('step-back-recommended').hidden=!browsing; $('step-tools').hidden=!next?.tool; $('tool-chain').textContent=next?.tool??''; const slot=$('step-form'), footer=$('step-footer'); slot.replaceChildren(); footer.replaceChildren(); - const instructions=next?.kind==='action'?next.actions??steps[next.stageId]?.actions:undefined; + const instructions=browsing||next?.kind==='action'?next.actions??steps[next.stageId]?.actions:undefined; if (instructions) { const list=element('ol','','action-checklist'); for (const item of instructions) list.append(element('li',item)); @@ -580,55 +1124,105 @@ function renderStep() { } if(next?.requiredEvidence.length) { const ul=element('ul','','review-list'); - for(const row of next.requiredEvidence) ul.append(element('li',row.label)); - slot.append(element('div','完成后留下','route-heading'),ul); + for(const row of next.requiredEvidence) { + const label=direct&&row.key==='run_id'?'本组开发机任务 ID 或已核实的训练记录':row.label; + const recorded=Boolean(report.resume.evidence[row.key]); + ul.append(element('li',label+(recorded?' ✓':''))); + } + slot.append(element('div','本步需要完成','route-heading'),ul); + // Allow direct recording both in suggested mode AND when browsing a stage from the timeline. if(!next.actions&&!['gamma_demo','gamma_trial'].includes(next.stageId)) { - footer.append(button('记录本步回执',()=>editEvidence(next.title,next.requiredEvidence.map(x=>x.key)),next.entry?'ghost':'primary')); + const actionVerb=next.stageId==='intro'?'写下我的观察目标':'填写本步记录'; + footer.append(button(actionVerb,()=>editEvidence(next.title,next.requiredEvidence.map(x=>x.key)),next.entry?'ghost':'primary')); + } + } + if(browsing) { + if(next?.entry&&!$('step-workspace').contains($(next.entry.section))) { + footer.prepend(button(next.entry.label,()=>showPanel(next.entry.section),'plain')); } + if(['train','check_run','break'].includes(next.stageId)) { + footer.append(button(direct?'记录原任务':'记录 RoboGO Run',editRun,'ghost')); + } + if(next && next.stageId!=='route') footer.append(button('复制给 Studio 助手',async()=>{ + try { + await navigator.clipboard.writeText(displayHelp+(next.tool?'\n优先使用实际可用的工具:'+next.tool:'')+'\n请给出本组真实回执。'); + notify('已复制本步指令,可直接粘贴到左侧 Studio 对话发送'); + reportUiEvent('prompt_copied','复制步骤指令:'+next.title,next.stageId); + } catch {notify('无法访问剪贴板,可选中文案复制。');} + },'plain')); + renderRoutes(); + return; + } + if(next?.entry&&!$('step-workspace').contains($(next.entry.section))) { + footer.prepend(button(next.entry.label,()=>showPanel(next.entry.section),'plain')); } - if(next?.entry) footer.prepend(button(next.entry.label,()=>showPanel(next.entry.section),'plain')); if(next?.stageId==='connect'&&report.resume.camera) footer.append(button('定位原始 ISP',()=>showPanel('camera-isp'),'plain')); if(next?.stageId==='baseline'&&next.requiredEvidence.some(x=>x.key==='baseline_raw')) { footer.append(button('登记 RAW 实采受阻',()=>editEvidence('记录 RAW 样例和实采缺口',['baseline_raw_sample']),'plain')); } - if(['data','check_run','train','break'].includes(next?.stageId)) footer.append(roboGoLink(report.training.source==='robogo'?report.training.receipt:undefined), - button('记录 RoboGO Run',editRun,next?.stageId==='check_run'?'primary':'ghost')); + if(['data','check_run','train','break'].includes(next?.stageId)) { + if(!direct) footer.append(roboGoLink(report.training.source==='robogo'?report.training.receipt:undefined)); + if(!direct||next.stageId!=='data') footer.append(button(direct?'记录原任务':'记录 RoboGO Run',editRun,next.stageId==='check_run'?'primary':'ghost')); + } + if(['data','train'].includes(next?.stageId)&&!report.training.id&&!roboGoStatus.uncertainTraining) { + footer.append(button(direct?'入口未就绪,先做 ISP':'跳过本组训练',()=>openDialog('先继续相机与 ISP',[ + element('p','继续相机和 ISP 步骤。到分流时,可使用课程预置模型或记录讲师演示。'), + ],()=>save({blockers:{[direct?'devmachine_unavailable':'training_image_unavailable']:'本组暂缓启动训练,分流时按实际产物选择。'}}, + '已跳过训练,继续当前课堂步骤'),'跳过训练'),'plain')); + } if(next?.stageId==='await_route') footer.append(backupButton()); - if(['resolve_blocker','recovery'].includes(next?.kind)) footer.append(button('更新阻塞回执',editBlockers,'primary')); + if(['resolve_blocker','recovery'].includes(next?.kind)) footer.append(button('更新异常记录',editBlockers,'primary')); if(next && next.stageId!=='route') footer.append(button('复制给 Studio 助手',async()=>{ - try {await navigator.clipboard.writeText(next.instruction+(next.tool?'\n优先使用实际可用的工具:'+next.tool:'')+'\n请给出本工位真实回执。');notify('已复制本步指令');} - catch {notify('无法访问剪贴板,可选中文案复制。');} + try { + await navigator.clipboard.writeText(displayHelp+(next.tool?'\n优先使用实际可用的工具:'+next.tool:'')+'\n请给出本组真实回执。'); + notify('已复制本步指令,可直接粘贴到左侧 Studio 对话发送'); + reportUiEvent('prompt_copied','复制步骤指令:'+next.title,next.stageId); + } catch {notify('无法访问剪贴板,可选中文案复制。');} },'plain')); renderRoutes(); } +$('step-back-recommended').onclick=()=>{ + selectStage(undefined); + $('step-title').tabIndex=-1; + $('step-title').focus({preventScroll:true}); +}; + function renderWorkspace() { - const next=report.nextStep; + const next=viewedStage?viewedStep():report.nextStep; const primary=$('step-workspace'); const tools=$('tool-panels'); const selected=[...(activePanels[next?.stageId]??(next?.entry?[next.entry.section]:next?[]:['delivery']))]; + if(viewedStage==='deploy') selected.push('training','board'); + if(next?.stageId==='formats') selected.unshift('calibration-demo','calibration-workbench','isp-demo'); + if(viewedStage==='break') selected.push('training'); if(next?.stageId==='connect'&&report.resume.camera) selected.push('camera-capture','camera-isp'); if(selected.includes('camera-capture')&&!report.resume.camera) selected.unshift('camera'); + const uniqueSelected=[...new Set(selected)]; for(const panel of toolPanels) { - if(selected.includes(panel.id)) continue; + if(uniqueSelected.includes(panel.id)) { + delete panel.dataset.tabHidden; + continue; + } const following=toolPanels.slice(toolPanels.indexOf(panel)+1).find(item=>item.parentElement===tools); if(panel.parentElement!==tools) tools.insertBefore(panel,following??null); } - for(const [index,id] of selected.entries()) { + for(const [index,id] of uniqueSelected.entries()) { const panel=$(id); - if(primary.children[index]!==panel) primary.insertBefore(panel,primary.children[index]??null); + if(panel&&primary.children[index]!==panel) primary.insertBefore(panel,primary.children[index]??null); } primary.classList.toggle('connect-panels',next?.stageId==='connect'); $('isp-title').textContent=next?.stageId==='connect'?'保存期初 ISP':'ISP 调参 · 两轮 Gamma 与单项练习'; + renderToolTabs(); } function renderParallelTraining() { const training=report?.training; if(!training) return; const elapsed=report.resume.elapsedMinutes; const panel=$('parallel-training'); - panel.hidden=Boolean(practiceReturnUrl)||!training.id&&(elapsed===undefined||elapsed=training.deployAt?'已到分流时间':'部署分流 '+formatted(training.deployAt); $('parallel-training-detail').textContent=[roboGoNote||last,cutoff].filter(Boolean).join(' · '); @@ -645,53 +1239,65 @@ function renderDeliveryChecklist() { const currentProof=Boolean(model&&boardProof?.receipt.modelSha256===model&& (path==='A'||path==='B')&&boardProof.path===path); const demoRecorded=Boolean(path==='C'&&evidence.demo_reference); + const demoWithoutDevice=Boolean(path==='C'&&!evidence.original_snapshot&&evidence.device_unused); + const restored=summary.restored||Boolean(evidence.restoration_and_release)||demoWithoutDevice; const rows=[ - ['两轮 Gamma 实拍与回读',summary.rounds===2,summary.rounds+' / 2 轮已齐备'], + ...(path!=='C'||evidence.original_snapshot||summary.rounds?[['两轮 Gamma 实拍与回读',summary.rounds===2,summary.rounds+' / 2 轮已齐备', + summary.rounds<2?button('去 ISP 面板',()=>showPanel('camera-isp'),'plain'):null]]:[]), [path==='C'?'讲师演示':'板端检测',demoRecorded||Boolean(currentProof&&target&&target!=='未验证'),path==='C'? (demoRecorded?'已记录演示来源':'等待演示来源'):currentProof? - (target&&target!=='未验证'?target:'已有板端回执,待记录目标判定'):'等待本工位板端回执'], - ['期初 ISP 恢复与停流',summary.restored||Boolean(evidence.restoration_and_release), - summary.restored?'独立回读一致,已停止采流':evidence.restoration_and_release?'已登记恢复回执':'等待恢复与停流回执'], + (target&&target!=='未验证'?target:'已有板端回执,待记录目标判定'):'等待本组板端回执',null], + ['期初 ISP 恢复与停流',restored, + summary.restored?'独立回读一致,已停止采流':evidence.restoration_and_release?'已登记恢复回执': + demoWithoutDevice?'已记录本组未启用设备':'等待恢复与停流', + !restored?button('去恢复并停流',()=>showPanel('camera-isp'),'plain'):null], ]; - $('delivery-checklist').replaceChildren(...rows.map(([title,complete,detail])=>{ + $('delivery-checklist').replaceChildren(...rows.map(([title,complete,detail,action])=>{ const row=element('li'); - row.append(element('strong',title),element('span',detail,complete?'evidence-ready':'')); + const right=element('div','','delivery-checklist-right'); + right.append(element('span',detail,complete?'evidence-ready':'')); + if(action) right.append(action); + row.append(element('strong',title),right); return row; })); } +function removeAttachment(index) { + const removed=files[index]; + if(!removed) return; + files=files.filter((_,i)=>i!==index); + for(const [frameId,entry] of attachedCameraEvidence.entries()) { + if(entry.file===removed) attachedCameraEvidence.delete(frameId); + } + render(); + notify('已移除附件:'+removed.name); +} function render() { report=derive(); const current=minute(); lastMinute=current; - $('clock-value').textContent=current===undefined?'未开始':(state.manual?'彩排 · ':'')+formatted(current); - $('start').textContent=state.anchor!==null?'计时中':current===undefined?'开始计时':'继续计时'; - $('start').disabled=state.anchor!==null||state.manual; - const currentStage=report.stages.find(stage=>stage.status==='current'); - $('timeline-summary').textContent=currentStage?'课堂流程 · '+currentStage.topic:'课堂流程'; - const timeline=$('timeline'); - timeline.replaceChildren(); - for(const s of report.stages.filter(s=>stages.has(s.id)&&s.id!=='train'&&s.id!=='wait_run')) { - const li=element('li','','state-'+s.status); - if(s.status==='current') li.setAttribute('aria-current','step'); - const item=element('div'); - item.append(element('div',s.topic,'stage-name'),element('span',formatted(s.start)+' – '+formatted(s.end) - +(s.status==='evidence_recorded'?' · 已留证':s.status==='blocked'?' · 受阻':''),'stage-time')); - li.append(element('span','','marker'),item); timeline.append(li); - } + $('clock-value').textContent=current===undefined?'未开始':(state.manual?'固定 · ':'')+formatted(current); + $('clock-meta').textContent='课堂进度 · '+(state.startClock||plan.referenceStart)+' 开场'; + $('start').textContent=state.anchor!==null?'计时中':state.manual?'恢复计时':current===undefined?'开始计时':'继续计时'; + $('start').disabled=state.anchor!==null; + renderWorkspace(); + renderTimeline(); renderStep(); renderEntryChoice(); - renderWorkspace(); - cameraPanel.render(); - preflightPanel.syncBinding(); - ispPanel.syncBinding(); - capturePanel.syncBinding(); - renderComparison(); - renderDetection(); - boardPanel.syncModel();boardPanel.render(); - $('training-state').textContent=runStatus[report.training.state]??'待检查'; + if(!practiceReturnUrl) { + cameraPanel.render(); + calibrationPanel.syncBinding(); + preflightPanel.syncBinding(); + ispPanel.syncBinding(); + capturePanel.syncBinding(); + renderComparison(); + renderDetection(); + boardPanel.syncModel();boardPanel.render(); + renderToolTabs(); + } + $('training-state').textContent=direct&&report.training.state==='not_submitted'?'待启动':runStatus[report.training.state]??'待检查'; $('training-state').className='status-tag'+(['failed','missed'].includes(report.training.state)?' blocked':report.training.state==='artifact_ready'?' ok':''); $('training-help').textContent=report.training.instruction; - $('run-edit').textContent=report.training.id?'更新原任务状态':'记录已有 Run'; + $('run-edit').textContent=report.training.id?'更新原任务状态':direct?'登记已有任务':'记录已有 Run'; const training=$('training-detail'); training.replaceChildren(); if(report.training.id) training.append(element('span',(report.training.source==='external'?'外部训练':report.training.source==='robogo'?'RoboGO 原 Run':'来源待核对')+' · '+report.training.id,'run-ref'), @@ -703,32 +1309,45 @@ function render() { if(report.training.checkedAtMinute!==undefined) training.append(element('small','最近核对 · '+formatted(report.training.checkedAtMinute),'last-checked')); if(report.training.etaMinute!==undefined) training.append(element('small','预计完成 · '+formatted(report.training.etaMinute),'last-checked')); const preflight=$('training-preflight'); - const preflightMessages={due:'11:30 预检到点,请核对原 Run,记录状态和预计完成时间。可以接着做当前 ISP 步骤。', - checked:'已记录 11:30 预检。继续本工位 ISP 步骤,11:40 开放分流。', - prepare_backup:'本组产物预计赶不上 11:40,或原任务未受理/失败。现在登记预置模型或讲师演示,11:40 再选路。'}; + const cutoff=formatted(plan.deadlines.deployAt); + const checkpoint=formatted(plan.deadlines.runCheckpoint); + const preflightMessages={due:checkpoint+' 预检到点,请核对原任务,记录状态和预计完成时间。可以接着做当前 ISP。', + checked:'已记录 '+checkpoint+' 预查。继续本组 ISP,'+cutoff+' 开放分流。', + prepare_backup:'本组产物预计赶不上 '+cutoff+',或原任务未受理/失败。现在登记预置模型或讲师演示。'}; preflight.hidden=!report.training.preflight; preflight.replaceChildren(); if(!preflight.hidden) { const actions=element('div','','button-row'); - if(report.training.id) actions.append(roboGoLink(report.training.source==='robogo'?report.training.receipt:undefined,'plain'),button('更新原任务状态',editRun)); + if(report.training.id) { + if(!direct||report.training.source==='robogo') actions.append(roboGoLink(report.training.receipt,'plain')); + actions.append(button('更新原任务状态',editRun)); + } if(report.training.preflight==='prepare_backup') actions.append(backupButton()); preflight.append(element('p',preflightMessages[report.training.preflight]),actions); } const {submitStart,submitBy,checkpointAt,deployAt}=report.training; - $('milestones').replaceChildren(...[[formatted(submitStart)+'–'+formatted(submitBy),'分批提交'], + $('milestones').replaceChildren(...[[formatted(submitStart)+'–'+formatted(submitBy),direct?'启动一次':'分批提交'], [formatted(checkpointAt),'助教预检'],[formatted(deployAt),'分流与部署']].map(([time,label])=>{ const entry=element('div');entry.append(element('strong',time),element('span',label));return entry; })); - $('evidence-count').textContent=Object.keys(report.resume.evidence).length+' 项回执'; + $('evidence-count').textContent=Object.keys(report.resume.evidence).length+' 项记录'; $('delivery-help').textContent=report.completion.lessonEvidenceComplete - ?'打开下载的文件,检查本工位记录与实际附件。' - :'可先保存当前记录和实际附件。未完成的环节会写进成果包。'; + ?'所有课堂核心记录已齐备,下载 ZIP 成果包并解压核对即可。' + :'可随时导出当前进度与附件,未完成的环节会在手册中标明。'; const assets=$('attachments'); - assets.replaceChildren(...files.map(file=>element('li',file.name+' · '+Math.round(file.size/1024)+' KB'))); + assets.replaceChildren(...files.map((file,index)=>{ + const item=element('li','','attachment-item'); + item.append(element('span',file.name+' · '+Math.max(1,Math.round(file.size/1024))+' KB'), + button('移除',()=>removeAttachment(index),'plain')); + return item; + })); const review=$('review'); const summary=element('ul','','review-list'); - for(const [k,v] of Object.entries(report.resume.evidence)) summary.append(element('li',labels[k]+' · '+v)); - review.replaceChildren(button('更新阻塞回执',editBlockers),summary); + for(const [k,v] of Object.entries(report.resume.evidence)) { + const label=direct&&k==='run_id'?'本组开发机任务 ID 或已核实的训练记录':labels[k]; + summary.append(element('li',label+' · '+v)); + } + review.replaceChildren(button('更新异常排查记录',editBlockers),summary.childElementCount?summary:element('p','暂未填写课堂记录。','action-copy')); renderRoboGo(); renderParallelTraining(); renderDeliveryChecklist(); @@ -738,36 +1357,91 @@ $('parallel-training-isp').onclick=()=>showPanel(report.resume.camera?'camera-is $('run-edit').onclick=editRun; $('read-training').onclick=readExternalTraining; $('start').onclick=()=>{ - if(state.anchor!==null||state.manual) return; + if(importingProgress||state.anchor!==null) return; const elapsed=minute()??0; state.anchor=Date.now()-elapsed*60000; - save({elapsedMinutes:elapsed},elapsed?'课堂计时已继续':'课堂计时已开始'); + state.manual=false; + save({elapsedMinutes:elapsed},elapsed?'已恢复课堂实时计时':'课堂计时已开始'); +}; +$('clock-config').onclick=()=>{ + const startField=field('startClock','本场实际开场时刻(如上午 09:30、下午 14:00)',{type:'time',value:state.startClock||plan.referenceStart,required:true}); + const stageField=field('stagePreset','按环节快速定位(可选)',{value:'',required:false,options:[ + ['','保持下方分钟数'], + ...plan.schedule.map(s=>[String(s.start),`${formatted(s.start)} · ${s.topic}(第 ${s.start} 分钟)`]), + ]}); + const minuteField=field('minute','开场后经过的分钟(0–180)',{type:'number',max:180,value:minute()??0}); + const modeField=field('mode','计时方式',{value:state.manual?'rehearsal':'live',options:[ + ['live','从当前进度继续实时计时(推荐)'], + ['rehearsal','固定在此刻用于彩排演示(暂停走时)'], + ]}); + stageField.querySelector('select').onchange=event=>{ + if(event.currentTarget.value!=='') minuteField.querySelector('input').value=event.currentTarget.value; + }; + openDialog('校准课堂时间与开场时刻',[startField,stageField,minuteField,modeField],data=>{ + if(importingProgress) return; + const n=Math.max(0,Math.min(180,Number(data.minute))); + const nextStart=/^\d{1,2}:\d{2}$/.test(data.startClock)?data.startClock:plan.referenceStart; + state.startClock=nextStart===plan.referenceStart?null:nextStart; + const run=report.resume.run; + const adjusted=run?.checkedAtMinute!==undefined && run.checkedAtMinute>n + ?Object.fromEntries(Object.entries(run).filter(([prop])=>prop!=='checkedAtMinute')):run; + if(data.mode==='rehearsal') { + state.anchor=null;state.manual=true; + } else { + state.anchor=Date.now()-n*60000;state.manual=false; + } + save({elapsedMinutes:n,...(adjusted?{run:adjusted}:{})},data.mode==='rehearsal'?'已固定到彩排时刻':'已校准课堂时间并继续计时'); + },'应用时间'); }; -$('clock-config').onclick=()=>openDialog('设定彩排进度',[ - field('minute','开场后经过的分钟(0–180)',{type:'number',max:180,value:minute()??0}), -],data=>{ - const n=Number(data.minute); - const run=report.resume.run; - const adjusted=run?.checkedAtMinute!==undefined && run.checkedAtMinute>n - ?Object.fromEntries(Object.entries(run).filter(([key])=>key!=='checkedAtMinute')):run; - state.anchor=null;state.manual=true; - save({elapsedMinutes:n,...(adjusted?{run:adjusted}:{})},'已设定彩排进度'); -}); $('import').onclick=()=>$('progress-file').click(); $('progress-file').onchange=async event=>{ const file=event.target.files[0];event.target.value=''; - if(!file||file.size>1024*1024) {if(file) notify('请选择小于 1 MB 的进度 JSON。');return;} + if(importingProgress||!file) return; + if(file.size>1024*1024) {notify('请选择小于 1 MB 的进度 JSON。');return;} + const control=$('import'); + importingProgress=true; + control.disabled=true; + control.textContent='正在导入…'; + updates++; try { - const input=JSON.parse(await file.text()); - const result=guideCourse(plan,input.resume??input); - state={resume:result.resume,anchor:null,manual:result.resume.elapsedMinutes!==undefined}; + let proposed; + try { + const input=JSON.parse(await file.text()); + proposed=guideCourse(plan,input.resume??input).resume; + } catch { + notify('无法读取进度。请选择工作台导出的进度 JSON 或工具的原始 JSON。'); + return; + } + await updateQueue; + const accepted=await writeSession(proposed,[],true,AbortSignal.timeout(10000)); + if(!accepted.resume||!Number.isInteger(accepted.revision)||accepted.revision{ const candidate=findPhoto(comparison.candidate); if(original&&candidate) meta.gammaComparison={original,candidate,readback:comparison.readback??null}; } + const handbookLabel=key=>direct&&key==='run_id'?'本组开发机任务 ID 或已核实的训练记录':labels[key]; + const gammaRounds=meta.ispSession?.rounds??[]; const notes=['# 视觉 Pipeline 个人手册','','完成路径 · '+(meta.path??'待选择'), - '课程记录 · '+(snapshot.completion.lessonEvidenceComplete?'本工位出具了所需回执':'还有待完成项'), - '实际附件 · '+artifacts.length,'','## Gamma 两轮记录','', - ...(meta.ispSession?.rounds??[]).map(round=>'- 第 '+round.number+' 轮 · '+(round.goal??'旧版记录')+' · '+ - (round.decision?(round.decision.choice==='keep'?'保留调整':'恢复原值')+' · '+round.decision.reason:'待记录取舍')), + '课程记录 · '+(snapshot.completion.lessonEvidenceComplete?'本组出具了所需回执':'还有待完成项'), + '实际附件 · '+artifacts.length, + ...(gammaRounds.length?['','## Gamma 两轮记录','', + ...gammaRounds.map(round=>'- 第 '+round.number+' 轮 · '+(round.goal??'旧版记录')+' · '+ + (round.decision?(round.decision.choice==='keep'?'保留调整':'恢复原值')+' · '+round.decision.reason:'待记录取舍'))]:[]), ...(meta.ispSession?.adjustments?.length?['','## 学员单项 ISP 实验','', ...meta.ispSession.adjustments.map(item=>'- 第 '+item.number+' 次 · '+item.label+' · '+ (item.after?item.beforeValue+' → '+item.afterValue+' '+item.unit:'实拍或回读待补')+' · '+ @@ -828,48 +1505,651 @@ $('export').onclick=async()=>{ '- 曝光时间 · '+(meta.ispSession.exposure.beforeUs/1000).toFixed(3)+' ms → '+(meta.ispSession.exposure.afterUs/1000).toFixed(3)+' ms', '- 模拟增益 · '+meta.ispSession.exposure.gain.toFixed(3)+'×', '- 期初 ISP · '+(meta.ispSession.exposure.restorationReadback?'回读已核对':'待恢复核对')]:[]), - '','## 已有回执','', - ...Object.entries(snapshot.resume.evidence).map(([k,v])=>'- '+labels[k]+':'+v), + '','## 已有记录','', + ...Object.entries(snapshot.resume.evidence).map(([k,v])=>'- '+handbookLabel(k)+':'+v), '','## 待完成与阻塞','',...snapshot.completion.unfinished.map(v=>'- '+v), ...Object.values(snapshot.resume.blockers).map(v=>'- '+v), ...(snapshot.nextStep?['- 下一步:'+snapshot.nextStep.instruction]:[]),'']; download(storedZip([['manifest.json',encode(JSON.stringify(meta,null,2))], ['resume.json',encode(JSON.stringify({resume:snapshot.resume},null,2))], ['handbook.md',encode(notes.join('\n'))],...entries]),practiceReturnUrl?'视觉-Pipeline-练习成果.zip':'视觉-Pipeline-个人成果.zip'); + reportUiEvent('export_downloaded','导出个人成果 ZIP('+artifacts.length+' 个附件)','deliver'); notify('已生成成果包。请打开 ZIP 核对文件。'); } catch {notify('成果包生成失败,请检查附件。');} finally {pending.disabled=false;} }; if(practiceReturnUrl) { document.body.classList.add('is-practice'); - $('import').hidden=true; + $('practice-content').hidden=false; + const gamma=$('practice-gamma'), note=$('practice-observation'); + const scenesWrap=$('practice-scenes'), presetsWrap=$('practice-presets'); + const stage=createCompareStage({element,button,defaultMode:'split',showHistogram:true,showLoupe:true}); + $('practice-stage').replaceChildren(stage.root); + + const fallbackScene={ + id:'chart',title:'课堂合成测试卡 · Gamma 练习',shortTitle:'合成测试卡(默认)', + source:'synthetic_course_chart',badge:'合成测试卡 · 无需相机', + description:'拖动滑块与卷帘对比不同 Gamma(0.55–1.45)对暗部笔画、背景细纹与亮部阶梯的影响;也可以在 Studio 对话里说「把课程示例图的 Gamma 调到 0.80」或「看 24 色卡示例」。', + placeholder:'例如:Gamma 0.80 下左侧暗部笔画更清楚,同时右上高光阶梯依然可分辨。', + recommendedGamma:0.80,captureSummary:'课堂标准合成测试卡(暗部文字 + 灰阶阶梯 + 细纹)', + ext:'png',prefix:'/isp-example/', + }; + let scenes=[fallbackScene]; + let currentScene=fallbackScene; + let sceneButtons=[]; + let practiceMode='lab'; // 'lab' | 'gamma' + + // Live 10-parameter Linear-Light Canvas ISP Lab state (bit-exact with Node MCP engine + bidirectional sync) + const labInputs={ + exposureEv:$('lab-ev'),shadows:$('lab-shadows'),highlights:$('lab-highlights'), + gamma:$('lab-gamma'),brightness:$('lab-bright'),contrast:$('lab-contrast'), + saturation:$('lab-sat'),wbShift:$('lab-wb'),denoise:$('lab-denoise'), + sharpness:$('lab-sharp'), + }; + const labCanvasBefore=document.createElement('canvas'); + const labCanvasAfter=document.createElement('canvas'); + let labSourceData=null; + let labOutputData=null; + let labSceneLoadedId=''; + let labLoadSeq=0; + let suppressUiSync=false; + let uiSyncTimer=null; + + const labParams=()=>normalizeIspParams({ + exposureEv:Number(labInputs.exposureEv.value), + shadows:Number(labInputs.shadows.value), + highlights:Number(labInputs.highlights.value), + gamma:Number(labInputs.gamma.value), + brightness:Number(labInputs.brightness.value), + contrast:Number(labInputs.contrast.value), + saturation:Number(labInputs.saturation.value), + wbShift:Number(labInputs.wbShift.value), + denoise:Number(labInputs.denoise.value), + sharpness:Number(labInputs.sharpness.value), + }); + const setLabParams=raw=>{ + const p=normalizeIspParams(raw??{}); + labInputs.exposureEv.value=String(p.exposureEv); + labInputs.shadows.value=String(p.shadows); + labInputs.highlights.value=String(p.highlights); + labInputs.gamma.value=String(p.gamma); + labInputs.brightness.value=String(p.brightness); + labInputs.contrast.value=String(p.contrast); + labInputs.saturation.value=String(p.saturation); + labInputs.wbShift.value=String(p.wbShift); + labInputs.denoise.value=String(p.denoise); + labInputs.sharpness.value=String(p.sharpness); + }; + const updateUndoButton=canUndo=>{ + const btn=$('practice-lab-undo'); + if(btn) btn.disabled=!canUndo; + }; + const pushPracticeUiState=(extra={})=>{ + if(!key||suppressUiSync) return; + clearTimeout(uiSyncTimer); + uiSyncTimer=setTimeout(async()=>{ + try { + const body={ + source:'ui', + mode:practiceMode, + scene:currentScene.id, + ...(practiceMode==='gamma'?{gamma:Number(gamma.value)}:{params:labParams()}), + ...extra, + }; + const res=await fetch('/practice/sync',{ + method:'POST', + headers:{'Content-Type':'application/json','X-Workshop-Session':key}, + body:JSON.stringify(body), + }); + if(res.ok) { + const data=await res.json(); + if(data?.practice) { + if(Number.isSafeInteger(data.practice.seq)) lastPracticeSeq=Math.max(lastPracticeSeq,data.practice.seq); + updateUndoButton(Boolean(data.practice.canUndo)); + } + } + } catch {} + }, extra.customImageBase64?30:260); + }; + const baseLabPresets=[ + {label:'暗部救回',params:{...DEFAULT_ISP_PARAMS,exposureEv:0.7,shadows:52,highlights:-25,gamma:0.72,brightness:2,contrast:1.10,saturation:1.12,denoise:0.30,sharpness:0.40}}, + {label:'逆光 WDR',params:{...DEFAULT_ISP_PARAMS,exposureEv:-0.2,shadows:68,highlights:-75,gamma:0.80,contrast:1.10,saturation:1.12,denoise:0.20,sharpness:0.35}}, + {label:'去灰通透',params:{...DEFAULT_ISP_PARAMS,exposureEv:-0.1,highlights:-10,gamma:1.20,brightness:-18,contrast:1.55,saturation:1.45,wbShift:-4,denoise:0.10,sharpness:0.50}}, + {label:'冷色纠偏',params:{...DEFAULT_ISP_PARAMS,exposureEv:0.1,gamma:0.95,contrast:1.05,saturation:1.10,wbShift:-36,sharpness:0.25}}, + {label:'细节锐化',params:{...DEFAULT_ISP_PARAMS,gamma:0.95,contrast:1.15,saturation:1.25,denoise:0.10,sharpness:1.10}}, + {label:'过锐副作用',params:{...DEFAULT_ISP_PARAMS,gamma:1.00,contrast:1.20,saturation:1.30,sharpness:2.00}}, + ]; + let activeLabPresets=baseLabPresets; + const syncLabPresets=p=>{ + const wrap=$('practice-lab-presets'); + for(const chip of wrap.querySelectorAll('button')) { + const preset=activeLabPresets[Number(chip.dataset.presetIndex)]; + const norm=preset?normalizeIspParams(preset.params):null; + const active=Boolean(norm)&&Object.entries(norm).every(([k,v])=>Math.abs((p[k]??0)-v)<1e-6); + chip.className='button '+(active?'primary':'ghost'); + chip.setAttribute('aria-pressed',String(active)); + } + }; + const renderLabPresetButtons=()=>{ + activeLabPresets=currentScene.recommendedLab + ? [{label:'本场景推荐调法',params:normalizeIspParams(currentScene.recommendedLab)},...baseLabPresets] + : baseLabPresets; + $('practice-lab-presets').replaceChildren(...activeLabPresets.map((preset,idx)=>{ + const chip=button(preset.label,()=>{ + setLabParams(preset.params); + renderLabFrame(true); + },'ghost'); + chip.dataset.presetIndex=String(idx); + chip.setAttribute('aria-pressed','false'); + return chip; + })); + syncLabPresets(labParams()); + }; + const renderLabReadouts=p=>{ + $('lab-ev-val').textContent=(p.exposureEv>0?'+':'')+p.exposureEv.toFixed(2)+' EV'; + $('lab-shadows-val').textContent=(p.shadows>0?'+':'')+String(p.shadows); + $('lab-highlights-val').textContent=(p.highlights>0?'+':'')+String(p.highlights); + $('lab-gamma-val').textContent=p.gamma.toFixed(2); + $('lab-bright-val').textContent=(p.brightness>0?'+':'')+String(p.brightness); + $('lab-contrast-val').textContent=p.contrast.toFixed(2); + $('lab-sat-val').textContent=p.saturation.toFixed(2); + $('lab-wb-val').textContent=p.wbShift===0?'0 中性':(p.wbShift>0?'+'+p.wbShift+' 暖':String(p.wbShift)+' 冷'); + $('lab-denoise-val').textContent=p.denoise.toFixed(2); + $('lab-sharp-val').textContent=p.sharpness.toFixed(2); + drawToneCurve($('practice-tone-curve'),p); + syncLabPresets(p); + }; + const renderLabFrame=(syncMode=false)=>{ + const p=labParams(); + renderLabReadouts(p); + if(!labSourceData||!labOutputData) return; + const processed=runLinearIsp(labSourceData.data,labSourceData.width,labSourceData.height,p,4); + labOutputData.data.set(processed); + labCanvasAfter.getContext('2d').putImageData(labOutputData,0,0); + const summaryText=formatIspParamSummary(p); + stage.setCanvases({ + beforeCanvas:labCanvasBefore,afterCanvas:labCanvasAfter, + beforeLabel:'基线 · 原始问题底图', + afterLabel:'调优 · '+summaryText, + beforeMeta:currentScene.shortTitle, + afterMeta:'线性 RGB 域 10 参数实时模拟 · 与对话同源', + }); + if(syncMode) pushPracticeUiState(syncMode==='drag'?{coalesce:true}:{}); + }; + const loadLabImageUrl=(src,id,onLoaded)=>{ + const seq=++labLoadSeq; + const img=new Image(); + img.onload=()=>{ + if(seq!==labLoadSeq) return; + const maxW=960; + const scale=img.naturalWidth>maxW?maxW/img.naturalWidth:1; + const w=Math.max(2,Math.round(img.naturalWidth*scale)); + const h=Math.max(2,Math.round(img.naturalHeight*scale)); + labCanvasBefore.width=w;labCanvasBefore.height=h; + labCanvasAfter.width=w;labCanvasAfter.height=h; + const bctx=labCanvasBefore.getContext('2d',{willReadFrequently:true}); + bctx.drawImage(img,0,0,w,h); + labSourceData=bctx.getImageData(0,0,w,h); + labOutputData=bctx.createImageData(w,h); + labSceneLoadedId=id; + if(practiceMode==='lab') renderLabFrame(false); + else if(currentScene.id==='custom') updateGamma(); + if(onLoaded) onLoaded(); + }; + img.src=src; + }; + const loadLabBase=scene=>loadLabImageUrl(scene.prefix+'gamma-20.'+scene.ext,scene.id); + let customObjectUrl=null; + const selectCustomImage=(src,label,goalText='',uploadToBackend=false)=>{ + currentScene={ + id:'custom',title:label||'本地图片 · 10 参数线性 ISP 实验室',shortTitle:label||'本地图片', + source:'local_image_10param_browser_sim',badge:'本地图片 · 双向实时联动', + diagnosis:goalText?'当前调优目标:'+goalText:'已载入本地图片,可点「AI 自动诊断调优」或直接在左侧 Studio 对话里让 AI 帮你调这张图。', + description:'本地图片采用纯 JS 线性 RGB 域 10 参数实时处理,不上传云端、不写板卡。', + recommendedNote:'提示:上传后可在左侧对话直接说「帮我自动优化右边这张图」或「暗部再提一点、别过曝」。', + placeholder:'记录本张本地图片的 ISP 调优目标与最终参数取舍。', + captureSummary:label||'本地导入图片', + ext:'jpg',prefix:'', + }; + $('example-title').textContent=currentScene.title; + $('practice-badge').textContent=currentScene.badge; + $('practice-desc').textContent=currentScene.description; + $('practice-diagnosis').hidden=false; + $('practice-diagnosis').textContent=currentScene.diagnosis; + $('practice-lab-tip').hidden=false; + $('practice-lab-tip').textContent=currentScene.recommendedNote; + $('practice-meta').hidden=false; + $('practice-meta').textContent=currentScene.captureSummary; + for(const btn of sceneButtons) {btn.className='button ghost';btn.setAttribute('aria-pressed','false');} + renderLabPresetButtons(); + setPracticeMode('lab'); + loadLabImageUrl(src,'custom:'+Date.now(),()=>{ + if(uploadToBackend) { + try { + const dataUrl=labCanvasBefore.toDataURL('image/jpeg',0.88); + const b64=dataUrl.split(',')[1]; + if(b64) pushPracticeUiState({customImageBase64:b64,customImageMimeType:'image/jpeg',customImageLabel:label}); + } catch {} + } + }); + }; + + renderLabPresetButtons(); + $('practice-lab-auto').onclick=()=>{ + if(!labSourceData) return; + const solved=solveAutoIsp(labSourceData.data,labSourceData.width,labSourceData.height,'',4); + setLabParams(solved.params); + renderLabFrame(true); + const msg=[ + `AI 自动诊断(${solved.iterations} 轮闭环):${solved.diagnosedDefects.join(';')}`, + ...(solved.refinements.length?[`二轮校验:${solved.refinements.join(';')}`]:[]), + ].join(' · '); + $('practice-diagnosis').hidden=false; + $('practice-diagnosis').textContent=msg; + notify('已完成 2-Pass AI 自动诊断并应用 10 项线性 ISP 参数。'); + }; + $('practice-lab-undo').onclick=async()=>{ + if(!key) return; + try { + const res=await fetch('/practice/undo',{method:'POST',headers:{'X-Workshop-Session':key}}); + if(!res.ok) { notify('当前没有可撤销的上一版参数。'); return; } + const data=await res.json(); + if(data?.practice) void applyRemotePractice(data.practice); + } catch { notify('撤销失败,请稍后重试。'); } + }; + $('practice-lab-reset').onclick=()=>{setLabParams({});renderLabFrame(true);}; + $('practice-upload-btn').onclick=()=>$('practice-upload').click(); + $('practice-upload').onchange=event=>{ + const file=event.target.files?.[0]; + if(!file) return; + if(customObjectUrl) URL.revokeObjectURL(customObjectUrl); + customObjectUrl=URL.createObjectURL(file); + setLabParams({}); + selectCustomImage(customObjectUrl,'本地图片 · '+file.name,'',true); + notify('已载入本地图并同步到工作台,现在可在左侧 Studio 对话直接让 AI 帮你调这张图。'); + event.target.value=''; + }; + $('practice-download-tuned').onclick=()=>{ + if(!labCanvasAfter.width||!labCanvasAfter.height) return; + labCanvasAfter.toBlob(blob=>{ + if(!blob) return; + download(blob,'ISP-调优成图-'+currentScene.id+'.jpg'); + notify('已下载当前 10 参数线性 ISP 调优成图。'); + },'image/jpeg',0.92); + }; + for(const input of Object.values(labInputs)) input.oninput=()=>renderLabFrame('drag'); + + const setPracticeMode=nextMode=>{ + practiceMode=nextMode==='lab'?'lab':'gamma'; + const isLab=practiceMode==='lab'; + $('practice-mode-gamma').className='isp-seg-btn'+(!isLab?' active':''); + $('practice-mode-gamma').setAttribute('aria-pressed',String(!isLab)); + $('practice-mode-lab').className='isp-seg-btn'+(isLab?' active':''); + $('practice-mode-lab').setAttribute('aria-pressed',String(isLab)); + $('practice-gamma-controls').hidden=isLab; + $('practice-lab-controls').hidden=!isLab; + $('practice-mode-tag').textContent=isLab?'前端 10 参数实时像素模拟 · 不写板卡':'单参数 Gamma 实时渲染 · 与对话一致'; + if(isLab) { + if(currentScene.id!=='custom'&&labSceneLoadedId!==currentScene.id) loadLabBase(currentScene); + else renderLabFrame(); + } else { + updateGamma(); + } + }; + $('practice-mode-gamma').onclick=()=>setPracticeMode('gamma'); + $('practice-mode-lab').onclick=()=>setPracticeMode('lab'); + + const draftKeyFor=id=>storageKey+':observation:course-gamma'+(id==='chart'?'':':'+id); + const updateGamma=()=>{ + const value=Number(gamma.value); + const idx=Math.round(value*20); + $('practice-gamma-value').value=value.toFixed(2); + if(currentScene.id==='custom') { + if(labSourceData&&labOutputData) { + const processed=runLinearIsp(labSourceData.data,labSourceData.width,labSourceData.height,normalizeIspParams({gamma:value}),4); + labOutputData.data.set(processed); + labCanvasAfter.getContext('2d').putImageData(labOutputData,0,0); + stage.setCanvases({ + beforeCanvas:labCanvasBefore,afterCanvas:labCanvasAfter, + beforeLabel:'基线 · Gamma 1.00', + afterLabel:'候选 · Gamma '+value.toFixed(2), + beforeMeta:currentScene.shortTitle, + afterMeta:'本地图片前端精确 Gamma 实时模拟 · 不写板卡', + }); + } + } else { + stage.setImages({ + beforeSrc:currentScene.prefix+'gamma-20.'+currentScene.ext, + afterSrc:currentScene.prefix+'gamma-'+idx+'.'+currentScene.ext, + beforeLabel:'基线 · Gamma 1.00', + afterLabel:'候选 · Gamma '+value.toFixed(2), + beforeMeta:currentScene.shortTitle, + afterMeta:currentScene.readbackHash?'回读 '+currentScene.readbackHash.slice(0,12):'离线曲线模拟', + beforeAlt:currentScene.shortTitle+' · 基线', + afterAlt:currentScene.shortTitle+' · Gamma '+value.toFixed(2), + }); + } + for(const chip of presetsWrap.querySelectorAll('button')) { + const active=Math.abs(Number(chip.dataset.gamma)-value)<1e-6; + chip.className='button '+(active?'primary':'ghost'); + chip.setAttribute('aria-pressed',String(active)); + } + }; + const renderPresets=()=>{ + const values=[ + {g:0.70,label:'0.70 提暗'}, + {g:0.85,label:'0.85 柔亮'}, + {g:1.00,label:'1.00 基线'}, + {g:1.20,label:'1.20 压实'}, + {g:1.35,label:'1.35 高反差'}, + ]; + if(currentScene.recommendedGamma&&!values.some(item=>Math.abs(item.g-currentScene.recommendedGamma)<1e-6)) { + values.push({g:currentScene.recommendedGamma,label:currentScene.recommendedGamma.toFixed(2)+' 推荐'}); + values.sort((a,b)=>a.g-b.g); + } + presetsWrap.replaceChildren(...values.map(item=>{ + const btn=button(item.label,()=>{gamma.value=item.g.toFixed(2);updateGamma();},'ghost'); + btn.dataset.gamma=item.g.toFixed(2); + return btn; + })); + }; + const selectScene=(scene,resetToRecommended=false)=>{ + currentScene=scene; + $('example-title').textContent=scene.title; + $('practice-badge').textContent=scene.badge||'无需连接相机'; + $('practice-desc').textContent=scene.description; + const diag=$('practice-diagnosis'); + if(scene.diagnosis) {diag.hidden=false;diag.textContent=scene.diagnosis;} + else {diag.hidden=true;diag.textContent='';} + const tip=$('practice-lab-tip'); + if(scene.recommendedNote) {tip.hidden=false;tip.textContent=scene.recommendedNote;} + else {tip.hidden=true;tip.textContent='';} + note.placeholder=scene.placeholder||fallbackScene.placeholder; + const meta=$('practice-meta'); + if(scene.captureSummary) { + meta.hidden=false; + meta.textContent=scene.captureSummary+(scene.readbackHash?' · 回读 '+scene.readbackHash.slice(0,12):''); + } else { + meta.hidden=true; + } + for(const [i,btn] of sceneButtons.entries()) { + const active=scenes[i]?.id===scene.id; + btn.className='button '+(active?'primary':'ghost'); + btn.setAttribute('aria-pressed',String(active)); + } + if(resetToRecommended&&Number.isFinite(scene.recommendedGamma)) { + gamma.value=scene.recommendedGamma.toFixed(2); + } + if(scene.recommendedLab) { + setLabParams(resetToRecommended?scene.recommendedLab:{}); + } else { + setLabParams({}); + } + renderPresets(); + renderLabPresetButtons(); + try {note.value=localStorage.getItem(draftKeyFor(scene.id))??'';} catch {note.value='';} + loadLabBase(scene); + if(practiceMode==='lab') renderLabFrame(resetToRecommended); + else updateGamma(); + }; + gamma.oninput=updateGamma; + note.oninput=()=>{ + try {localStorage.setItem(draftKeyFor(currentScene.id),note.value);} catch {} + }; + $('practice-export').disabled=false; + $('practice-note').onsubmit=event=>{ + event.preventDefault(); + if(!note.value.trim()) {note.focus();return;} + const scope=stage.getStats(); + const compactStats=s=>s?{meanLuma:Number(s.meanLuma.toFixed(2)),darkPct:Number(s.darkPct.toFixed(2)),clipPct:Number(s.clipPct.toFixed(2)),meanSat:Number(s.meanSat.toFixed(2)),edgeSharpness:Number(s.edgeSharpness.toFixed(2))}:undefined; + const record={ + schema:'rdk.isp-example-observation.v1', + mode:practiceMode, + scene:currentScene.id, + sceneTitle:currentScene.title, + source:practiceMode==='lab'?currentScene.source+'_7param_browser_sim':currentScene.source, + parameter:practiceMode==='lab'?'multi_isp_lab':'gamma', + baseline:1, + gamma:practiceMode==='lab'?labParams().gamma:Number(gamma.value), + ...(practiceMode==='lab'?{labParameters:labParams()}:{}), + ...(scope.before&&scope.after?{histogramSummary:{before:compactStats(scope.before),after:compactStats(scope.after)}}:{}), + observation:note.value.trim(), + ...(currentScene.device?{device:currentScene.device,date:currentScene.date,frameId:currentScene.frameId,sourceImageSha256:currentScene.sourceImageSha256,readbackHash:currentScene.readbackHash}:{}), + exportedAt:new Date().toISOString(), + }; + download(new Blob([JSON.stringify(record,null,2)],{type:'application/json'}),'ISP-示例图观察记录-'+currentScene.id+'.json'); + }; + let lastPracticeSeq=0; + async function applyRemotePractice(payload) { + if(!payload||!Number.isSafeInteger(payload.seq)||payload.seq<=lastPracticeSeq) return; + lastPracticeSeq=payload.seq; + updateUndoButton(Boolean(payload.canUndo)); + if(payload.source==='ui') return; + suppressUiSync=true; + try { + if(payload.hasCustomImage) { + try { + const res=await fetch('/practice/custom-image?seq='+payload.seq,{headers:{'X-Workshop-Session':key}}); + if(res.ok) { + const blob=await res.blob(); + if(customObjectUrl) URL.revokeObjectURL(customObjectUrl); + customObjectUrl=URL.createObjectURL(blob); + setLabParams(payload.params??{}); + selectCustomImage(customObjectUrl,payload.customImageLabel||'AI 同步本地图',payload.goal??'',false); + notify(payload.source==='undo'?'已撤销到上一版本地图 ISP 参数。':'已实时同步 AI 对话调参(本地图片)。'); + return; + } + } catch {} + } + const target=payload.scene?scenes.find(s=>s.id===payload.scene):null; + if(target) selectScene(target,false); + if(payload.mode==='gamma'&&Number.isFinite(payload.gamma)) { + gamma.value=payload.gamma.toFixed(2); + setPracticeMode('gamma'); + updateGamma(); + } else { + setLabParams(payload.params??{}); + setPracticeMode('lab'); + renderLabFrame(false); + } + if(payload.goal) { + $('practice-diagnosis').hidden=false; + $('practice-diagnosis').textContent='AI 对话调优目标:'+payload.goal+(target?.diagnosis?' · '+target.diagnosis:''); + } + notify(payload.source==='undo'?'已撤销到上一版 ISP 参数。':'已实时同步 AI 对话 ISP 参数。'); + } finally { + suppressUiSync=false; + } + } + async function connectPracticeEvents() { + if(!key) return; + let retryMs=1000; + for(;;) { + try { + const response=await fetch('/events',{headers:{'X-Workshop-Session':key}}); + if(!response.ok||!response.body) throw new Error(); + retryMs=1000; + const reader=response.body.getReader(); + const decoder=new TextDecoder(); + let buf=''; + for(;;) { + const {done,value}=await reader.read(); + if(done) break; + buf+=decoder.decode(value,{stream:true}); + let split; + while((split=buf.indexOf('\n\n'))!==-1) { + const block=buf.slice(0,split); + buf=buf.slice(split+2); + let dataLine=''; + for(const line of block.split('\n')) { + if(line.startsWith('data:')) dataLine+=(dataLine?'\n':'')+line.slice(5).trim(); + } + if(!dataLine) continue; + try { + const evt=JSON.parse(dataLine); + if(evt.practice) void applyRemotePractice(evt.practice); + } catch {} + } + } + } catch {} + await new Promise(r=>setTimeout(r,retryMs)); + retryMs=Math.min(retryMs*2,10000); + } + } + renderLabReadouts(labParams()); + selectScene(fallbackScene,false); + fetch('/isp-example/scenes.json').then(r=>r.ok?r.json():null).then(data=>{ + if(!Array.isArray(data?.scenes)||!data.scenes.length) return; + scenes=data.scenes; + sceneButtons=scenes.map(scene=>button(scene.shortTitle,()=>selectScene(scene,true),'ghost')); + scenesWrap.replaceChildren(...sceneButtons); + if(initialPractice) void applyRemotePractice(initialPractice); + else selectScene(scenes[0],true); + void connectPracticeEvents(); + }).catch(()=>{}); } -render(); +setupCalibrationExercise({$,element,openWorkbench:()=>openCalibrationPanel('calibration-workbench')}); void renderIspDemo({$,element,button}); -cameraPanel.syncBinding(); +render(); + if(!practiceReturnUrl) { - void pollRoboGo(); - setInterval(()=>void pollRoboGo(),4000); -} -setInterval(()=>{ - if(minute()!==lastMinute&&!$('dialog').open) { - if(state.anchor!==null) save({elapsedMinutes:minute()},null); - else render(); + $('station-health-diag').onclick=openHealthDiagnostics; + cameraPanel.syncBinding(); + void refreshStationHealth(true); + if(!direct||state.resume.run?.source==='robogo') { + void pollRoboGo(true); + setInterval(()=>void pollRoboGo(),4000); } -},5000); -if(resume) setInterval(async()=>{ - if(updates) return; - try { - const response=await fetch('/session',{headers:{'X-Workshop-Session':key}}); - if(!response.ok) return; - const result=await response.json(); - if(!updates&&result.revision>sessionRevision) {applySession(result);cameraPanel.syncBinding();} - } catch {} -},2000); -setInterval(cameraPanel.poll,3500); -setInterval(capturePanel.poll,1800); -setInterval(preflightPanel.poll,1800); -setInterval(ispPanel.poll,1800); -const initialPanel=new URLSearchParams(location.search).get('panel'); -if(['capture','preflight','isp'].includes(initialPanel)) showPanel('camera-'+initialPanel); -setInterval(boardPanel.poll,900); + setInterval(()=>{ + if(!importingProgress&&minute()!==lastMinute&&!$('dialog').open) { + if(state.anchor!==null) save({elapsedMinutes:minute()},null); + else render(); + } + },5000); + async function syncRemoteSession(force=false) { + if(updates||(!force&&document.hidden)) return; + try { + const response=await fetch('/session',{headers:{'X-Workshop-Session':key,'X-Workshop-Poll':'1'}}); + if(!response.ok) return; + const result=await response.json(); + if(typeof result.stationActive==='boolean'&&result.stationActive!==stationActive) { + stationActive=result.stationActive; + renderEntryChoice(); + } + if(!updates&&result.revision>sessionRevision) { + applySession(result); + cameraPanel.syncBinding(); + void refreshStationHealth(); + } + if(result.focus) handleRemoteFocus(result.focus); + } catch {} + } + let sseController=null, sseRetryMs=1000, sseRetryTimer=null; + async function connectLiveEvents() { + if(document.hidden||sseController) return; + const controller=new AbortController(); + sseController=controller; + try { + const response=await fetch('/events',{headers:{'X-Workshop-Session':key},signal:controller.signal}); + if(!response.ok||!response.body) throw new Error('events_unavailable'); + updateSyncBadge(true); + sseRetryMs=1000; + const reader=response.body.getReader(); + const decoder=new TextDecoder(); + let buffer=''; + for(;;) { + const {done,value}=await reader.read(); + if(done) break; + buffer+=decoder.decode(value,{stream:true}); + let split; + while((split=buffer.indexOf('\n\n'))!==-1) { + const block=buffer.slice(0,split); + buffer=buffer.slice(split+2); + let eventName='', dataLine=''; + for(const line of block.split('\n')) { + if(line.startsWith('event:')) eventName=line.slice(6).trim(); + else if(line.startsWith('data:')) dataLine+=(dataLine?'\n':'')+line.slice(5).trim(); + } + if(!dataLine) continue; + let payload; + try { payload=JSON.parse(dataLine); } catch { continue; } + if(eventName==='ready') { + if(Number.isSafeInteger(payload.focusSeq)) lastFocusSeq=Math.max(lastFocusSeq,payload.focusSeq); + if(payload.focus&&Number.isSafeInteger(payload.focus.seq)) lastFocusSeq=Math.max(lastFocusSeq,payload.focus.seq); + continue; + } + if(payload.focus) handleRemoteFocus(payload.focus); + const topic=payload.topic; + if(topic==='session') void syncRemoteSession(true); + else if(topic==='robogo') { void pollRoboGo(true); void refreshStationHealth(true); } + else if(topic==='preflight') { void preflightPanel.poll(); void refreshStationHealth(true); } + else if(topic==='capture') { void capturePanel.poll(); void refreshStationHealth(true); } + else if(topic==='isp') { void ispPanel.poll(); void refreshStationHealth(true); } + else if(topic==='calibration') { void calibrationPanel.refreshRecords(); void refreshStationHealth(true); } + else if(topic==='board') { void boardPanel.poll(); void refreshStationHealth(true); } + else if(topic==='practice') { notify('AI 对话已更新示例图 ISP 参数,点右上角「示例图练习」可继续拖拽微调。'); } + } + } + } catch { + // Fall back to bounded polling and reconnect with backoff. + } finally { + if(sseController===controller) sseController=null; + updateSyncBadge(false); + if(!document.hidden) { + clearTimeout(sseRetryTimer); + sseRetryTimer=setTimeout(()=>void connectLiveEvents(),sseRetryMs); + sseRetryMs=Math.min(sseRetryMs*2,10000); + } + } + } + void connectLiveEvents(); + window.addEventListener('rdk-studio-navigate',event=>{ + const detail=event?.detail??{}; + if(typeof detail.href==='string') { + try { + const parsed=new URL(detail.href); + if(parsed.origin===location.origin&&parsed.hash===location.hash) { + history.replaceState(null,'',parsed.pathname+parsed.search+parsed.hash); + applyPanelQuery(parsed.search); + void syncRemoteSession(true); + return; + } + } catch {} + } + if(typeof detail.search==='string') applyPanelQuery(detail.search); + }); + // Fallback polling runs at relaxed cadence while SSE is connected, and normal cadence if disconnected. + let pollTick=0; + setInterval(()=>{ + if(document.hidden) return; + pollTick++; + const slow=sseConnected; + if(resume&&(pollTick%7===0||!slow)) void syncRemoteSession(); + if(pollTick%6===0||(!slow&&pollTick%2===0)) void cameraPanel.poll(); + if(pollTick%6===0||!slow) { + void capturePanel.poll(); + void preflightPanel.poll(); + void ispPanel.poll(); + } + if(pollTick%8===0) void refreshStationHealth(); + },2000); + setInterval(()=>{ + if(document.hidden) return; + if(!$('board').hidden||!sseConnected) void boardPanel.poll(); + },700); + document.addEventListener('visibilitychange',()=>{ + if(document.hidden) { + if(sseController) { sseController.abort(); sseController=null; } + clearTimeout(sseRetryTimer); + updateSyncBadge(false); + } else { + void connectLiveEvents(); + void syncRemoteSession(true); + void preflightPanel.poll(); + void refreshStationHealth(true); + if(!direct||state.resume.run?.source==='robogo') void pollRoboGo(); + } + }); + if(initialPanel) applyPanelQuery(location.search); +} +} diff --git a/plugins/rdk-camera-workshop/web/board-panel.mjs b/plugins/rdk-camera-workshop/web/board-panel.mjs index 4529a05..310b4a2 100644 --- a/plugins/rdk-camera-workshop/web/board-panel.mjs +++ b/plugins/rdk-camera-workshop/web/board-panel.mjs @@ -2,9 +2,26 @@ import {normalizedModelHash,presetModelHash} from '/guide.mjs'; const phases={before:'调前',after:'调后',live:'本轮'}; const liveWindowMs=3500; -const errors={board_archive_unconfigured:'请用 Studio 在本工位运行课程检测入口并配置其结果目录。', +const errors={board_launcher_unconfigured:'本组还没连接一键检测入口。请助教配置检测启动器,或由助教运行课程检测后读取回执。', + board_launcher_invalid:'本板端检测启动配置无法读取。请助教检查启动配置。', + board_launcher_model_unbound:'检测启动器尚未绑定这条路径的模型。请助教核对模型 SHA-256。', + board_launcher_camera_unbound:'当前相机和板端检测配置不一致。请助教核对设备关联。', + board_launcher_route_unready:'请先补齐所选路径的模型回执,并通过本组设备连接检查。', + board_launcher_camera_busy:'相机正在采集或有 ISP 修改待处理。请先完成当前操作并恢复原始 ISP。', + board_launcher_running:'检测已启动。请等待本轮结束。', + board_launcher_locked:'设备正被另一轮检测占用,或上次任务没有完成清理。请助教检查板端采流状态。', + board_launcher_start_failed:'检测启动失败。请助教核对板卡连接和本机启动配置。', + board_launcher_run_failed:'板端检测未完成。请助教检查本轮 runner.log。', + board_launcher_timeout:'等待板端检测超时。请助教检查板卡和 runner.log。', + board_launcher_receipt_incomplete:'检测未形成完整回执。请助教检查实拍、ISP 回读和停流结果。', + board_launcher_isp_unavailable:'当前实验无法运行已核对的 Gamma。请确认本轮已完成回读并保存取舍。', + board_launcher_comparison_unavailable:'请先完成单项 Gamma、核对回读并恢复原始配置。板端检测启动器须支持双段对照。', + board_launcher_comparison_scene_unconfirmed:'请先固定相机、照明和场景。', + board_comparison_unavailable:'本轮缺少两段完整的实拍或原始配置恢复回执。', + board_comparison_region_invalid:'请选择课程类别,再圈出一个完整目标所在的区域。', + board_archive_unconfigured:'没有可读取的板端结果目录。', board_receipt_pending:'板端尚未写出回执。请确认本组任务已启动,再刷新。', - board_model_mismatch:'板上模型与本工位训练产物的哈希不一致,请核对实际 .bin。', + board_model_mismatch:'板端模型与本组所选模型的 SHA-256 不一致,请核对当前路径使用的 .bin 文件。', board_receipt_changed:'板端已写出新的运行回执。请刷新板端结果后再对照或留证。', board_asset_integrity_failed:'文件字节或配置回读和板端回执不一致,请检查原始制品。', board_asset_missing:'这份证据还没有归档,请刷新或核对板端结果。'}; @@ -21,12 +38,43 @@ export function createBoardPanel({key,$,element,button,notify,getReport,save,att let lastAdvance; let watchRequested=false; let pending=false; - const refreshButton=button('读取板端检测',()=>refresh(),'primary'); + let staticUrl; + let launchState,launchIssue='',launching=false,launchCheck=0,checkingLaunch=false; + let advances=[]; + let buffered=[],receivedSha; + let scored; + const ispMode=document.createElement('select'); + const currentIsp=element('option','用当前 ISP');currentIsp.value='current'; + const approvedIsp=element('option','用已核对的 Gamma,检测后恢复');approvedIsp.value='approved'; + const comparisonIsp=element('option','对照当前 ISP 与已核对的 Gamma');comparisonIsp.value='comparison'; + ispMode.setAttribute('aria-label','检测使用的 ISP 配置'); + ispMode.append(currentIsp,approvedIsp,comparisonIsp); + ispMode.onchange=()=>{fixedScene.checked=false;render();}; + const sceneControl=element('label','','board-fixed-scene'); + const fixedScene=document.createElement('input'); + fixedScene.type='checkbox'; + fixedScene.onchange=render; + sceneControl.append(fixedScene,element('span','已固定相机、照明和场景,采集期间保持不动。')); + const launchButton=button('加载模型并开始检测',launch,'primary'); + const refreshButton=button('读取既有板端回执',()=>refresh(),'ghost'); const gammaButton=button('看 Gamma 实拍前后',compareGamma,'ghost'); + const staticButton=button('查看静态样张结果',toggleStatic,'ghost'); const adoptButton=button('采用回执并留证',saveEvidence,'ghost'); - $('board-actions').append(refreshButton,gammaButton,adoptButton); - async function fetchResult(part,timeout=15000) { - const response=await fetch('/board/'+part,{headers:{'X-Workshop-Session':key},signal:AbortSignal.timeout(timeout)}); + const staticFigure=element('figure','','camera-archive-preview board-preview'); + const staticImage=element('img'); + staticImage.alt='课程静态样张的 BPU 检测结果'; + staticFigure.append(staticImage,element('figcaption','课程静态样张 · 用于核对 BPU 与标签')); + staticFigure.hidden=true; + const comparisonRoot=element('section','','board-comparison'); + comparisonRoot.hidden=true; + let comparisonReceipt,comparisonUrls=[]; + $('board-actions').append(ispMode,sceneControl,launchButton,refreshButton,staticButton,gammaButton,adoptButton); + $('board-evidence').before(staticFigure,comparisonRoot); + async function fetchResult(part,timeout=15000,method='GET',mode,body,background=false) { + const headers={'X-Workshop-Session':key,...(background?{'X-Workshop-Poll':'1'}:{}),...(mode?{'X-Workshop-ISP-Mode':mode}:{}), + ...(mode==='comparison'&&fixedScene.checked?{'X-Workshop-Fixed-Scene':'1'}:{}), + ...(body?{'Content-Type':'application/json'}:{})}; + const response=await fetch('/board/'+part,{method,headers,body:body&&JSON.stringify(body),signal:AbortSignal.timeout(timeout)}); if(!response.ok) { const {error}=await response.json().catch(()=>({})); throw new Error(errors[error]??'板端回执读取失败,请核对结果文件。'); @@ -49,11 +97,174 @@ export function createBoardPanel({key,$,element,button,notify,getReport,save,att const path=course.routing.selected; if(lastModel===model&&lastPath===path) return; lastModel=model;lastPath=path;generation++;report=undefined;issue='';reading=false; + launchState=undefined;launchIssue='';launchCheck=0; + ispMode.value='current'; watchRequested=false;pending=false;clearPreview(); } function clearPreview() { if(preview) URL.revokeObjectURL(preview.url); - preview=undefined;lastAdvance=undefined; + if(staticUrl) URL.revokeObjectURL(staticUrl); + staticUrl=undefined;staticFigure.hidden=true;staticImage.removeAttribute('src'); + staticButton.textContent='查看静态样张结果'; + preview=undefined;lastAdvance=undefined;advances=[]; + buffered=[];receivedSha=undefined; + clearComparison(); + } + function clearComparison() { + for(const url of comparisonUrls) URL.revokeObjectURL(url); + comparisonUrls=[]; + comparisonReceipt=undefined;scored=undefined; + comparisonRoot.hidden=true; + comparisonRoot.replaceChildren(); + } + function renderComparison(recorded) { + if(!recorded?.comparison) return; + if(comparisonReceipt===recorded.receiptSha256) return; + clearComparison(); + comparisonReceipt=recorded.receiptSha256; + comparisonRoot.hidden=false; + const initialHint='核对同一目标在两张实拍里的位置。在调前图点目标框的两个对角,再选择类别计算。'; + const hint=element('p',initialHint); + const grid=element('div','','board-comparison-images'); + const result=element('div','','board-comparison-result'); + result.setAttribute('aria-live','polite'); + comparisonRoot.append(element('h3','同一场景 · Gamma 检测对照'),hint,grid); + const markers=[]; + const values=['左','上','右','下'].map(label=>{ + const field=element('label',label+' (%)'); + const input=element('input'); + input.type='number';input.min='0';input.max='100';input.step='0.1'; + field.append(input); + return {field,input}; + }); + let first; + const region=()=>values.map(({input})=>input.value===''?NaN:Number(input.value)/100); + function updateRegion() { + scored=undefined; + result.replaceChildren(); + const [left,top,right,bottom]=region(); + hint.textContent=[left,top,right,bottom].every(Number.isFinite)&&left=right||top>=bottom; + if(!marker.hidden) { + marker.style.setProperty('--roi-left',left*100+'%'); + marker.style.setProperty('--roi-top',top*100+'%'); + marker.style.setProperty('--roi-width',(right-left)*100+'%'); + marker.style.setProperty('--roi-height',(bottom-top)*100+'%'); + } + } + } + for(const {input} of values) input.oninput=updateRegion; + for(const [phase,title] of [['before','当前 ISP'],['after','已核对的 Gamma']]) { + const figure=element('figure'); + const surface=element('div','','board-comparison-frame'); + const photo=element('img'); + photo.alt=title+'的 X5 实拍与检测框'; + const marker=element('div','','board-roi'); + marker.hidden=true; + markers.push(marker); + const state=element('p','正在读取实拍…','board-image-status'); + surface.append(photo,marker,state); + figure.append(surface,element('figcaption',title)); + grid.append(figure); + if(phase==='before') { + surface.classList.add('select-region'); + surface.onclick=event=>{ + if(!photo.complete||!photo.naturalWidth) return; + const rect=photo.getBoundingClientRect(); + const limit=value=>Math.max(0,Math.min(100,value)); + const point=[limit(100*(event.clientX-rect.left)/rect.width),limit(100*(event.clientY-rect.top)/rect.height)]; + if(!first) { + first=point; + hint.textContent='已选第一个角,点目标框的另一个对角。'; + return; + } + const bounds=[Math.min(first[0],point[0]),Math.min(first[1],point[1]), + Math.max(first[0],point[0]),Math.max(first[1],point[1])]; + values.forEach(({input},i)=>{input.value=bounds[i].toFixed(1);}); + first=undefined;updateRegion(); + }; + } + void fetchArtifact(recorded,recorded.comparison[phase].file).then(response=>response.blob()).then(blob=>{ + if(comparisonReceipt!==recorded.receiptSha256) return; + const url=URL.createObjectURL(blob); + comparisonUrls.push(url); + photo.onload=()=>{state.hidden=true;}; + photo.onerror=()=>{state.textContent='实拍解码失败,请重新读取板端回执。';}; + photo.src=url; + }).catch(error=>{state.textContent=error.message;}); + } + const label=document.createElement('select'); + label.setAttribute('aria-label','目标课程类别'); + label.append(...[['','选择课程类别'],['park','停车标识 park'],['qrcode','二维码 qrcode'],['obstacle','路锥等障碍物 obstacle']].map(([value,title])=>{ + const option=element('option',title);option.value=value;return option; + })); + label.onchange=updateRegion; + const form=element('div','','board-comparison-tools'); + const coordinates=element('details','','proof-details'); + const fields=element('div','','board-coordinates'); + fields.append(...values.map(({field})=>field)); + coordinates.append(element('summary','键盘输入目标框坐标'),fields); + async function evaluateTarget(targetAbsent) { + scoreButton.disabled=absentButton.disabled=true; + try { + if(targetAbsent) { + first=undefined; + values.forEach(({input})=>{input.value='';}); + label.value=''; + updateRegion(); + } + const inputs={receiptSha256:recorded.receiptSha256,...(targetAbsent?{targetAbsent}:{label:label.value,region:region()})}; + const next=await(await fetchResult('score',10000,'POST',undefined,inputs)).json(); + if(comparisonReceipt!==recorded.receiptSha256||(targetAbsent?label.value||region().some(Number.isFinite): + inputs.label!==label.value||!inputs.region.every((value,index)=>value===region()[index]))) return; + scored=next; + if(targetAbsent) hint.textContent='两张图用于核对取流、Gamma 和背景框。'; + const cards=element('div','','board-comparison-images'); + for(const [phase,title] of [['before','当前 ISP'],['after','Gamma']]) { + const data=next.results[phase]; + const card=element('div','','board-comparison-card'); + card.append(element('strong',title), + element('b',targetAbsent?`${data.frames} 帧 · ${data.unmatchedBoxes} 个框`:`${data.matchedFrames}/${data.frames} 帧检出`), + element('span',targetAbsent?'课程目标待测':`最长连续 ${data.longestMatch} 帧 · ${data.unmatchedBoxes} 个不匹配框`)); + cards.append(card); + } + result.replaceChildren(cards,element('p',(targetAbsent?'目标检出留待课程实物验收。': + '框须匹配所选类别,且与所圈区域重叠达到 IoU 0.30。不匹配框需结合画面复核。')+ + '原始 ISP 已恢复,采用回执时会一并保存本次对照。')); + } catch(error) {result.textContent=error.message;} + finally {scoreButton.disabled=absentButton.disabled=false;} + } + const scoreButton=button('计算检出对照',()=>evaluateTarget(false),'primary'); + const absentButton=button('未摆放课程目标',()=>evaluateTarget(true),'ghost'); + form.append(label,scoreButton,absentButton); + comparisonRoot.append(form,coordinates,result); + } + async function checkLaunch() { + if(checkingLaunch||launching||Date.now()-launchCheck<1400) return; + launchCheck=Date.now();checkingLaunch=true; + const model=lastModel,path=lastPath,checkedAt=launchCheck; + try { + const next=await(await fetchResult('launch',2500,'GET',undefined,undefined,true)).json(); + if(model===lastModel&&path===lastPath&&checkedAt===launchCheck&&!launching) {launchState=next;launchIssue='';} + } catch(error) { + if(model===lastModel&&path===lastPath&&checkedAt===launchCheck&&!launching) launchIssue=error.name==='TimeoutError'?'板端检测状态读取超时,正在重试。':error.message; + } finally {checkingLaunch=false;render();} + } + async function launch() { + if(launching||!launchState?.ready) return; + launching=true;launchIssue='';render(); + const model=lastModel,path=lastPath; + try { + const next=await(await fetchResult('launch',5000,'POST',ispMode.value)).json(); + if(model!==lastModel||path!==lastPath) return; + launchState=next;generation++;reading=false;report=undefined; + watchRequested=true;issue='';pending=false;clearPreview(); + void refresh(true); + } catch(error) { + launchIssue=error.name==='TimeoutError'?'正在核对启动状态。请等状态刷新后再操作。':error.message; + } finally {launching=false;launchCheck=0;render();} } async function refresh(automatic=false) { if(reading) return; @@ -61,26 +272,25 @@ export function createBoardPanel({key,$,element,button,notify,getReport,save,att reading=true; if(!automatic) {watchRequested=true;issue='';render();} try { - const known=preview?.frame.sha256; - const {view:next,imageBase64,previewPending}=await(await fetchResult('preview'+(known?'?known='+known:''),2800)).json(); + const known=receivedSha; + const {view:next,imageBase64,previewPending,frames}=await(await fetchResult('preview?batch=1'+(known?'&known='+known:''),2800,'GET',undefined,undefined,automatic)).json(); if(current!==generation) return; if(next.modelSha256!==lastModel) throw new Error(errors.board_model_mismatch); - if(report&&next.runId!==report.runId&&imageBase64===undefined) clearPreview(); + if(report&&next.runId!==report.runId) clearPreview(); const frame=next.latestDetection; const sameRun=Boolean(preview&&next.runId&&preview.runId===next.runId); if(sameRun&&frame&&BigInt(frame.sdkTimestampNs)BigInt(preview.frame.sdkTimestampNs); - if(imageBase64) { - const bytes=Uint8Array.from(atob(imageBase64),value=>value.charCodeAt(0)); - const url=URL.createObjectURL(new Blob([bytes],{type:'image/jpeg'})); - if(preview) URL.revokeObjectURL(preview.url); - preview={url,frame,runId:next.runId}; - } else { - preview.frame=frame;preview.runId=next.runId; - } - if(advances) lastAdvance=Date.now(); - else if(!sameRun) lastAdvance=undefined; + if(frames?.length) { + buffered=[...buffered,...frames].slice(-4); + receivedSha=frames.at(-1).frame.sha256; + } else if(frame&&(imageBase64||known===frame.sha256&&preview?.frame.sha256===frame.sha256)) { + if(next.status!=='started') buffered=[]; + receivedSha=frame.sha256; + displayFrame(frame,imageBase64,next.runId); + } + if(next.status!=='started'&&buffered.length) { + const latest=buffered.at(-1);buffered=[]; + displayFrame(latest.frame,latest.imageBase64,next.runId); } report=next;pending=Boolean(previewPending);issue=''; } catch(error) { @@ -88,6 +298,34 @@ export function createBoardPanel({key,$,element,button,notify,getReport,save,att } finally {if(current===generation) {reading=false;render();}} } + function displayFrame(frame,imageBase64,runId) { + const sameRun=Boolean(preview&&runId&&preview.runId===runId); + const advanced=sameRun&&BigInt(frame.sdkTimestampNs)>BigInt(preview.frame.sdkTimestampNs); + if(imageBase64) { + const bytes=Uint8Array.from(atob(imageBase64),value=>value.charCodeAt(0)); + const url=URL.createObjectURL(new Blob([bytes],{type:'image/jpeg'})); + if(preview) URL.revokeObjectURL(preview.url); + preview={url,frame,runId}; + } else if(preview) {preview.frame=frame;preview.runId=runId;} + if(advanced) { + lastAdvance=Date.now(); + advances=[...advances.filter(value=>value>=lastAdvance-5000),lastAdvance]; + } else if(!sameRun) {lastAdvance=undefined;} + } + async function toggleStatic() { + if(!staticFigure.hidden) {staticFigure.hidden=true;staticButton.textContent='查看静态样张结果';return;} + const current=report; + staticButton.disabled=true; + try { + if(!staticUrl) { + const result=await(await fetchArtifact(current,'static-detection.jpg')).blob(); + if(current?.runId!==report?.runId||current?.modelSha256!==report?.modelSha256) return; + staticUrl=URL.createObjectURL(result);staticImage.src=staticUrl; + } + staticFigure.hidden=false;staticButton.textContent='收起静态样张'; + } catch(error) {notify(error.message);} + finally {staticButton.disabled=false;} + } async function compareGamma() { const current=report; try { @@ -103,19 +341,24 @@ export function createBoardPanel({key,$,element,button,notify,getReport,save,att } catch(error) {notify(error.message);} } async function saveEvidence() { - if(saving) return; + if(saving||report?.status!=='completed'||launchState?.run&&launchState.run.state!=='completed') return; saving=true;render(); const recorded=report; + const comparisonScore=scored?.receiptSha256===recorded.receiptSha256?scored:undefined; const receiptNames=['receipt.json',...recorded.snapshotNames]; const initialPath=getReport().routing.selected; try { - const names=[...receiptNames,...recorded.assets.map(item=>item.file)]; + const samples=recorded.comparison?[recorded.comparison.before.file,recorded.comparison.after.file, + ...recorded.assets.filter(asset=>asset.kind==='static_detection').map(asset=>asset.file)]: + recorded.assets.map(item=>item.file); + const names=[...receiptNames,...samples]; const files=await Promise.all(names.map(async name=>{ const blob=await(await fetchArtifact(recorded,name)).blob(); return new File([blob],'板端-'+name,{type:blob.type}); })); + if(comparisonScore) files.push(new File([JSON.stringify(comparisonScore,null,2)],'板端-Gamma检测对照.json',{type:'application/json'})); const course=getReport(); - if(course.routing.selected!==initialPath||activeModel(course)!==recorded.modelSha256) throw new Error('工位路径或模型已变化,请重新读取回执。'); + if(course.routing.selected!==initialPath||activeModel(course)!==recorded.modelSha256) throw new Error('检测路径或模型已变化,请重新读取回执。'); attach(files,recorded); const evidence={...course.resume.evidence}; if(recorded.status==='completed'&&recorded.frameCount>0&&recorded.previewStopped&&recorded.staticBpu) { @@ -175,16 +418,22 @@ export function createBoardPanel({key,$,element,button,notify,getReport,save,att if(panel.hidden) return; $('board-title').textContent=course.routing.selected==='B'?'预置模型检测':'本组模型检测'; const r=report; + const job=launchState?.run; + const preparing=launching||job?.state==='running'; + const comparing=ispMode.value==='comparison'; + const jobError=launchIssue||errors[job?.error]; const streaming=r?.status==='started'&&Boolean(preview)&&!issue&&!pending&& lastAdvance!==undefined&&Date.now()-lastAdvance<=liveWindowMs; const done=r?.status==='completed'||r?.status==='failed'; - $('board-status').textContent=issue?'需要处理':streaming?'实时更新':r?.status==='failed'?'板端任务失败': + $('board-status').textContent=jobError?'检测需要处理':streaming?'实时更新':preparing?'正在加载模型和相机':issue?'需要处理':r?.status==='failed'?'板端任务失败': pending?'同步新帧中':r?.status==='completed'?'运行结束 · 已归档':r||reading?'等待板端新帧':'等待读取'; $('board-status').className='status-tag'+(issue||r?.status==='failed'?' blocked':streaming||r?.status==='completed'?' ok':''); - $('board-help').textContent=issue||(preview? + $('board-help').textContent=jobError||(!preparing&&issue)||(preview? done?'查看本轮归档帧,按你选定的目标记录是否检出。': + comparing||r?.stage==='before'||r?.stage==='after'?'请保持相机、照明和场景不动,等待两段采集和恢复。': '移动课程目标,观察框和类别的变化。按你选择的目标记录是否检出。': - '从本工位启动课程检测。收到与模型及 ISP 匹配的新帧后,这里会显示带框画面。'); + preparing?'正在核对模型、启动 BPU 和相机。': + errors[launchState?.reason]||'启动课程检测,在画面里移动目标,观察检测框与类别。'); const figure=$('board-frame'); const img=$('board-frame-image'); figure.hidden=!preview; @@ -194,25 +443,39 @@ export function createBoardPanel({key,$,element,button,notify,getReport,save,att $('board-frame-caption').textContent=phases[frame.phase]+' · '+(streaming?'新帧正在更新':done?'本轮归档帧':'最近已验证帧')+ ' · SDK '+frame.sdkTimestampNs; const boxes=Object.entries(frame.counts).filter(([,count])=>count>0).map(([name,count])=>name+' ×'+count).join('、'); - $('board-frame-detail').textContent='此帧推理 '+frame.forwardMs.toFixed(1)+' ms · '+(boxes||'此帧无检测框'); + const fps=streaming&&advances.length>2?((advances.length-1)*1000/(advances.at(-1)-advances[0])).toFixed(1):undefined; + $('board-frame-detail').textContent='此帧 BPU 推理 '+frame.forwardMs.toFixed(1)+' ms · '+(boxes||'此帧无检测框')+ + (fps?' · 工作台显示 '+fps+' 帧/秒':''); } else { img.removeAttribute('src'); $('board-frame-detail').textContent=''; } - refreshButton.textContent=preview?'刷新板端画面':'读取板端检测'; + launchButton.hidden=!launchState?.ready&&!preparing; + launchButton.disabled=preparing||comparing&&!fixedScene.checked; + launchButton.textContent=preparing?'检测运行中':comparing?'开始两段检测':job?'重新检测':'加载模型并开始检测'; + ispMode.hidden=!launchState?.canUseApprovedIsp||launchButton.hidden; + ispMode.disabled=preparing; + comparisonIsp.disabled=!launchState?.canCompareIsp&&!preparing; + sceneControl.hidden=!comparing||launchButton.hidden; + if(!launchState?.canUseApprovedIsp) ispMode.value='current'; + refreshButton.textContent=preview?'刷新板端画面':'读取既有板端回执'; refreshButton.disabled=reading; + staticButton.hidden=r?.status!=='completed'||!r.assets.some(asset=>asset.kind==='static_detection'); gammaButton.hidden=!(r?.assets.some(asset=>asset.kind==='before')&&r.assets.some(asset=>asset.kind==='after')); - adoptButton.hidden=r?.status!=='completed'; + adoptButton.hidden=r?.status!=='completed'||Boolean(job&&job.state!=='completed'); adoptButton.textContent=saving?'正在保存':'采用回执并留证'; adoptButton.disabled=saving; const display=$('board-evidence'); const auditOpen=display.querySelector('details')?.open??false; display.replaceChildren(); if(!r) return; + renderComparison(r); const items=element('ol','','action-checklist'); for(const [name,value] of [['核对板上模型',`${course.routing.selected==='B'?'预置模型':'本组模型'} SHA-256 已匹配 · ${r.modelSha256.slice(0,12)}…`], ['执行 BPU 推理',r.staticBpu?'静态前向已通过':'等待静态前向'], - ['Gamma 与相机',r.assets.some(asset=>asset.kind==='after')?'原始和调整后实拍均已留证':r.cameraIdentity?'相机已出图,等待后续回读':'等待相机取流'], + ['ISP 与相机',r.approvedGamma?'实际生效的 Gamma 曲线已回读': + r.assets.some(asset=>asset.kind==='after')?'调前调后实拍已留证': + r.readbackHash?'实际检测流 ISP 已回读':r.cameraIdentity?'相机已启动,正在读 ISP':'等待相机取流'], ['保存板端结果',r.frameCount?`已归档 ${r.frameCount} 张连续检测帧`:'等待真实 SDK 帧'], ['恢复原配置',r.restoration==='verified'&&r.previewStopped?'回读一致,已停止采流':r.restoration==='no_write'&&r.previewStopped?'未写入 ISP,已停止采流':r.restoration==='unconfirmed'?'恢复待复核':'等待恢复和停流']]) { const row=element('li');row.append(element('strong',name+' · '),element('span',value));items.append(row); @@ -220,15 +483,19 @@ export function createBoardPanel({key,$,element,button,notify,getReport,save,att const audit=element('details','','proof-details'); audit.open=auditOpen; audit.append(element('summary','查看上板、取流和恢复回执'),items); - const counts=Object.entries(r.phases??{}).map(([phase,v])=>`${phase==='before'?'调整前':phase==='after'?'调整后':'实时采流'} ${v.frames} 帧,${v.boxes} 个检测框`); + const counts=Object.entries(r.phases??{}).map(([phase,v])=>`${phase==='before'?'调整前':phase==='after'?'调整后':'实时采流'} ${v.frames} 帧,${v.boxes} 个检测框`+ + (Number.isFinite(v.processingFps)?`,板端处理 ${v.processingFps.toFixed(1)} 帧/秒`:'')); if(counts.length) display.append(element('p',counts.join(' | '),'camera-run-state')); if(r.failure) display.append(element('p','板端提示 · '+r.failure,'camera-run-state')); display.append(audit); } function poll() { if(!lastModel||$('board').hidden||document.hidden) return; + void checkLaunch(); + const next=buffered.shift(); + if(next) {displayFrame(next.frame,next.imageBase64,report?.runId);render();} const current=getReport().nextStep?.stageId; - if(!watchRequested&&!['deploy','live','preset_deploy'].includes(current)) return; + if(!watchRequested&&launchState?.run?.state!=='running'&&!['deploy','live','preset_deploy'].includes(current)) return; if(report?.status==='failed'||report?.status==='completed'&&!pending||issue===errors.board_archive_unconfigured) return; void refresh(true); } diff --git a/plugins/rdk-camera-workshop/web/calibration-demo/exercise.json b/plugins/rdk-camera-workshop/web/calibration-demo/exercise.json new file mode 100644 index 0000000..e1ad8e7 --- /dev/null +++ b/plugins/rdk-camera-workshop/web/calibration-demo/exercise.json @@ -0,0 +1 @@ +{"schema":"rdk.course-calibration-exercise.v1","commit":"889d1a02e8a4eaca16b4df44cc54b24ab7a100f0","darkCrop":{"width":8,"height":8,"bayer":"RGGB","bitDepth":12,"codes":[80,90,80,90,80,90,80,90,100,110,100,110,100,110,100,110,80,90,80,90,80,90,80,90,100,110,100,110,100,110,100,110,80,90,80,90,80,90,80,90,100,110,100,110,100,110,100,110,80,90,80,90,80,90,80,90,100,110,100,110,100,110,100,110]},"flatCornerToCentre":{"before":0.625315,"after":0.994305}} diff --git a/plugins/rdk-camera-workshop/web/calibration-demo/flat-after.png b/plugins/rdk-camera-workshop/web/calibration-demo/flat-after.png new file mode 100644 index 0000000..7f1b83f Binary files /dev/null and b/plugins/rdk-camera-workshop/web/calibration-demo/flat-after.png differ diff --git a/plugins/rdk-camera-workshop/web/calibration-demo/flat-before.png b/plugins/rdk-camera-workshop/web/calibration-demo/flat-before.png new file mode 100644 index 0000000..04b5cec Binary files /dev/null and b/plugins/rdk-camera-workshop/web/calibration-demo/flat-before.png differ diff --git a/plugins/rdk-camera-workshop/web/calibration-demo/preview.png b/plugins/rdk-camera-workshop/web/calibration-demo/preview.png new file mode 100644 index 0000000..717a71e Binary files /dev/null and b/plugins/rdk-camera-workshop/web/calibration-demo/preview.png differ diff --git a/plugins/rdk-camera-workshop/web/calibration-demo/result.json b/plugins/rdk-camera-workshop/web/calibration-demo/result.json new file mode 100644 index 0000000..b26951c --- /dev/null +++ b/plugins/rdk-camera-workshop/web/calibration-demo/result.json @@ -0,0 +1,39 @@ +{ + "schema": "rdk.course-calibration-demo.v1", + "repository": "https://github.com/D-Robotics/isp-calibration-tool", + "branch": "numeric-calibration-closeout", + "commit": "889d1a02e8a4eaca16b4df44cc54b24ab7a100f0", + "input": "upstream_synthetic_raw_demo", + "deviceUsed": false, + "modules": [ + "black_level", + "shading_mesh", + "shading_radial", + "gamma_tone", + "ccm", + "awb", + "ca", + "noise", + "scaler", + "iridix", + "ta" + ], + "metrics": { + "ccm_max_abs_error": 0.018179136269928176, + "black_r": 80.0, + "shading_corner_over_centre": 1.765625, + "noise_profile_0": 0.0, + "scaler_phase0_sum": 64.0, + "iridix_exponent": 1.0, + "parameter_count": 54.0, + "de00": 2.0424596801565738, + "ta_frames": 3.0 + }, + "sha256": { + "static-calibrations.json": "deeee2a8f6f5e24c302eeb451cccbd8012c63229b356bf7c05d375532375e700", + "preview.png": "361583151e68d274ddd86244e3e01128d3f950c0a3a61f7a810b075d903947a2", + "exercise.json": "608abdd29fc0326d9a7754394f33222f75194eac9878ac4f7c53685c4af6433e", + "flat-before.png": "164ac29e1ae6a5888ac8c797ff4f3565e2c1fa2ef8382f7d5489251b0cadbe36", + "flat-after.png": "b610b86008de30547f221da55b5b837bb74de44aee6f92f3e7658415d8319332" + } +} diff --git a/plugins/rdk-camera-workshop/web/calibration-demo/static-calibrations.json b/plugins/rdk-camera-workshop/web/calibration-demo/static-calibrations.json new file mode 100644 index 0000000..22cdb43 --- /dev/null +++ b/plugins/rdk-camera-workshop/web/calibration-demo/static-calibrations.json @@ -0,0 +1,15974 @@ +{ + "luts": [ + { + "__comment": "CALIBRATION_BLACK_LEVEL_R", + "type": "FW_API_LUT", + "name": "CALIBRATION_BLACK_LEVEL_R", + "width": "2", + "value": [ + 0, + 80, + 0, + 80 + ], + "rows": "2", + "cols": "2" + }, + { + "__comment": "CALIBRATION_BLACK_LEVEL_GR", + "type": "FW_API_LUT", + "name": "CALIBRATION_BLACK_LEVEL_GR", + "width": "2", + "value": [ + 0, + 90, + 0, + 90 + ], + "rows": "2", + "cols": "2" + }, + { + "__comment": "CALIBRATION_BLACK_LEVEL_GB", + "type": "FW_API_LUT", + "name": "CALIBRATION_BLACK_LEVEL_GB", + "width": "2", + "value": [ + 0, + 100, + 0, + 100 + ], + "rows": "2", + "cols": "2" + }, + { + "__comment": "CALIBRATION_BLACK_LEVEL_B", + "type": "FW_API_LUT", + "name": "CALIBRATION_BLACK_LEVEL_B", + "width": "2", + "value": [ + 0, + 110, + 0, + 110 + ], + "rows": "2", + "cols": "2" + }, + { + "__comment": "CALIBRATION_GAMMA_FE", + "type": "FW_API_LUT", + "name": "CALIBRATION_GAMMA_FE", + "width": "4", + "value": [ + 0, + 4096, + 8192, + 12288, + 16384, + 20480, + 24576, + 28672, + 32768, + 36864, + 40960, + 45056, + 49152, + 53248, + 57344, + 61440, + 65536, + 69632, + 73728, + 77824, + 81920, + 86016, + 90112, + 94208, + 98304, + 102400, + 106496, + 110592, + 114688, + 118784, + 122880, + 126976, + 131072, + 135168, + 139264, + 143360, + 147456, + 151552, + 155648, + 159744, + 163840, + 167936, + 172032, + 176128, + 180224, + 184320, + 188416, + 192512, + 196608, + 200704, + 204800, + 208896, + 212992, + 217088, + 221184, + 225280, + 229376, + 233472, + 237568, + 241664, + 245760, + 249856, + 253952, + 258048, + 262144, + 266240, + 270336, + 274432, + 278528, + 282624, + 286720, + 290816, + 294912, + 299008, + 303104, + 307200, + 311296, + 315392, + 319488, + 323584, + 327680, + 331776, + 335872, + 339968, + 344064, + 348160, + 352256, + 356352, + 360448, + 364544, + 368640, + 372736, + 376832, + 380928, + 385024, + 389120, + 393216, + 397312, + 401408, + 405504, + 409600, + 413696, + 417792, + 421888, + 425984, + 430080, + 434176, + 438272, + 442368, + 446464, + 450560, + 454656, + 458752, + 462848, + 466944, + 471040, + 475136, + 479232, + 483328, + 487424, + 491520, + 495616, + 499712, + 503808, + 507904, + 512000, + 516096, + 520192, + 524288, + 528384, + 532480, + 536576, + 540672, + 544768, + 548864, + 552960, + 557056, + 561152, + 565248, + 569344, + 573440, + 577536, + 581632, + 585728, + 589824, + 593920, + 598016, + 602112, + 606208, + 610304, + 614400, + 618496, + 622592, + 626688, + 630784, + 634880, + 638976, + 643072, + 647168, + 651264, + 655360, + 659456, + 663552, + 667648, + 671744, + 675840, + 679936, + 684032, + 688128, + 692224, + 696320, + 700416, + 704512, + 708608, + 712704, + 716800, + 720896, + 724992, + 729088, + 733184, + 737280, + 741376, + 745472, + 749568, + 753664, + 757760, + 761856, + 765952, + 770048, + 774144, + 778240, + 782336, + 786432, + 790528, + 794624, + 798720, + 802816, + 806912, + 811008, + 815104, + 819200, + 823296, + 827392, + 831488, + 835584, + 839680, + 843776, + 847872, + 851968, + 856064, + 860160, + 864256, + 868352, + 872448, + 876544, + 880640, + 884736, + 888832, + 892928, + 897024, + 901120, + 905216, + 909312, + 913408, + 917504, + 921600, + 925696, + 929792, + 933888, + 937984, + 942080, + 946176, + 950272, + 954368, + 958464, + 962560, + 966656, + 970752, + 974848, + 978944, + 983040, + 987136, + 991232, + 995328, + 999424, + 1003520, + 1007616, + 1011712, + 1015808, + 1019904, + 1024000, + 1028096, + 1032192, + 1036288, + 1040384, + 1044480, + 1048576, + 1052672, + 1056768, + 1060864, + 1064960, + 1069056, + 1073152, + 1077248, + 1081344, + 1085440, + 1089536, + 1093632, + 1097728, + 1101824, + 1105920, + 1110016, + 1114112, + 1118208, + 1122304, + 1126400, + 1130496, + 1134592, + 1138688, + 1142784, + 1146880, + 1150976, + 1155072, + 1159168, + 1163264, + 1167360, + 1171456, + 1175552, + 1179648, + 1183744, + 1187840, + 1191936, + 1196032, + 1200128, + 1204224, + 1208320, + 1212416, + 1216512, + 1220608, + 1224704, + 1228800, + 1232896, + 1236992, + 1241088, + 1245184, + 1249280, + 1253376, + 1257472, + 1261568, + 1265664, + 1269760, + 1273856, + 1277952, + 1282048, + 1286144, + 1290240, + 1294336, + 1298432, + 1302528, + 1306624, + 1310720, + 1314816, + 1318912, + 1323008, + 1327104, + 1331200, + 1335296, + 1339392, + 1343488, + 1347584, + 1351680, + 1355776, + 1359872, + 1363968, + 1368064, + 1372160, + 1376256, + 1380352, + 1384448, + 1388544, + 1392640, + 1396736, + 1400832, + 1404928, + 1409024, + 1413120, + 1417216, + 1421312, + 1425408, + 1429504, + 1433600, + 1437696, + 1441792, + 1445888, + 1449984, + 1454080, + 1458176, + 1462272, + 1466368, + 1470464, + 1474560, + 1478656, + 1482752, + 1486848, + 1490944, + 1495040, + 1499136, + 1503232, + 1507328, + 1511424, + 1515520, + 1519616, + 1523712, + 1527808, + 1531904, + 1536000, + 1540096, + 1544192, + 1548288, + 1552384, + 1556480, + 1560576, + 1564672, + 1568768, + 1572864, + 1576960, + 1581056, + 1585152, + 1589248, + 1593344, + 1597440, + 1601536, + 1605632, + 1609728, + 1613824, + 1617920, + 1622016, + 1626112, + 1630208, + 1634304, + 1638400, + 1642496, + 1646592, + 1650688, + 1654784, + 1658880, + 1662976, + 1667072, + 1671168, + 1675264, + 1679360, + 1683456, + 1687552, + 1691648, + 1695744, + 1699840, + 1703936, + 1708032, + 1712128, + 1716224, + 1720320, + 1724416, + 1728512, + 1732608, + 1736704, + 1740800, + 1744896, + 1748992, + 1753088, + 1757184, + 1761280, + 1765376, + 1769472, + 1773568, + 1777664, + 1781760, + 1785856, + 1789952, + 1794048, + 1798144, + 1802240, + 1806336, + 1810432, + 1814528, + 1818624, + 1822720, + 1826816, + 1830912, + 1835008, + 1839104, + 1843200, + 1847296, + 1851392, + 1855488, + 1859584, + 1863680, + 1867776, + 1871872, + 1875968, + 1880064, + 1884160, + 1888256, + 1892352, + 1896448, + 1900544, + 1904640, + 1908736, + 1912832, + 1916928, + 1921024, + 1925120, + 1929216, + 1933312, + 1937408, + 1941504, + 1945600, + 1949696, + 1953792, + 1957888, + 1961984, + 1966080, + 1970176, + 1974272, + 1978368, + 1982464, + 1986560, + 1990656, + 1994752, + 1998848, + 2002944, + 2007040, + 2011136, + 2015232, + 2019328, + 2023424, + 2027520, + 2031616, + 2035712, + 2039808, + 2043904, + 2048000, + 2052096, + 2056192, + 2060288, + 2064384, + 2068480, + 2072576, + 2076672, + 2080768, + 2084864, + 2088960, + 2093056, + 2097152, + 2101248, + 2105344, + 2109440, + 2113536, + 2117632, + 2121728, + 2125824, + 2129920, + 2134016, + 2138112, + 2142208, + 2146304, + 2150400, + 2154496, + 2158592, + 2162688, + 2166784, + 2170880, + 2174976, + 2179072, + 2183168, + 2187264, + 2191360, + 2195456, + 2199552, + 2203648, + 2207744, + 2211840, + 2215936, + 2220032, + 2224128, + 2228224, + 2232320, + 2236416, + 2240512, + 2244608, + 2248704, + 2252800, + 2256896, + 2260992, + 2265088, + 2269184, + 2273280, + 2277376, + 2281472, + 2285568, + 2289664, + 2293760, + 2297856, + 2301952, + 2306048, + 2310144, + 2314240, + 2318336, + 2322432, + 2326528, + 2330624, + 2334720, + 2338816, + 2342912, + 2347008, + 2351104, + 2355200, + 2359296, + 2363392, + 2367488, + 2371584, + 2375680, + 2379776, + 2383872, + 2387968, + 2392064, + 2396160, + 2400256, + 2404352, + 2408448, + 2412544, + 2416640, + 2420736, + 2424832, + 2428928, + 2433024, + 2437120, + 2441216, + 2445312, + 2449408, + 2453504, + 2457600, + 2461696, + 2465792, + 2469888, + 2473984, + 2478080, + 2482176, + 2486272, + 2490368, + 2494464, + 2498560, + 2502656, + 2506752, + 2510848, + 2514944, + 2519040, + 2523136, + 2527232, + 2531328, + 2535424, + 2539520, + 2543616, + 2547712, + 2551808, + 2555904, + 2560000, + 2564096, + 2568192, + 2572288, + 2576384, + 2580480, + 2584576, + 2588672, + 2592768, + 2596864, + 2600960, + 2605056, + 2609152, + 2613248, + 2617344, + 2621440, + 2625536, + 2629632, + 2633728, + 2637824, + 2641920, + 2646016, + 2650112, + 2654208, + 2658304, + 2662400, + 2666496, + 2670592, + 2674688, + 2678784, + 2682880, + 2686976, + 2691072, + 2695168, + 2699264, + 2703360, + 2707456, + 2711552, + 2715648, + 2719744, + 2723840, + 2727936, + 2732032, + 2736128, + 2740224, + 2744320, + 2748416, + 2752512, + 2756608, + 2760704, + 2764800, + 2768896, + 2772992, + 2777088, + 2781184, + 2785280, + 2789376, + 2793472, + 2797568, + 2801664, + 2805760, + 2809856, + 2813952, + 2818048, + 2822144, + 2826240, + 2830336, + 2834432, + 2838528, + 2842624, + 2846720, + 2850816, + 2854912, + 2859008, + 2863104, + 2867200, + 2871296, + 2875392, + 2879488, + 2883584, + 2887680, + 2891776, + 2895872, + 2899968, + 2904064, + 2908160, + 2912256, + 2916352, + 2920448, + 2924544, + 2928640, + 2932736, + 2936832, + 2940928, + 2945024, + 2949120, + 2953216, + 2957312, + 2961408, + 2965504, + 2969600, + 2973696, + 2977792, + 2981888, + 2985984, + 2990080, + 2994176, + 2998272, + 3002368, + 3006464, + 3010560, + 3014656, + 3018752, + 3022848, + 3026944, + 3031040, + 3035136, + 3039232, + 3043328, + 3047424, + 3051520, + 3055616, + 3059712, + 3063808, + 3067904, + 3072000, + 3076096, + 3080192, + 3084288, + 3088384, + 3092480, + 3096576, + 3100672, + 3104768, + 3108864, + 3112960, + 3117056, + 3121152, + 3125248, + 3129344, + 3133440, + 3137536, + 3141632, + 3145728, + 3149824, + 3153920, + 3158016, + 3162112, + 3166208, + 3170304, + 3174400, + 3178496, + 3182592, + 3186688, + 3190784, + 3194880, + 3198976, + 3203072, + 3207168, + 3211264, + 3215360, + 3219456, + 3223552, + 3227648, + 3231744, + 3235840, + 3239936, + 3244032, + 3248128, + 3252224, + 3256320, + 3260416, + 3264512, + 3268608, + 3272704, + 3276800, + 3280896, + 3284992, + 3289088, + 3293184, + 3297280, + 3301376, + 3305472, + 3309568, + 3313664, + 3317760, + 3321856, + 3325952, + 3330048, + 3334144, + 3338240, + 3342336, + 3346432, + 3350528, + 3354624, + 3358720, + 3362816, + 3366912, + 3371008, + 3375104, + 3379200, + 3383296, + 3387392, + 3391488, + 3395584, + 3399680, + 3403776, + 3407872, + 3411968, + 3416064, + 3420160, + 3424256, + 3428352, + 3432448, + 3436544, + 3440640, + 3444736, + 3448832, + 3452928, + 3457024, + 3461120, + 3465216, + 3469312, + 3473408, + 3477504, + 3481600, + 3485696, + 3489792, + 3493888, + 3497984, + 3502080, + 3506176, + 3510272, + 3514368, + 3518464, + 3522560, + 3526656, + 3530752, + 3534848, + 3538944, + 3543040, + 3547136, + 3551232, + 3555328, + 3559424, + 3563520, + 3567616, + 3571712, + 3575808, + 3579904, + 3584000, + 3588096, + 3592192, + 3596288, + 3600384, + 3604480, + 3608576, + 3612672, + 3616768, + 3620864, + 3624960, + 3629056, + 3633152, + 3637248, + 3641344, + 3645440, + 3649536, + 3653632, + 3657728, + 3661824, + 3665920, + 3670016, + 3674112, + 3678208, + 3682304, + 3686400, + 3690496, + 3694592, + 3698688, + 3702784, + 3706880, + 3710976, + 3715072, + 3719168, + 3723264, + 3727360, + 3731456, + 3735552, + 3739648, + 3743744, + 3747840, + 3751936, + 3756032, + 3760128, + 3764224, + 3768320, + 3772416, + 3776512, + 3780608, + 3784704, + 3788800, + 3792896, + 3796992, + 3801088, + 3805184, + 3809280, + 3813376, + 3817472, + 3821568, + 3825664, + 3829760, + 3833856, + 3837952, + 3842048, + 3846144, + 3850240, + 3854336, + 3858432, + 3862528, + 3866624, + 3870720, + 3874816, + 3878912, + 3883008, + 3887104, + 3891200, + 3895296, + 3899392, + 3903488, + 3907584, + 3911680, + 3915776, + 3919872, + 3923968, + 3928064, + 3932160, + 3936256, + 3940352, + 3944448, + 3948544, + 3952640, + 3956736, + 3960832, + 3964928, + 3969024, + 3973120, + 3977216, + 3981312, + 3985408, + 3989504, + 3993600, + 3997696, + 4001792, + 4005888, + 4009984, + 4014080, + 4018176, + 4022272, + 4026368, + 4030464, + 4034560, + 4038656, + 4042752, + 4046848, + 4050944, + 4055040, + 4059136, + 4063232, + 4067328, + 4071424, + 4075520, + 4079616, + 4083712, + 4087808, + 4091904, + 4096000, + 4100096, + 4104192, + 4108288, + 4112384, + 4116480, + 4120576, + 4124672, + 4128768, + 4132864, + 4136960, + 4141056, + 4145152, + 4149248, + 4153344, + 4157440, + 4161536, + 4165632, + 4169728, + 4173824, + 4177920, + 4182016, + 4186112, + 4190208, + 4194304, + 4198400, + 4202496, + 4206592, + 4210688, + 4214784, + 4218880, + 4222976, + 4227072, + 4231168, + 4235264, + 4239360, + 4243456, + 4247552, + 4251648, + 4255744, + 4259840, + 4263936, + 4268032, + 4272128, + 4276224, + 4280320, + 4284416, + 4288512, + 4292608, + 4296704, + 4300800, + 4304896, + 4308992, + 4313088, + 4317184, + 4321280, + 4325376, + 4329472, + 4333568, + 4337664, + 4341760, + 4345856, + 4349952, + 4354048, + 4358144, + 4362240, + 4366336, + 4370432, + 4374528, + 4378624, + 4382720, + 4386816, + 4390912, + 4395008, + 4399104, + 4403200, + 4407296, + 4411392, + 4415488, + 4419584, + 4423680, + 4427776, + 4431872, + 4435968, + 4440064, + 4444160, + 4448256, + 4452352, + 4456448, + 4460544, + 4464640, + 4468736, + 4472832, + 4476928, + 4481024, + 4485120, + 4489216, + 4493312, + 4497408, + 4501504, + 4505600, + 4509696, + 4513792, + 4517888, + 4521984, + 4526080, + 4530176, + 4534272, + 4538368, + 4542464, + 4546560, + 4550656, + 4554752, + 4558848, + 4562944, + 4567040, + 4571136, + 4575232, + 4579328, + 4583424, + 4587520, + 4591616, + 4595712, + 4599808, + 4603904, + 4608000, + 4612096, + 4616192, + 4620288, + 4624384, + 4628480, + 4632576, + 4636672, + 4640768, + 4644864, + 4648960, + 4653056, + 4657152, + 4661248, + 4665344, + 4669440, + 4673536, + 4677632, + 4681728, + 4685824, + 4689920, + 4694016, + 4698112, + 4702208, + 4706304, + 4710400, + 4714496, + 4718592, + 4722688, + 4726784, + 4730880, + 4734976, + 4739072, + 4743168, + 4747264, + 4751360, + 4755456, + 4759552, + 4763648, + 4767744, + 4771840, + 4775936, + 4780032, + 4784128, + 4788224, + 4792320, + 4796416, + 4800512, + 4804608, + 4808704, + 4812800, + 4816896, + 4820992, + 4825088, + 4829184, + 4833280, + 4837376, + 4841472, + 4845568, + 4849664, + 4853760, + 4857856, + 4861952, + 4866048, + 4870144, + 4874240, + 4878336, + 4882432, + 4886528, + 4890624, + 4894720, + 4898816, + 4902912, + 4907008, + 4911104, + 4915200, + 4919296, + 4923392, + 4927488, + 4931584, + 4935680, + 4939776, + 4943872, + 4947968, + 4952064, + 4956160, + 4960256, + 4964352, + 4968448, + 4972544, + 4976640, + 4980736, + 4984832, + 4988928, + 4993024, + 4997120, + 5001216, + 5005312, + 5009408, + 5013504, + 5017600, + 5021696, + 5025792, + 5029888, + 5033984, + 5038080, + 5042176, + 5046272, + 5050368, + 5054464, + 5058560, + 5062656, + 5066752, + 5070848, + 5074944, + 5079040, + 5083136, + 5087232, + 5091328, + 5095424, + 5099520, + 5103616, + 5107712, + 5111808, + 5115904, + 5120000, + 5124096, + 5128192, + 5132288, + 5136384, + 5140480, + 5144576, + 5148672, + 5152768, + 5156864, + 5160960, + 5165056, + 5169152, + 5173248, + 5177344, + 5181440, + 5185536, + 5189632, + 5193728, + 5197824, + 5201920, + 5206016, + 5210112, + 5214208, + 5218304, + 5222400, + 5226496, + 5230592, + 5234688, + 5238784, + 5242880, + 5246976, + 5251072, + 5255168, + 5259264, + 5263360, + 5267456, + 5271552, + 5275648, + 5279744, + 5283840, + 5287936, + 5292032, + 5296128, + 5300224, + 5304320, + 5308416, + 5312512, + 5316608, + 5320704, + 5324800, + 5328896, + 5332992, + 5337088, + 5341184, + 5345280, + 5349376, + 5353472, + 5357568, + 5361664, + 5365760, + 5369856, + 5373952, + 5378048, + 5382144, + 5386240, + 5390336, + 5394432, + 5398528, + 5402624, + 5406720, + 5410816, + 5414912, + 5419008, + 5423104, + 5427200, + 5431296, + 5435392, + 5439488, + 5443584, + 5447680, + 5451776, + 5455872, + 5459968, + 5464064, + 5468160, + 5472256, + 5476352, + 5480448, + 5484544, + 5488640, + 5492736, + 5496832, + 5500928, + 5505024, + 5509120, + 5513216, + 5517312, + 5521408, + 5525504, + 5529600, + 5533696, + 5537792, + 5541888, + 5545984, + 5550080, + 5554176, + 5558272, + 5562368, + 5566464, + 5570560, + 5574656, + 5578752, + 5582848, + 5586944, + 5591040, + 5595136, + 5599232, + 5603328, + 5607424, + 5611520, + 5615616, + 5619712, + 5623808, + 5627904, + 5632000, + 5636096, + 5640192, + 5644288, + 5648384, + 5652480, + 5656576, + 5660672, + 5664768, + 5668864, + 5672960, + 5677056, + 5681152, + 5685248, + 5689344, + 5693440, + 5697536, + 5701632, + 5705728, + 5709824, + 5713920, + 5718016, + 5722112, + 5726208, + 5730304, + 5734400, + 5738496, + 5742592, + 5746688, + 5750784, + 5754880, + 5758976, + 5763072, + 5767168, + 5771264, + 5775360, + 5779456, + 5783552, + 5787648, + 5791744, + 5795840, + 5799936, + 5804032, + 5808128, + 5812224, + 5816320, + 5820416, + 5824512, + 5828608, + 5832704, + 5836800, + 5840896, + 5844992, + 5849088, + 5853184, + 5857280, + 5861376, + 5865472, + 5869568, + 5873664, + 5877760, + 5881856, + 5885952, + 5890048, + 5894144, + 5898240, + 5902336, + 5906432, + 5910528, + 5914624, + 5918720, + 5922816, + 5926912, + 5931008, + 5935104, + 5939200, + 5943296, + 5947392, + 5951488, + 5955584, + 5959680, + 5963776, + 5967872, + 5971968, + 5976064, + 5980160, + 5984256, + 5988352, + 5992448, + 5996544, + 6000640, + 6004736, + 6008832, + 6012928, + 6017024, + 6021120, + 6025216, + 6029312, + 6033408, + 6037504, + 6041600, + 6045696, + 6049792, + 6053888, + 6057984, + 6062080, + 6066176, + 6070272, + 6074368, + 6078464, + 6082560, + 6086656, + 6090752, + 6094848, + 6098944, + 6103040, + 6107136, + 6111232, + 6115328, + 6119424, + 6123520, + 6127616, + 6131712, + 6135808, + 6139904, + 6144000, + 6148096, + 6152192, + 6156288, + 6160384, + 6164480, + 6168576, + 6172672, + 6176768, + 6180864, + 6184960, + 6189056, + 6193152, + 6197248, + 6201344, + 6205440, + 6209536, + 6213632, + 6217728, + 6221824, + 6225920, + 6230016, + 6234112, + 6238208, + 6242304, + 6246400, + 6250496, + 6254592, + 6258688, + 6262784, + 6266880, + 6270976, + 6275072, + 6279168, + 6283264, + 6287360, + 6291456, + 6295552, + 6299648, + 6303744, + 6307840, + 6311936, + 6316032, + 6320128, + 6324224, + 6328320, + 6332416, + 6336512, + 6340608, + 6344704, + 6348800, + 6352896, + 6356992, + 6361088, + 6365184, + 6369280, + 6373376, + 6377472, + 6381568, + 6385664, + 6389760, + 6393856, + 6397952, + 6402048, + 6406144, + 6410240, + 6414336, + 6418432, + 6422528, + 6426624, + 6430720, + 6434816, + 6438912, + 6443008, + 6447104, + 6451200, + 6455296, + 6459392, + 6463488, + 6467584, + 6471680, + 6475776, + 6479872, + 6483968, + 6488064, + 6492160, + 6496256, + 6500352, + 6504448, + 6508544, + 6512640, + 6516736, + 6520832, + 6524928, + 6529024, + 6533120, + 6537216, + 6541312, + 6545408, + 6549504, + 6553600, + 6557696, + 6561792, + 6565888, + 6569984, + 6574080, + 6578176, + 6582272, + 6586368, + 6590464, + 6594560, + 6598656, + 6602752, + 6606848, + 6610944, + 6615040, + 6619136, + 6623232, + 6627328, + 6631424, + 6635520, + 6639616, + 6643712, + 6647808, + 6651904, + 6656000, + 6660096, + 6664192, + 6668288, + 6672384, + 6676480, + 6680576, + 6684672, + 6688768, + 6692864, + 6696960, + 6701056, + 6705152, + 6709248, + 6713344, + 6717440, + 6721536, + 6725632, + 6729728, + 6733824, + 6737920, + 6742016, + 6746112, + 6750208, + 6754304, + 6758400, + 6762496, + 6766592, + 6770688, + 6774784, + 6778880, + 6782976, + 6787072, + 6791168, + 6795264, + 6799360, + 6803456, + 6807552, + 6811648, + 6815744, + 6819840, + 6823936, + 6828032, + 6832128, + 6836224, + 6840320, + 6844416, + 6848512, + 6852608, + 6856704, + 6860800, + 6864896, + 6868992, + 6873088, + 6877184, + 6881280, + 6885376, + 6889472, + 6893568, + 6897664, + 6901760, + 6905856, + 6909952, + 6914048, + 6918144, + 6922240, + 6926336, + 6930432, + 6934528, + 6938624, + 6942720, + 6946816, + 6950912, + 6955008, + 6959104, + 6963200, + 6967296, + 6971392, + 6975488, + 6979584, + 6983680, + 6987776, + 6991872, + 6995968, + 7000064, + 7004160, + 7008256, + 7012352, + 7016448, + 7020544, + 7024640, + 7028736, + 7032832, + 7036928, + 7041024, + 7045120, + 7049216, + 7053312, + 7057408, + 7061504, + 7065600, + 7069696, + 7073792, + 7077888, + 7081984, + 7086080, + 7090176, + 7094272, + 7098368, + 7102464, + 7106560, + 7110656, + 7114752, + 7118848, + 7122944, + 7127040, + 7131136, + 7135232, + 7139328, + 7143424, + 7147520, + 7151616, + 7155712, + 7159808, + 7163904, + 7168000, + 7172096, + 7176192, + 7180288, + 7184384, + 7188480, + 7192576, + 7196672, + 7200768, + 7204864, + 7208960, + 7213056, + 7217152, + 7221248, + 7225344, + 7229440, + 7233536, + 7237632, + 7241728, + 7245824, + 7249920, + 7254016, + 7258112, + 7262208, + 7266304, + 7270400, + 7274496, + 7278592, + 7282688, + 7286784, + 7290880, + 7294976, + 7299072, + 7303168, + 7307264, + 7311360, + 7315456, + 7319552, + 7323648, + 7327744, + 7331840, + 7335936, + 7340032, + 7344128, + 7348224, + 7352320, + 7356416, + 7360512, + 7364608, + 7368704, + 7372800, + 7376896, + 7380992, + 7385088, + 7389184, + 7393280, + 7397376, + 7401472, + 7405568, + 7409664, + 7413760, + 7417856, + 7421952, + 7426048, + 7430144, + 7434240, + 7438336, + 7442432, + 7446528, + 7450624, + 7454720, + 7458816, + 7462912, + 7467008, + 7471104, + 7475200, + 7479296, + 7483392, + 7487488, + 7491584, + 7495680, + 7499776, + 7503872, + 7507968, + 7512064, + 7516160, + 7520256, + 7524352, + 7528448, + 7532544, + 7536640, + 7540736, + 7544832, + 7548928, + 7553024, + 7557120, + 7561216, + 7565312, + 7569408, + 7573504, + 7577600, + 7581696, + 7585792, + 7589888, + 7593984, + 7598080, + 7602176, + 7606272, + 7610368, + 7614464, + 7618560, + 7622656, + 7626752, + 7630848, + 7634944, + 7639040, + 7643136, + 7647232, + 7651328, + 7655424, + 7659520, + 7663616, + 7667712, + 7671808, + 7675904, + 7680000, + 7684096, + 7688192, + 7692288, + 7696384, + 7700480, + 7704576, + 7708672, + 7712768, + 7716864, + 7720960, + 7725056, + 7729152, + 7733248, + 7737344, + 7741440, + 7745536, + 7749632, + 7753728, + 7757824, + 7761920, + 7766016, + 7770112, + 7774208, + 7778304, + 7782400, + 7786496, + 7790592, + 7794688, + 7798784, + 7802880, + 7806976, + 7811072, + 7815168, + 7819264, + 7823360, + 7827456, + 7831552, + 7835648, + 7839744, + 7843840, + 7847936, + 7852032, + 7856128, + 7860224, + 7864320, + 7868416, + 7872512, + 7876608, + 7880704, + 7884800, + 7888896, + 7892992, + 7897088, + 7901184, + 7905280, + 7909376, + 7913472, + 7917568, + 7921664, + 7925760, + 7929856, + 7933952, + 7938048, + 7942144, + 7946240, + 7950336, + 7954432, + 7958528, + 7962624, + 7966720, + 7970816, + 7974912, + 7979008, + 7983104, + 7987200, + 7991296, + 7995392, + 7999488, + 8003584, + 8007680, + 8011776, + 8015872, + 8019968, + 8024064, + 8028160, + 8032256, + 8036352, + 8040448, + 8044544, + 8048640, + 8052736, + 8056832, + 8060928, + 8065024, + 8069120, + 8073216, + 8077312, + 8081408, + 8085504, + 8089600, + 8093696, + 8097792, + 8101888, + 8105984, + 8110080, + 8114176, + 8118272, + 8122368, + 8126464, + 8130560, + 8134656, + 8138752, + 8142848, + 8146944, + 8151040, + 8155136, + 8159232, + 8163328, + 8167424, + 8171520, + 8175616, + 8179712, + 8183808, + 8187904, + 8192000, + 8196096, + 8200192, + 8204288, + 8208384, + 8212480, + 8216576, + 8220672, + 8224768, + 8228864, + 8232960, + 8237056, + 8241152, + 8245248, + 8249344, + 8253440, + 8257536, + 8261632, + 8265728, + 8269824, + 8273920, + 8278016, + 8282112, + 8286208, + 8290304, + 8294400, + 8298496, + 8302592, + 8306688, + 8310784, + 8314880, + 8318976, + 8323072, + 8327168, + 8331264, + 8335360, + 8339456, + 8343552, + 8347648, + 8351744, + 8355840, + 8359936, + 8364032, + 8368128, + 8372224, + 8376320, + 8380416, + 8384512, + 8388608, + 8392704, + 8396800, + 8400896, + 8404992, + 8409088, + 8413184, + 8417280, + 8421376, + 8425472, + 8429568, + 8433664, + 8437760, + 8441856, + 8445952, + 8450048, + 8454144, + 8458240, + 8462336, + 8466432, + 8470528, + 8474624, + 8478720, + 8482816, + 8486912, + 8491008, + 8495104, + 8499200, + 8503296, + 8507392, + 8511488, + 8515584, + 8519680, + 8523776, + 8527872, + 8531968, + 8536064, + 8540160, + 8544256, + 8548352, + 8552448, + 8556544, + 8560640, + 8564736, + 8568832, + 8572928, + 8577024, + 8581120, + 8585216, + 8589312, + 8593408, + 8597504, + 8601600, + 8605696, + 8609792, + 8613888, + 8617984, + 8622080, + 8626176, + 8630272, + 8634368, + 8638464, + 8642560, + 8646656, + 8650752, + 8654848, + 8658944, + 8663040, + 8667136, + 8671232, + 8675328, + 8679424, + 8683520, + 8687616, + 8691712, + 8695808, + 8699904, + 8704000, + 8708096, + 8712192, + 8716288, + 8720384, + 8724480, + 8728576, + 8732672, + 8736768, + 8740864, + 8744960, + 8749056, + 8753152, + 8757248, + 8761344, + 8765440, + 8769536, + 8773632, + 8777728, + 8781824, + 8785920, + 8790016, + 8794112, + 8798208, + 8802304, + 8806400, + 8810496, + 8814592, + 8818688, + 8822784, + 8826880, + 8830976, + 8835072, + 8839168, + 8843264, + 8847360, + 8851456, + 8855552, + 8859648, + 8863744, + 8867840, + 8871936, + 8876032, + 8880128, + 8884224, + 8888320, + 8892416, + 8896512, + 8900608, + 8904704, + 8908800, + 8912896, + 8916992, + 8921088, + 8925184, + 8929280, + 8933376, + 8937472, + 8941568, + 8945664, + 8949760, + 8953856, + 8957952, + 8962048, + 8966144, + 8970240, + 8974336, + 8978432, + 8982528, + 8986624, + 8990720, + 8994816, + 8998912, + 9003008, + 9007104, + 9011200, + 9015296, + 9019392, + 9023488, + 9027584, + 9031680, + 9035776, + 9039872, + 9043968, + 9048064, + 9052160, + 9056256, + 9060352, + 9064448, + 9068544, + 9072640, + 9076736, + 9080832, + 9084928, + 9089024, + 9093120, + 9097216, + 9101312, + 9105408, + 9109504, + 9113600, + 9117696, + 9121792, + 9125888, + 9129984, + 9134080, + 9138176, + 9142272, + 9146368, + 9150464, + 9154560, + 9158656, + 9162752, + 9166848, + 9170944, + 9175040, + 9179136, + 9183232, + 9187328, + 9191424, + 9195520, + 9199616, + 9203712, + 9207808, + 9211904, + 9216000, + 9220096, + 9224192, + 9228288, + 9232384, + 9236480, + 9240576, + 9244672, + 9248768, + 9252864, + 9256960, + 9261056, + 9265152, + 9269248, + 9273344, + 9277440, + 9281536, + 9285632, + 9289728, + 9293824, + 9297920, + 9302016, + 9306112, + 9310208, + 9314304, + 9318400, + 9322496, + 9326592, + 9330688, + 9334784, + 9338880, + 9342976, + 9347072, + 9351168, + 9355264, + 9359360, + 9363456, + 9367552, + 9371648, + 9375744, + 9379840, + 9383936, + 9388032, + 9392128, + 9396224, + 9400320, + 9404416, + 9408512, + 9412608, + 9416704, + 9420800, + 9424896, + 9428992, + 9433088, + 9437184, + 9441280, + 9445376, + 9449472, + 9453568, + 9457664, + 9461760, + 9465856, + 9469952, + 9474048, + 9478144, + 9482240, + 9486336, + 9490432, + 9494528, + 9498624, + 9502720, + 9506816, + 9510912, + 9515008, + 9519104, + 9523200, + 9527296, + 9531392, + 9535488, + 9539584, + 9543680, + 9547776, + 9551872, + 9555968, + 9560064, + 9564160, + 9568256, + 9572352, + 9576448, + 9580544, + 9584640, + 9588736, + 9592832, + 9596928, + 9601024, + 9605120, + 9609216, + 9613312, + 9617408, + 9621504, + 9625600, + 9629696, + 9633792, + 9637888, + 9641984, + 9646080, + 9650176, + 9654272, + 9658368, + 9662464, + 9666560, + 9670656, + 9674752, + 9678848, + 9682944, + 9687040, + 9691136, + 9695232, + 9699328, + 9703424, + 9707520, + 9711616, + 9715712, + 9719808, + 9723904, + 9728000, + 9732096, + 9736192, + 9740288, + 9744384, + 9748480, + 9752576, + 9756672, + 9760768, + 9764864, + 9768960, + 9773056, + 9777152, + 9781248, + 9785344, + 9789440, + 9793536, + 9797632, + 9801728, + 9805824, + 9809920, + 9814016, + 9818112, + 9822208, + 9826304, + 9830400, + 9834496, + 9838592, + 9842688, + 9846784, + 9850880, + 9854976, + 9859072, + 9863168, + 9867264, + 9871360, + 9875456, + 9879552, + 9883648, + 9887744, + 9891840, + 9895936, + 9900032, + 9904128, + 9908224, + 9912320, + 9916416, + 9920512, + 9924608, + 9928704, + 9932800, + 9936896, + 9940992, + 9945088, + 9949184, + 9953280, + 9957376, + 9961472, + 9965568, + 9969664, + 9973760, + 9977856, + 9981952, + 9986048, + 9990144, + 9994240, + 9998336, + 10002432, + 10006528, + 10010624, + 10014720, + 10018816, + 10022912, + 10027008, + 10031104, + 10035200, + 10039296, + 10043392, + 10047488, + 10051584, + 10055680, + 10059776, + 10063872, + 10067968, + 10072064, + 10076160, + 10080256, + 10084352, + 10088448, + 10092544, + 10096640, + 10100736, + 10104832, + 10108928, + 10113024, + 10117120, + 10121216, + 10125312, + 10129408, + 10133504, + 10137600, + 10141696, + 10145792, + 10149888, + 10153984, + 10158080, + 10162176, + 10166272, + 10170368, + 10174464, + 10178560, + 10182656, + 10186752, + 10190848, + 10194944, + 10199040, + 10203136, + 10207232, + 10211328, + 10215424, + 10219520, + 10223616, + 10227712, + 10231808, + 10235904, + 10240000, + 10244096, + 10248192, + 10252288, + 10256384, + 10260480, + 10264576, + 10268672, + 10272768, + 10276864, + 10280960, + 10285056, + 10289152, + 10293248, + 10297344, + 10301440, + 10305536, + 10309632, + 10313728, + 10317824, + 10321920, + 10326016, + 10330112, + 10334208, + 10338304, + 10342400, + 10346496, + 10350592, + 10354688, + 10358784, + 10362880, + 10366976, + 10371072, + 10375168, + 10379264, + 10383360, + 10387456, + 10391552, + 10395648, + 10399744, + 10403840, + 10407936, + 10412032, + 10416128, + 10420224, + 10424320, + 10428416, + 10432512, + 10436608, + 10440704, + 10444800, + 10448896, + 10452992, + 10457088, + 10461184, + 10465280, + 10469376, + 10473472, + 10477568, + 10481664, + 10485760, + 10489856, + 10493952, + 10498048, + 10502144, + 10506240, + 10510336, + 10514432, + 10518528, + 10522624, + 10526720, + 10530816, + 10534912, + 10539008, + 10543104, + 10547200, + 10551296, + 10555392, + 10559488, + 10563584, + 10567680, + 10571776, + 10575872, + 10579968, + 10584064, + 10588160, + 10592256, + 10596352, + 10600448, + 10604544, + 10608640, + 10612736, + 10616832, + 10620928, + 10625024, + 10629120, + 10633216, + 10637312, + 10641408, + 10645504, + 10649600, + 10653696, + 10657792, + 10661888, + 10665984, + 10670080, + 10674176, + 10678272, + 10682368, + 10686464, + 10690560, + 10694656, + 10698752, + 10702848, + 10706944, + 10711040, + 10715136, + 10719232, + 10723328, + 10727424, + 10731520, + 10735616, + 10739712, + 10743808, + 10747904, + 10752000, + 10756096, + 10760192, + 10764288, + 10768384, + 10772480, + 10776576, + 10780672, + 10784768, + 10788864, + 10792960, + 10797056, + 10801152, + 10805248, + 10809344, + 10813440, + 10817536, + 10821632, + 10825728, + 10829824, + 10833920, + 10838016, + 10842112, + 10846208, + 10850304, + 10854400, + 10858496, + 10862592, + 10866688, + 10870784, + 10874880, + 10878976, + 10883072, + 10887168, + 10891264, + 10895360, + 10899456, + 10903552, + 10907648, + 10911744, + 10915840, + 10919936, + 10924032, + 10928128, + 10932224, + 10936320, + 10940416, + 10944512, + 10948608, + 10952704, + 10956800, + 10960896, + 10964992, + 10969088, + 10973184, + 10977280, + 10981376, + 10985472, + 10989568, + 10993664, + 10997760, + 11001856, + 11005952, + 11010048, + 11014144, + 11018240, + 11022336, + 11026432, + 11030528, + 11034624, + 11038720, + 11042816, + 11046912, + 11051008, + 11055104, + 11059200, + 11063296, + 11067392, + 11071488, + 11075584, + 11079680, + 11083776, + 11087872, + 11091968, + 11096064, + 11100160, + 11104256, + 11108352, + 11112448, + 11116544, + 11120640, + 11124736, + 11128832, + 11132928, + 11137024, + 11141120, + 11145216, + 11149312, + 11153408, + 11157504, + 11161600, + 11165696, + 11169792, + 11173888, + 11177984, + 11182080, + 11186176, + 11190272, + 11194368, + 11198464, + 11202560, + 11206656, + 11210752, + 11214848, + 11218944, + 11223040, + 11227136, + 11231232, + 11235328, + 11239424, + 11243520, + 11247616, + 11251712, + 11255808, + 11259904, + 11264000, + 11268096, + 11272192, + 11276288, + 11280384, + 11284480, + 11288576, + 11292672, + 11296768, + 11300864, + 11304960, + 11309056, + 11313152, + 11317248, + 11321344, + 11325440, + 11329536, + 11333632, + 11337728, + 11341824, + 11345920, + 11350016, + 11354112, + 11358208, + 11362304, + 11366400, + 11370496, + 11374592, + 11378688, + 11382784, + 11386880, + 11390976, + 11395072, + 11399168, + 11403264, + 11407360, + 11411456, + 11415552, + 11419648, + 11423744, + 11427840, + 11431936, + 11436032, + 11440128, + 11444224, + 11448320, + 11452416, + 11456512, + 11460608, + 11464704, + 11468800, + 11472896, + 11476992, + 11481088, + 11485184, + 11489280, + 11493376, + 11497472, + 11501568, + 11505664, + 11509760, + 11513856, + 11517952, + 11522048, + 11526144, + 11530240, + 11534336, + 11538432, + 11542528, + 11546624, + 11550720, + 11554816, + 11558912, + 11563008, + 11567104, + 11571200, + 11575296, + 11579392, + 11583488, + 11587584, + 11591680, + 11595776, + 11599872, + 11603968, + 11608064, + 11612160, + 11616256, + 11620352, + 11624448, + 11628544, + 11632640, + 11636736, + 11640832, + 11644928, + 11649024, + 11653120, + 11657216, + 11661312, + 11665408, + 11669504, + 11673600, + 11677696, + 11681792, + 11685888, + 11689984, + 11694080, + 11698176, + 11702272, + 11706368, + 11710464, + 11714560, + 11718656, + 11722752, + 11726848, + 11730944, + 11735040, + 11739136, + 11743232, + 11747328, + 11751424, + 11755520, + 11759616, + 11763712, + 11767808, + 11771904, + 11776000, + 11780096, + 11784192, + 11788288, + 11792384, + 11796480, + 11800576, + 11804672, + 11808768, + 11812864, + 11816960, + 11821056, + 11825152, + 11829248, + 11833344, + 11837440, + 11841536, + 11845632, + 11849728, + 11853824, + 11857920, + 11862016, + 11866112, + 11870208, + 11874304, + 11878400, + 11882496, + 11886592, + 11890688, + 11894784, + 11898880, + 11902976, + 11907072, + 11911168, + 11915264, + 11919360, + 11923456, + 11927552, + 11931648, + 11935744, + 11939840, + 11943936, + 11948032, + 11952128, + 11956224, + 11960320, + 11964416, + 11968512, + 11972608, + 11976704, + 11980800, + 11984896, + 11988992, + 11993088, + 11997184, + 12001280, + 12005376, + 12009472, + 12013568, + 12017664, + 12021760, + 12025856, + 12029952, + 12034048, + 12038144, + 12042240, + 12046336, + 12050432, + 12054528, + 12058624, + 12062720, + 12066816, + 12070912, + 12075008, + 12079104, + 12083200, + 12087296, + 12091392, + 12095488, + 12099584, + 12103680, + 12107776, + 12111872, + 12115968, + 12120064, + 12124160, + 12128256, + 12132352, + 12136448, + 12140544, + 12144640, + 12148736, + 12152832, + 12156928, + 12161024, + 12165120, + 12169216, + 12173312, + 12177408, + 12181504, + 12185600, + 12189696, + 12193792, + 12197888, + 12201984, + 12206080, + 12210176, + 12214272, + 12218368, + 12222464, + 12226560, + 12230656, + 12234752, + 12238848, + 12242944, + 12247040, + 12251136, + 12255232, + 12259328, + 12263424, + 12267520, + 12271616, + 12275712, + 12279808, + 12283904, + 12288000, + 12292096, + 12296192, + 12300288, + 12304384, + 12308480, + 12312576, + 12316672, + 12320768, + 12324864, + 12328960, + 12333056, + 12337152, + 12341248, + 12345344, + 12349440, + 12353536, + 12357632, + 12361728, + 12365824, + 12369920, + 12374016, + 12378112, + 12382208, + 12386304, + 12390400, + 12394496, + 12398592, + 12402688, + 12406784, + 12410880, + 12414976, + 12419072, + 12423168, + 12427264, + 12431360, + 12435456, + 12439552, + 12443648, + 12447744, + 12451840, + 12455936, + 12460032, + 12464128, + 12468224, + 12472320, + 12476416, + 12480512, + 12484608, + 12488704, + 12492800, + 12496896, + 12500992, + 12505088, + 12509184, + 12513280, + 12517376, + 12521472, + 12525568, + 12529664, + 12533760, + 12537856, + 12541952, + 12546048, + 12550144, + 12554240, + 12558336, + 12562432, + 12566528, + 12570624, + 12574720, + 12578816, + 12582912, + 12587008, + 12591104, + 12595200, + 12599296, + 12603392, + 12607488, + 12611584, + 12615680, + 12619776, + 12623872, + 12627968, + 12632064, + 12636160, + 12640256, + 12644352, + 12648448, + 12652544, + 12656640, + 12660736, + 12664832, + 12668928, + 12673024, + 12677120, + 12681216, + 12685312, + 12689408, + 12693504, + 12697600, + 12701696, + 12705792, + 12709888, + 12713984, + 12718080, + 12722176, + 12726272, + 12730368, + 12734464, + 12738560, + 12742656, + 12746752, + 12750848, + 12754944, + 12759040, + 12763136, + 12767232, + 12771328, + 12775424, + 12779520, + 12783616, + 12787712, + 12791808, + 12795904, + 12800000, + 12804096, + 12808192, + 12812288, + 12816384, + 12820480, + 12824576, + 12828672, + 12832768, + 12836864, + 12840960, + 12845056, + 12849152, + 12853248, + 12857344, + 12861440, + 12865536, + 12869632, + 12873728, + 12877824, + 12881920, + 12886016, + 12890112, + 12894208, + 12898304, + 12902400, + 12906496, + 12910592, + 12914688, + 12918784, + 12922880, + 12926976, + 12931072, + 12935168, + 12939264, + 12943360, + 12947456, + 12951552, + 12955648, + 12959744, + 12963840, + 12967936, + 12972032, + 12976128, + 12980224, + 12984320, + 12988416, + 12992512, + 12996608, + 13000704, + 13004800, + 13008896, + 13012992, + 13017088, + 13021184, + 13025280, + 13029376, + 13033472, + 13037568, + 13041664, + 13045760, + 13049856, + 13053952, + 13058048, + 13062144, + 13066240, + 13070336, + 13074432, + 13078528, + 13082624, + 13086720, + 13090816, + 13094912, + 13099008, + 13103104, + 13107200, + 13111296, + 13115392, + 13119488, + 13123584, + 13127680, + 13131776, + 13135872, + 13139968, + 13144064, + 13148160, + 13152256, + 13156352, + 13160448, + 13164544, + 13168640, + 13172736, + 13176832, + 13180928, + 13185024, + 13189120, + 13193216, + 13197312, + 13201408, + 13205504, + 13209600, + 13213696, + 13217792, + 13221888, + 13225984, + 13230080, + 13234176, + 13238272, + 13242368, + 13246464, + 13250560, + 13254656, + 13258752, + 13262848, + 13266944, + 13271040, + 13275136, + 13279232, + 13283328, + 13287424, + 13291520, + 13295616, + 13299712, + 13303808, + 13307904, + 13312000, + 13316096, + 13320192, + 13324288, + 13328384, + 13332480, + 13336576, + 13340672, + 13344768, + 13348864, + 13352960, + 13357056, + 13361152, + 13365248, + 13369344, + 13373440, + 13377536, + 13381632, + 13385728, + 13389824, + 13393920, + 13398016, + 13402112, + 13406208, + 13410304, + 13414400, + 13418496, + 13422592, + 13426688, + 13430784, + 13434880, + 13438976, + 13443072, + 13447168, + 13451264, + 13455360, + 13459456, + 13463552, + 13467648, + 13471744, + 13475840, + 13479936, + 13484032, + 13488128, + 13492224, + 13496320, + 13500416, + 13504512, + 13508608, + 13512704, + 13516800, + 13520896, + 13524992, + 13529088, + 13533184, + 13537280, + 13541376, + 13545472, + 13549568, + 13553664, + 13557760, + 13561856, + 13565952, + 13570048, + 13574144, + 13578240, + 13582336, + 13586432, + 13590528, + 13594624, + 13598720, + 13602816, + 13606912, + 13611008, + 13615104, + 13619200, + 13623296, + 13627392, + 13631488, + 13635584, + 13639680, + 13643776, + 13647872, + 13651968, + 13656064, + 13660160, + 13664256, + 13668352, + 13672448, + 13676544, + 13680640, + 13684736, + 13688832, + 13692928, + 13697024, + 13701120, + 13705216, + 13709312, + 13713408, + 13717504, + 13721600, + 13725696, + 13729792, + 13733888, + 13737984, + 13742080, + 13746176, + 13750272, + 13754368, + 13758464, + 13762560, + 13766656, + 13770752, + 13774848, + 13778944, + 13783040, + 13787136, + 13791232, + 13795328, + 13799424, + 13803520, + 13807616, + 13811712, + 13815808, + 13819904, + 13824000, + 13828096, + 13832192, + 13836288, + 13840384, + 13844480, + 13848576, + 13852672, + 13856768, + 13860864, + 13864960, + 13869056, + 13873152, + 13877248, + 13881344, + 13885440, + 13889536, + 13893632, + 13897728, + 13901824, + 13905920, + 13910016, + 13914112, + 13918208, + 13922304, + 13926400, + 13930496, + 13934592, + 13938688, + 13942784, + 13946880, + 13950976, + 13955072, + 13959168, + 13963264, + 13967360, + 13971456, + 13975552, + 13979648, + 13983744, + 13987840, + 13991936, + 13996032, + 14000128, + 14004224, + 14008320, + 14012416, + 14016512, + 14020608, + 14024704, + 14028800, + 14032896, + 14036992, + 14041088, + 14045184, + 14049280, + 14053376, + 14057472, + 14061568, + 14065664, + 14069760, + 14073856, + 14077952, + 14082048, + 14086144, + 14090240, + 14094336, + 14098432, + 14102528, + 14106624, + 14110720, + 14114816, + 14118912, + 14123008, + 14127104, + 14131200, + 14135296, + 14139392, + 14143488, + 14147584, + 14151680, + 14155776, + 14159872, + 14163968, + 14168064, + 14172160, + 14176256, + 14180352, + 14184448, + 14188544, + 14192640, + 14196736, + 14200832, + 14204928, + 14209024, + 14213120, + 14217216, + 14221312, + 14225408, + 14229504, + 14233600, + 14237696, + 14241792, + 14245888, + 14249984, + 14254080, + 14258176, + 14262272, + 14266368, + 14270464, + 14274560, + 14278656, + 14282752, + 14286848, + 14290944, + 14295040, + 14299136, + 14303232, + 14307328, + 14311424, + 14315520, + 14319616, + 14323712, + 14327808, + 14331904, + 14336000, + 14340096, + 14344192, + 14348288, + 14352384, + 14356480, + 14360576, + 14364672, + 14368768, + 14372864, + 14376960, + 14381056, + 14385152, + 14389248, + 14393344, + 14397440, + 14401536, + 14405632, + 14409728, + 14413824, + 14417920, + 14422016, + 14426112, + 14430208, + 14434304, + 14438400, + 14442496, + 14446592, + 14450688, + 14454784, + 14458880, + 14462976, + 14467072, + 14471168, + 14475264, + 14479360, + 14483456, + 14487552, + 14491648, + 14495744, + 14499840, + 14503936, + 14508032, + 14512128, + 14516224, + 14520320, + 14524416, + 14528512, + 14532608, + 14536704, + 14540800, + 14544896, + 14548992, + 14553088, + 14557184, + 14561280, + 14565376, + 14569472, + 14573568, + 14577664, + 14581760, + 14585856, + 14589952, + 14594048, + 14598144, + 14602240, + 14606336, + 14610432, + 14614528, + 14618624, + 14622720, + 14626816, + 14630912, + 14635008, + 14639104, + 14643200, + 14647296, + 14651392, + 14655488, + 14659584, + 14663680, + 14667776, + 14671872, + 14675968, + 14680064, + 14684160, + 14688256, + 14692352, + 14696448, + 14700544, + 14704640, + 14708736, + 14712832, + 14716928, + 14721024, + 14725120, + 14729216, + 14733312, + 14737408, + 14741504, + 14745600, + 14749696, + 14753792, + 14757888, + 14761984, + 14766080, + 14770176, + 14774272, + 14778368, + 14782464, + 14786560, + 14790656, + 14794752, + 14798848, + 14802944, + 14807040, + 14811136, + 14815232, + 14819328, + 14823424, + 14827520, + 14831616, + 14835712, + 14839808, + 14843904, + 14848000, + 14852096, + 14856192, + 14860288, + 14864384, + 14868480, + 14872576, + 14876672, + 14880768, + 14884864, + 14888960, + 14893056, + 14897152, + 14901248, + 14905344, + 14909440, + 14913536, + 14917632, + 14921728, + 14925824, + 14929920, + 14934016, + 14938112, + 14942208, + 14946304, + 14950400, + 14954496, + 14958592, + 14962688, + 14966784, + 14970880, + 14974976, + 14979072, + 14983168, + 14987264, + 14991360, + 14995456, + 14999552, + 15003648, + 15007744, + 15011840, + 15015936, + 15020032, + 15024128, + 15028224, + 15032320, + 15036416, + 15040512, + 15044608, + 15048704, + 15052800, + 15056896, + 15060992, + 15065088, + 15069184, + 15073280, + 15077376, + 15081472, + 15085568, + 15089664, + 15093760, + 15097856, + 15101952, + 15106048, + 15110144, + 15114240, + 15118336, + 15122432, + 15126528, + 15130624, + 15134720, + 15138816, + 15142912, + 15147008, + 15151104, + 15155200, + 15159296, + 15163392, + 15167488, + 15171584, + 15175680, + 15179776, + 15183872, + 15187968, + 15192064, + 15196160, + 15200256, + 15204352, + 15208448, + 15212544, + 15216640, + 15220736, + 15224832, + 15228928, + 15233024, + 15237120, + 15241216, + 15245312, + 15249408, + 15253504, + 15257600, + 15261696, + 15265792, + 15269888, + 15273984, + 15278080, + 15282176, + 15286272, + 15290368, + 15294464, + 15298560, + 15302656, + 15306752, + 15310848, + 15314944, + 15319040, + 15323136, + 15327232, + 15331328, + 15335424, + 15339520, + 15343616, + 15347712, + 15351808, + 15355904, + 15360000, + 15364096, + 15368192, + 15372288, + 15376384, + 15380480, + 15384576, + 15388672, + 15392768, + 15396864, + 15400960, + 15405056, + 15409152, + 15413248, + 15417344, + 15421440, + 15425536, + 15429632, + 15433728, + 15437824, + 15441920, + 15446016, + 15450112, + 15454208, + 15458304, + 15462400, + 15466496, + 15470592, + 15474688, + 15478784, + 15482880, + 15486976, + 15491072, + 15495168, + 15499264, + 15503360, + 15507456, + 15511552, + 15515648, + 15519744, + 15523840, + 15527936, + 15532032, + 15536128, + 15540224, + 15544320, + 15548416, + 15552512, + 15556608, + 15560704, + 15564800, + 15568896, + 15572992, + 15577088, + 15581184, + 15585280, + 15589376, + 15593472, + 15597568, + 15601664, + 15605760, + 15609856, + 15613952, + 15618048, + 15622144, + 15626240, + 15630336, + 15634432, + 15638528, + 15642624, + 15646720, + 15650816, + 15654912, + 15659008, + 15663104, + 15667200, + 15671296, + 15675392, + 15679488, + 15683584, + 15687680, + 15691776, + 15695872, + 15699968, + 15704064, + 15708160, + 15712256, + 15716352, + 15720448, + 15724544, + 15728640, + 15732736, + 15736832, + 15740928, + 15745024, + 15749120, + 15753216, + 15757312, + 15761408, + 15765504, + 15769600, + 15773696, + 15777792, + 15781888, + 15785984, + 15790080, + 15794176, + 15798272, + 15802368, + 15806464, + 15810560, + 15814656, + 15818752, + 15822848, + 15826944, + 15831040, + 15835136, + 15839232, + 15843328, + 15847424, + 15851520, + 15855616, + 15859712, + 15863808, + 15867904, + 15872000, + 15876096, + 15880192, + 15884288, + 15888384, + 15892480, + 15896576, + 15900672, + 15904768, + 15908864, + 15912960, + 15917056, + 15921152, + 15925248, + 15929344, + 15933440, + 15937536, + 15941632, + 15945728, + 15949824, + 15953920, + 15958016, + 15962112, + 15966208, + 15970304, + 15974400, + 15978496, + 15982592, + 15986688, + 15990784, + 15994880, + 15998976, + 16003072, + 16007168, + 16011264, + 16015360, + 16019456, + 16023552, + 16027648, + 16031744, + 16035840, + 16039936, + 16044032, + 16048128, + 16052224, + 16056320, + 16060416, + 16064512, + 16068608, + 16072704, + 16076800, + 16080896, + 16084992, + 16089088, + 16093184, + 16097280, + 16101376, + 16105472, + 16109568, + 16113664, + 16117760, + 16121856, + 16125952, + 16130048, + 16134144, + 16138240, + 16142336, + 16146432, + 16150528, + 16154624, + 16158720, + 16162816, + 16166912, + 16171008, + 16175104, + 16179200, + 16183296, + 16187392, + 16191488, + 16195584, + 16199680, + 16203776, + 16207872, + 16211968, + 16216064, + 16220160, + 16224256, + 16228352, + 16232448, + 16236544, + 16240640, + 16244736, + 16248832, + 16252928, + 16257024, + 16261120, + 16265216, + 16269312, + 16273408, + 16277504, + 16281600, + 16285696, + 16289792, + 16293888, + 16297984, + 16302080, + 16306176, + 16310272, + 16314368, + 16318464, + 16322560, + 16326656, + 16330752, + 16334848, + 16338944, + 16343040, + 16347136, + 16351232, + 16355328, + 16359424, + 16363520, + 16367616, + 16371712, + 16375808, + 16379904, + 16384000, + 16388096, + 16392192, + 16396288, + 16400384, + 16404480, + 16408576, + 16412672, + 16416768, + 16420864, + 16424960, + 16429056, + 16433152, + 16437248, + 16441344, + 16445440, + 16449536, + 16453632, + 16457728, + 16461824, + 16465920, + 16470016, + 16474112, + 16478208, + 16482304, + 16486400, + 16490496, + 16494592, + 16498688, + 16502784, + 16506880, + 16510976, + 16515072, + 16519168, + 16523264, + 16527360, + 16531456, + 16535552, + 16539648, + 16543744, + 16547840, + 16551936, + 16556032, + 16560128, + 16564224, + 16568320, + 16572416, + 16576512, + 16580608, + 16584704, + 16588800, + 16592896, + 16596992, + 16601088, + 16605184, + 16609280, + 16613376, + 16617472, + 16621568, + 16625664, + 16629760, + 16633856, + 16637952, + 16642048, + 16646144, + 16650240, + 16654336, + 16658432, + 16662528, + 16666624, + 16670720, + 16674816, + 16678912, + 16683008, + 16687104, + 16691200, + 16695296, + 16699392, + 16703488, + 16707584, + 16711680, + 16715776, + 16719872, + 16723968, + 16728064, + 16732160, + 16736256, + 16740352, + 16744448, + 16748544, + 16752640, + 16756736, + 16760832, + 16764928, + 16769024, + 16773120, + 16777216 + ], + "rows": "1", + "cols": "4097" + }, + { + "__comment": "CALIBRATION_NOISE_PROFILE", + "type": "FW_API_LUT", + "name": "CALIBRATION_NOISE_PROFILE", + "width": "1", + "value": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "rows": "1", + "cols": "128" + }, + { + "__comment": "CALIBRATION_DEMOSAIC", + "type": "FW_API_LUT", + "name": "CALIBRATION_DEMOSAIC", + "width": "1", + "value": [ + 1, + 17, + 27, + 31, + 34, + 37, + 39, + 41, + 42, + 44, + 45, + 46, + 47, + 48, + 49, + 50, + 51, + 51, + 52, + 53, + 53, + 53, + 54, + 55, + 55, + 56, + 56, + 57, + 57, + 57, + 58, + 58, + 59, + 59, + 59, + 60, + 60, + 60, + 61, + 61, + 61, + 61, + 62, + 62, + 62, + 62, + 63, + 63, + 63, + 63, + 64, + 64, + 64, + 64, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 66, + 66, + 66, + 67, + 67, + 67, + 67, + 67, + 67, + 68, + 68, + 68, + 68, + 68, + 68, + 68, + 69, + 69, + 69, + 69, + 69, + 69, + 70, + 70, + 70, + 70, + 70, + 70, + 70, + 70, + 71, + 71, + 71, + 71, + 71, + 71, + 71, + 71, + 72, + 72, + 72, + 72, + 72, + 72, + 72, + 72, + 72, + 73, + 73, + 73, + 73, + 73, + 73, + 73, + 73, + 73, + 73, + 74, + 74, + 74, + 74, + 74, + 74, + 74, + 74, + 74, + 74 + ], + "rows": "1", + "cols": "128" + }, + { + "__comment": "8-bit normalised noise profile for WDR stitching", + "type": "FW_API_LUT", + "name": "CALIBRATION_WDR_NP_LUT", + "width": "1", + "value": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "rows": "1", + "cols": "128" + }, + { + "__comment": "CALIBRATION_SHADING_RADIAL_R", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_RADIAL_R", + "width": "2", + "value": [ + 4096, + 4110, + 4125, + 4140, + 4154, + 4169, + 4184, + 4199, + 4215, + 4230, + 4245, + 4261, + 4276, + 4292, + 4308, + 4324, + 4340, + 4356, + 4372, + 4388, + 4405, + 4422, + 4438, + 4455, + 4472, + 4489, + 4507, + 4524, + 4542, + 4559, + 4577, + 4595, + 4613, + 4631, + 4650, + 4668, + 4687, + 4706, + 4725, + 4744, + 4763, + 4783, + 4803, + 4822, + 4842, + 4863, + 4883, + 4903, + 4924, + 4945, + 4966, + 4987, + 5009, + 5030, + 5052, + 5074, + 5096, + 5118, + 5141, + 5163, + 5186, + 5209, + 5233, + 5256, + 5280, + 5304, + 5328, + 5352, + 5376, + 5401, + 5426, + 5451, + 5476, + 5502, + 5527, + 5553, + 5579, + 5605, + 5632, + 5659, + 5686, + 5713, + 5740, + 5767, + 5795, + 5823, + 5851, + 5880, + 5908, + 5937, + 5966, + 5995, + 6024, + 6054, + 6083, + 6113, + 6143, + 6174, + 6204, + 6235, + 6266, + 6297, + 6328, + 6359, + 6390, + 6422, + 6454, + 6486, + 6518, + 6550, + 6582, + 6615, + 6647, + 6680, + 6713, + 6746, + 6779, + 6812, + 6845, + 6878, + 6911, + 6944, + 6978, + 7011, + 7044, + 7077, + 7111, + 7144, + 7177 + ], + "rows": "1", + "cols": "129" + }, + { + "__comment": "CALIBRATION_SHADING_RADIAL_G", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_RADIAL_G", + "width": "2", + "value": [ + 4096, + 4111, + 4125, + 4140, + 4155, + 4170, + 4184, + 4200, + 4215, + 4230, + 4245, + 4261, + 4276, + 4292, + 4308, + 4324, + 4340, + 4356, + 4372, + 4389, + 4405, + 4422, + 4439, + 4455, + 4472, + 4490, + 4507, + 4524, + 4542, + 4559, + 4577, + 4595, + 4613, + 4632, + 4650, + 4669, + 4687, + 4706, + 4725, + 4744, + 4764, + 4783, + 4803, + 4823, + 4843, + 4863, + 4883, + 4903, + 4924, + 4945, + 4966, + 4987, + 5009, + 5030, + 5052, + 5074, + 5096, + 5118, + 5141, + 5163, + 5186, + 5209, + 5233, + 5256, + 5280, + 5304, + 5328, + 5352, + 5376, + 5401, + 5426, + 5451, + 5476, + 5502, + 5527, + 5553, + 5579, + 5606, + 5632, + 5659, + 5686, + 5713, + 5740, + 5768, + 5796, + 5824, + 5852, + 5880, + 5909, + 5937, + 5966, + 5996, + 6025, + 6054, + 6084, + 6114, + 6144, + 6175, + 6205, + 6236, + 6266, + 6297, + 6329, + 6360, + 6391, + 6423, + 6455, + 6487, + 6519, + 6551, + 6583, + 6615, + 6648, + 6681, + 6713, + 6746, + 6779, + 6812, + 6845, + 6878, + 6911, + 6944, + 6977, + 7010, + 7043, + 7076, + 7109, + 7142, + 7175 + ], + "rows": "1", + "cols": "129" + }, + { + "__comment": "CALIBRATION_SHADING_RADIAL_B", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_RADIAL_B", + "width": "2", + "value": [ + 4096, + 4111, + 4125, + 4140, + 4155, + 4170, + 4185, + 4200, + 4215, + 4230, + 4246, + 4261, + 4277, + 4293, + 4308, + 4324, + 4340, + 4356, + 4373, + 4389, + 4406, + 4422, + 4439, + 4456, + 4473, + 4490, + 4507, + 4525, + 4542, + 4560, + 4577, + 4595, + 4614, + 4632, + 4650, + 4669, + 4687, + 4706, + 4725, + 4744, + 4764, + 4783, + 4803, + 4823, + 4843, + 4863, + 4883, + 4903, + 4924, + 4945, + 4966, + 4987, + 5009, + 5030, + 5052, + 5074, + 5096, + 5118, + 5141, + 5164, + 5186, + 5210, + 5233, + 5256, + 5280, + 5304, + 5328, + 5352, + 5377, + 5402, + 5427, + 5452, + 5477, + 5503, + 5528, + 5554, + 5581, + 5607, + 5634, + 5660, + 5687, + 5715, + 5742, + 5770, + 5798, + 5826, + 5854, + 5882, + 5911, + 5940, + 5969, + 5998, + 6028, + 6057, + 6087, + 6117, + 6147, + 6178, + 6208, + 6239, + 6270, + 6301, + 6332, + 6363, + 6395, + 6426, + 6458, + 6490, + 6522, + 6554, + 6586, + 6618, + 6651, + 6683, + 6716, + 6748, + 6781, + 6813, + 6846, + 6879, + 6911, + 6944, + 6977, + 7009, + 7042, + 7075, + 7107, + 7139, + 7171 + ], + "rows": "1", + "cols": "129" + }, + { + "__comment": "CALIBRATION_SHADING_RADIAL_IR", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_RADIAL_IR", + "width": "2", + "value": [ + 4096, + 4111, + 4125, + 4140, + 4155, + 4170, + 4184, + 4200, + 4215, + 4230, + 4245, + 4261, + 4276, + 4292, + 4308, + 4324, + 4340, + 4356, + 4372, + 4389, + 4405, + 4422, + 4439, + 4455, + 4472, + 4490, + 4507, + 4524, + 4542, + 4559, + 4577, + 4595, + 4613, + 4632, + 4650, + 4669, + 4687, + 4706, + 4725, + 4744, + 4764, + 4783, + 4803, + 4823, + 4843, + 4863, + 4883, + 4903, + 4924, + 4945, + 4966, + 4987, + 5009, + 5030, + 5052, + 5074, + 5096, + 5118, + 5141, + 5163, + 5186, + 5209, + 5233, + 5256, + 5280, + 5304, + 5328, + 5352, + 5376, + 5401, + 5426, + 5451, + 5476, + 5502, + 5527, + 5553, + 5579, + 5606, + 5632, + 5659, + 5686, + 5713, + 5740, + 5768, + 5796, + 5824, + 5852, + 5880, + 5909, + 5937, + 5966, + 5996, + 6025, + 6054, + 6084, + 6114, + 6144, + 6175, + 6205, + 6236, + 6266, + 6297, + 6329, + 6360, + 6391, + 6423, + 6455, + 6487, + 6519, + 6551, + 6583, + 6615, + 6648, + 6681, + 6713, + 6746, + 6779, + 6812, + 6845, + 6878, + 6911, + 6944, + 6977, + 7010, + 7043, + 7076, + 7109, + 7142, + 7175 + ], + "rows": "1", + "cols": "129" + }, + { + "__comment": "RX RY MULTRX MULTRY GX GY MULTGX MULTGY BX BY MULTBX MULTBY IRX IRY MULTIRX MULTIRY", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_RADIAL_CENTRE_AND_MULT", + "width": "2", + "value": [ + 49, + 33, + 65535, + 65535, + 49, + 32, + 65535, + 65535, + 48, + 32, + 65535, + 65535, + 49, + 32, + 65535, + 65535 + ], + "rows": "1", + "cols": "16" + }, + { + "__comment": "CALIBRATION_SHADING_LS_A_R", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_LS_A_R", + "width": "1", + "value": [ + 113, + 107, + 101, + 96, + 92, + 88, + 85, + 83, + 81, + 79, + 77, + 76, + 75, + 75, + 74, + 74, + 74, + 74, + 75, + 75, + 76, + 78, + 80, + 81, + 84, + 86, + 89, + 93, + 98, + 103, + 109, + 115, + 110, + 105, + 99, + 94, + 90, + 87, + 84, + 81, + 79, + 78, + 76, + 75, + 74, + 73, + 73, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 78, + 80, + 82, + 85, + 88, + 91, + 96, + 101, + 107, + 113, + 107, + 102, + 97, + 92, + 88, + 85, + 82, + 80, + 78, + 76, + 75, + 73, + 73, + 72, + 72, + 71, + 72, + 72, + 72, + 73, + 74, + 75, + 77, + 78, + 81, + 83, + 86, + 89, + 93, + 98, + 104, + 110, + 105, + 100, + 95, + 90, + 86, + 83, + 81, + 78, + 76, + 75, + 73, + 72, + 71, + 71, + 71, + 70, + 70, + 71, + 71, + 72, + 72, + 74, + 75, + 77, + 79, + 82, + 84, + 88, + 92, + 96, + 102, + 107, + 103, + 98, + 93, + 88, + 85, + 82, + 79, + 77, + 75, + 74, + 72, + 71, + 70, + 70, + 69, + 69, + 69, + 70, + 70, + 71, + 71, + 73, + 74, + 76, + 78, + 80, + 83, + 86, + 90, + 94, + 100, + 105, + 101, + 96, + 91, + 87, + 84, + 81, + 78, + 76, + 74, + 73, + 71, + 70, + 69, + 69, + 69, + 68, + 68, + 69, + 69, + 70, + 70, + 72, + 73, + 75, + 77, + 79, + 82, + 85, + 88, + 93, + 98, + 103, + 99, + 94, + 90, + 86, + 82, + 79, + 77, + 75, + 73, + 72, + 70, + 69, + 69, + 68, + 68, + 68, + 68, + 68, + 68, + 69, + 70, + 71, + 72, + 74, + 76, + 78, + 80, + 83, + 87, + 91, + 96, + 101, + 97, + 93, + 88, + 84, + 81, + 78, + 76, + 74, + 72, + 71, + 70, + 69, + 68, + 67, + 67, + 67, + 67, + 67, + 67, + 68, + 69, + 70, + 71, + 73, + 75, + 77, + 79, + 82, + 86, + 90, + 95, + 99, + 96, + 91, + 87, + 83, + 80, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 67, + 67, + 68, + 69, + 71, + 72, + 74, + 76, + 78, + 81, + 84, + 88, + 93, + 98, + 94, + 90, + 86, + 82, + 79, + 77, + 74, + 72, + 71, + 69, + 68, + 67, + 66, + 66, + 66, + 65, + 65, + 66, + 66, + 67, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 92, + 96, + 93, + 89, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 69, + 71, + 72, + 74, + 77, + 79, + 83, + 86, + 91, + 95, + 93, + 89, + 85, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 95, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 64, + 64, + 65, + 65, + 65, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 85, + 90, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 72, + 73, + 76, + 78, + 82, + 85, + 89, + 94, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 94, + 93, + 89, + 85, + 81, + 78, + 76, + 73, + 72, + 70, + 69, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 67, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 91, + 95, + 94, + 90, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 91, + 96, + 95, + 91, + 86, + 83, + 79, + 77, + 75, + 73, + 71, + 70, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 66, + 66, + 67, + 68, + 69, + 70, + 72, + 73, + 75, + 78, + 80, + 84, + 88, + 92, + 97, + 96, + 92, + 87, + 84, + 81, + 78, + 75, + 73, + 72, + 70, + 69, + 68, + 67, + 67, + 67, + 66, + 66, + 67, + 67, + 68, + 68, + 69, + 71, + 72, + 74, + 76, + 79, + 82, + 85, + 89, + 94, + 98, + 98, + 94, + 89, + 85, + 82, + 79, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 68, + 67, + 67, + 67, + 67, + 68, + 68, + 69, + 70, + 72, + 73, + 75, + 77, + 80, + 83, + 86, + 90, + 95, + 100, + 100, + 95, + 90, + 86, + 83, + 80, + 78, + 75, + 74, + 72, + 71, + 70, + 69, + 68, + 68, + 68, + 68, + 68, + 69, + 69, + 70, + 71, + 73, + 74, + 76, + 78, + 81, + 84, + 88, + 92, + 97, + 102, + 102, + 97, + 92, + 88, + 84, + 81, + 79, + 77, + 75, + 73, + 72, + 71, + 70, + 69, + 69, + 69, + 69, + 69, + 69, + 70, + 71, + 72, + 74, + 75, + 77, + 79, + 82, + 85, + 89, + 93, + 99, + 104, + 104, + 99, + 94, + 89, + 86, + 83, + 80, + 78, + 76, + 74, + 73, + 72, + 71, + 70, + 70, + 70, + 70, + 70, + 70, + 71, + 72, + 73, + 75, + 76, + 78, + 81, + 84, + 87, + 91, + 95, + 101, + 106, + 106, + 101, + 96, + 91, + 87, + 84, + 81, + 79, + 77, + 76, + 74, + 73, + 72, + 71, + 71, + 71, + 71, + 71, + 72, + 72, + 73, + 74, + 76, + 78, + 80, + 82, + 85, + 88, + 92, + 97, + 103, + 109, + 109, + 103, + 98, + 93, + 89, + 86, + 83, + 81, + 79, + 77, + 75, + 74, + 73, + 73, + 72, + 72, + 72, + 72, + 73, + 73, + 74, + 76, + 77, + 79, + 81, + 84, + 87, + 90, + 95, + 100, + 105, + 111, + 111, + 106, + 100, + 95, + 91, + 87, + 84, + 82, + 80, + 78, + 77, + 75, + 74, + 74, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 77, + 79, + 81, + 83, + 85, + 88, + 92, + 96, + 102, + 108, + 114, + 114, + 107, + 101, + 96, + 92, + 89, + 86, + 83, + 81, + 79, + 78, + 76, + 75, + 75, + 74, + 74, + 74, + 75, + 75, + 76, + 77, + 78, + 80, + 82, + 84, + 87, + 90, + 94, + 98, + 103, + 110, + 116 + ], + "rows": "1", + "cols": "1024" + }, + { + "__comment": "CALIBRATION_SHADING_LS_A_G", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_LS_A_G", + "width": "1", + "value": [ + 113, + 107, + 101, + 96, + 92, + 88, + 85, + 83, + 81, + 79, + 77, + 76, + 75, + 75, + 74, + 74, + 74, + 74, + 75, + 75, + 76, + 78, + 80, + 81, + 84, + 86, + 89, + 93, + 98, + 103, + 109, + 115, + 110, + 105, + 99, + 94, + 90, + 87, + 84, + 81, + 79, + 78, + 76, + 75, + 74, + 73, + 73, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 78, + 80, + 82, + 85, + 88, + 91, + 96, + 101, + 107, + 113, + 107, + 102, + 97, + 92, + 88, + 85, + 82, + 80, + 78, + 76, + 75, + 73, + 73, + 72, + 72, + 71, + 72, + 72, + 72, + 73, + 74, + 75, + 77, + 78, + 81, + 83, + 86, + 89, + 93, + 98, + 104, + 110, + 105, + 100, + 95, + 90, + 86, + 83, + 81, + 78, + 76, + 75, + 73, + 72, + 71, + 71, + 70, + 70, + 70, + 71, + 71, + 72, + 72, + 74, + 75, + 77, + 79, + 81, + 84, + 88, + 92, + 96, + 102, + 107, + 103, + 98, + 93, + 88, + 85, + 82, + 79, + 77, + 75, + 74, + 72, + 71, + 70, + 70, + 69, + 69, + 69, + 70, + 70, + 71, + 71, + 73, + 74, + 76, + 78, + 80, + 83, + 86, + 90, + 94, + 100, + 105, + 101, + 96, + 91, + 87, + 84, + 81, + 78, + 76, + 74, + 73, + 71, + 70, + 69, + 69, + 69, + 68, + 68, + 69, + 69, + 70, + 70, + 72, + 73, + 75, + 77, + 79, + 82, + 85, + 88, + 93, + 98, + 103, + 99, + 94, + 90, + 86, + 82, + 79, + 77, + 75, + 73, + 72, + 70, + 69, + 69, + 68, + 68, + 68, + 68, + 68, + 68, + 69, + 70, + 71, + 72, + 74, + 76, + 78, + 80, + 83, + 87, + 91, + 96, + 101, + 97, + 93, + 88, + 84, + 81, + 78, + 76, + 74, + 72, + 71, + 70, + 69, + 68, + 67, + 67, + 67, + 67, + 67, + 67, + 68, + 69, + 70, + 71, + 73, + 75, + 77, + 79, + 82, + 86, + 90, + 95, + 99, + 96, + 91, + 87, + 83, + 80, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 67, + 67, + 68, + 69, + 71, + 72, + 74, + 76, + 78, + 81, + 84, + 88, + 93, + 98, + 94, + 90, + 86, + 82, + 79, + 77, + 74, + 72, + 71, + 69, + 68, + 67, + 66, + 66, + 66, + 65, + 65, + 66, + 66, + 67, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 92, + 96, + 93, + 89, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 69, + 71, + 72, + 74, + 77, + 79, + 83, + 86, + 91, + 95, + 93, + 89, + 85, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 95, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 64, + 64, + 65, + 65, + 65, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 85, + 90, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 72, + 73, + 76, + 78, + 82, + 85, + 89, + 94, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 94, + 93, + 89, + 85, + 81, + 78, + 76, + 73, + 72, + 70, + 69, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 67, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 91, + 95, + 94, + 90, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 91, + 96, + 95, + 91, + 86, + 83, + 79, + 77, + 75, + 73, + 71, + 70, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 66, + 66, + 67, + 68, + 69, + 70, + 72, + 73, + 75, + 78, + 80, + 84, + 88, + 92, + 97, + 96, + 92, + 87, + 84, + 81, + 78, + 75, + 73, + 72, + 70, + 69, + 68, + 67, + 67, + 67, + 66, + 66, + 67, + 67, + 68, + 68, + 69, + 71, + 72, + 74, + 76, + 79, + 82, + 85, + 89, + 94, + 98, + 98, + 94, + 89, + 85, + 82, + 79, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 68, + 67, + 67, + 67, + 67, + 68, + 68, + 69, + 70, + 72, + 73, + 75, + 77, + 80, + 83, + 86, + 90, + 95, + 100, + 100, + 95, + 90, + 86, + 83, + 80, + 78, + 75, + 74, + 72, + 71, + 70, + 69, + 68, + 68, + 68, + 68, + 68, + 69, + 69, + 70, + 71, + 73, + 74, + 76, + 78, + 81, + 84, + 88, + 92, + 97, + 102, + 102, + 97, + 92, + 88, + 84, + 81, + 79, + 77, + 75, + 73, + 72, + 71, + 70, + 69, + 69, + 69, + 69, + 69, + 69, + 70, + 71, + 72, + 74, + 75, + 77, + 79, + 82, + 85, + 89, + 93, + 99, + 104, + 104, + 99, + 94, + 89, + 86, + 83, + 80, + 78, + 76, + 74, + 73, + 72, + 71, + 70, + 70, + 70, + 70, + 70, + 70, + 71, + 72, + 73, + 75, + 76, + 78, + 81, + 84, + 87, + 91, + 95, + 101, + 106, + 106, + 101, + 96, + 91, + 87, + 84, + 81, + 79, + 77, + 76, + 74, + 73, + 72, + 71, + 71, + 71, + 71, + 71, + 72, + 72, + 73, + 74, + 76, + 78, + 80, + 82, + 85, + 88, + 92, + 97, + 103, + 109, + 109, + 103, + 98, + 93, + 89, + 86, + 83, + 81, + 79, + 77, + 75, + 74, + 73, + 73, + 72, + 72, + 72, + 72, + 73, + 73, + 74, + 76, + 77, + 79, + 81, + 84, + 87, + 90, + 95, + 100, + 105, + 111, + 111, + 106, + 100, + 95, + 91, + 87, + 84, + 82, + 80, + 78, + 77, + 75, + 74, + 74, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 77, + 79, + 81, + 83, + 85, + 89, + 92, + 96, + 102, + 108, + 114, + 114, + 107, + 101, + 96, + 92, + 89, + 86, + 83, + 81, + 79, + 78, + 76, + 75, + 75, + 74, + 74, + 74, + 75, + 75, + 76, + 77, + 78, + 80, + 82, + 84, + 87, + 90, + 94, + 98, + 103, + 110, + 116 + ], + "rows": "1", + "cols": "1024" + }, + { + "__comment": "CALIBRATION_SHADING_LS_A_B", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_LS_A_B", + "width": "1", + "value": [ + 113, + 107, + 101, + 96, + 92, + 88, + 85, + 83, + 81, + 79, + 77, + 76, + 75, + 75, + 74, + 74, + 74, + 74, + 75, + 75, + 76, + 78, + 80, + 81, + 84, + 86, + 89, + 93, + 98, + 103, + 109, + 115, + 110, + 105, + 99, + 94, + 90, + 87, + 84, + 81, + 79, + 78, + 76, + 75, + 74, + 73, + 73, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 78, + 80, + 82, + 85, + 88, + 91, + 96, + 101, + 107, + 113, + 107, + 102, + 97, + 92, + 88, + 85, + 82, + 80, + 78, + 76, + 75, + 73, + 73, + 72, + 72, + 71, + 72, + 72, + 72, + 73, + 74, + 75, + 77, + 78, + 81, + 83, + 86, + 89, + 93, + 98, + 104, + 110, + 105, + 100, + 95, + 90, + 86, + 83, + 81, + 78, + 76, + 75, + 73, + 72, + 71, + 71, + 70, + 70, + 70, + 71, + 71, + 72, + 72, + 74, + 75, + 77, + 79, + 81, + 84, + 88, + 92, + 96, + 102, + 107, + 103, + 98, + 93, + 88, + 85, + 82, + 79, + 77, + 75, + 74, + 72, + 71, + 70, + 70, + 69, + 69, + 69, + 70, + 70, + 71, + 71, + 73, + 74, + 76, + 78, + 80, + 83, + 86, + 90, + 94, + 100, + 105, + 101, + 96, + 91, + 87, + 84, + 81, + 78, + 76, + 74, + 73, + 71, + 70, + 69, + 69, + 69, + 68, + 68, + 69, + 69, + 70, + 70, + 72, + 73, + 75, + 77, + 79, + 82, + 85, + 88, + 93, + 98, + 103, + 99, + 94, + 90, + 86, + 82, + 79, + 77, + 75, + 73, + 72, + 70, + 69, + 69, + 68, + 68, + 68, + 68, + 68, + 68, + 69, + 70, + 71, + 72, + 74, + 76, + 78, + 80, + 83, + 87, + 91, + 96, + 101, + 97, + 93, + 88, + 84, + 81, + 78, + 76, + 74, + 72, + 71, + 70, + 68, + 68, + 67, + 67, + 67, + 67, + 67, + 67, + 68, + 69, + 70, + 71, + 73, + 75, + 77, + 79, + 82, + 86, + 90, + 95, + 99, + 96, + 91, + 87, + 83, + 80, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 67, + 67, + 68, + 69, + 70, + 72, + 74, + 76, + 78, + 81, + 84, + 88, + 93, + 98, + 94, + 90, + 86, + 82, + 79, + 77, + 74, + 72, + 71, + 69, + 68, + 67, + 66, + 66, + 66, + 65, + 65, + 66, + 66, + 67, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 92, + 96, + 93, + 89, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 69, + 71, + 72, + 74, + 77, + 79, + 83, + 86, + 91, + 95, + 93, + 89, + 85, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 95, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 64, + 64, + 65, + 65, + 65, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 85, + 90, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 72, + 73, + 76, + 78, + 82, + 85, + 89, + 94, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 94, + 93, + 89, + 85, + 81, + 78, + 76, + 73, + 72, + 70, + 69, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 67, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 91, + 95, + 94, + 90, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 91, + 96, + 95, + 91, + 86, + 83, + 79, + 77, + 75, + 73, + 71, + 70, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 66, + 66, + 67, + 68, + 69, + 70, + 72, + 73, + 75, + 78, + 80, + 84, + 88, + 92, + 97, + 96, + 92, + 87, + 84, + 81, + 78, + 75, + 73, + 72, + 70, + 69, + 68, + 67, + 67, + 66, + 66, + 66, + 67, + 67, + 68, + 68, + 69, + 71, + 72, + 74, + 76, + 79, + 82, + 85, + 89, + 94, + 98, + 98, + 94, + 89, + 85, + 82, + 79, + 77, + 74, + 73, + 71, + 70, + 69, + 68, + 68, + 67, + 67, + 67, + 67, + 68, + 68, + 69, + 70, + 72, + 73, + 75, + 77, + 80, + 83, + 86, + 90, + 95, + 100, + 100, + 95, + 90, + 86, + 83, + 80, + 78, + 75, + 74, + 72, + 71, + 70, + 69, + 68, + 68, + 68, + 68, + 68, + 69, + 69, + 70, + 71, + 73, + 74, + 76, + 78, + 81, + 84, + 88, + 92, + 97, + 102, + 102, + 97, + 92, + 88, + 84, + 81, + 79, + 77, + 75, + 73, + 72, + 71, + 70, + 69, + 69, + 69, + 69, + 69, + 69, + 70, + 71, + 72, + 74, + 75, + 77, + 79, + 82, + 85, + 89, + 93, + 99, + 104, + 104, + 99, + 94, + 89, + 86, + 83, + 80, + 78, + 76, + 74, + 73, + 72, + 71, + 70, + 70, + 70, + 70, + 70, + 70, + 71, + 72, + 73, + 75, + 76, + 78, + 81, + 84, + 87, + 91, + 95, + 101, + 106, + 106, + 101, + 96, + 91, + 87, + 84, + 81, + 79, + 77, + 76, + 74, + 73, + 72, + 71, + 71, + 71, + 71, + 71, + 72, + 72, + 73, + 74, + 76, + 78, + 80, + 82, + 85, + 88, + 92, + 97, + 103, + 109, + 109, + 103, + 98, + 93, + 89, + 86, + 83, + 81, + 79, + 77, + 75, + 74, + 73, + 73, + 72, + 72, + 72, + 72, + 73, + 73, + 74, + 76, + 77, + 79, + 81, + 84, + 87, + 90, + 95, + 100, + 105, + 111, + 111, + 106, + 100, + 95, + 91, + 87, + 84, + 82, + 80, + 78, + 77, + 75, + 74, + 74, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 77, + 79, + 81, + 83, + 85, + 89, + 92, + 96, + 102, + 108, + 114, + 114, + 107, + 101, + 96, + 92, + 89, + 86, + 83, + 81, + 79, + 78, + 76, + 75, + 75, + 74, + 74, + 74, + 75, + 75, + 76, + 77, + 78, + 80, + 82, + 84, + 87, + 90, + 94, + 98, + 103, + 110, + 116 + ], + "rows": "1", + "cols": "1024" + }, + { + "__comment": "CALIBRATION_SHADING_LS_TL84_R", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_LS_TL84_R", + "width": "1", + "value": [ + 113, + 107, + 101, + 96, + 92, + 88, + 85, + 83, + 81, + 79, + 77, + 76, + 75, + 75, + 74, + 74, + 74, + 74, + 75, + 75, + 76, + 78, + 80, + 81, + 84, + 86, + 89, + 93, + 98, + 103, + 109, + 115, + 110, + 105, + 99, + 94, + 90, + 87, + 84, + 81, + 79, + 78, + 76, + 75, + 74, + 73, + 73, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 78, + 80, + 82, + 85, + 88, + 91, + 96, + 101, + 107, + 113, + 107, + 102, + 97, + 92, + 88, + 85, + 82, + 80, + 78, + 76, + 75, + 73, + 73, + 72, + 72, + 71, + 72, + 72, + 72, + 73, + 74, + 75, + 77, + 78, + 81, + 83, + 86, + 89, + 93, + 98, + 104, + 110, + 105, + 100, + 95, + 90, + 86, + 83, + 81, + 78, + 76, + 75, + 73, + 72, + 71, + 71, + 71, + 70, + 70, + 71, + 71, + 72, + 72, + 74, + 75, + 77, + 79, + 82, + 84, + 88, + 92, + 96, + 102, + 107, + 103, + 98, + 93, + 88, + 85, + 82, + 79, + 77, + 75, + 74, + 72, + 71, + 70, + 70, + 69, + 69, + 69, + 70, + 70, + 71, + 71, + 73, + 74, + 76, + 78, + 80, + 83, + 86, + 90, + 94, + 100, + 105, + 101, + 96, + 91, + 87, + 84, + 81, + 78, + 76, + 74, + 73, + 71, + 70, + 69, + 69, + 69, + 68, + 68, + 69, + 69, + 70, + 70, + 72, + 73, + 75, + 77, + 79, + 82, + 85, + 88, + 93, + 98, + 103, + 99, + 94, + 90, + 86, + 82, + 79, + 77, + 75, + 73, + 72, + 70, + 69, + 69, + 68, + 68, + 68, + 68, + 68, + 68, + 69, + 70, + 71, + 72, + 74, + 76, + 78, + 80, + 83, + 87, + 91, + 96, + 101, + 97, + 93, + 88, + 84, + 81, + 78, + 76, + 74, + 72, + 71, + 70, + 69, + 68, + 67, + 67, + 67, + 67, + 67, + 67, + 68, + 69, + 70, + 71, + 73, + 75, + 77, + 79, + 82, + 86, + 90, + 95, + 99, + 96, + 91, + 87, + 83, + 80, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 67, + 67, + 68, + 69, + 71, + 72, + 74, + 76, + 78, + 81, + 84, + 88, + 93, + 98, + 94, + 90, + 86, + 82, + 79, + 77, + 74, + 72, + 71, + 69, + 68, + 67, + 66, + 66, + 66, + 65, + 65, + 66, + 66, + 67, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 92, + 96, + 93, + 89, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 69, + 71, + 72, + 74, + 77, + 79, + 83, + 86, + 91, + 95, + 93, + 89, + 85, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 95, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 64, + 64, + 65, + 65, + 65, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 85, + 90, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 72, + 73, + 76, + 78, + 82, + 85, + 89, + 94, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 94, + 93, + 89, + 85, + 81, + 78, + 76, + 73, + 72, + 70, + 69, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 67, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 91, + 95, + 94, + 90, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 91, + 96, + 95, + 91, + 86, + 83, + 79, + 77, + 75, + 73, + 71, + 70, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 66, + 66, + 67, + 68, + 69, + 70, + 72, + 73, + 75, + 78, + 80, + 84, + 88, + 92, + 97, + 96, + 92, + 87, + 84, + 81, + 78, + 75, + 73, + 72, + 70, + 69, + 68, + 67, + 67, + 67, + 66, + 66, + 67, + 67, + 68, + 68, + 69, + 71, + 72, + 74, + 76, + 79, + 82, + 85, + 89, + 94, + 98, + 98, + 94, + 89, + 85, + 82, + 79, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 68, + 67, + 67, + 67, + 67, + 68, + 68, + 69, + 70, + 72, + 73, + 75, + 77, + 80, + 83, + 86, + 90, + 95, + 100, + 100, + 95, + 90, + 86, + 83, + 80, + 78, + 75, + 74, + 72, + 71, + 70, + 69, + 68, + 68, + 68, + 68, + 68, + 69, + 69, + 70, + 71, + 73, + 74, + 76, + 78, + 81, + 84, + 88, + 92, + 97, + 102, + 102, + 97, + 92, + 88, + 84, + 81, + 79, + 77, + 75, + 73, + 72, + 71, + 70, + 69, + 69, + 69, + 69, + 69, + 69, + 70, + 71, + 72, + 74, + 75, + 77, + 79, + 82, + 85, + 89, + 93, + 99, + 104, + 104, + 99, + 94, + 89, + 86, + 83, + 80, + 78, + 76, + 74, + 73, + 72, + 71, + 70, + 70, + 70, + 70, + 70, + 70, + 71, + 72, + 73, + 75, + 76, + 78, + 81, + 84, + 87, + 91, + 95, + 101, + 106, + 106, + 101, + 96, + 91, + 87, + 84, + 81, + 79, + 77, + 76, + 74, + 73, + 72, + 71, + 71, + 71, + 71, + 71, + 72, + 72, + 73, + 74, + 76, + 78, + 80, + 82, + 85, + 88, + 92, + 97, + 103, + 109, + 109, + 103, + 98, + 93, + 89, + 86, + 83, + 81, + 79, + 77, + 75, + 74, + 73, + 73, + 72, + 72, + 72, + 72, + 73, + 73, + 74, + 76, + 77, + 79, + 81, + 84, + 87, + 90, + 95, + 100, + 105, + 111, + 111, + 106, + 100, + 95, + 91, + 87, + 84, + 82, + 80, + 78, + 77, + 75, + 74, + 74, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 77, + 79, + 81, + 83, + 85, + 88, + 92, + 96, + 102, + 108, + 114, + 114, + 107, + 101, + 96, + 92, + 89, + 86, + 83, + 81, + 79, + 78, + 76, + 75, + 75, + 74, + 74, + 74, + 75, + 75, + 76, + 77, + 78, + 80, + 82, + 84, + 87, + 90, + 94, + 98, + 103, + 110, + 116 + ], + "rows": "1", + "cols": "1024" + }, + { + "__comment": "CALIBRATION_SHADING_LS_TL84_G", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_LS_TL84_G", + "width": "1", + "value": [ + 113, + 107, + 101, + 96, + 92, + 88, + 85, + 83, + 81, + 79, + 77, + 76, + 75, + 75, + 74, + 74, + 74, + 74, + 75, + 75, + 76, + 78, + 80, + 81, + 84, + 86, + 89, + 93, + 98, + 103, + 109, + 115, + 110, + 105, + 99, + 94, + 90, + 87, + 84, + 81, + 79, + 78, + 76, + 75, + 74, + 73, + 73, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 78, + 80, + 82, + 85, + 88, + 91, + 96, + 101, + 107, + 113, + 107, + 102, + 97, + 92, + 88, + 85, + 82, + 80, + 78, + 76, + 75, + 73, + 73, + 72, + 72, + 71, + 72, + 72, + 72, + 73, + 74, + 75, + 77, + 78, + 81, + 83, + 86, + 89, + 93, + 98, + 104, + 110, + 105, + 100, + 95, + 90, + 86, + 83, + 81, + 78, + 76, + 75, + 73, + 72, + 71, + 71, + 70, + 70, + 70, + 71, + 71, + 72, + 72, + 74, + 75, + 77, + 79, + 81, + 84, + 88, + 92, + 96, + 102, + 107, + 103, + 98, + 93, + 88, + 85, + 82, + 79, + 77, + 75, + 74, + 72, + 71, + 70, + 70, + 69, + 69, + 69, + 70, + 70, + 71, + 71, + 73, + 74, + 76, + 78, + 80, + 83, + 86, + 90, + 94, + 100, + 105, + 101, + 96, + 91, + 87, + 84, + 81, + 78, + 76, + 74, + 73, + 71, + 70, + 69, + 69, + 69, + 68, + 68, + 69, + 69, + 70, + 70, + 72, + 73, + 75, + 77, + 79, + 82, + 85, + 88, + 93, + 98, + 103, + 99, + 94, + 90, + 86, + 82, + 79, + 77, + 75, + 73, + 72, + 70, + 69, + 69, + 68, + 68, + 68, + 68, + 68, + 68, + 69, + 70, + 71, + 72, + 74, + 76, + 78, + 80, + 83, + 87, + 91, + 96, + 101, + 97, + 93, + 88, + 84, + 81, + 78, + 76, + 74, + 72, + 71, + 70, + 69, + 68, + 67, + 67, + 67, + 67, + 67, + 67, + 68, + 69, + 70, + 71, + 73, + 75, + 77, + 79, + 82, + 86, + 90, + 95, + 99, + 96, + 91, + 87, + 83, + 80, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 67, + 67, + 68, + 69, + 71, + 72, + 74, + 76, + 78, + 81, + 84, + 88, + 93, + 98, + 94, + 90, + 86, + 82, + 79, + 77, + 74, + 72, + 71, + 69, + 68, + 67, + 66, + 66, + 66, + 65, + 65, + 66, + 66, + 67, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 92, + 96, + 93, + 89, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 69, + 71, + 72, + 74, + 77, + 79, + 83, + 86, + 91, + 95, + 93, + 89, + 85, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 95, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 64, + 64, + 65, + 65, + 65, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 85, + 90, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 72, + 73, + 76, + 78, + 82, + 85, + 89, + 94, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 94, + 93, + 89, + 85, + 81, + 78, + 76, + 73, + 72, + 70, + 69, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 67, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 91, + 95, + 94, + 90, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 91, + 96, + 95, + 91, + 86, + 83, + 79, + 77, + 75, + 73, + 71, + 70, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 66, + 66, + 67, + 68, + 69, + 70, + 72, + 73, + 75, + 78, + 80, + 84, + 88, + 92, + 97, + 96, + 92, + 87, + 84, + 81, + 78, + 75, + 73, + 72, + 70, + 69, + 68, + 67, + 67, + 67, + 66, + 66, + 67, + 67, + 68, + 68, + 69, + 71, + 72, + 74, + 76, + 79, + 82, + 85, + 89, + 94, + 98, + 98, + 94, + 89, + 85, + 82, + 79, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 68, + 67, + 67, + 67, + 67, + 68, + 68, + 69, + 70, + 72, + 73, + 75, + 77, + 80, + 83, + 86, + 90, + 95, + 100, + 100, + 95, + 90, + 86, + 83, + 80, + 78, + 75, + 74, + 72, + 71, + 70, + 69, + 68, + 68, + 68, + 68, + 68, + 69, + 69, + 70, + 71, + 73, + 74, + 76, + 78, + 81, + 84, + 88, + 92, + 97, + 102, + 102, + 97, + 92, + 88, + 84, + 81, + 79, + 77, + 75, + 73, + 72, + 71, + 70, + 69, + 69, + 69, + 69, + 69, + 69, + 70, + 71, + 72, + 74, + 75, + 77, + 79, + 82, + 85, + 89, + 93, + 99, + 104, + 104, + 99, + 94, + 89, + 86, + 83, + 80, + 78, + 76, + 74, + 73, + 72, + 71, + 70, + 70, + 70, + 70, + 70, + 70, + 71, + 72, + 73, + 75, + 76, + 78, + 81, + 84, + 87, + 91, + 95, + 101, + 106, + 106, + 101, + 96, + 91, + 87, + 84, + 81, + 79, + 77, + 76, + 74, + 73, + 72, + 71, + 71, + 71, + 71, + 71, + 72, + 72, + 73, + 74, + 76, + 78, + 80, + 82, + 85, + 88, + 92, + 97, + 103, + 109, + 109, + 103, + 98, + 93, + 89, + 86, + 83, + 81, + 79, + 77, + 75, + 74, + 73, + 73, + 72, + 72, + 72, + 72, + 73, + 73, + 74, + 76, + 77, + 79, + 81, + 84, + 87, + 90, + 95, + 100, + 105, + 111, + 111, + 106, + 100, + 95, + 91, + 87, + 84, + 82, + 80, + 78, + 77, + 75, + 74, + 74, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 77, + 79, + 81, + 83, + 85, + 89, + 92, + 96, + 102, + 108, + 114, + 114, + 107, + 101, + 96, + 92, + 89, + 86, + 83, + 81, + 79, + 78, + 76, + 75, + 75, + 74, + 74, + 74, + 75, + 75, + 76, + 77, + 78, + 80, + 82, + 84, + 87, + 90, + 94, + 98, + 103, + 110, + 116 + ], + "rows": "1", + "cols": "1024" + }, + { + "__comment": "CALIBRATION_SHADING_LS_TL84_B", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_LS_TL84_B", + "width": "1", + "value": [ + 113, + 107, + 101, + 96, + 92, + 88, + 85, + 83, + 81, + 79, + 77, + 76, + 75, + 75, + 74, + 74, + 74, + 74, + 75, + 75, + 76, + 78, + 80, + 81, + 84, + 86, + 89, + 93, + 98, + 103, + 109, + 115, + 110, + 105, + 99, + 94, + 90, + 87, + 84, + 81, + 79, + 78, + 76, + 75, + 74, + 73, + 73, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 78, + 80, + 82, + 85, + 88, + 91, + 96, + 101, + 107, + 113, + 107, + 102, + 97, + 92, + 88, + 85, + 82, + 80, + 78, + 76, + 75, + 73, + 73, + 72, + 72, + 71, + 72, + 72, + 72, + 73, + 74, + 75, + 77, + 78, + 81, + 83, + 86, + 89, + 93, + 98, + 104, + 110, + 105, + 100, + 95, + 90, + 86, + 83, + 81, + 78, + 76, + 75, + 73, + 72, + 71, + 71, + 70, + 70, + 70, + 71, + 71, + 72, + 72, + 74, + 75, + 77, + 79, + 81, + 84, + 88, + 92, + 96, + 102, + 107, + 103, + 98, + 93, + 88, + 85, + 82, + 79, + 77, + 75, + 74, + 72, + 71, + 70, + 70, + 69, + 69, + 69, + 70, + 70, + 71, + 71, + 73, + 74, + 76, + 78, + 80, + 83, + 86, + 90, + 94, + 100, + 105, + 101, + 96, + 91, + 87, + 84, + 81, + 78, + 76, + 74, + 73, + 71, + 70, + 69, + 69, + 69, + 68, + 68, + 69, + 69, + 70, + 70, + 72, + 73, + 75, + 77, + 79, + 82, + 85, + 88, + 93, + 98, + 103, + 99, + 94, + 90, + 86, + 82, + 79, + 77, + 75, + 73, + 72, + 70, + 69, + 69, + 68, + 68, + 68, + 68, + 68, + 68, + 69, + 70, + 71, + 72, + 74, + 76, + 78, + 80, + 83, + 87, + 91, + 96, + 101, + 97, + 93, + 88, + 84, + 81, + 78, + 76, + 74, + 72, + 71, + 70, + 68, + 68, + 67, + 67, + 67, + 67, + 67, + 67, + 68, + 69, + 70, + 71, + 73, + 75, + 77, + 79, + 82, + 86, + 90, + 95, + 99, + 96, + 91, + 87, + 83, + 80, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 67, + 67, + 68, + 69, + 70, + 72, + 74, + 76, + 78, + 81, + 84, + 88, + 93, + 98, + 94, + 90, + 86, + 82, + 79, + 77, + 74, + 72, + 71, + 69, + 68, + 67, + 66, + 66, + 66, + 65, + 65, + 66, + 66, + 67, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 92, + 96, + 93, + 89, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 69, + 71, + 72, + 74, + 77, + 79, + 83, + 86, + 91, + 95, + 93, + 89, + 85, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 95, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 64, + 64, + 65, + 65, + 65, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 85, + 90, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 72, + 73, + 76, + 78, + 82, + 85, + 89, + 94, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 94, + 93, + 89, + 85, + 81, + 78, + 76, + 73, + 72, + 70, + 69, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 67, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 91, + 95, + 94, + 90, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 91, + 96, + 95, + 91, + 86, + 83, + 79, + 77, + 75, + 73, + 71, + 70, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 66, + 66, + 67, + 68, + 69, + 70, + 72, + 73, + 75, + 78, + 80, + 84, + 88, + 92, + 97, + 96, + 92, + 87, + 84, + 81, + 78, + 75, + 73, + 72, + 70, + 69, + 68, + 67, + 67, + 66, + 66, + 66, + 67, + 67, + 68, + 68, + 69, + 71, + 72, + 74, + 76, + 79, + 82, + 85, + 89, + 94, + 98, + 98, + 94, + 89, + 85, + 82, + 79, + 77, + 74, + 73, + 71, + 70, + 69, + 68, + 68, + 67, + 67, + 67, + 67, + 68, + 68, + 69, + 70, + 72, + 73, + 75, + 77, + 80, + 83, + 86, + 90, + 95, + 100, + 100, + 95, + 90, + 86, + 83, + 80, + 78, + 75, + 74, + 72, + 71, + 70, + 69, + 68, + 68, + 68, + 68, + 68, + 69, + 69, + 70, + 71, + 73, + 74, + 76, + 78, + 81, + 84, + 88, + 92, + 97, + 102, + 102, + 97, + 92, + 88, + 84, + 81, + 79, + 77, + 75, + 73, + 72, + 71, + 70, + 69, + 69, + 69, + 69, + 69, + 69, + 70, + 71, + 72, + 74, + 75, + 77, + 79, + 82, + 85, + 89, + 93, + 99, + 104, + 104, + 99, + 94, + 89, + 86, + 83, + 80, + 78, + 76, + 74, + 73, + 72, + 71, + 70, + 70, + 70, + 70, + 70, + 70, + 71, + 72, + 73, + 75, + 76, + 78, + 81, + 84, + 87, + 91, + 95, + 101, + 106, + 106, + 101, + 96, + 91, + 87, + 84, + 81, + 79, + 77, + 76, + 74, + 73, + 72, + 71, + 71, + 71, + 71, + 71, + 72, + 72, + 73, + 74, + 76, + 78, + 80, + 82, + 85, + 88, + 92, + 97, + 103, + 109, + 109, + 103, + 98, + 93, + 89, + 86, + 83, + 81, + 79, + 77, + 75, + 74, + 73, + 73, + 72, + 72, + 72, + 72, + 73, + 73, + 74, + 76, + 77, + 79, + 81, + 84, + 87, + 90, + 95, + 100, + 105, + 111, + 111, + 106, + 100, + 95, + 91, + 87, + 84, + 82, + 80, + 78, + 77, + 75, + 74, + 74, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 77, + 79, + 81, + 83, + 85, + 89, + 92, + 96, + 102, + 108, + 114, + 114, + 107, + 101, + 96, + 92, + 89, + 86, + 83, + 81, + 79, + 78, + 76, + 75, + 75, + 74, + 74, + 74, + 75, + 75, + 76, + 77, + 78, + 80, + 82, + 84, + 87, + 90, + 94, + 98, + 103, + 110, + 116 + ], + "rows": "1", + "cols": "1024" + }, + { + "__comment": "CALIBRATION_SHADING_LS_D65_R", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_LS_D65_R", + "width": "1", + "value": [ + 113, + 107, + 101, + 96, + 92, + 88, + 85, + 83, + 81, + 79, + 77, + 76, + 75, + 75, + 74, + 74, + 74, + 74, + 75, + 75, + 76, + 78, + 80, + 81, + 84, + 86, + 89, + 93, + 98, + 103, + 109, + 115, + 110, + 105, + 99, + 94, + 90, + 87, + 84, + 81, + 79, + 78, + 76, + 75, + 74, + 73, + 73, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 78, + 80, + 82, + 85, + 88, + 91, + 96, + 101, + 107, + 113, + 107, + 102, + 97, + 92, + 88, + 85, + 82, + 80, + 78, + 76, + 75, + 73, + 73, + 72, + 72, + 71, + 72, + 72, + 72, + 73, + 74, + 75, + 77, + 78, + 81, + 83, + 86, + 89, + 93, + 98, + 104, + 110, + 105, + 100, + 95, + 90, + 86, + 83, + 81, + 78, + 76, + 75, + 73, + 72, + 71, + 71, + 71, + 70, + 70, + 71, + 71, + 72, + 72, + 74, + 75, + 77, + 79, + 82, + 84, + 88, + 92, + 96, + 102, + 107, + 103, + 98, + 93, + 88, + 85, + 82, + 79, + 77, + 75, + 74, + 72, + 71, + 70, + 70, + 69, + 69, + 69, + 70, + 70, + 71, + 71, + 73, + 74, + 76, + 78, + 80, + 83, + 86, + 90, + 94, + 100, + 105, + 101, + 96, + 91, + 87, + 84, + 81, + 78, + 76, + 74, + 73, + 71, + 70, + 69, + 69, + 69, + 68, + 68, + 69, + 69, + 70, + 70, + 72, + 73, + 75, + 77, + 79, + 82, + 85, + 88, + 93, + 98, + 103, + 99, + 94, + 90, + 86, + 82, + 79, + 77, + 75, + 73, + 72, + 70, + 69, + 69, + 68, + 68, + 68, + 68, + 68, + 68, + 69, + 70, + 71, + 72, + 74, + 76, + 78, + 80, + 83, + 87, + 91, + 96, + 101, + 97, + 93, + 88, + 84, + 81, + 78, + 76, + 74, + 72, + 71, + 70, + 69, + 68, + 67, + 67, + 67, + 67, + 67, + 67, + 68, + 69, + 70, + 71, + 73, + 75, + 77, + 79, + 82, + 86, + 90, + 95, + 99, + 96, + 91, + 87, + 83, + 80, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 67, + 67, + 68, + 69, + 71, + 72, + 74, + 76, + 78, + 81, + 84, + 88, + 93, + 98, + 94, + 90, + 86, + 82, + 79, + 77, + 74, + 72, + 71, + 69, + 68, + 67, + 66, + 66, + 66, + 65, + 65, + 66, + 66, + 67, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 92, + 96, + 93, + 89, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 69, + 71, + 72, + 74, + 77, + 79, + 83, + 86, + 91, + 95, + 93, + 89, + 85, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 95, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 64, + 64, + 65, + 65, + 65, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 85, + 90, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 72, + 73, + 76, + 78, + 82, + 85, + 89, + 94, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 94, + 93, + 89, + 85, + 81, + 78, + 76, + 73, + 72, + 70, + 69, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 67, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 91, + 95, + 94, + 90, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 91, + 96, + 95, + 91, + 86, + 83, + 79, + 77, + 75, + 73, + 71, + 70, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 66, + 66, + 67, + 68, + 69, + 70, + 72, + 73, + 75, + 78, + 80, + 84, + 88, + 92, + 97, + 96, + 92, + 87, + 84, + 81, + 78, + 75, + 73, + 72, + 70, + 69, + 68, + 67, + 67, + 67, + 66, + 66, + 67, + 67, + 68, + 68, + 69, + 71, + 72, + 74, + 76, + 79, + 82, + 85, + 89, + 94, + 98, + 98, + 94, + 89, + 85, + 82, + 79, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 68, + 67, + 67, + 67, + 67, + 68, + 68, + 69, + 70, + 72, + 73, + 75, + 77, + 80, + 83, + 86, + 90, + 95, + 100, + 100, + 95, + 90, + 86, + 83, + 80, + 78, + 75, + 74, + 72, + 71, + 70, + 69, + 68, + 68, + 68, + 68, + 68, + 69, + 69, + 70, + 71, + 73, + 74, + 76, + 78, + 81, + 84, + 88, + 92, + 97, + 102, + 102, + 97, + 92, + 88, + 84, + 81, + 79, + 77, + 75, + 73, + 72, + 71, + 70, + 69, + 69, + 69, + 69, + 69, + 69, + 70, + 71, + 72, + 74, + 75, + 77, + 79, + 82, + 85, + 89, + 93, + 99, + 104, + 104, + 99, + 94, + 89, + 86, + 83, + 80, + 78, + 76, + 74, + 73, + 72, + 71, + 70, + 70, + 70, + 70, + 70, + 70, + 71, + 72, + 73, + 75, + 76, + 78, + 81, + 84, + 87, + 91, + 95, + 101, + 106, + 106, + 101, + 96, + 91, + 87, + 84, + 81, + 79, + 77, + 76, + 74, + 73, + 72, + 71, + 71, + 71, + 71, + 71, + 72, + 72, + 73, + 74, + 76, + 78, + 80, + 82, + 85, + 88, + 92, + 97, + 103, + 109, + 109, + 103, + 98, + 93, + 89, + 86, + 83, + 81, + 79, + 77, + 75, + 74, + 73, + 73, + 72, + 72, + 72, + 72, + 73, + 73, + 74, + 76, + 77, + 79, + 81, + 84, + 87, + 90, + 95, + 100, + 105, + 111, + 111, + 106, + 100, + 95, + 91, + 87, + 84, + 82, + 80, + 78, + 77, + 75, + 74, + 74, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 77, + 79, + 81, + 83, + 85, + 88, + 92, + 96, + 102, + 108, + 114, + 114, + 107, + 101, + 96, + 92, + 89, + 86, + 83, + 81, + 79, + 78, + 76, + 75, + 75, + 74, + 74, + 74, + 75, + 75, + 76, + 77, + 78, + 80, + 82, + 84, + 87, + 90, + 94, + 98, + 103, + 110, + 116 + ], + "rows": "1", + "cols": "1024" + }, + { + "__comment": "CALIBRATION_SHADING_LS_D65_G", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_LS_D65_G", + "width": "1", + "value": [ + 113, + 107, + 101, + 96, + 92, + 88, + 85, + 83, + 81, + 79, + 77, + 76, + 75, + 75, + 74, + 74, + 74, + 74, + 75, + 75, + 76, + 78, + 80, + 81, + 84, + 86, + 89, + 93, + 98, + 103, + 109, + 115, + 110, + 105, + 99, + 94, + 90, + 87, + 84, + 81, + 79, + 78, + 76, + 75, + 74, + 73, + 73, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 78, + 80, + 82, + 85, + 88, + 91, + 96, + 101, + 107, + 113, + 107, + 102, + 97, + 92, + 88, + 85, + 82, + 80, + 78, + 76, + 75, + 73, + 73, + 72, + 72, + 71, + 72, + 72, + 72, + 73, + 74, + 75, + 77, + 78, + 81, + 83, + 86, + 89, + 93, + 98, + 104, + 110, + 105, + 100, + 95, + 90, + 86, + 83, + 81, + 78, + 76, + 75, + 73, + 72, + 71, + 71, + 70, + 70, + 70, + 71, + 71, + 72, + 72, + 74, + 75, + 77, + 79, + 81, + 84, + 88, + 92, + 96, + 102, + 107, + 103, + 98, + 93, + 88, + 85, + 82, + 79, + 77, + 75, + 74, + 72, + 71, + 70, + 70, + 69, + 69, + 69, + 70, + 70, + 71, + 71, + 73, + 74, + 76, + 78, + 80, + 83, + 86, + 90, + 94, + 100, + 105, + 101, + 96, + 91, + 87, + 84, + 81, + 78, + 76, + 74, + 73, + 71, + 70, + 69, + 69, + 69, + 68, + 68, + 69, + 69, + 70, + 70, + 72, + 73, + 75, + 77, + 79, + 82, + 85, + 88, + 93, + 98, + 103, + 99, + 94, + 90, + 86, + 82, + 79, + 77, + 75, + 73, + 72, + 70, + 69, + 69, + 68, + 68, + 68, + 68, + 68, + 68, + 69, + 70, + 71, + 72, + 74, + 76, + 78, + 80, + 83, + 87, + 91, + 96, + 101, + 97, + 93, + 88, + 84, + 81, + 78, + 76, + 74, + 72, + 71, + 70, + 69, + 68, + 67, + 67, + 67, + 67, + 67, + 67, + 68, + 69, + 70, + 71, + 73, + 75, + 77, + 79, + 82, + 86, + 90, + 95, + 99, + 96, + 91, + 87, + 83, + 80, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 67, + 67, + 68, + 69, + 71, + 72, + 74, + 76, + 78, + 81, + 84, + 88, + 93, + 98, + 94, + 90, + 86, + 82, + 79, + 77, + 74, + 72, + 71, + 69, + 68, + 67, + 66, + 66, + 66, + 65, + 65, + 66, + 66, + 67, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 92, + 96, + 93, + 89, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 69, + 71, + 72, + 74, + 77, + 79, + 83, + 86, + 91, + 95, + 93, + 89, + 85, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 95, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 64, + 64, + 65, + 65, + 65, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 85, + 90, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 72, + 73, + 76, + 78, + 82, + 85, + 89, + 94, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 94, + 93, + 89, + 85, + 81, + 78, + 76, + 73, + 72, + 70, + 69, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 67, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 91, + 95, + 94, + 90, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 91, + 96, + 95, + 91, + 86, + 83, + 79, + 77, + 75, + 73, + 71, + 70, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 66, + 66, + 67, + 68, + 69, + 70, + 72, + 73, + 75, + 78, + 80, + 84, + 88, + 92, + 97, + 96, + 92, + 87, + 84, + 81, + 78, + 75, + 73, + 72, + 70, + 69, + 68, + 67, + 67, + 67, + 66, + 66, + 67, + 67, + 68, + 68, + 69, + 71, + 72, + 74, + 76, + 79, + 82, + 85, + 89, + 94, + 98, + 98, + 94, + 89, + 85, + 82, + 79, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 68, + 67, + 67, + 67, + 67, + 68, + 68, + 69, + 70, + 72, + 73, + 75, + 77, + 80, + 83, + 86, + 90, + 95, + 100, + 100, + 95, + 90, + 86, + 83, + 80, + 78, + 75, + 74, + 72, + 71, + 70, + 69, + 68, + 68, + 68, + 68, + 68, + 69, + 69, + 70, + 71, + 73, + 74, + 76, + 78, + 81, + 84, + 88, + 92, + 97, + 102, + 102, + 97, + 92, + 88, + 84, + 81, + 79, + 77, + 75, + 73, + 72, + 71, + 70, + 69, + 69, + 69, + 69, + 69, + 69, + 70, + 71, + 72, + 74, + 75, + 77, + 79, + 82, + 85, + 89, + 93, + 99, + 104, + 104, + 99, + 94, + 89, + 86, + 83, + 80, + 78, + 76, + 74, + 73, + 72, + 71, + 70, + 70, + 70, + 70, + 70, + 70, + 71, + 72, + 73, + 75, + 76, + 78, + 81, + 84, + 87, + 91, + 95, + 101, + 106, + 106, + 101, + 96, + 91, + 87, + 84, + 81, + 79, + 77, + 76, + 74, + 73, + 72, + 71, + 71, + 71, + 71, + 71, + 72, + 72, + 73, + 74, + 76, + 78, + 80, + 82, + 85, + 88, + 92, + 97, + 103, + 109, + 109, + 103, + 98, + 93, + 89, + 86, + 83, + 81, + 79, + 77, + 75, + 74, + 73, + 73, + 72, + 72, + 72, + 72, + 73, + 73, + 74, + 76, + 77, + 79, + 81, + 84, + 87, + 90, + 95, + 100, + 105, + 111, + 111, + 106, + 100, + 95, + 91, + 87, + 84, + 82, + 80, + 78, + 77, + 75, + 74, + 74, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 77, + 79, + 81, + 83, + 85, + 89, + 92, + 96, + 102, + 108, + 114, + 114, + 107, + 101, + 96, + 92, + 89, + 86, + 83, + 81, + 79, + 78, + 76, + 75, + 75, + 74, + 74, + 74, + 75, + 75, + 76, + 77, + 78, + 80, + 82, + 84, + 87, + 90, + 94, + 98, + 103, + 110, + 116 + ], + "rows": "1", + "cols": "1024" + }, + { + "__comment": "CALIBRATION_SHADING_LS_D65_B", + "type": "FW_API_LUT", + "name": "CALIBRATION_SHADING_LS_D65_B", + "width": "1", + "value": [ + 113, + 107, + 101, + 96, + 92, + 88, + 85, + 83, + 81, + 79, + 77, + 76, + 75, + 75, + 74, + 74, + 74, + 74, + 75, + 75, + 76, + 78, + 80, + 81, + 84, + 86, + 89, + 93, + 98, + 103, + 109, + 115, + 110, + 105, + 99, + 94, + 90, + 87, + 84, + 81, + 79, + 78, + 76, + 75, + 74, + 73, + 73, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 78, + 80, + 82, + 85, + 88, + 91, + 96, + 101, + 107, + 113, + 107, + 102, + 97, + 92, + 88, + 85, + 82, + 80, + 78, + 76, + 75, + 73, + 73, + 72, + 72, + 71, + 72, + 72, + 72, + 73, + 74, + 75, + 77, + 78, + 81, + 83, + 86, + 89, + 93, + 98, + 104, + 110, + 105, + 100, + 95, + 90, + 86, + 83, + 81, + 78, + 76, + 75, + 73, + 72, + 71, + 71, + 70, + 70, + 70, + 71, + 71, + 72, + 72, + 74, + 75, + 77, + 79, + 81, + 84, + 88, + 92, + 96, + 102, + 107, + 103, + 98, + 93, + 88, + 85, + 82, + 79, + 77, + 75, + 74, + 72, + 71, + 70, + 70, + 69, + 69, + 69, + 70, + 70, + 71, + 71, + 73, + 74, + 76, + 78, + 80, + 83, + 86, + 90, + 94, + 100, + 105, + 101, + 96, + 91, + 87, + 84, + 81, + 78, + 76, + 74, + 73, + 71, + 70, + 69, + 69, + 69, + 68, + 68, + 69, + 69, + 70, + 70, + 72, + 73, + 75, + 77, + 79, + 82, + 85, + 88, + 93, + 98, + 103, + 99, + 94, + 90, + 86, + 82, + 79, + 77, + 75, + 73, + 72, + 70, + 69, + 69, + 68, + 68, + 68, + 68, + 68, + 68, + 69, + 70, + 71, + 72, + 74, + 76, + 78, + 80, + 83, + 87, + 91, + 96, + 101, + 97, + 93, + 88, + 84, + 81, + 78, + 76, + 74, + 72, + 71, + 70, + 68, + 68, + 67, + 67, + 67, + 67, + 67, + 67, + 68, + 69, + 70, + 71, + 73, + 75, + 77, + 79, + 82, + 86, + 90, + 95, + 99, + 96, + 91, + 87, + 83, + 80, + 77, + 75, + 73, + 71, + 70, + 69, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 67, + 67, + 68, + 69, + 70, + 72, + 74, + 76, + 78, + 81, + 84, + 88, + 93, + 98, + 94, + 90, + 86, + 82, + 79, + 77, + 74, + 72, + 71, + 69, + 68, + 67, + 66, + 66, + 66, + 65, + 65, + 66, + 66, + 67, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 92, + 96, + 93, + 89, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 69, + 71, + 72, + 74, + 77, + 79, + 83, + 86, + 91, + 95, + 93, + 89, + 85, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 95, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 65, + 64, + 64, + 65, + 65, + 65, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 85, + 90, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 94, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 91, + 87, + 83, + 80, + 77, + 75, + 72, + 71, + 69, + 68, + 67, + 66, + 65, + 64, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 71, + 73, + 76, + 78, + 81, + 85, + 89, + 93, + 92, + 88, + 84, + 80, + 77, + 75, + 73, + 71, + 69, + 68, + 67, + 66, + 65, + 65, + 64, + 64, + 64, + 64, + 65, + 65, + 66, + 67, + 68, + 70, + 72, + 73, + 76, + 78, + 82, + 85, + 89, + 94, + 92, + 88, + 84, + 81, + 78, + 75, + 73, + 71, + 70, + 68, + 67, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 90, + 94, + 93, + 89, + 85, + 81, + 78, + 76, + 73, + 72, + 70, + 69, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 65, + 65, + 66, + 67, + 68, + 69, + 70, + 72, + 74, + 76, + 79, + 82, + 86, + 91, + 95, + 94, + 90, + 85, + 82, + 79, + 76, + 74, + 72, + 70, + 69, + 68, + 67, + 66, + 66, + 65, + 65, + 65, + 65, + 66, + 66, + 67, + 68, + 70, + 71, + 73, + 75, + 77, + 80, + 83, + 87, + 91, + 96, + 95, + 91, + 86, + 83, + 79, + 77, + 75, + 73, + 71, + 70, + 68, + 67, + 67, + 66, + 66, + 66, + 66, + 66, + 66, + 67, + 68, + 69, + 70, + 72, + 73, + 75, + 78, + 80, + 84, + 88, + 92, + 97, + 96, + 92, + 87, + 84, + 81, + 78, + 75, + 73, + 72, + 70, + 69, + 68, + 67, + 67, + 66, + 66, + 66, + 67, + 67, + 68, + 68, + 69, + 71, + 72, + 74, + 76, + 79, + 82, + 85, + 89, + 94, + 98, + 98, + 94, + 89, + 85, + 82, + 79, + 77, + 74, + 73, + 71, + 70, + 69, + 68, + 68, + 67, + 67, + 67, + 67, + 68, + 68, + 69, + 70, + 72, + 73, + 75, + 77, + 80, + 83, + 86, + 90, + 95, + 100, + 100, + 95, + 90, + 86, + 83, + 80, + 78, + 75, + 74, + 72, + 71, + 70, + 69, + 68, + 68, + 68, + 68, + 68, + 69, + 69, + 70, + 71, + 73, + 74, + 76, + 78, + 81, + 84, + 88, + 92, + 97, + 102, + 102, + 97, + 92, + 88, + 84, + 81, + 79, + 77, + 75, + 73, + 72, + 71, + 70, + 69, + 69, + 69, + 69, + 69, + 69, + 70, + 71, + 72, + 74, + 75, + 77, + 79, + 82, + 85, + 89, + 93, + 99, + 104, + 104, + 99, + 94, + 89, + 86, + 83, + 80, + 78, + 76, + 74, + 73, + 72, + 71, + 70, + 70, + 70, + 70, + 70, + 70, + 71, + 72, + 73, + 75, + 76, + 78, + 81, + 84, + 87, + 91, + 95, + 101, + 106, + 106, + 101, + 96, + 91, + 87, + 84, + 81, + 79, + 77, + 76, + 74, + 73, + 72, + 71, + 71, + 71, + 71, + 71, + 72, + 72, + 73, + 74, + 76, + 78, + 80, + 82, + 85, + 88, + 92, + 97, + 103, + 109, + 109, + 103, + 98, + 93, + 89, + 86, + 83, + 81, + 79, + 77, + 75, + 74, + 73, + 73, + 72, + 72, + 72, + 72, + 73, + 73, + 74, + 76, + 77, + 79, + 81, + 84, + 87, + 90, + 95, + 100, + 105, + 111, + 111, + 106, + 100, + 95, + 91, + 87, + 84, + 82, + 80, + 78, + 77, + 75, + 74, + 74, + 73, + 73, + 73, + 74, + 74, + 75, + 76, + 77, + 79, + 81, + 83, + 85, + 89, + 92, + 96, + 102, + 108, + 114, + 114, + 107, + 101, + 96, + 92, + 89, + 86, + 83, + 81, + 79, + 78, + 76, + 75, + 75, + 74, + 74, + 74, + 75, + 75, + 76, + 77, + 78, + 80, + 82, + 84, + 87, + 90, + 94, + 98, + 103, + 110, + 116 + ], + "rows": "1", + "cols": "1024" + }, + { + "__comment": "CALIBRATION_GAMMA", + "type": "FW_API_LUT", + "name": "CALIBRATION_GAMMA", + "width": "4", + "value": [ + 0, + 2312, + 4623, + 6935, + 9247, + 11536, + 13632, + 15543, + 17309, + 18958, + 20508, + 21976, + 23372, + 24705, + 25982, + 27211, + 28395, + 29539, + 30647, + 31721, + 32765, + 33781, + 34770, + 35734, + 36676, + 37597, + 38497, + 39379, + 40243, + 41090, + 41921, + 42737, + 43539, + 44327, + 45102, + 45864, + 46615, + 47354, + 48083, + 48800, + 49508, + 50206, + 50895, + 51575, + 52247, + 52909, + 53564, + 54211, + 54851, + 55483, + 56108, + 56727, + 57339, + 57944, + 58543, + 59136, + 59723, + 60304, + 60880, + 61450, + 62015, + 62575, + 63130, + 63680, + 64225, + 64766, + 65302, + 65833, + 66360, + 66883, + 67402, + 67917, + 68428, + 68934, + 69437, + 69937, + 70432, + 70925, + 71413, + 71898, + 72380, + 72859, + 73334, + 73806, + 74275, + 74741, + 75204, + 75664, + 76121, + 76575, + 77026, + 77475, + 77921, + 78364, + 78805, + 79243, + 79678, + 80111, + 80542, + 80970, + 81396, + 81820, + 82241, + 82660, + 83077, + 83491, + 83903, + 84314, + 84722, + 85128, + 85532, + 85934, + 86334, + 86732, + 87128, + 87522, + 87914, + 88305, + 88694, + 89080, + 89465, + 89849, + 90230, + 90610, + 90988, + 91365, + 91739, + 92113, + 92484, + 92854, + 93223, + 93589, + 93955, + 94318, + 94681, + 95041, + 95401, + 95759, + 96115, + 96470, + 96824, + 97176, + 97527, + 97876, + 98225, + 98571, + 98917, + 99261, + 99604, + 99946, + 100286, + 100625, + 100963, + 101300, + 101636, + 101970, + 102303, + 102635, + 102966, + 103295, + 103624, + 103951, + 104277, + 104603, + 104927, + 105250, + 105572, + 105892, + 106212, + 106531, + 106849, + 107165, + 107481, + 107796, + 108109, + 108422, + 108734, + 109044, + 109354, + 109663, + 109971, + 110278, + 110583, + 110889, + 111193, + 111496, + 111798, + 112100, + 112400, + 112700, + 112999, + 113297, + 113594, + 113890, + 114185, + 114480, + 114773, + 115066, + 115358, + 115650, + 115940, + 116230, + 116519, + 116807, + 117094, + 117381, + 117666, + 117951, + 118236, + 118519, + 118802, + 119084, + 119365, + 119646, + 119926, + 120205, + 120483, + 120761, + 121038, + 121314, + 121590, + 121865, + 122139, + 122412, + 122685, + 122957, + 123229, + 123500, + 123770, + 124040, + 124308, + 124577, + 124844, + 125111, + 125378, + 125644, + 125909, + 126173, + 126437, + 126700, + 126963, + 127225, + 127487, + 127748, + 128008, + 128268, + 128527, + 128785, + 129043, + 129301, + 129558, + 129814, + 130069, + 130325, + 130579, + 130833, + 131071 + ], + "rows": "1", + "cols": "257" + }, + { + "__comment": "RR RG RB GR GG GB BR BG BB", + "type": "FW_API_LUT", + "name": "CALIBRATION_MT_ABSOLUTE_LS_A_CCM", + "width": "2", + "value": [ + 303, + 32804, + 32779, + 32793, + 294, + 32781, + 32780, + 32819, + 319 + ], + "rows": "1", + "cols": "9" + }, + { + "__comment": "RR RG RB GR GG GB BR BG BB", + "type": "FW_API_LUT", + "name": "CALIBRATION_MT_ABSOLUTE_LS_D40_CCM", + "width": "2", + "value": [ + 303, + 32804, + 32779, + 32793, + 294, + 32781, + 32780, + 32819, + 319 + ], + "rows": "1", + "cols": "9" + }, + { + "__comment": "RR RG RB GR GG GB BR BG BB", + "type": "FW_API_LUT", + "name": "CALIBRATION_MT_ABSOLUTE_LS_D50_CCM", + "width": "2", + "value": [ + 303, + 32804, + 32779, + 32793, + 294, + 32781, + 32780, + 32819, + 319 + ], + "rows": "1", + "cols": "9" + }, + { + "__comment": "CALIBRATION_LIGHT_SRC", + "type": "FW_API_LUT", + "name": "CALIBRATION_LIGHT_SRC", + "width": "2", + "value": [ + 282, + 205 + ], + "rows": "1", + "cols": "2" + }, + { + "__comment": "CALIBRATION_RG_POS", + "type": "FW_API_LUT", + "name": "CALIBRATION_RG_POS", + "width": "2", + "value": [ + 215, + 230, + 239, + 248, + 256, + 266, + 275, + 284, + 292, + 301, + 310, + 319, + 328, + 337, + 365 + ], + "rows": "1", + "cols": "15" + }, + { + "__comment": "CALIBRATION_BG_POS", + "type": "FW_API_LUT", + "name": "CALIBRATION_BG_POS", + "width": "2", + "value": [ + 120, + 140, + 152, + 164, + 176, + 188, + 200, + 212, + 223, + 235, + 247, + 256, + 271, + 283, + 309 + ], + "rows": "1", + "cols": "15" + }, + { + "__comment": "CALIBRATION_MESH_RGBG_WEIGHT", + "type": "FW_API_LUT", + "name": "CALIBRATION_MESH_RGBG_WEIGHT", + "width": "2", + "value": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 4, + 19, + 44, + 79, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 12, + 48, + 125, + 256, + 251, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 12, + 47, + 123, + 217, + 256, + 120, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 11, + 45, + 121, + 215, + 256, + 204, + 19, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 13, + 44, + 118, + 212, + 256, + 207, + 112, + 1, + 0, + 0, + 0, + 0, + 0, + 3, + 15, + 52, + 119, + 256, + 256, + 209, + 114, + 42, + 0, + 0, + 0, + 0, + 0, + 3, + 16, + 56, + 135, + 215, + 256, + 209, + 117, + 43, + 11, + 0, + 0, + 0, + 0, + 3, + 15, + 60, + 141, + 228, + 255, + 204, + 112, + 42, + 11, + 2, + 0, + 0, + 0, + 3, + 17, + 52, + 138, + 226, + 254, + 206, + 114, + 43, + 11, + 2, + 0, + 0, + 0, + 4, + 18, + 62, + 134, + 230, + 253, + 191, + 108, + 40, + 10, + 2, + 0, + 0, + 0, + 1, + 17, + 64, + 150, + 227, + 251, + 185, + 94, + 37, + 9, + 2, + 0, + 0, + 0, + 0, + 3, + 42, + 118, + 216, + 256, + 203, + 111, + 42, + 13, + 2, + 0, + 0, + 0, + 0, + 0, + 20, + 124, + 256, + 254, + 200, + 91, + 28, + 6, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 69, + 256, + 256, + 203, + 115, + 35, + 7, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 158, + 245, + 147, + 49, + 11, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "rows": "15", + "cols": "15" + }, + { + "__comment": "CALIBRATION_MESH_LS_WEIGHT", + "type": "FW_API_LUT", + "name": "CALIBRATION_MESH_LS_WEIGHT", + "width": "2", + "value": [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 3, + 4, + 25, + 42, + 53, + 57, + 53, + 42, + 25, + 4, + 3, + 0, + 0, + 0, + 0, + 4, + 131, + 157, + 179, + 193, + 198, + 193, + 179, + 157, + 131, + 4, + 0, + 0, + 0, + 0, + 25, + 157, + 188, + 214, + 232, + 238, + 232, + 214, + 188, + 157, + 25, + 0, + 0, + 0, + 0, + 42, + 179, + 214, + 243, + 255, + 256, + 255, + 243, + 214, + 179, + 42, + 0, + 0, + 0, + 0, + 53, + 193, + 232, + 255, + 256, + 256, + 256, + 255, + 232, + 193, + 53, + 0, + 0, + 0, + 0, + 57, + 198, + 238, + 256, + 256, + 256, + 256, + 256, + 238, + 198, + 57, + 0, + 0, + 0, + 0, + 53, + 193, + 232, + 255, + 256, + 256, + 256, + 255, + 232, + 193, + 53, + 0, + 0, + 0, + 0, + 42, + 179, + 214, + 243, + 255, + 256, + 255, + 243, + 214, + 179, + 42, + 0, + 0, + 0, + 0, + 25, + 157, + 188, + 214, + 232, + 238, + 232, + 214, + 188, + 157, + 25, + 0, + 0, + 0, + 0, + 4, + 131, + 157, + 179, + 193, + 198, + 193, + 179, + 157, + 131, + 4, + 0, + 0, + 0, + 0, + 3, + 4, + 25, + 42, + 53, + 57, + 53, + 42, + 25, + 4, + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "rows": "15", + "cols": "15" + }, + { + "__comment": "CALIBRATION_MESH_COLOR_TEMPERATURE", + "type": "FW_API_LUT", + "name": "CALIBRATION_MESH_COLOR_TEMPERATURE", + "width": "2", + "value": [ + 256, + 269, + 278, + 286, + 293, + 303, + 311, + 319, + 327, + 335, + 343, + 351, + 351, + 351, + 351, + 239, + 245, + 252, + 261, + 268, + 277, + 286, + 294, + 301, + 310, + 318, + 326, + 335, + 343, + 351, + 234, + 239, + 243, + 246, + 253, + 262, + 271, + 279, + 286, + 295, + 303, + 311, + 320, + 328, + 351, + 228, + 234, + 237, + 240, + 243, + 247, + 255, + 264, + 271, + 279, + 288, + 296, + 304, + 313, + 351, + 222, + 228, + 231, + 235, + 238, + 242, + 245, + 248, + 256, + 264, + 273, + 281, + 289, + 298, + 323, + 216, + 222, + 226, + 229, + 232, + 236, + 239, + 243, + 246, + 249, + 257, + 266, + 274, + 282, + 308, + 211, + 216, + 220, + 223, + 226, + 230, + 233, + 237, + 240, + 243, + 247, + 250, + 259, + 267, + 293, + 205, + 211, + 214, + 217, + 221, + 224, + 228, + 231, + 234, + 238, + 241, + 245, + 248, + 252, + 278, + 200, + 205, + 209, + 212, + 215, + 219, + 223, + 226, + 229, + 232, + 236, + 239, + 243, + 246, + 264, + 195, + 200, + 203, + 206, + 210, + 213, + 217, + 220, + 223, + 227, + 230, + 234, + 237, + 240, + 351, + 183, + 192, + 198, + 201, + 204, + 208, + 211, + 214, + 218, + 221, + 224, + 228, + 231, + 235, + 245, + 175, + 184, + 189, + 195, + 200, + 203, + 207, + 210, + 213, + 217, + 220, + 223, + 227, + 230, + 241, + 161, + 170, + 175, + 181, + 185, + 191, + 197, + 203, + 206, + 209, + 213, + 216, + 220, + 223, + 234, + 154, + 160, + 165, + 169, + 174, + 180, + 186, + 191, + 196, + 204, + 207, + 211, + 214, + 217, + 228, + 154, + 154, + 154, + 154, + 154, + 161, + 166, + 167, + 171, + 177, + 182, + 188, + 193, + 205, + 216 + ], + "rows": "15", + "cols": "15" + }, + { + "__comment": "RG, BG, MULT. final wb gain adjuster for a sky scene. devided by CALIBRATION_WB_STRENGTH_MULT in use", + "type": "FW_API_LUT", + "name": "CALIBRATION_WB_STRENGTH", + "width": "2", + "value": [ + 1000, + 1000, + 1000 + ], + "rows": "1", + "cols": "3" + }, + { + "__comment": "lux threshold for sky", + "type": "FW_API_LUT", + "name": "CALIBRATION_SKY_LUX_TH", + "width": "4", + "value": [ + 10000 + ], + "rows": "1", + "cols": "1" + }, + { + "__comment": "1D rg/bg readout from color_temp", + "type": "FW_API_LUT", + "name": "CALIBRATION_CT_RG_POS_CALC", + "width": "2", + "value": [ + 230, + 241, + 256, + 307, + 346 + ], + "rows": "1", + "cols": "5" + }, + { + "__comment": "1D rg/bg readout from color_temp", + "type": "FW_API_LUT", + "name": "CALIBRATION_CT_BG_POS_CALC", + "width": "2", + "value": [ + 294, + 282, + 256, + 192, + 141 + ], + "rows": "1", + "cols": "5" + }, + { + "__comment": "CALIBRATION_COLOR_TEMP", + "type": "FW_API_LUT", + "name": "CALIBRATION_COLOR_TEMP", + "width": "2", + "value": [ + 154, + 167, + 200, + 250, + 351 + ], + "rows": "1", + "cols": "5" + }, + { + "__comment": "CALIBRATION_CT65POS", + "type": "FW_API_LUT", + "name": "CALIBRATION_CT65POS", + "width": "2", + "value": [ + 0 + ], + "rows": "1", + "cols": "1" + }, + { + "__comment": "CALIBRATION_CT40POS", + "type": "FW_API_LUT", + "name": "CALIBRATION_CT40POS", + "width": "2", + "value": [ + 4 + ], + "rows": "1", + "cols": "1" + }, + { + "__comment": "CALIBRATION_CT30POS", + "type": "FW_API_LUT", + "name": "CALIBRATION_CT30POS", + "width": "2", + "value": [ + 4 + ], + "rows": "1", + "cols": "1" + }, + { + "__comment": "CALIBRATION_EVTOLUX_EV_LUT", + "type": "FW_API_LUT", + "name": "CALIBRATION_EVTOLUX_EV_LUT", + "width": "4", + "value": [ + 0 + ], + "rows": "1", + "cols": "1" + }, + { + "__comment": "CALIBRATION_EVTOLUX_LUX_LUT", + "type": "FW_API_LUT", + "name": "CALIBRATION_EVTOLUX_LUX_LUT", + "width": "4", + "value": [ + 0 + ], + "rows": "1", + "cols": "1" + }, + { + "__comment": "sequence: 1.DAY_LIGHT, 2.CLOUDY, 3.INCANDESCENT, 4.FLOURESCENT, 5.TWILIGHT, 6.SHADE, 7.WARM_FLOURESCENT", + "type": "FW_API_LUT", + "name": "CALIBRATION_AWB_SCENE_PRESETS", + "width": "2", + "value": [ + 272, + 232, + 285, + 223, + 189, + 465, + 213, + 341, + 213, + 341, + 285, + 223, + 189, + 465 + ], + "rows": "7", + "cols": "2" + }, + { + "__comment": "1.enable_ML 2.low_Lux_th, 3.high_Lux_th, 4.contrast_th, 5.bg_th, 6.bg_weight, 7.rg_high_lux_max, 8.rg_high_lux_min", + "type": "FW_API_LUT", + "name": "CALIBRATION_AWB_MIX_LIGHT_PARAMETERS", + "width": "2", + "value": [ + 0, + 600, + 2500, + 40000, + 500, + 0, + 300, + 256 + ], + "rows": "1", + "cols": "8" + }, + { + "__comment": "AWB color preference", + "type": "FW_API_LUT", + "name": "CALIBRATION_AWB_WARMING_CCT", + "width": "2", + "value": [ + 7500, + 6000, + 4700, + 2800 + ], + "rows": "1", + "cols": "4" + }, + { + "__comment": "R G B", + "type": "FW_API_LUT", + "name": "CALIBRATION_AWB_WARMING_LS_A", + "width": "2", + "value": [ + 256, + 256, + 256 + ], + "rows": "1", + "cols": "3" + }, + { + "__comment": "R G B", + "type": "FW_API_LUT", + "name": "CALIBRATION_AWB_WARMING_LS_D75", + "width": "2", + "value": [ + 256, + 256, + 256 + ], + "rows": "1", + "cols": "3" + }, + { + "__comment": "R G B", + "type": "FW_API_LUT", + "name": "CALIBRATION_AWB_WARMING_LS_D50", + "width": "2", + "value": [ + 256, + 256, + 256 + ], + "rows": "1", + "cols": "3" + }, + { + "__comment": "CALIBRATION_STATIC_WB", + "type": "FW_API_LUT", + "name": "CALIBRATION_STATIC_WB", + "width": "2", + "value": [ + 256, + 256, + 256, + 256 + ], + "rows": "1", + "cols": "4" + }, + { + "__comment": "CALIBRATION_IRIDIX_ASYMMETRY", + "type": "FW_API_LUT", + "name": "CALIBRATION_IRIDIX_ASYMMETRY", + "width": "4", + "value": [ + 0, + 518215, + 1020667, + 1508064, + 1981073, + 2440322, + 2886403, + 3319873, + 3741261, + 4151064, + 4549753, + 4937776, + 5315553, + 5683486, + 6041956, + 6391320, + 6731923, + 7064091, + 7388132, + 7704341, + 8012998, + 8314373, + 8608717, + 8896275, + 9177280, + 9451951, + 9720502, + 9983136, + 10240043, + 10491413, + 10737417, + 10978229, + 11214013, + 11444922, + 11671106, + 11892709, + 12109870, + 12322719, + 12531385, + 12735988, + 12936647, + 13133476, + 13326582, + 13516069, + 13702042, + 13884592, + 14063816, + 14239804, + 14412641, + 14582413, + 14749199, + 14913080, + 15074127, + 15232417, + 15388019, + 15540998, + 15691424, + 15839358, + 15984863, + 16127995, + 16268815, + 16407376, + 16543734, + 16677942, + 16777215 + ], + "rows": "1", + "cols": "65" + }, + { + "__comment": "CALIBRATION_CA_CORRECTION_MEM", + "type": "FW_API_LUT", + "name": "CALIBRATION_CA_CORRECTION_MEM", + "width": "2", + "value": [ + 0, + 0, + 0, + 32768, + 0, + 0, + 30984, + 0, + 64889, + 103, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "rows": "4", + "cols": "10" + }, + { + "__comment": "CALIBRATION_CA_CORRECTION", + "type": "FW_API_LUT", + "name": "CALIBRATION_CA_CORRECTION", + "width": "2", + "value": [ + 0, + 8, + 6 + ], + "rows": "1", + "cols": "3" + }, + { + "__comment": "CALIBRATION_CA_FILTER_MEM", + "type": "FW_API_LUT", + "name": "CALIBRATION_CA_FILTER_MEM", + "width": "4", + "value": [ + 32768, + 229629, + 491259, + 4278943225, + 4279204855, + 4262689525, + 4246239220, + 4229788915, + 4213338610, + 4196888050, + 4197214450, + 4180763890, + 4164313330, + 4147928050, + 4131477235, + 4115091955, + 4098641140, + 4082190325, + 4082516470, + 4066065655, + 4066391800, + 4066652665, + 4066913530, + 4067239930, + 4067500795, + 4084473340, + 4101445885, + 4118418430, + 4152037375, + 4185721855, + 4219340544, + 4253025024 + ], + "rows": "1", + "cols": "32" + } + ], + "target": "static" +} diff --git a/plugins/rdk-camera-workshop/web/calibration-exercise.mjs b/plugins/rdk-camera-workshop/web/calibration-exercise.mjs new file mode 100644 index 0000000..146e81f --- /dev/null +++ b/plugins/rdk-camera-workshop/web/calibration-exercise.mjs @@ -0,0 +1,287 @@ +const channels=['R','Gr','Gb','B']; +const channelAt=(x,y)=>2*(y%2)+x%2; + +// Standard 24-patch ColorChecker Classic sRGB reference values (D65) for educational CCM preview. +const colorCheckerSrgb=[ + ['深肤色',115,82,68],['浅肤色',194,150,130],['蓝天',98,122,157],['叶绿',87,108,67],['蓝花',133,128,177],['蓝绿',103,189,170], + ['橙色',214,126,44],['紫蓝',80,91,166],['中红',193,90,99],['紫色',94,60,108],['黄绿',157,188,64],['橙黄',224,163,46], + ['蓝色',56,61,150],['绿色',70,148,73],['红色',175,54,60],['黄色',231,199,31],['品红',187,86,149],['青色',8,133,161], + ['白 9.5',243,243,242],['中性 8',200,200,200],['中性 6.5',160,160,160],['中性 5',122,122,121],['中性 3.5',85,85,85],['黑 2',52,52,52], +]; + +const srgbToLinear=c=>{const v=c/255;return v<=0.04045?v/12.92:Math.pow((v+0.055)/1.055,2.4);}; +const linearToSrgb=v=>{const c=Math.min(1,Math.max(0,v));const s=c<=0.0031308?12.92*c:1.055*Math.pow(c,1/2.4)-0.055;return Math.round(s*255);}; +const toCssRgb=rgb=>'rgb('+rgb.map(linearToSrgb).join(',')+')'; + +export function decodeCcmMatrix(table) { + const lut=table?.luts?.find(item=>item.name==='CALIBRATION_MT_ABSOLUTE_LS_D50_CCM'); + if(!lut||!Array.isArray(lut.value)||lut.value.length!==9) throw new Error('invalid_calibration_exercise'); + const vals=lut.value.map(code=>code>=32768?-(code-32768)/256:code/256); + return [vals.slice(0,3),vals.slice(3,6),vals.slice(6,9)]; +} + +export function decodeAwbCurve(table) { + const find=name=>table?.luts?.find(item=>item.name===name)?.value; + const temps=find('CALIBRATION_COLOR_TEMP'),rgs=find('CALIBRATION_CT_RG_POS_CALC'),bgs=find('CALIBRATION_CT_BG_POS_CALC'); + if(!Array.isArray(temps)||!Array.isArray(rgs)||!Array.isArray(bgs)||!temps.length||temps.length!==rgs.length||temps.length!==bgs.length) { + throw new Error('invalid_calibration_exercise'); + } + const labels=['D65 日光','晴朗日光','D50 标准','冷白荧光','暖钨丝 A']; + return temps.map((mired,index)=>{ + const kelvin=Math.round(1e6/mired); + const rgRatio=rgs[index]/256, bgRatio=bgs[index]/256; + return { + label:labels[index]??(kelvin+' K'), + kelvin, + rgRatio, + bgRatio, + redGain:1/rgRatio, + greenGain:1, + blueGain:1/bgRatio, + }; + }); +} + +function invert3x3(m) { + const [[a,b,c],[d,e,f],[g,h,i]]=m; + const A=e*i-f*h, B=-(d*i-f*g), C=d*h-e*g; + const D=-(b*i-c*h), E=a*i-c*g, F=-(a*h-b*g); + const G=b*f-c*e, H=-(a*f-c*d), I=a*e-b*d; + const det=a*A+b*B+c*C; + return [[A/det,D/det,G/det],[B/det,E/det,H/det],[C/det,F/det,I/det]]; +} + +function mul3(m,v) { + return [ + m[0][0]*v[0]+m[0][1]*v[1]+m[0][2]*v[2], + m[1][0]*v[0]+m[1][1]*v[1]+m[1][2]*v[2], + m[2][0]*v[0]+m[2][1]*v[1]+m[2][2]*v[2], + ]; +} + +export function darkFrameMeans({width,height,bayer,bitDepth,codes}) { + if(width!==8||height!==8||bayer!=='RGGB'||bitDepth!==12|| + !Array.isArray(codes)||codes.length!==width*height|| + codes.some(code=>!Number.isInteger(code)||code<0||code>4095)) { + throw new Error('invalid_calibration_exercise'); + } + const sums=[0,0,0,0]; + for(let y=0;y[name,sums[index]/16])); +} + +export function setupCalibrationExercise({$,element,openWorkbench}) { + const panel=$('calibration-demo'); + const status=$('calibration-demo-status'); + const retry=$('calibration-demo-retry'); + const result=$('calibration-demo-result'); + const slider=$('calibration-demo-slider'); + const image=$('calibration-demo-split'); + const regions=$('calibration-demo-regions'); + const regionLayer=$('calibration-demo-region-layer'); + let loading=false; + + function updateSplit() { + const before=Number(slider.value); + image.style.setProperty('--split',before+'%'); + image.classList.toggle('hide-before-label',before<23); + image.classList.toggle('hide-after-label',before>77); + slider.setAttribute('aria-valuetext','校正前 '+before+'%,校正后 '+(100-before)+'%'); + } + function placeSplit(event) { + const bounds=image.getBoundingClientRect(); + slider.value=String(Math.round(100*(event.clientX-bounds.left)/bounds.width)); + updateSplit(); + } + image.addEventListener('pointerdown',event=>{ + if(!event.isPrimary||event.button!==0) return; + image.setPointerCapture(event.pointerId); + if(event.pointerType==='mouse') slider.focus({preventScroll:true}); + placeSplit(event); + }); + image.addEventListener('pointermove',event=>{ + if(image.hasPointerCapture(event.pointerId)) placeSplit(event); + }); + slider.oninput=updateSplit; + updateSplit(); + regions.onclick=()=>{ + const show=regionLayer.hidden; + regionLayer.hidden=!show; + regions.setAttribute('aria-pressed',String(show)); + regions.textContent=show?'隐藏取样区':'显示取样区'; + }; + $('calibration-demo-open-live').onclick=openWorkbench; + + function renderDarkExercise(darkCrop,table) { + const original=Object.fromEntries(table.luts.map(lut=>[lut.name,lut.value])); + const calculated=$('calibration-demo-calculated'); + const output=$('calibration-demo-values'); + const bayer=$('calibration-demo-bayer'); + const tiles=darkCrop.codes.map((_,index)=>{ + const channel=channels[channelAt(index%darkCrop.width,Math.floor(index/darkCrop.width))]; + const cell=element('i','','bayer-'+channel.toLowerCase()); + cell.title=channel+' · '+darkCrop.codes[index]+' DN'; + return cell; + }); + bayer.replaceChildren(...tiles); + const cells=channels.map(channel=>{ + const card=element('div','','dark-value bayer-'+channel.toLowerCase()); + const value=element('strong','—'); + card.append(element('span',channel),value); + return [card,value]; + }); + output.replaceChildren(...cells.map(([card])=>card)); + const compute=(manual=false)=>{ + try { + const values=Object.entries(darkFrameMeans(darkCrop)); + const matches=values.every(([channel,value])=> + original['CALIBRATION_BLACK_LEVEL_'+channel.toUpperCase()]?.[1]===value); + values.forEach(([,value],index)=>{cells[index][1].textContent=value+' DN';}); + calculated.textContent=(manual?'已重新在浏览器实算:':'浏览器实算均值:')+ + values.map(([channel,value])=>channel+' '+value).join(' · ')+' DN · '+ + (matches?'与上游标定表一致。':'与上游标定表有差异,请核对计算记录。'); + } catch { + calculated.textContent='示例样本无法计算,请重新打开工作台。'; + } + }; + $('calibration-demo-calculate').onclick=()=>compute(true); + compute(false); + } + + function renderCcmExercise(table,record) { + const grid=$('calibration-demo-ccm-grid'); + const matrixBox=$('calibration-demo-ccm-matrix'); + const sliderCcm=$('calibration-demo-ccm-strength'); + const strengthOut=$('calibration-demo-ccm-strength-val'); + const metric=$('calibration-demo-ccm-metric'); + if(!grid||!matrixBox||!sliderCcm) return; + const ccm=decodeCcmMatrix(table); + const inv=invert3x3(ccm); + const de00=record?.metrics?.de00; + const maxErr=record?.metrics?.ccm_max_abs_error; + if(metric) metric.textContent=Number.isFinite(de00)?'ΔE00 '+de00.toFixed(2)+(Number.isFinite(maxErr)?' · 最大残差 '+maxErr.toFixed(4):''):'已标定'; + const rawPatches=colorCheckerSrgb.map(([name,r,g,b])=>({ + name, + raw:mul3(inv,[srgbToLinear(r),srgbToLinear(g),srgbToLinear(b)]), + })); + const patches=rawPatches.map(item=>{ + const tile=element('div','','ccm-patch'); + tile.title=item.name; + tile.style.setProperty('--before',toCssRgb(item.raw)); + return tile; + }); + grid.replaceChildren(...patches); + const tbl=element('table','','calibration-table calibration-matrix'); + const head=tbl.createTHead().insertRow(); + for(const h of ['输出/输入','R','G','B']) { const th=element('th',h); th.scope='col'; head.append(th); } + const tbody=tbl.createTBody(); + const cellRefs=[]; + ['R','G','B'].forEach((ch,r)=>{ + const tr=tbody.insertRow(); + const th=element('th',ch); th.scope='row'; tr.append(th); + const rowCells=[]; + for(let c=0;c<3;c++) { const td=element('td'); tr.append(td); rowCells.push(td); } + cellRefs.push(rowCells); + }); + matrixBox.replaceChildren(tbl); + const update=()=>{ + const t=Number(sliderCcm.value)/100; + if(strengthOut) strengthOut.textContent=Math.round(t*100)+'%'; + const blended=ccm.map((row,r)=>row.map((val,c)=>(r===c?1:0)+t*(val-(r===c?1:0)))); + blended.forEach((row,r)=>row.forEach((val,c)=>{cellRefs[r][c].textContent=(val>=0?'+':'')+val.toFixed(3);})); + rawPatches.forEach((item,index)=>{ + patches[index].style.setProperty('--after',toCssRgb(mul3(blended,item.raw))); + }); + }; + sliderCcm.oninput=update; + update(); + } + + function renderAwbExercise(table) { + const tabs=$('calibration-demo-awb-lights'); + const before=$('calibration-demo-awb-before'); + const after=$('calibration-demo-awb-after'); + const gainsBox=$('calibration-demo-awb-gains'); + const caption=$('calibration-demo-awb-caption'); + if(!tabs||!before||!after||!gainsBox) return; + const points=decodeAwbCurve(table); + let active=points.length-1; + const render=()=>{ + const p=points[active]; + for(const btn of tabs.querySelectorAll('button')) { + const selected=Number(btn.dataset.index)===active; + btn.className='button '+(selected?'primary':'ghost'); + btn.setAttribute('aria-pressed',String(selected)); + } + const base=0.34; + const raw=[base*p.rgRatio,base,base*p.bgRatio]; + const maxRaw=Math.max(0.01,...raw); + const scale=0.62/maxRaw; + before.style.backgroundColor=toCssRgb(raw.map(v=>v*scale)); + after.style.backgroundColor=toCssRgb([0.36,0.36,0.36]); + gainsBox.replaceChildren(); + const maxGain=Math.max(2,p.redGain,p.greenGain,p.blueGain); + for(const [ch,val,key] of [['R',p.redGain,'R'],['G',p.greenGain,'Gr'],['B',p.blueGain,'B']]) { + const row=element('div','','calibration-channel-row'); + const meter=element('span','','calibration-channel-meter'); + const bar=element('span'); bar.dataset.channel=key; bar.style.width=(val/maxGain*100)+'%'; + meter.append(bar); + row.append(element('dt',ch),meter,element('dd',val.toFixed(2)+'×','calibration-numeric')); + gainsBox.append(row); + } + if(caption) caption.textContent=p.label+'('+p.kelvin+' K):未校正 R/G = '+p.rgRatio.toFixed(2)+',B/G = '+p.bgRatio.toFixed(2)+';乘以增益后三通道回归 1.00 : 1.00 : 1.00 中性灰。'; + }; + tabs.replaceChildren(...points.map((point,index)=>{ + const btn=element('button',point.kelvin+' K','button ghost'); + btn.type='button'; btn.dataset.index=String(index); + btn.onclick=()=>{active=index;render();}; + return btn; + })); + render(); + } + + async function load() { + if(loading||!result.hidden) return; + loading=true; + status.hidden=false; + status.textContent='正在读取示例…'; + retry.hidden=true; + try { + const data=Promise.all(['result.json','exercise.json','static-calibrations.json'].map(async name=>{ + const response=await fetch('/calibration-demo/'+name,{signal:AbortSignal.timeout(10000)}); + if(!response.ok) throw new Error('calibration_demo_unavailable'); + return response.json(); + })); + const previews=Promise.all(['before','after'].map(async phase=>{ + const preview=$('calibration-demo-'+phase); + preview.src='/calibration-demo/flat-'+phase+'.png'; + await preview.decode(); + })); + const [[record,exercise,table]]=await Promise.all([data,previews]); + if(exercise.commit!==record.commit) throw new Error('invalid_calibration_exercise'); + const percent=new Intl.NumberFormat('zh-CN',{style:'percent',minimumFractionDigits:1,maximumFractionDigits:1}); + for(const [phase,label] of [['before','校正前'],['after','校正后']]) { + const ratio=exercise.flatCornerToCentre[phase]; + $('calibration-demo-'+phase+'-label').textContent=label+' · '+percent.format(ratio); + $('calibration-demo-'+phase+'-bar').style.setProperty('--brightness',Math.min(1,ratio)*100+'%'); + } + renderDarkExercise(exercise.darkCrop,table); + renderCcmExercise(table,record); + renderAwbExercise(table); + $('calibration-demo-source').textContent='ISP Calibration Tool · '+record.commit.slice(0,7)+ + ' · 导出 '+record.metrics.parameter_count+' 项参数。两张图使用相同的显示曲线。'; + status.hidden=true; + result.hidden=false; + } catch { + status.textContent='示例暂时无法读取。'; + retry.hidden=false; + } finally { + loading=false; + } + } + retry.onclick=load; + panel.addEventListener('toggle',()=>{if(panel.open) void load();}); + if(panel.open) void load(); +} diff --git a/plugins/rdk-camera-workshop/web/calibration-panel.mjs b/plugins/rdk-camera-workshop/web/calibration-panel.mjs new file mode 100644 index 0000000..ce9b611 --- /dev/null +++ b/plugins/rdk-camera-workshop/web/calibration-panel.mjs @@ -0,0 +1,977 @@ +const operations={blc:'黑电平',lsc:'镜头阴影',ccm:'色彩矩阵',awb:'白平衡'}; +const stageOrder=['blc','lsc','ccm','awb']; +const stageHeadings={ + blc:'新建黑电平(BLC)任务', + lsc:'新建镜头阴影(LSC)任务', + ccm:'新建色彩矩阵(CCM)任务', + awb:'新建白平衡(AWB)任务', +}; +const engineLabels={ispstudio:'ISPStudio','ispcal-lsc':'ispcal-lsc (李乔龙)',numpy:'NumPy'}; +const stageEngines={ + blc:['ispstudio','numpy'], + lsc:['ispcal-lsc','ispstudio','numpy'], + ccm:['ispstudio','numpy'], + awb:['ispstudio','numpy'], +}; +const statuses={queued:'待计算',running:'正在计算',completed:'已计算',failed:'计算失败',interrupted:'计算中断'}; +const channels=['R','Gr','Gb','B']; +const rgb=['R','G','B']; +const waiting=ms=>new Promise(resolve=>setTimeout(resolve,ms)); +const number=(value,places=3)=>Number.isFinite(value)?value.toLocaleString('zh-CN',{maximumFractionDigits:places}):'—'; +const errors={ + camera_binding_invalid:'相机实验已变更,请重新打开本组标定。', + camera_auth_required:'当前账号无法读取实验,请检查相机服务登录状态。', + camera_archive_missing:'服务端没有这个实验或标定记录,请核对当前关联。', + camera_unconfigured:'请先在相机插件配置相机服务连接。', + camera_capture_unconfirmed:'相机服务返回超时。请先刷新任务,核对是否已受理。', + camera_service_unreachable:'暂时连不上相机服务,请刷新重试。', + camera_service_error:'相机服务暂未返回有效回执,请刷新记录。', + camera_calibration_busy:'正在处理本组标定请求,请稍后刷新。', + camera_calibration_file_too_large:'请选择不超过 1 MB 的 JSON 文件。', + camera_calibration_invalid:'标定参数或 JSON 格式有误,请核对字段后重试。', + camera_calibration_sample_unavailable:'所选 RAW 或测量资产缺少有效归档记录,请刷新后重新选择。', + vision_calibration_invalid_request:'标定输入格式有误,请检查样本 ID、采集条件和选项。', + vision_calibration_input_kind_mismatch:'请选择符合该算法的 RAW 样本或色卡测量。', + vision_calibration_capture_metadata_conflict:'曝光或增益与样本归档记录不一致,请重新选择。', + vision_calibration_ispstudio_unavailable:'服务端 ISPStudio 当前不可用,可切换 ispcal-lsc 或 NumPy 引擎。', + vision_calibration_ispcal_lsc_unavailable:'服务端 ispcal-lsc 引擎当前不可用,可切换 ISPStudio 或 NumPy。', + vision_calibration_ispcal_lsc_mesh_minimum_six_nodes:'ispcal-lsc 网格行列数均需 ≥ 6(推荐 17 × 17)。', + vision_calibration_ispstudio_mesh_minimum_six_nodes:'ISPStudio 网格行列数均需 ≥ 6(推荐 17 × 17)。', + vision_calibration_dependency_numpy_missing:'服务端缺少 NumPy 标定运行环境,请联系助教检查。', + vision_calibration_mixed_capture_modes_or_exposure:'所选 RAW 的采集设置不一致。使用同模式、同曝光、同增益的一组重新登记。', + vision_calibration_black_levels_or_grid_required:'镜头阴影和白平衡需要四通道黑电平,镜头阴影还需网格尺寸。', + vision_calibration_blocked_light_dark_capture_required:'黑电平标定需要完全遮光的暗场 RAW。', + vision_calibration_dark_sample_light_leak_saturation_or_drift:'暗场存在漏光、饱和或漂移,请核对遮光并重新采集。', + vision_calibration_at_least_three_frames_required:'请选择至少三张符合条件的 RAW。', + vision_calibration_illumination_nonuniform:'平场光照不够均匀,请核对照度网格记录或重新采集。', + vision_calibration_flat_field_saturated:'平场 RAW 有饱和像素,请降低曝光后重新采集。', + vision_calibration_awb_multiple_recorded_illuminants_required:'白平衡需要至少两组不同光源色温的灰卡 RAW。', + vision_calibration_roi_bounds_or_bayer_alignment_invalid:'AWB 灰卡 ROI 需满足宽/高 ≥ 4 且 x、y、宽、高均为偶数(2×2 Bayer 对齐),且不能超出图像边界。', + vision_calibration_illuminant_selection_required:'AWB 多光源标定结果上板时需指定具体光源 ID(options.illuminantId)。', + vision_calibration_ccm_training_or_heldout_residual_exceeded:'色卡拟合误差超过阈值,请核对参考色值、测量区域和训练/验证划分。', + vision_calibration_capacity_exceeded:'服务端计算资源忙,请稍后重试当前任务。', + vision_calibration_task_busy:'服务端正在计算该任务,请刷新记录。', +}; +const message=error=>errors[error?.message]??(error?.message?.startsWith('vision_calibration_') + ?'标定未完成,请核对素材和采集条件。技术回执 '+error.message + :'标定暂未完成,请刷新记录后重试。'); +const fail=code=>{throw new Error(code);}; + +const colorCheckerRefs=[ + ['P01_DarkSkin',[0.451,0.322,0.267]],['P02_LightSkin',[0.761,0.588,0.510]],['P03_BlueSky',[0.384,0.478,0.616]], + ['P04_Foliage',[0.341,0.424,0.263]],['P05_BlueFlower',[0.522,0.502,0.694]],['P06_BluishGreen',[0.404,0.741,0.667]], + ['P07_Orange',[0.839,0.494,0.173]],['P08_PurplishBlue',[0.314,0.357,0.651]],['P09_ModerateRed',[0.757,0.353,0.388]], + ['P10_Purple',[0.369,0.235,0.424]],['P11_YellowGreen',[0.616,0.737,0.251]],['P12_OrangeYellow',[0.878,0.639,0.180]], + ['P13_Blue',[0.220,0.239,0.588]],['P14_Green',[0.275,0.580,0.286]],['P15_Red',[0.686,0.212,0.235]], + ['P16_Yellow',[0.906,0.780,0.122]],['P17_Magenta',[0.733,0.337,0.584]],['P18_Cyan',[0.031,0.522,0.631]], + ['P19_White',[0.953,0.953,0.949]],['P20_Neutral8',[0.784,0.784,0.784]],['P21_Neutral65',[0.627,0.627,0.627]], + ['P22_Neutral5',[0.478,0.478,0.475]],['P23_Neutral35',[0.333,0.333,0.333]],['P24_Black',[0.204,0.204,0.204]], +]; + +function engineReady(engine) { + if(!engine?.available) return false; + if(engine.id==='ispstudio'||engine.id==='ispcal-lsc') return /^[a-f0-9]{64}$/.test(engine.sourceSha256??''); + return true; +} + +function captureSettings(sample) { + const {width,height,bitDepth,bayer,whiteLevel,exposureUs,gain}=sample.metadata??{}; + if(Number.isFinite(exposureUs)&&exposureUs>=1&&exposureUs<=60_000_000&& + Number.isFinite(gain)&&gain>=.0001&&gain<=65_536) { + return JSON.stringify([width,height,bitDepth,bayer,whiteLevel,exposureUs,gain]); + } +} +function arrayOfNumbers(value,length) { + return Array.isArray(value)&&value.length===length&&value.every(Number.isFinite); +} +function matrixOfNumbers(value,rows,cols) { + return Array.isArray(value)&&value.length===rows&&value.every(row=>arrayOfNumbers(row,cols)); +} +function parseLuxList(text) { + const parts=String(text??'').trim().split(/[\s,;,;]+/).filter(Boolean); + if(parts.length<5||parts.length>256) return null; + const nums=parts.map(Number); + return nums.every(v=>Number.isFinite(v)&&v>0)?nums:null; +} +function readBlackLevels(prefix,$) { + const keys=[['R','r'],['Gr','gr'],['Gb','gb'],['B','b']]; + const out={}; + for(const [ch,suffix] of keys) { + const raw=$(prefix+suffix)?.value?.trim(); + if(raw===''||raw===undefined) return null; + const val=Number(raw); + if(!Number.isFinite(val)||val<0||val>65534) return null; + out[ch]=val; + } + return out; +} + +function resultVisual(operation,parameters,element) { + const {values,statistics,grid}=parameters??{}; + const visual=element('div','','calibration-visual'); + function stat(label,value) { + const item=element('div'); + item.append(element('dt',label),element('dd',value)); + return item; + } + function table(headers,rows,className) { + const node=element('table','',className); + const head=node.createTHead().insertRow(); + for(const label of headers) { + const col=element('th',label);col.scope='col';head.append(col); + } + const body=node.createTBody(); + for(const [name,...values] of rows) { + const row=body.insertRow(); + const label=element('th',name);label.scope='row';row.append(label); + for(const value of values) row.append(element('td',value)); + } + return node; + } + if(operation==='blc'&&channels.every(channel=>Number.isFinite(values?.[channel])&&values[channel]>=0)) { + const max=Math.max(1,...channels.map(channel=>values[channel])); + const chart=element('dl','','calibration-channels'); + for(const channel of channels) { + const row=element('div','','calibration-channel-row'); + const mark=element('span','','calibration-channel-meter');mark.setAttribute('aria-hidden','true'); + const bar=element('span');bar.dataset.channel=channel; + bar.style.width=(values[channel]/max*100)+'%';mark.append(bar); + const reading=element('dd',number(values[channel])+' DN','calibration-numeric'); + const spread=statistics?.[channel]?.frameMeanSpreadCodes??statistics?.[channel]?.frameMedianSpreadCodes; + if(Number.isFinite(spread)) reading.append(element('small','帧间极差 '+number(spread)+' DN')); + row.append(element('dt',channel),mark,reading); + chart.append(row); + } + visual.append(chart,element('p','DN 是原始像素码值。条形用于比较四个 Bayer 通道的黑电平。','calibration-small')); + } + if(operation==='lsc'&&Number.isInteger(grid?.rows)&&Number.isInteger(grid?.cols)&& + grid.rows>=2&&grid.cols>=2&&grid.rows<=33&&grid.cols<=33&& + channels.every(channel=>matrixOfNumbers(values?.[channel],grid.rows,grid.cols))) { + const levels=channels.flatMap(channel=>values[channel].flat()); + const low=Math.min(...levels),high=Math.max(...levels); + const heatmaps=element('div','','calibration-heatmaps'); + for(const channel of channels) { + const map=values[channel]; + const tile=element('figure','','calibration-heatmap'); + const canvas=element('canvas');canvas.width=grid.cols;canvas.height=grid.rows; + canvas.setAttribute('role','img'); + canvas.setAttribute('aria-label',channel+' 通道校正增益热图'); + const ctx=canvas.getContext('2d'); + if(ctx) { + map.forEach((row,y)=>row.forEach((gain,x)=>{ + const t=high===low?0:(gain-low)/(high-low); + ctx.fillStyle='rgb('+[28+224*t,62+112*t,116-61*t].map(Math.round).join(',')+')'; + ctx.fillRect(x,y,1,1); + })); + } + const valuesInChannel=map.flat(); + const range=number(Math.min(...valuesInChannel))+'–'+number(Math.max(...valuesInChannel))+'×'; + const caption=element('figcaption'); + caption.append(element('strong',channel),element('span',range)); + tile.append(caption,canvas);heatmaps.append(tile); + } + const legend=element('div','','calibration-gradient-label'); + const gradient=element('span');gradient.setAttribute('aria-hidden','true'); + legend.append(element('span',number(low)+'×'),gradient,element('span',number(high)+'×')); + visual.append(heatmaps,legend,element('p',grid.rows+' × '+grid.cols+' 校正网格。颜色越暖,补偿增益越大。四图共用一条色标。','calibration-small')); + } + if(operation==='ccm'&&matrixOfNumbers(values,3,3)) { + const matrix=table(['输出/输入',...rgb],values.map((row,index)=> + [rgb[index],...row.map(value=>number(value,4))]),'calibration-table calibration-matrix'); + visual.append(matrix); + const summaries=element('dl','','calibration-statistics'); + for(const [key,label] of [['trainRmseLinear','拟合误差'],['heldoutRmseLinear','独立验证误差']]) { + if(Number.isFinite(statistics?.[key])) summaries.append(stat(label,number(statistics[key],5))); + } + if(summaries.childElementCount) visual.append(summaries,element('p','误差单位为线性 RGB 均方根误差。','calibration-small')); + } + if(operation==='awb'&&Array.isArray(values)&&values.length&&values.every(light=> + light&&typeof light.illuminantId==='string'&&Number.isFinite(light.colorTemperatureK)&& + ['redGain','greenGain','blueGain'].every(key=>Number.isFinite(light[key])))) { + const rows=[...values].sort((a,b)=>a.colorTemperatureK-b.colorTemperatureK).map(light=>[ + light.illuminantId+' · '+number(light.colorTemperatureK,0)+' K', + ...['redGain','greenGain','blueGain'].map(key=>number(light[key])+'×'), + ]); + visual.append(table(['光源','R','G','B'],rows,'calibration-table'), + element('p','每行是一组实测光源的白平衡增益。绿通道为基准。','calibration-small')); + } + if(!visual.childElementCount) visual.append(element('p','此回执没有可视化的数值。可下载完整结果核对。','action-copy')); + return visual; +} + +export function createCalibrationPanel({key,$,element,button,notify,getBinding,showCamera,showCapture,showExample,isExampleOpen}) { + const panel=$('calibration-workbench'), status=$('calibration-status'); + const body=$('calibration-body'), tasks=$('calibration-tasks'), outcome=$('calibration-outcome'); + const refresh=$('calibration-refresh'), darkForm=$('calibration-dark-form'), createDark=$('calibration-create-dark'); + const samples=$('calibration-dark-samples'), archive=$('calibration-materials'), count=$('calibration-sample-count'); + const fileForm=$('calibration-file-form'), measurementForm=$('calibration-measurement-form'); + const sensorMode=$('calibration-sensor-mode'), confirmed=$('calibration-dark-confirmed'); + const recovery=$('calibration-recovery'), noRaw=$('calibration-no-raw'); + const enginesBar=$('calibration-engines-bar'), pipelineBar=$('calibration-pipeline'); + const engineSelect=$('calibration-engine'), newTitle=$('calibration-new-title'); + + const lscForm=$('calibration-lsc-form'), lscSamples=$('calibration-lsc-samples'), lscCount=$('calibration-lsc-count'); + const lscMode=$('calibration-lsc-mode'), lscIlluminant=$('calibration-lsc-illuminant'); + const lscRows=$('calibration-lsc-rows'), lscCols=$('calibration-lsc-cols'), lscLux=$('calibration-lsc-lux'); + const createLsc=$('calibration-create-lsc'); + + const ccmForm=$('calibration-ccm-form'), ccmUploadForm=$('calibration-ccm-upload-form'); + const ccmAsset=$('calibration-ccm-asset'), ccmCount=$('calibration-ccm-count'), createCcm=$('calibration-create-ccm'); + + const awbForm=$('calibration-awb-form'), awbMode=$('calibration-awb-mode'); + const awbGroupsEl=$('calibration-awb-groups'), awbCount=$('calibration-awb-count'), createAwb=$('calibration-create-awb'); + + let binding,catalog,selectedTask,busy=false,generation=0,activeStage='blc'; + let candidates=new Map(),selected=new Set(),selectedLsc=new Set(); + const stageEngineChoice=new Map(); + let cachedBlcValues=null; + let awbGroups=[ + {illuminantId:'D65',colorTemperatureK:'6500',x:'160',y:'120',width:'160',height:'120',sampleIds:new Set()}, + {illuminantId:'A',colorTemperatureK:'2856',x:'160',y:'120',width:'160',height:'120',sampleIds:new Set()}, + ]; + + function setStatus(text,tone='') { + status.textContent=text; + status.dataset.tone=tone; + } + function readyEngineList(stage=activeStage) { + const allowed=stageEngines[stage]??['ispstudio','numpy']; + return allowed.filter(id=>engineReady(catalog?.engines?.find(item=>item.id===id))); + } + function selectedEngine() { + const val=engineSelect?.value; + const ready=readyEngineList(); + return ready.includes(val)?val:(ready[0]??null); + } + function renderEnginesAndPipeline() { + if(!catalog) return; + enginesBar.replaceChildren(); + const sorted=[...catalog.engines].sort((a,b)=> + ['ispcal-lsc','ispstudio','numpy'].indexOf(a.id)-['ispcal-lsc','ispstudio','numpy'].indexOf(b.id)); + for(const eng of sorted) { + const ok=engineReady(eng); + const pill=element('span','','calibration-engine-pill'+(ok?' ok':'')); + pill.append(element('i'),element('span',(engineLabels[eng.id]??eng.id)+' · '+(ok?'就绪':'未就绪'))); + if(eng.sourceSha256) pill.title='SHA-256: '+eng.sourceSha256; + enginesBar.append(pill); + } + pipelineBar.replaceChildren(); + stageOrder.forEach((stage,index)=>{ + const stageTasks=catalog.tasks.filter(t=>t.operation===stage); + const done=stageTasks.filter(t=>t.status==='completed').length; + const active=stageTasks.some(t=>t.status==='running'||t.status==='queued'); + const btn=element('button','','calibration-stage-btn'+(stage===activeStage?' is-active':'')+(done?' is-done':'')); + btn.type='button'; + btn.setAttribute('role','tab'); + btn.setAttribute('aria-selected',String(stage===activeStage)); + btn.dataset.stage=stage; + btn.append( + element('strong',(index+1)+'. '+stage.toUpperCase()+' '+operations[stage]), + element('span',done?'已完成 ×'+done:active?'进行中':'待标定'), + ); + btn.onclick=()=>{activeStage=stage;syncStageView();}; + pipelineBar.append(btn); + }); + } + function syncEngineOptions() { + if(!catalog) return; + const allowed=stageEngines[activeStage]??['ispstudio','numpy']; + const preferred=stageEngineChoice.get(activeStage); + engineSelect.replaceChildren(); + for(const id of allowed) { + const eng=catalog.engines.find(item=>item.id===id); + const ok=engineReady(eng); + const opt=element('option',(engineLabels[id]??id)+(ok?'':'(服务端未就绪)')); + opt.value=id; + opt.disabled=!ok; + engineSelect.append(opt); + } + const ready=readyEngineList(); + if(preferred&&ready.includes(preferred)) engineSelect.value=preferred; + else if(ready.length) engineSelect.value=ready[0]; + } + function syncStageView() { + newTitle.textContent=stageHeadings[activeStage]??'新建标定任务'; + for(const stage of stageOrder) { + $('calibration-stage-'+stage).hidden=stage!==activeStage; + } + syncEngineOptions(); + renderEnginesAndPipeline(); + updateControls(); + } + function latestCompletedBlc() { + return catalog?.tasks?.findLast(task=>task.operation==='blc'&&task.status==='completed'); + } + async function fillBlcInto(prefix) { + const blcTask=latestCompletedBlc(); + if(!blcTask) { + notify?.('本组还没有已完成的黑电平(BLC)任务,请先完成第 1 步。'); + return; + } + const apply=vals=>{ + $('calibration-'+prefix+'-bl-r').value=String(vals.R); + $('calibration-'+prefix+'-bl-gr').value=String(vals.Gr); + $('calibration-'+prefix+'-bl-gb').value=String(vals.Gb); + $('calibration-'+prefix+'-bl-b').value=String(vals.B); + updateControls(); + notify?.('已自动填入本组最新 BLC 四通道黑电平。'); + }; + if(cachedBlcValues?.taskId===blcTask.id) { + apply(cachedBlcValues.values); + return; + } + await perform('正在读取本组已算 BLC…',async()=>{ + const {result}=await request('result',{taskId:blcTask.id}); + const vals=result?.parameters?.values; + if(!channels.every(ch=>Number.isFinite(vals?.[ch]))) fail('camera_calibration_invalid'); + cachedBlcValues={taskId:blcTask.id,values:vals}; + apply(vals); + return {text:'已填入最新黑电平参数。',tone:'success'}; + }); + } + function renderAwbGroups() { + awbGroupsEl.replaceChildren(); + const usedElsewhere=(excludeIndex)=>{ + const set=new Set(); + awbGroups.forEach((group,idx)=>{if(idx!==excludeIndex) for(const sid of group.sampleIds) set.add(sid);}); + return set; + }; + awbGroups.forEach((group,idx)=>{ + const card=element('div','','calibration-awb-group'); + const head=element('div','','calibration-awb-group-head'); + head.append(element('span','光源组 #'+(idx+1))); + if(awbGroups.length>2) { + head.append(button('移除',()=>{awbGroups.splice(idx,1);renderAwbGroups();updateControls();},'plain')); + } + const meta=element('div','','calibration-form-grid'); + const idLabel=element('label','光源 ID','field'); + const idInput=element('input'); idInput.value=group.illuminantId; idInput.maxLength=128; idInput.required=true; + idInput.oninput=()=>{group.illuminantId=idInput.value.trim();updateControls();}; + idLabel.append(idInput); + const ctLabel=element('label','色温(K)','field'); + const ctInput=element('input'); ctInput.type='number'; ctInput.min='1000'; ctInput.max='25000'; ctInput.value=group.colorTemperatureK; ctInput.required=true; + ctInput.oninput=()=>{group.colorTemperatureK=ctInput.value;updateControls();}; + ctLabel.append(ctInput); + meta.append(idLabel,ctLabel); + + const roiWrap=element('div','','calibration-roi-grid'); + for(const [fieldKey,labelText] of [['x','ROI X'],['y','ROI Y'],['width','宽 W'],['height','高 H']]) { + const lbl=element('label',labelText,'field'); + const inp=element('input'); inp.type='number'; inp.min=fieldKey==='x'||fieldKey==='y'?'0':'4'; inp.step='2'; inp.value=group[fieldKey]; inp.required=true; + inp.oninput=()=>{group[fieldKey]=inp.value;updateControls();}; + lbl.append(inp);roiWrap.append(lbl); + } + + const list=element('div','','calibration-samples'); + const taken=usedElsewhere(idx); + const firstId=group.sampleIds.values().next().value; + const groupSettings=candidates.get(firstId)?.settings; + for(const {sample,settings} of candidates.values()) { + const {scene,exposureUs,gain,width,height,bayer}=sample.metadata; + const lbl=element('label','','calibration-sample'); + const check=element('input'); check.type='checkbox'; check.value=sample.id; + check.checked=group.sampleIds.has(sample.id); + check.disabled=busy||(!check.checked&&(taken.has(sample.id)||group.sampleIds.size>=16||(groupSettings&&settings!==groupSettings))); + check.onchange=()=>{ + if(check.checked) group.sampleIds.add(sample.id); else group.sampleIds.delete(sample.id); + renderAwbGroups();updateControls(); + }; + const info=element('span','','calibration-sample-info'); + const nameRow=element('span','','calibration-sample-name'); + const code=element('code',sample.id.slice(-8)); code.title=sample.id; + nameRow.append(element('strong',scene||'Bayer RAW'),code); + info.append(nameRow,element('small',[width&&height?width+'×'+height:'',bayer,number(exposureUs/1000)+' ms',number(gain)+'×'].filter(Boolean).join(' · '))); + lbl.append(check,info); + list.append(lbl); + } + card.append(head,meta,roiWrap,list); + awbGroupsEl.append(card); + }); + } + function updateControls() { + const engine=selectedEngine(); + const hasEngine=Boolean(engine); + const needRaw=activeStage!=='ccm'; + body.hidden=!catalog; + refresh.hidden=!binding; + refresh.disabled=busy; + engineSelect.disabled=busy||!catalog; + noRaw.hidden=!catalog||!needRaw||candidates.size>0; + darkForm.hidden=candidates.size===0; + lscForm.hidden=candidates.size===0; + awbForm.hidden=candidates.size===0; + + $('calibration-create').disabled=busy||!catalog||!catalog.engines.some(engineReady); + $('calibration-import').disabled=busy||!catalog; + $('calibration-ccm-upload').disabled=busy||!catalog; + $('calibration-task-file').disabled=busy; + $('calibration-measurement-file').disabled=busy; + $('calibration-ccm-upload-file').disabled=busy; + $('calibration-lsc-fill-blc').disabled=busy||!latestCompletedBlc(); + $('calibration-awb-fill-blc').disabled=busy||!latestCompletedBlc(); + $('calibration-awb-add-group').disabled=busy||awbGroups.length>=8; + + // BLC controls + const settings=candidates.get(selected.values().next().value)?.settings; + sensorMode.disabled=busy; + confirmed.disabled=busy; + const modeValid=/^[A-Za-z0-9_-]{1,128}$/.test(sensorMode.value.trim()); + createDark.disabled=busy||!hasEngine||selected.size<3||!modeValid||!confirmed.checked; + const nextDark=!hasEngine?'服务端暂无可用标定引擎。':!modeValid?'填写相机模式 ID 后才能登记。':!confirmed.checked?'请确认采集条件和遮光。':'已具备登记条件(引擎:'+(engineLabels[engine]??engine)+')。'; + count.textContent=selected.size+' 张已选'+(selected.size<3?',还需 '+(3-selected.size)+' 张同条件 RAW。':'。 '+nextDark); + for(const check of samples.querySelectorAll('input')) { + check.disabled=busy||!check.checked&&(selected.size>=32||(settings&&candidates.get(check.value)?.settings!==settings)); + } + + // LSC controls + const lscSettings=candidates.get(selectedLsc.values().next().value)?.settings; + const lscModeOk=/^[A-Za-z0-9_-]{1,128}$/.test(lscMode.value.trim()); + const lscLightOk=/^[A-Za-z0-9_-]{1,128}$/.test(lscIlluminant.value.trim()); + const lscBl=readBlackLevels('calibration-lsc-bl-',$); + const rows=Number(lscRows.value), cols=Number(lscCols.value); + const minGrid=engine==='numpy'?2:6; + const gridOk=Number.isInteger(rows)&&Number.isInteger(cols)&&rows>=minGrid&&rows<=33&&cols>=minGrid&&cols<=33; + const lux=parseLuxList(lscLux.value); + createLsc.disabled=busy||!hasEngine||selectedLsc.size<3||!lscModeOk||!lscLightOk||!lscBl||!gridOk||!lux; + const lscHint=!hasEngine?'服务端暂无可用 LSC 引擎。' + :selectedLsc.size<3?'还需 '+(3-selectedLsc.size)+' 张同条件平场 RAW。' + :!lscModeOk||!lscLightOk?'请填写相机模式与光源标识。' + :!lscBl?'请填写四通道黑电平(或点「一键填入已算 BLC」)。' + :!gridOk?(engine==='numpy'?'网格范围 2–33。':'所选引擎要求网格行列数 ≥ 6(推荐 17 × 17)。') + :!lux?'请填写至少 5 个照度计正数读数(逗号分隔)。' + :'已具备登记条件(引擎:'+(engineLabels[engine]??engine)+')。'; + lscCount.textContent=selectedLsc.size+' 张平场已选 · '+lscHint; + for(const check of lscSamples.querySelectorAll('input')) { + check.disabled=busy||!check.checked&&(selectedLsc.size>=32||(lscSettings&&candidates.get(check.value)?.settings!==lscSettings)); + } + + // CCM controls + const assetCount=catalog?.assets?.length??0; + ccmAsset.disabled=busy||!assetCount; + createCcm.disabled=busy||!hasEngine||!ccmAsset.value; + ccmCount.textContent=!assetCount + ?'尚无已归档色卡测量,请先下载模板、填入实测线性 RGB 并上传归档。' + :!hasEngine?'服务端暂无可用 CCM 引擎。' + :'共 '+assetCount+' 份色卡测量资产可选(引擎:'+(engineLabels[engine]??engine)+')。'; + + // AWB controls + const awbModeOk=/^[A-Za-z0-9_-]{1,128}$/.test(awbMode.value.trim()); + const awbBl=readBlackLevels('calibration-awb-bl-',$); + const lightSet=new Set(); + let totalAwbSamples=0; + const groupsValid=awbGroups.length>=2&&awbGroups.every(g=>{ + const idOk=/^[A-Za-z0-9_-]{1,128}$/.test(g.illuminantId)&&!lightSet.has(g.illuminantId); + if(idOk) lightSet.add(g.illuminantId); + const ct=Number(g.colorTemperatureK); + const x=Number(g.x),y=Number(g.y),w=Number(g.width),h=Number(g.height); + totalAwbSamples+=g.sampleIds.size; + return idOk&&Number.isFinite(ct)&&ct>=1000&&ct<=25000&& + Number.isInteger(x)&&x>=0&&x%2===0&&Number.isInteger(y)&&y>=0&&y%2===0&& + Number.isInteger(w)&&w>=4&&w%2===0&&Number.isInteger(h)&&h>=4&&h%2===0&& + g.sampleIds.size>=3&&g.sampleIds.size<=16; + })&&totalAwbSamples<=32; + createAwb.disabled=busy||!hasEngine||!awbModeOk||!awbBl||!groupsValid; + awbCount.textContent=!hasEngine?'服务端暂无可用 AWB 引擎。' + :!awbModeOk?'请填写相机模式 ID。' + :!awbBl?'请填写四通道黑电平(或点「一键填入已算 BLC」)。' + :!groupsValid?'至少 2 组不同光源 ID,每组需填写合法色温与 2×2 Bayer 偶数对齐 ROI(宽/高 ≥ 4)并勾选 ≥ 3 张不重复灰卡 RAW。' + :'已配置 '+awbGroups.length+' 组光源、共 '+totalAwbSamples+' 张灰卡 RAW(引擎:'+(engineLabels[engine]??engine)+')。'; + const awbCards=[...awbGroupsEl.querySelectorAll('.calibration-awb-group')]; + awbCards.forEach((card,idx)=>{ + const group=awbGroups[idx]; + if(!group) return; + const taken=new Set(); + awbGroups.forEach((other,j)=>{if(j!==idx) for(const sid of other.sampleIds) taken.add(sid);}); + const firstId=group.sampleIds.values().next().value; + const groupSettings=candidates.get(firstId)?.settings; + for(const check of card.querySelectorAll('.calibration-samples input[type=checkbox]')) { + const sid=check.value; + check.disabled=busy||(!check.checked&&(taken.has(sid)||group.sampleIds.size>=16||(groupSettings&&candidates.get(sid)?.settings!==groupSettings))); + } + for(const fieldInput of card.querySelectorAll('input:not([type=checkbox]),button')) { + fieldInput.disabled=busy; + } + }); + + for(const action of tasks.querySelectorAll('button')) action.disabled=busy; + panel.setAttribute('aria-busy',String(busy)); + } + async function request(action,args={},mutating=false) { + const expected=binding,issued=generation; + const values={experimentId:expected,action,...args}; + const url='/calibration'+(mutating?'':'?'+new URLSearchParams(values)); + let response; + try { + response=await fetch(url,{headers:{'X-Workshop-Session':key,...(mutating?{'Content-Type':'application/json'}:{})}, + ...(mutating?{method:'POST',body:JSON.stringify(values)}:{})}); + } catch {fail('camera_service_unreachable');} + if(expected!==binding||issued!==generation) fail('camera_binding_invalid'); + const result=await response.json().catch(()=>null); + if(expected!==binding||issued!==generation) fail('camera_binding_invalid'); + if(!response.ok||!result) fail(result?.error??'camera_service_error'); + return result; + } + function saveJson(data,name) { + const href=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)+'\n'],{type:'application/json'})); + const link=element('a');link.href=href;link.download=name;link.click(); + setTimeout(()=>URL.revokeObjectURL(href),1000); + } + function downloadCcmTemplate() { + const ref=catalog?.samples?.[0]??catalog?.frames?.[0]; + const width=ref?.metadata?.width??ref?.width??1920; + const height=ref?.metadata?.height??ref?.height??1080; + const sourceArtifactId=ref?.id??'00000000-0000-4000-8000-000000000001'; + const cellW=Math.max(16,Math.floor(width/10)); + const cellH=Math.max(16,Math.floor(height/8)); + const template={ + target:'recorded_color_chart', + measurementSpace:'camera-linear-rgb', + preprocessing:'blc_lsc_awb_applied_linear_raw', + referenceEncoding:'srgb', + referenceWhitePoint:'D65', + referenceIlluminantId:'D65', + imageWidth:width, + imageHeight:height, + illuminant:{id:'D65',colorTemperatureK:6500,source:'recorded-camera-artifact'}, + patches:colorCheckerRefs.map(([patchId,refRgb],index)=>{ + const col=index%6,row=Math.floor(index/6); + const linear=refRgb.map(v=>Number((v<=0.04045?v/12.92:Math.pow((v+0.055)/1.055,2.4)).toFixed(4))); + return { + patchId, + sourceArtifactId, + roi:{x:col*(cellW+8)+8,y:row*(cellH+8)+8,width:cellW,height:cellH}, + measuredLinearRgb:linear.map(v=>Math.min(0.95,Math.max(0.01,v))), + referenceRgb:refRgb, + split:index<18?'train':'heldout', + }; + }), + }; + saveJson(template,'ccm-colorchecker-measurement-template.json'); + notify?.('已下载 24 色卡线性测量模板 JSON,填入实测线性 RGB 后上传归档即可。'); + } + function renderSamplePicker(container,selectedSet,onChange) { + container.replaceChildren(); + for(const {sample} of candidates.values()) { + const {scene,exposureUs,gain,width,height,bitDepth,bayer}=sample.metadata; + const label=element('label','','calibration-sample'); + const check=element('input');check.type='checkbox';check.value=sample.id;check.checked=selectedSet.has(sample.id); + check.onchange=()=>{ + if(check.checked) selectedSet.add(sample.id);else selectedSet.delete(sample.id); + onChange(); + }; + const text=element('span','','calibration-sample-info'); + const heading=element('span','','calibration-sample-name'); + const sampleRef=element('code',sample.id.slice(-8));sampleRef.title=sample.id; + heading.append(element('strong',scene||'Bayer RAW'),sampleRef); + text.append(heading, + element('small',[width&&height?width+' × '+height:'',bitDepth?bitDepth+' bit':'',bayer, + number(exposureUs/1000)+' ms',number(gain)+'×'].filter(Boolean).join(' · '))); + label.append(check,text);container.append(label); + } + } + function renderMaterials() { + archive.replaceChildren(); + candidates=new Map(); + const groups=new Map(); + for(const sample of catalog.samples) { + const settings=captureSettings(sample); + if(!settings) continue; + const group=groups.get(settings)??[]; + group.push({sample,settings});groups.set(settings,group); + } + for(const group of groups.values()) { + if(group.length<3) continue; + for(const row of group) candidates.set(row.sample.id,row); + } + selected=new Set([...selected].filter(id=>candidates.has(id))); + selectedLsc=new Set([...selectedLsc].filter(id=>candidates.has(id))); + for(const g of awbGroups) g.sampleIds=new Set([...g.sampleIds].filter(id=>candidates.has(id))); + + const firstSample=candidates.values().next().value?.sample?.metadata; + if(firstSample?.width&&firstSample?.height) { + for(const g of awbGroups) { + if(Number(g.x)+Number(g.width)>firstSample.width||Number(g.y)+Number(g.height)>firstSample.height) { + g.width=String(Math.max(16,Math.floor(firstSample.width/4)&~1)); + g.height=String(Math.max(16,Math.floor(firstSample.height/4)&~1)); + g.x=String(Math.floor((firstSample.width-Number(g.width))/2)&~1); + g.y=String(Math.floor((firstSample.height-Number(g.height))/2)&~1); + } + } + } + + $('calibration-raw-help').textContent=!catalog.samples.length + ?'本组还没有 Bayer RAW。在同一相机模式、曝光和增益下采集并归档至少三张,或切到「3. CCM」使用色卡测量 JSON。' + :'现有归档中找不到三张同条件、带曝光与增益记录的 RAW。请补采后刷新。'; + renderSamplePicker(samples,selected,()=>{confirmed.checked=false;updateControls();}); + renderSamplePicker(lscSamples,selectedLsc,updateControls); + renderAwbGroups(); + + // Populate CCM asset select + const prevAsset=ccmAsset.value; + ccmAsset.replaceChildren(); + if(!catalog.assets.length) { + const opt=element('option','(请先上传归档色卡测量 JSON)'); opt.value=''; ccmAsset.append(opt); + } else { + for(const asset of [...catalog.assets].reverse()) { + const opt=element('option',(asset.kind||'色卡测量')+' · '+asset.id.slice(-8)); + opt.value=asset.id; ccmAsset.append(opt); + } + if(catalog.assets.some(a=>a.id===prevAsset)) ccmAsset.value=prevAsset; + } + + // Provenance & engine info + for(const eng of catalog.engines) { + const line=element('p',(engineLabels[eng.id]??eng.id)+' · '+(engineReady(eng)?'可用':'不可用')+' ','calibration-small'); + if(eng.sourceSha256) line.append(element('code',eng.sourceSha256.slice(0,16)+'…')); + else if(eng.error) line.append(element('code',eng.error)); + archive.append(line); + } + const list=element('ul','','review-list'); + for(const [items,label] of [[catalog.samples,'Bayer RAW'],[catalog.frames,'实拍图'],[catalog.assets,'线性色卡测量']]) { + for(const item of items) { + const line=element('li',(item.metadata?.scene||item.scene||label)+' · '); + line.append(element('code',item.id));list.append(line); + } + } + archive.append(list.childElementCount?list:element('p','目前没有可引用的素材。','action-copy')); + } + function renderTasks() { + tasks.replaceChildren(); + if(!catalog.tasks.length) { + tasks.append(element('p','还没有标定任务。按上方 1→4 流水线选取 RAW 或色卡测量,登记后即可离线计算。','calibration-empty action-copy')); + return; + } + for(const task of [...catalog.tasks].reverse()) { + const card=element('article','','calibration-task');card.dataset.task=task.id; + const head=element('div','','calibration-task-head'); + const title=element('h4',operations[task.operation]??task.operation); + const tag=element('span',statuses[task.status]??task.status, + 'status-tag'+(task.status==='completed'?' ok':['failed','interrupted'].includes(task.status)?' blocked':'')); + head.append(title,tag); + const count=task.inputs?.length; + const provenance=element('p',[engineLabels[task.engine]??task.engine??'NumPy',count?count+' 份素材':'',task.id.slice(-8)].filter(Boolean).join(' · '),'calibration-small'); + card.append(head,provenance); + if(task.error) card.append(element('p',message({message:task.error}),'calibration-task-error')); + const actions=element('div','','button-row'); + if(['queued','failed','interrupted'].includes(task.status)) { + const action=button(task.status==='queued'?'开始离线计算':'重新计算',()=>void run(task),'primary'); + action.dataset.primary='true';actions.append(action); + } + if(task.status==='completed') { + const result=button('查看结果',()=>void inspect(task,'result'),'ghost'); + const plan=button('应用条件',()=>void inspect(task,'apply_plan'),'plain'); + result.setAttribute('aria-controls',outcome.id);plan.setAttribute('aria-controls',outcome.id); + actions.append(result,plan); + } + if(actions.childElementCount) card.append(actions); + if(selectedTask===task.id) card.classList.add('is-selected'); + tasks.append(card); + } + } + async function load() { + catalog=await request('overview'); + recovery.hidden=true; + renderMaterials(); + renderTasks(); + syncStageView(); + const readyNames=catalog.engines.filter(engineReady).map(e=>engineLabels[e.id]??e.id); + const inventory=catalog.samples.length+' 张 RAW · '+catalog.tasks.length+' 项任务'; + return inventory+(readyNames.length?' · 可用引擎:'+readyNames.join(' / '):' · 暂无可用离线引擎'); + } + function showRecovery(text) { + recovery.hidden=false; + $('calibration-recovery-text').textContent=text; + $('calibration-connect').hidden=Boolean(binding)||!showCamera; + $('calibration-example').hidden=!showExample||Boolean(isExampleOpen?.()); + } + const loadRecords=()=>perform('正在读取本组记录…',async()=>{ + const text=await load(); + return {text}; + }); + async function perform(pending,work) { + if(busy||!binding) return; + const current=++generation; + busy=true;setStatus(pending);updateControls(); + let result; + try { + result=await work(current); + if(generation===current) setStatus(result.text,result.tone); + } catch(error) { + if(generation!==current) return; + setStatus(message(error),'error'); + if(!catalog) showRecovery('可以刷新记录,也可以先完成离线示例。'); + } finally { + if(generation===current) { + busy=false;updateControls();result?.focus?.(); + } + } + } + function focusOutcome() { + const heading=outcome.querySelector('h4'); + if(!heading) return; + heading.tabIndex=-1;heading.focus({preventScroll:true});heading.scrollIntoView({block:'nearest'}); + } + function focusTask(id) { + const card=[...tasks.children].find(node=>node.dataset.task===id); + const target=card?.querySelector('button')??card?.querySelector('h4'); + if(!target) return; + if(target.tagName==='H4') target.tabIndex=-1; + target.focus({preventScroll:true});target.scrollIntoView({block:'nearest'}); + } + function showOutcome(task,children) { + selectedTask=task.id; + outcome.replaceChildren(...children); + for(const card of tasks.children) card.classList.toggle('is-selected',card.dataset.task===task.id); + } + async function readResult(task) { + const {result}=await request('result',{taskId:task.id}); + if(task.operation==='blc'&&channels.every(ch=>Number.isFinite(result?.parameters?.values?.[ch]))) { + cachedBlcValues={taskId:task.id,values:result.parameters.values}; + } + const name=operations[task.operation]; + const sources=element('details','','proof-details'); + sources.append(element('summary','计算来源')); + const provenance=element('p',[result.executor,(result.inputArtifacts?.length??task.inputs?.length)? + (result.inputArtifacts?.length??task.inputs?.length)+' 份输入':''].filter(Boolean).join(' · '),'calibration-small'); + sources.append(provenance); + for(const [label,value] of [['输出 SHA-256',result.outputSha256], + ['引擎 SHA-256',result.algorithm?.sourceSha256??task.engineSourceSha256]]) { + if(typeof value!=='string'||!value) continue; + const hash=element('p',label+' ','calibration-small');hash.append(element('code',value));sources.append(hash); + } + const actions=element('div','','button-row'); + actions.append(button('下载结果 JSON',()=>saveJson(result,task.operation+'-calibration-'+task.id+'.json'),'ghost'), + button('应用条件',()=>void inspect(task,'apply_plan'),'plain')); + showOutcome(task,[element('h4',name+'结果 · '+(engineLabels[task.engine]??task.engine??'NumPy')),resultVisual(task.operation,result.parameters,element), + element('p','离线计算已完成。板端应用和画质仍待实拍验证。','calibration-small'),actions,sources]); + } + async function readPlan(task) { + const {plan}=await request('apply_plan',{taskId:task.id}); + const mapping=plan.runtimeMapping; + const explanations={declared:'该设备已声明 SDK 映射。经你确认后可由 Studio 相机助手执行上板并自动回读验证。', + unavailable:'当前设备缺少匹配的 SDK 映射。请联系助教核对板卡、传感器和 SDK 版本。', + unknown:'还需核对当前设备支持的 SDK 映射。'}; + const explanation=explanations[mapping?.status]??(plan.mappingAvailability==='unavailable' + ?explanations.unavailable:explanations.unknown); + const identifiers=Object.entries({板卡:plan.target?.board,传感器:plan.target?.sensorModel,SDK:plan.target?.sdkVersion}).filter(([,value])=>value); + const info=element('p',identifiers.map(([label,value])=>label+' '+value).join(' · '),'calibration-small'); + const actions=element('div','','button-row'); + if(mapping?.status==='declared') { + const awbNote=task.operation==='awb' + ?',并传入 options: { illuminantId: "'+(plan.availableIlluminantIds?.[0]??'<色温/光源ID>')+'" }' + +(plan.availableIlluminantIds?.length?'(可选光源:'+plan.availableIlluminantIds.join(' / ')+')':'') + :''; + const promptText='请用 vision_calibration_apply 将本组实验 '+binding+' 的 '+operations[task.operation]+' 标定任务 '+task.id+' 应用到相机'+awbNote+',回读参数并拍验证帧对比画质。'; + actions.append(button('复制上板应用指令给 Studio 助手',async()=>{ + try { + await navigator.clipboard.writeText(promptText); + notify?.('已复制上板指令,直接粘贴发送给左侧 Studio 助手即可触发审批上板。'); + } catch { + notify?.('请将以下指令发给 Studio 助手:'+promptText); + } + },'primary')); + } + if(showCapture) actions.append(button('去拍照对比画质',showCapture,'ghost')); + actions.append(button('下载应用规划',()=>saveJson(plan,task.operation+'-apply-plan-'+task.id+'.json'),'plain'), + button('返回结果',()=>void inspect(task,'result'),'plain')); + showOutcome(task,[element('h4','应用条件 · '+operations[task.operation]),element('p',explanation,'action-copy'), + ...(identifiers.length?[info]:[]),actions]); + } + async function inspect(task,action) { + await perform(action==='result'?'正在读取计算结果…':'正在核对应用条件…',async()=>{ + await (action==='result'?readResult(task):readPlan(task)); + return {text:action==='result'?'已读取本组标定结果。':'已读取本组应用条件。',focus:focusOutcome}; + }); + } + async function run(task) { + await perform('正在提交离线计算…',async current=>{ + const asyncRun=task.engine==='ispstudio'||task.engine==='ispcal-lsc'; + let readback=await request(asyncRun?'run_async':'run',{taskId:task.id},true); + if(asyncRun) { + for(let checks=0;checks<110&&generation===current&& + (readback.task.status==='running'||readback.pendingRequest?.status==='submitting');checks++) { + setStatus(readback.task.status==='running'?'服务端正在计算,可留在这里查看结果。':'等待服务端确认本次计算…'); + await waiting(1100); + if(generation!==current) fail('camera_binding_invalid'); + readback=await request('task',{taskId:task.id}); + } + } + await load(); + if(readback.task.status==='completed') { + try {await readResult(readback.task);} + catch { + return {text:'计算已完成。暂时读不到回执,请从当前任务重新查看结果。',tone:'error',focus:()=>focusTask(task.id)}; + } + return {text:'标定计算完成。',tone:'success',focus:focusOutcome}; + } + if(readback.task.status==='failed'||readback.pendingRequest?.status==='request_failed') { + return {text:message({message:readback.task.error??readback.pendingRequest?.error}),tone:'error',focus:()=>focusTask(task.id)}; + } + if(readback.task.status==='running') return {text:'服务端仍在计算。稍后刷新记录查看结果。'}; + if(readback.task.status==='interrupted') return {text:'计算已中断,可在当前任务重新计算。',tone:'error',focus:()=>focusTask(task.id)}; + return {text:'服务端尚未确认开始计算。请先刷新记录,核对任务状态。'}; + }); + } + async function readFile(input) { + const file=input.files[0]; + if(!file) fail('camera_calibration_invalid'); + if(file.size>1024*1024) fail('camera_calibration_file_too_large'); + try {return JSON.parse(await file.text());} + catch {fail('camera_calibration_invalid');} + } + darkForm.onsubmit=event=>{ + event.preventDefault(); + if(createDark.disabled) return; + void perform('正在登记黑电平任务…',async()=>{ + const engine=selectedEngine(); + const input={sampleIds:[...selected],sensorMode:sensorMode.value.trim(),darkConfirmed:confirmed.checked,...(engine?{engine}:{})}; + const result=await request('create_dark',{input},true); + await load(); + const text=result.reused?'已找到这组素材的已有黑电平任务。':'黑电平任务已登记,可以开始离线计算。'; + return {text,tone:'success',focus:()=>focusTask(result.task.id)}; + }); + }; + lscForm.onsubmit=event=>{ + event.preventDefault(); + if(createLsc.disabled) return; + void perform('正在登记镜头阴影任务…',async()=>{ + const engine=selectedEngine(); + const blackLevels=readBlackLevels('calibration-lsc-bl-',$); + const luxSamples=parseLuxList(lscLux.value); + const input={ + sampleIds:[...selectedLsc],sensorMode:lscMode.value.trim(),illuminantId:lscIlluminant.value.trim(), + blackLevels,grid:{rows:Number(lscRows.value),cols:Number(lscCols.value)},luxSamples,...(engine?{engine}:{}), + }; + const result=await request('create_lsc',{input},true); + await load(); + const text=result.reused?'已找到这组素材的已有镜头阴影任务。':'镜头阴影任务已登记,可以开始离线计算。'; + return {text,tone:'success',focus:()=>focusTask(result.task.id)}; + }); + }; + ccmUploadForm.onsubmit=event=>{ + event.preventDefault(); + void perform('正在归档色卡测量…',async current=>{ + const input=await readFile($('calibration-ccm-upload-file')); + if(current!==generation) fail('camera_binding_invalid'); + const created=await request('import_measurement',{input},true); + await load();ccmUploadForm.reset(); + if(created?.asset?.id) ccmAsset.value=created.asset.id; + updateControls(); + return {text:'色卡测量已归档,可直接登记色彩矩阵任务。',tone:'success'}; + }); + }; + ccmForm.onsubmit=event=>{ + event.preventDefault(); + if(createCcm.disabled) return; + void perform('正在登记色彩矩阵任务…',async()=>{ + const engine=selectedEngine(); + const input={assetId:ccmAsset.value,...(engine?{engine}:{})}; + const result=await request('create_ccm',{input},true); + await load(); + const text=result.reused?'已找到该测量资产的已有 CCM 任务。':'色彩矩阵任务已登记,可以开始离线计算。'; + return {text,tone:'success',focus:()=>focusTask(result.task.id)}; + }); + }; + awbForm.onsubmit=event=>{ + event.preventDefault(); + if(createAwb.disabled) return; + void perform('正在登记白平衡任务…',async()=>{ + const engine=selectedEngine(); + const blackLevels=readBlackLevels('calibration-awb-bl-',$); + const groups=awbGroups.map(g=>({ + illuminantId:g.illuminantId.trim(), + colorTemperatureK:Number(g.colorTemperatureK), + roi:{x:Number(g.x),y:Number(g.y),width:Number(g.width),height:Number(g.height)}, + sampleIds:[...g.sampleIds], + })); + const input={sensorMode:awbMode.value.trim(),blackLevels,groups,...(engine?{engine}:{})}; + const result=await request('create_awb',{input},true); + await load(); + const text=result.reused?'已找到这组光源的已有白平衡任务。':'白平衡任务已登记,可以开始离线计算。'; + return {text,tone:'success',focus:()=>focusTask(result.task.id)}; + }); + }; + fileForm.onsubmit=event=>{ + event.preventDefault(); + void perform('正在登记标定任务…',async current=>{ + const task=await readFile($('calibration-task-file')); + if(current!==generation) fail('camera_binding_invalid'); + if(!task||!Object.hasOwn(operations,task.operation)||!Array.isArray(task.inputs)) fail('camera_calibration_invalid'); + const ready=readyEngineList(task.operation); + const engine=task.engine??ready[0]??'numpy'; + const result=await request('create',{input:{...task,engine}},true); + await load();fileForm.reset(); + return {text:'任务已登记,可以开始离线计算。',tone:'success',focus:()=>focusTask(result.task.id)}; + }); + }; + measurementForm.onsubmit=event=>{ + event.preventDefault(); + void perform('正在归档色卡测量…',async current=>{ + const input=await readFile($('calibration-measurement-file')); + if(current!==generation) fail('camera_binding_invalid'); + await request('import_measurement',{input},true); + await load();measurementForm.reset(); + return {text:'色卡测量已归档,可在色彩矩阵步骤或素材列表查看。',tone:'success'}; + }); + }; + + $('calibration-connect').onclick=showCamera; + $('calibration-capture').onclick=showCapture; + $('calibration-lsc-fill-blc').onclick=()=>void fillBlcInto('lsc'); + $('calibration-awb-fill-blc').onclick=()=>void fillBlcInto('awb'); + $('calibration-ccm-template').onclick=downloadCcmTemplate; + $('calibration-awb-add-group').onclick=()=>{ + if(awbGroups.length>=8) return; + const defaults=[['TL84','4000'],['D50','5000'],['CWF','4150'],['H','2300'],['D75','7500'],['LED','5600']]; + const pick=defaults.find(([id])=>!awbGroups.some(g=>g.illuminantId===id))??['L'+(awbGroups.length+1),'5000']; + awbGroups.push({illuminantId:pick[0],colorTemperatureK:pick[1],x:'160',y:'120',width:'160',height:'120',sampleIds:new Set()}); + renderAwbGroups();updateControls(); + }; + for(const id of ['calibration-example','calibration-raw-example']) $(id).onclick=showExample; + for(const [id,action] of [['calibration-capture',showCapture],['calibration-example',showExample],['calibration-raw-example',showExample]]) { + $(id).hidden=!action; + } + engineSelect.addEventListener('change',()=>{ + if(engineSelect.value) stageEngineChoice.set(activeStage,engineSelect.value); + updateControls(); + }); + for(const input of [sensorMode,confirmed,lscMode,lscIlluminant,lscRows,lscCols,lscLux, + $('calibration-lsc-bl-r'),$('calibration-lsc-bl-gr'),$('calibration-lsc-bl-gb'),$('calibration-lsc-bl-b'), + ccmAsset,awbMode,$('calibration-awb-bl-r'),$('calibration-awb-bl-gr'),$('calibration-awb-bl-gb'),$('calibration-awb-bl-b')]) { + if(input) input.addEventListener(input.type==='checkbox'||input.tagName==='SELECT'?'change':'input',updateControls); + } + refresh.onclick=loadRecords; + panel.addEventListener('toggle',()=>{if(panel.open&&!catalog) void loadRecords();}); + + function syncBinding() { + const next=getBinding()?.experimentId; + if(next===binding) { + if(!recovery.hidden) $('calibration-example').hidden=!showExample||Boolean(isExampleOpen?.()); + return; + } + generation++; + binding=next;catalog=undefined;busy=false;selectedTask=undefined;cachedBlcValues=null; + selected.clear();selectedLsc.clear();candidates.clear(); + for(const g of awbGroups) g.sampleIds.clear(); + tasks.replaceChildren();outcome.replaceChildren();archive.replaceChildren(); + samples.replaceChildren();lscSamples.replaceChildren();awbGroupsEl.replaceChildren(); + darkForm.reset();lscForm.reset();ccmForm.reset();ccmUploadForm.reset();awbForm.reset();fileForm.reset();measurementForm.reset(); + recovery.hidden=Boolean(binding); + setStatus(binding?'展开后读取本组素材和任务。':'本组相机实验尚未关联。'); + if(!binding) showRecovery('关联后可使用本组的 Bayer RAW 和测量记录。'); + updateControls(); + if(panel.open&&binding) void loadRecords(); + } + async function refreshRecords() { + if(!binding||busy) return; + if(!panel.open&&!catalog) return; + try { + const text=await load(); + setStatus(text); + } catch {} + } + setStatus('本组相机实验尚未关联。'); + showRecovery('关联后可使用本组的 Bayer RAW 和测量记录。'); + updateControls(); + return {syncBinding,refreshRecords}; +} diff --git a/plugins/rdk-camera-workshop/web/camera-panel.mjs b/plugins/rdk-camera-workshop/web/camera-panel.mjs index ad266ff..0b74bf1 100644 --- a/plugins/rdk-camera-workshop/web/camera-panel.mjs +++ b/plugins/rdk-camera-workshop/web/camera-panel.mjs @@ -1,11 +1,12 @@ const messages={ + camera_credential_missing:'已找到相机连接配置,但缺少凭据文件。请在相机插件重新配置相机凭据,再刷新。', camera_unconfigured:'先在 Camera Workshop 配置相机服务,再回来刷新。', camera_configuration_invalid:'本机连接配置不可读或格式有误。请在相机插件运行连接自检。', camera_service_unreachable:'暂时联系不到相机服务,请检查服务是否在线。', camera_auth_required:'当前身份无法读取相机实验,请在 Camera Workshop 核对账号。', camera_archive_missing:'当前身份看不到这个实验或帧,请重新选择实验。', camera_frame_integrity_failed:'存档字节与回执不符。请在相机插件检查原始帧。', - camera_binding_invalid:'工位相机关联已变更,请刷新当前实验。', + camera_binding_invalid:'相机关联已变更,请刷新当前实验。', }; const archiveTime=value=>typeof value==='string'&&!Number.isNaN(Date.parse(value))?new Date(value).toLocaleString('zh-CN',{hour12:false}):'时间待核对'; const statusLabels={queued:'排队',running:'执行中',completed:'完成',canceled:'已取消',failed:'失败',interrupted:'中断'}; @@ -18,8 +19,8 @@ export function createCameraPanel({key, $, element, button, field, openDialog, n let loading=false; let thumbnail; - async function request(path) { - const response=await fetch(path,{headers:{'X-Workshop-Session':key}}); + async function request(path,background=false) { + const response=await fetch(path,{headers:{'X-Workshop-Session':key,...(background?{'X-Workshop-Poll':'1'}:{})}}); if(!response.ok) { const body=await response.json().catch(()=>({})); throw new Error(messages[body.error]??'读取相机记录失败,请刷新重试。'); @@ -29,10 +30,13 @@ export function createCameraPanel({key, $, element, button, field, openDialog, n async function chooseExperiment() { try { const {experiments}=await (await request('/camera/experiments')).json(); - if(!experiments.length) {notify('当前账号没有相机实验。请先在 Camera Workshop 创建本工位实验。');return;} - openDialog('关联本工位相机实验',[ - field('experimentId','实验名称',{value:getBinding()?.experimentId??'',options:[['','选择此工位的实验'], - ...experiments.map(exp=>[exp.id,exp.title+' · '+(exp.sensorModel??'相机型号待确认')])]}), + if(!experiments.length) {notify('当前账号没有相机实验。请先在 Camera Workshop 创建本组实验。');return;} + const sorted=[...experiments].sort((a,b)=>(Date.parse(b.updatedAt)||0)-(Date.parse(a.updatedAt)||0)); + const defaultId=getBinding()?.experimentId??sorted[0].id; + openDialog('关联本组相机实验',[ + element('p',getBinding()?'切换本组关联的相机实验,原实验记录仍保留。':'已默认选中最近更新的实验,确认后即可运行预检、拍照与调参。','action-copy'), + field('experimentId','实验名称',{value:defaultId,options:[ + ...sorted.map((exp,idx)=>[exp.id,(idx===0?'[最近] ':'')+exp.title+' · '+(exp.sensorModel??'相机型号待确认')])]}), ],data=>bind({experimentId:data.experimentId}),'关联'); } catch(error) { notify(error.message); } } @@ -85,7 +89,7 @@ export function createCameraPanel({key, $, element, button, field, openDialog, n const image=element('img','','camera-frame-preview'); const href=URL.createObjectURL(entry.file); image.alt='Camera Workshop 相机存档';image.src=href; - openDialog('本工位相机存档',[image,element('p',`${frame.width} × ${frame.height} · 存档于 ${archiveTime(frame.archivedAt)}`)],()=>{ + openDialog('本组相机存档',[image,element('p',`${frame.width} × ${frame.height} · 存档于 ${archiveTime(frame.archivedAt)}`)],()=>{ if(entry.experimentId!==getBinding()?.experimentId) throw new Error(messages.camera_binding_invalid); attach([entry]); },'附入成果包'); @@ -145,7 +149,7 @@ export function createCameraPanel({key, $, element, button, field, openDialog, n } } function poll() { - if(!loading&&!$('dialog').open&&['queued','running'].includes(archive?.activeRun?.status)) void refresh(); + if(!document.hidden&&!loading&&!$('dialog').open&&['queued','running'].includes(archive?.activeRun?.status)) void refresh(); } return {render,syncBinding,poll}; } diff --git a/plugins/rdk-camera-workshop/web/capture-panel.mjs b/plugins/rdk-camera-workshop/web/capture-panel.mjs index e65cb4c..6c4bb77 100644 --- a/plugins/rdk-camera-workshop/web/capture-panel.mjs +++ b/plugins/rdk-camera-workshop/web/capture-panel.mjs @@ -1,7 +1,8 @@ const labels={photo:'本轮照片',raw:'Bayer RAW',isp:'ISP 显示图',render:'RAW 重渲染'}; -const descriptions={raw:'传感器采样的灰度预览,可下载原始 Bayer 文件。',isp:'相机经当前 ISP 输出的画面。',render:'使用这组 RAW 和已回读配置重渲染。'}; +const descriptions={raw:'传感器 Bayer 采样的预览,可下载原始文件。',isp:'相机经当前 ISP 输出的画面。',render:'使用这组 RAW 和已回读配置重渲染。'}; const messages={ - camera_binding_invalid:'先关联本工位的相机实验。', + camera_credential_missing:'已找到相机连接配置,但缺少凭据文件。请在相机插件重新配置相机凭据,再刷新。', + camera_binding_invalid:'先关联本组相机实验。', camera_capture_busy:'相机正在采集。请先等待当前操作结束。', camera_capture_unconfirmed:'相机服务未返回完整回执。先核对实验存档,再决定是否重采。', camera_scene_required:'请填写固定场景。', @@ -23,7 +24,7 @@ const explain=code=>messages[code]??(code?.includes('raw_replay')?'请核对 SDK :code?'相机服务未完成此项。技术回执 '+code:'相机服务暂无回执。'); const unconfirmedCapture=new Set(['camera_capture_unconfirmed','vision_device_transport_failed']); -export function createCapturePanel({key,$,element,button,field,openDialog,notify,getBinding,attach}) { +export function createCapturePanel({key,$,element,button,field,openDialog,notify,getBinding,canRefresh=()=>true,attach}) { let bindingId; let capture; let note=''; @@ -31,8 +32,8 @@ export function createCapturePanel({key,$,element,button,field,openDialog,notify let refreshing=false; const previews=new Map(); const route=(kind,asset,preview=false)=>'/camera/capture/file/'+kind+'?id='+encodeURIComponent(asset.id)+(preview?'&preview=1':''); - async function request(path,body) { - const headers={'X-Workshop-Session':key,...(body?{'Content-Type':'application/json'}:{})}; + async function request(path,body,background=false) { + const headers={'X-Workshop-Session':key,...(background?{'X-Workshop-Poll':'1'}:{}),...(body?{'Content-Type':'application/json'}:{})}; const response=await fetch(path,{headers,...(body?{method:'POST',body:JSON.stringify(body)}:{})}); if(!response.ok) throw new Error(explain((await response.json().catch(()=>({}))).error)); return response; @@ -78,21 +79,27 @@ export function createCapturePanel({key,$,element,button,field,openDialog,notify render(); } async function poll() { - if(!bindingId||refreshing||busy) return; + if(!bindingId||!canRefresh()||refreshing||busy||document.hidden) return; const id=bindingId; refreshing=true; try { - const value=await(await request('/camera/capture')).json(); - if(id===bindingId&&!busy) {if(note) {note='';render();}update(value.capture);} + const value=await(await request('/camera/capture',undefined,true)).json(); + if(id===bindingId&&canRefresh()&&!busy&&(value.experimentId===undefined||value.experimentId===id)) { + if(note) {note='';render();} + update(value.capture); + } } catch(error) { - if(id===bindingId&&!busy&¬e!==error.message) {note=error.message;render();} + if(id===bindingId&&canRefresh()&&!busy&¬e!==error.message) {note=error.message;render();} } finally {refreshing=false;} } function syncBinding() { const next=getBinding()?.experimentId??null; - if(next===bindingId) return; - bindingId=next;note=''; - update(undefined);render();void poll(); + const changed=next!==bindingId; + if(changed) { + bindingId=next;note=''; + update(undefined);render(); + } + if(bindingId&&canRefresh()&&(changed||!capture)) void poll(); } async function start(action,scene) { if(busy||capture?.running) return; @@ -143,9 +150,10 @@ export function createCapturePanel({key,$,element,button,field,openDialog,notify grid.replaceChildren();actions.replaceChildren(); const active=busy||Boolean(capture?.running); const complete=['raw','isp','render'].every(kind=>capture?.assets[kind]); - status.textContent=active?'正在采集':complete?'三图已归档':!bindingId?'未关联':'待采集或补齐'; + const replayNeedsNewRaw=capture?.errors.render==='vision_raw_replay_capture_metadata_required'; + status.textContent=active?'正在采集':complete?'三图已归档':!bindingId?'未关联':replayNeedsNewRaw?'重渲染需重新采集 RAW':'待采集或补齐'; status.className='status-tag'+(complete&&!active?' ok':''); - help.textContent=note||(capture?.recording?'已取到部分回执,课程记录保存失败。请保留原件。':!bindingId?'先在上方关联本工位相机实验。' + help.textContent=note||(capture?.recording?'已取到部分回执,课程记录保存失败。请保留原件。':!bindingId?'先在上方关联本组相机实验。' :capture?.scene?'固定场景 · '+capture.scene+'。RAW 与 ISP 分次采集,渲染使用同组 RAW。' :'拍一张当前照片,或在固定场景下采集三张基线图。'); const group=element('div','','capture-cards'); @@ -156,9 +164,9 @@ export function createCapturePanel({key,$,element,button,field,openDialog,notify actions.append(button('拍一张照片',()=>start('photo'),'ghost')); if(capture?.scene&&!complete) { const unconfirmed=['raw','isp','render'].some(kind=>unconfirmedCapture.has(capture.errors[kind])); - if(!unconfirmed) actions.append(button('继续补齐三图',()=>start('baseline',capture.scene),'primary')); - actions.append(button('重采三图',()=>askScene('retake','重采一组基线'),unconfirmed?'primary':'plain')); - if(capture.assets.raw&&!capture.assets.render&&!unconfirmedCapture.has(capture.errors.render)) { + if(!unconfirmed&&!replayNeedsNewRaw) actions.append(button('继续补齐三图',()=>start('baseline',capture.scene),'primary')); + actions.append(button('重采三图',()=>askScene('retake','重采一组基线'),unconfirmed||replayNeedsNewRaw?'primary':'plain')); + if(capture.assets.raw&&!capture.assets.render&&!replayNeedsNewRaw&&!unconfirmedCapture.has(capture.errors.render)) { actions.append(button('重试本组渲染',()=>start('render'),'plain')); } } else actions.append(button(complete?'重采三图':'采集三张基线图',()=>askScene(complete?'retake':'baseline','固定场景并采集'),'primary')); diff --git a/plugins/rdk-camera-workshop/web/image-compare.mjs b/plugins/rdk-camera-workshop/web/image-compare.mjs new file mode 100644 index 0000000..02f287d --- /dev/null +++ b/plugins/rdk-camera-workshop/web/image-compare.mjs @@ -0,0 +1,711 @@ +// Zero-dependency interactive ISP image comparison, split-curtain, 2.5x loupe, +// live dual RGB/luminance histogram scope, and 7-parameter real-time ISP lab (with USM sharpness). + +const SCOPE_W = 240; +const SCOPE_H = 135; + +function sampleSource(source) { + if (!source) return null; + const isCanvas = source instanceof HTMLCanvasElement; + const nw = isCanvas ? source.width : source.naturalWidth; + const nh = isCanvas ? source.height : source.naturalHeight; + if (!nw || !nh) return null; + const canvas = document.createElement('canvas'); + canvas.width = SCOPE_W; + canvas.height = SCOPE_H; + const ctx = canvas.getContext('2d', { willReadFrequently: true }); + ctx.drawImage(source, 0, 0, SCOPE_W, SCOPE_H); + const data = ctx.getImageData(0, 0, SCOPE_W, SCOPE_H).data; + const rHist = new Uint32Array(256); + const gHist = new Uint32Array(256); + const bHist = new Uint32Array(256); + const yHist = new Uint32Array(256); + const pixels = SCOPE_W * SCOPE_H; + const yPlane = new Float32Array(pixels); + let ySum = 0; + let sSum = 0; + let darkCount = 0; + let clipCount = 0; + for (let i = 0, p = 0; i < data.length; i += 4, p++) { + const r = data[i]; + const g = data[i + 1]; + const b = data[i + 2]; + const yF = 0.299 * r + 0.587 * g + 0.114 * b; + yPlane[p] = yF; + const y = Math.min(255, Math.round(yF)); + rHist[r]++; + gHist[g]++; + bHist[b]++; + yHist[y]++; + ySum += y; + if (y < 16) darkCount++; + if (y > 248) clipCount++; + const mx = r > g ? (r > b ? r : b) : (g > b ? g : b); + const mn = r < g ? (r < b ? r : b) : (g < b ? g : b); + sSum += mx > 0 ? ((mx - mn) / mx) * 255 : 0; + } + let gradSum = 0; + for (let row = 0; row < SCOPE_H - 1; row++) { + const base = row * SCOPE_W; + for (let col = 0; col < SCOPE_W - 1; col++) { + const idx = base + col; + const cur = yPlane[idx]; + gradSum += Math.abs(yPlane[idx + 1] - cur) + Math.abs(yPlane[idx + SCOPE_W] - cur); + } + } + const edgeSharpness = gradSum / (2 * (SCOPE_W - 1) * (SCOPE_H - 1)); + return { + rHist, gHist, bHist, yHist, + meanLuma: ySum / pixels, + darkPct: (darkCount / pixels) * 100, + clipPct: (clipCount / pixels) * 100, + meanSat: sSum / pixels, + edgeSharpness, + }; +} + +function smoothHist(hist) { + const out = new Float32Array(256); + for (let i = 0; i < 256; i++) { + let sum = 0; + let count = 0; + for (let k = Math.max(0, i - 2); k <= Math.min(255, i + 2); k++) { + sum += hist[k]; + count++; + } + out[i] = sum / count; + } + return out; +} + +function renderHistogramCanvas(canvas, beforeStats, afterStats) { + const dpr = Math.min(window.devicePixelRatio || 1, 2); + const cssW = Math.max(260, Math.round(canvas.clientWidth || 520)); + const cssH = 92; + if (canvas.width !== cssW * dpr || canvas.height !== cssH * dpr) { + canvas.width = cssW * dpr; + canvas.height = cssH * dpr; + } + const ctx = canvas.getContext('2d'); + ctx.save(); + ctx.scale(dpr, dpr); + ctx.fillStyle = '#0f192b'; + ctx.fillRect(0, 0, cssW, cssH); + + // Subtle vertical exposure zone gridlines (25%, 50%, 75%) + ctx.strokeStyle = 'rgba(148, 174, 214, 0.16)'; + ctx.lineWidth = 1; + for (const frac of [0.25, 0.5, 0.75]) { + const x = Math.round(cssW * frac) + 0.5; + ctx.beginPath(); + ctx.moveTo(x, 0); + ctx.lineTo(x, cssH); + ctx.stroke(); + } + // Shadow/highlight threshold markers (<16 and >248) + ctx.fillStyle = 'rgba(148, 174, 214, 0.08)'; + ctx.fillRect(0, 0, (16 / 255) * cssW, cssH); + ctx.fillStyle = 'rgba(248, 113, 113, 0.12)'; + ctx.fillRect((248 / 255) * cssW, 0, (7 / 255) * cssW, cssH); + + if (!beforeStats && !afterStats) { + ctx.restore(); + return; + } + + const target = afterStats || beforeStats; + const rS = smoothHist(target.rHist); + const gS = smoothHist(target.gHist); + const bS = smoothHist(target.bHist); + const yAfter = smoothHist(target.yHist); + const yBefore = beforeStats ? smoothHist(beforeStats.yHist) : null; + + // Compute robust peak excluding extreme pure-0 / pure-255 spikes so midtones stay readable + let peak = 1; + for (let i = 4; i < 252; i++) { + peak = Math.max(peak, rS[i], gS[i], bS[i], yAfter[i], yBefore ? yBefore[i] : 0); + } + const padTop = 8; + const usableH = cssH - padTop - 4; + const yOf = val => cssH - 2 - Math.min(1, val / peak) * usableH; + + const drawCurve = (arr, stroke, fill, dashed = false) => { + ctx.save(); + if (dashed) ctx.setLineDash([4, 3]); + ctx.beginPath(); + for (let i = 0; i < 256; i++) { + const x = (i / 255) * cssW; + const y = yOf(arr[i]); + if (i === 0) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + } + if (fill) { + ctx.lineTo(cssW, cssH - 2); + ctx.lineTo(0, cssH - 2); + ctx.closePath(); + ctx.fillStyle = fill; + ctx.fill(); + ctx.beginPath(); + for (let i = 0; i < 256; i++) { + const x = (i / 255) * cssW; + const y = yOf(arr[i]); + if (i === 0) ctx.moveTo(x, y); + else ctx.lineTo(x, y); + } + } + ctx.strokeStyle = stroke; + ctx.lineWidth = dashed ? 1.3 : 1.4; + ctx.stroke(); + ctx.restore(); + }; + + // Candidate R, G, B translucent studio scopes + drawCurve(rS, 'rgba(248, 113, 113, 0.72)', 'rgba(248, 113, 113, 0.14)'); + drawCurve(gS, 'rgba(52, 211, 153, 0.72)', 'rgba(52, 211, 153, 0.13)'); + drawCurve(bS, 'rgba(96, 165, 250, 0.78)', 'rgba(96, 165, 250, 0.16)'); + // Candidate Luminance crisp outline + drawCurve(yAfter, 'rgba(241, 245, 249, 0.92)', null); + // Baseline Luminance dashed overlay for direct shift comparison + if (yBefore && afterStats) { + drawCurve(yBefore, 'rgba(251, 191, 36, 0.85)', null, true); + } + ctx.restore(); +} + +let reusableLumaBuf = null; + +export function applyIspPipeline(srcData, dstData, params) { + const { + exposureEv = 0, + gamma = 1, + brightness = 0, + contrast = 1, + saturation = 1, + wbShift = 0, + sharpness = 0, + } = params; + + const expMul = Math.pow(2, exposureEv); + const rWb = wbShift >= 0 ? 1 + (wbShift / 100) * 0.78 : 1 + (wbShift / 100) * 0.55; + const bWb = wbShift <= 0 ? 1 + (-wbShift / 100) * 0.95 : 1 - (wbShift / 100) * 0.55; + const brightOff = brightness / 255; + + const lutR = new Uint8Array(256); + const lutG = new Uint8Array(256); + const lutB = new Uint8Array(256); + for (let i = 0; i < 256; i++) { + const base = i / 255; + for (const [mul, lut] of [[expMul * rWb, lutR], [expMul, lutG], [expMul * bWb, lutB]]) { + let v = Math.min(1, Math.max(0, base * mul)); + if (gamma !== 1) v = Math.pow(v, gamma); + if (contrast !== 1) v = (v - 0.5) * contrast + 0.5; + if (brightOff !== 0) v += brightOff; + lut[i] = v <= 0 ? 0 : v >= 1 ? 255 : Math.round(v * 255); + } + } + + const s = srcData.data; + const d = dstData.data; + const w = srcData.width; + const h = srcData.height; + const totalPixels = w * h; + const useSat = Math.abs(saturation - 1) > 1e-4; + const useSharp = sharpness > 1e-4 && w > 2 && h > 2; + if (useSharp && (!reusableLumaBuf || reusableLumaBuf.length !== totalPixels)) { + reusableLumaBuf = new Float32Array(totalPixels); + } + for (let i = 0, p = 0; i < s.length; i += 4, p++) { + let r = lutR[s[i]]; + let g = lutG[s[i + 1]]; + let b = lutB[s[i + 2]]; + if (useSat) { + const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; + r = Math.min(255, Math.max(0, Math.round(luma + (r - luma) * saturation))); + g = Math.min(255, Math.max(0, Math.round(luma + (g - luma) * saturation))); + b = Math.min(255, Math.max(0, Math.round(luma + (b - luma) * saturation))); + } + d[i] = r; + d[i + 1] = g; + d[i + 2] = b; + d[i + 3] = 255; + if (useSharp) reusableLumaBuf[p] = 0.2126 * r + 0.7152 * g + 0.0722 * b; + } + + if (useSharp) { + const amount = sharpness * 1.45; + const y = reusableLumaBuf; + for (let row = 1; row < h - 1; row++) { + const rOff = row * w; + const up = rOff - w; + const dn = rOff + w; + for (let col = 1; col < w - 1; col++) { + const idx = rOff + col; + const blur = ( + y[up + col - 1] + 2 * y[up + col] + y[up + col + 1] + + 2 * y[idx - 1] + 4 * y[idx] + 2 * y[idx + 1] + + y[dn + col - 1] + 2 * y[dn + col] + y[dn + col + 1] + ) * 0.0625; + const delta = Math.round((y[idx] - blur) * amount); + if (delta !== 0) { + const px = idx << 2; + let r = d[px] + delta; + let g = d[px + 1] + delta; + let b = d[px + 2] + delta; + d[px] = r < 0 ? 0 : r > 255 ? 255 : r; + d[px + 1] = g < 0 ? 0 : g > 255 ? 255 : g; + d[px + 2] = b < 0 ? 0 : b > 255 ? 255 : b; + } + } + } + } +} + +export function drawToneCurve(canvas, params) { + const { exposureEv = 0, gamma = 1, brightness = 0, contrast = 1, wbShift = 0 } = params; + const dpr = Math.min(window.devicePixelRatio || 1, 2); + const w = 156; + const h = 104; + if (canvas.width !== w * dpr || canvas.height !== h * dpr) { + canvas.width = w * dpr; + canvas.height = h * dpr; + } + const ctx = canvas.getContext('2d'); + ctx.save(); + ctx.scale(dpr, dpr); + ctx.fillStyle = '#0f192b'; + ctx.fillRect(0, 0, w, h); + + const pad = 10; + const iw = w - pad * 2; + const ih = h - pad * 2; + ctx.strokeStyle = 'rgba(148, 174, 214, 0.16)'; + ctx.lineWidth = 1; + for (const f of [0.25, 0.5, 0.75]) { + ctx.beginPath(); + ctx.moveTo(pad + iw * f, pad); + ctx.lineTo(pad + iw * f, pad + ih); + ctx.moveTo(pad, pad + ih * f); + ctx.lineTo(pad + iw, pad + ih * f); + ctx.stroke(); + } + // Identity dashed line + ctx.save(); + ctx.setLineDash([3, 3]); + ctx.strokeStyle = 'rgba(203, 213, 225, 0.4)'; + ctx.beginPath(); + ctx.moveTo(pad, pad + ih); + ctx.lineTo(pad + iw, pad); + ctx.stroke(); + ctx.restore(); + + const expMul = Math.pow(2, exposureEv); + const brightOff = brightness / 255; + const plot = (mul, stroke, lw = 2) => { + ctx.beginPath(); + for (let i = 0; i <= 64; i++) { + const x = i / 64; + let v = Math.min(1, Math.max(0, x * mul)); + if (gamma !== 1) v = Math.pow(v, gamma); + if (contrast !== 1) v = (v - 0.5) * contrast + 0.5; + v = Math.min(1, Math.max(0, v + brightOff)); + const px = pad + x * iw; + const py = pad + (1 - v) * ih; + if (i === 0) ctx.moveTo(px, py); + else ctx.lineTo(px, py); + } + ctx.strokeStyle = stroke; + ctx.lineWidth = lw; + ctx.stroke(); + }; + + if (Math.abs(wbShift) > 1) { + const rWb = wbShift >= 0 ? 1 + (wbShift / 100) * 0.78 : 1 + (wbShift / 100) * 0.55; + const bWb = wbShift <= 0 ? 1 + (-wbShift / 100) * 0.95 : 1 - (wbShift / 100) * 0.55; + plot(expMul * rWb, 'rgba(248, 113, 113, 0.72)', 1.3); + plot(expMul * bWb, 'rgba(96, 165, 250, 0.78)', 1.3); + } + plot(expMul, '#60a5fa', 2.2); + ctx.restore(); +} + +export function createCompareStage({ + element, + button, + beforeLabel = '基线 · 调前', + afterLabel = '候选 · 调后', + defaultMode = 'split', + showHistogram = true, + showLoupe = true, +} = {}) { + const el = element || ((tag, text = '', cls = '') => { + const node = document.createElement(tag); + if (cls) node.className = cls; + if (text) node.textContent = text; + return node; + }); + const btn = button || ((text, onClick, variant = 'ghost') => { + const b = el('button', text, 'button ' + variant); + b.type = 'button'; + b.onclick = onClick; + return b; + }); + + let mode = defaultMode; + let pos = 50; + let loupeEnabled = false; + let scopeVisible = showHistogram; + let beforeSource = null; + let afterSource = null; + let curBeforeLabel = beforeLabel; + let curAfterLabel = afterLabel; + let curBeforeMeta = ''; + let curAfterMeta = ''; + let lastStats = { before: null, after: null }; + + const root = el('div', '', 'isp-compare-widget'); + + // Toolbar: Segmented view mode + Loupe toggle + Scope toggle + const toolbar = el('div', '', 'isp-compare-toolbar'); + const modeGroup = el('div', '', 'isp-segmented'); + modeGroup.setAttribute('role', 'group'); + modeGroup.setAttribute('aria-label', '对照视图模式'); + const splitBtn = btn('卷帘对比', () => setMode('split'), 'plain'); + const sideBtn = btn('并排对照', () => setMode('side'), 'plain'); + modeGroup.append(splitBtn, sideBtn); + + const toolGroup = el('div', '', 'isp-compare-tools'); + const loupeBtn = btn('2.5× 放大镜', () => { + loupeEnabled = !loupeEnabled; + syncToolbar(); + if (!loupeEnabled) loupeEl.hidden = true; + }, 'ghost'); + const scopeBtn = btn('实时直方图', () => { + scopeVisible = !scopeVisible; + syncToolbar(); + if (scopeVisible) refreshScope(); + }, 'ghost'); + if (showLoupe) toolGroup.append(loupeBtn); + toolGroup.append(scopeBtn); + toolbar.append(modeGroup, toolGroup); + + // Split curtain container + const splitStage = el('div', '', 'isp-split-stage'); + splitStage.style.setProperty('--split-pos', pos + '%'); + const afterLayer = el('div', '', 'isp-split-layer isp-split-after'); + const beforeLayer = el('div', '', 'isp-split-layer isp-split-before'); + const badgeBefore = el('span', curBeforeLabel, 'isp-stage-badge isp-stage-badge-left'); + const badgeAfter = el('span', curAfterLabel, 'isp-stage-badge isp-stage-badge-right'); + + const divider = el('div', '', 'isp-split-divider'); + const handle = el('button', '', 'isp-split-handle'); + handle.type = 'button'; + handle.setAttribute('role', 'slider'); + handle.setAttribute('aria-label', '左右拖动对比调前与调后画面'); + handle.setAttribute('aria-valuemin', '0'); + handle.setAttribute('aria-valuemax', '100'); + handle.setAttribute('aria-valuenow', String(pos)); + handle.innerHTML = ''; + divider.append(handle); + + // Synchronized 2.5x Loupe overlay + const loupeEl = el('div', '', 'isp-loupe'); + loupeEl.hidden = true; + const loupeCanvas = document.createElement('canvas'); + loupeCanvas.width = 168; + loupeCanvas.height = 168; + const loupeLabel = el('span', '2.5× · 基线 | 候选', 'isp-loupe-label'); + loupeEl.append(loupeCanvas, loupeLabel); + + splitStage.append(afterLayer, beforeLayer, badgeBefore, badgeAfter, divider, loupeEl); + + // Split receipt strip below curtain + const splitMetaBar = el('div', '', 'isp-split-meta'); + const splitMetaLeft = el('span', '', 'isp-split-meta-item'); + const splitMetaRight = el('span', '', 'isp-split-meta-item'); + splitMetaBar.append(splitMetaLeft, splitMetaRight); + + // Side-by-side container + const sideStage = el('div', '', 'comparison-images isp-side-stage'); + const sideBeforeFig = el('figure', '', 'comparison-frame'); + const sideBeforeSlot = el('div', '', 'isp-side-media'); + const sideBeforeCap = el('figcaption', ''); + sideBeforeFig.append(sideBeforeSlot, sideBeforeCap); + + const sideAfterFig = el('figure', '', 'comparison-frame'); + const sideAfterSlot = el('div', '', 'isp-side-media'); + const sideAfterCap = el('figcaption', ''); + sideAfterFig.append(sideAfterSlot, sideAfterCap); + sideStage.append(sideBeforeFig, sideAfterFig); + + // Live Dual RGB/Luma Histogram Scope panel + const scopeBox = el('div', '', 'isp-scope-box'); + const scopeHead = el('div', '', 'isp-scope-head'); + scopeHead.append( + el('strong', '实时亮度与 RGB 直方图'), + el('span', '虚线:基线亮度 · 实线:候选 RGB / 亮度', 'isp-scope-legend'), + ); + const scopeCanvas = document.createElement('canvas'); + scopeCanvas.className = 'isp-scope-canvas'; + scopeCanvas.setAttribute('aria-label', '调前调后实时直方图'); + const metricsBar = el('div', '', 'isp-scope-metrics'); + scopeBox.append(scopeHead, scopeCanvas, metricsBar); + + root.append(toolbar, splitStage, splitMetaBar, sideStage, scopeBox); + + function syncToolbar() { + splitBtn.className = 'isp-seg-btn' + (mode === 'split' ? ' active' : ''); + splitBtn.setAttribute('aria-pressed', String(mode === 'split')); + sideBtn.className = 'isp-seg-btn' + (mode === 'side' ? ' active' : ''); + sideBtn.setAttribute('aria-pressed', String(mode === 'side')); + loupeBtn.className = 'button ' + (loupeEnabled ? 'primary' : 'ghost'); + loupeBtn.setAttribute('aria-pressed', String(loupeEnabled)); + scopeBtn.className = 'button ' + (scopeVisible ? 'primary' : 'ghost'); + scopeBtn.setAttribute('aria-pressed', String(scopeVisible)); + splitStage.hidden = mode !== 'split'; + splitMetaBar.hidden = mode !== 'split' || (!curBeforeMeta && !curAfterMeta); + sideStage.hidden = mode !== 'side'; + scopeBox.hidden = !scopeVisible; + } + + function setPosition(nextPct) { + pos = Math.max(0, Math.min(100, Math.round(nextPct * 10) / 10)); + splitStage.style.setProperty('--split-pos', pos + '%'); + handle.setAttribute('aria-valuenow', String(Math.round(pos))); + } + + function syncAspectRatio() { + const src = afterSource || beforeSource; + if (!src) return; + const isCanvas = src instanceof HTMLCanvasElement; + const nw = isCanvas ? src.width : src.naturalWidth; + const nh = isCanvas ? src.height : src.naturalHeight; + if (nw > 0 && nh > 0) { + splitStage.style.aspectRatio = `${nw} / ${nh}`; + sideBeforeSlot.style.aspectRatio = `${nw} / ${nh}`; + sideAfterSlot.style.aspectRatio = `${nw} / ${nh}`; + } + } + + function syncLabels() { + badgeBefore.textContent = curBeforeLabel; + badgeAfter.textContent = curAfterLabel; + splitMetaLeft.textContent = curBeforeMeta ? `${curBeforeLabel} · ${curBeforeMeta}` : ''; + splitMetaRight.textContent = curAfterMeta ? `${curAfterLabel} · ${curAfterMeta}` : ''; + splitMetaBar.hidden = mode !== 'split' || (!curBeforeMeta && !curAfterMeta); + + sideBeforeCap.textContent = curBeforeLabel; + if (curBeforeMeta) sideBeforeCap.append(el('small', curBeforeMeta, 'isp-demo-receipt')); + sideAfterCap.textContent = curAfterLabel; + if (curAfterMeta) sideAfterCap.append(el('small', curAfterMeta, 'isp-demo-receipt')); + } + + function syncMediaMount() { + if (!beforeSource || !afterSource) return; + if (mode === 'split') { + beforeLayer.replaceChildren(beforeSource); + afterLayer.replaceChildren(afterSource); + } else { + sideBeforeSlot.replaceChildren(beforeSource); + sideAfterSlot.replaceChildren(afterSource); + } + syncAspectRatio(); + } + + function setMode(nextMode) { + mode = nextMode === 'side' ? 'side' : 'split'; + syncMediaMount(); + syncToolbar(); + } + + function formatDelta(beforeVal, afterVal, digits = 1, suffix = '') { + const diff = afterVal - beforeVal; + const sign = diff > 0.05 ? '+' : ''; + return `${beforeVal.toFixed(digits)}${suffix} → ${afterVal.toFixed(digits)}${suffix} (${sign}${diff.toFixed(digits)}${suffix})`; + } + + function refreshScope() { + syncAspectRatio(); + const bStats = sampleSource(beforeSource); + const aStats = sampleSource(afterSource); + lastStats = { before: bStats, after: aStats }; + if (!scopeVisible) return lastStats; + renderHistogramCanvas(scopeCanvas, bStats, aStats); + if (bStats && aStats) { + metricsBar.replaceChildren( + metricPill('均亮 Y', formatDelta(bStats.meanLuma, aStats.meanLuma, 1)), + metricPill('暗部 (<16)', formatDelta(bStats.darkPct, aStats.darkPct, 1, '%')), + metricPill('高光裁切 (>248)', formatDelta(bStats.clipPct, aStats.clipPct, 1, '%')), + metricPill('平均饱和度', formatDelta(bStats.meanSat, aStats.meanSat, 1)), + metricPill('边缘锐度', formatDelta(bStats.edgeSharpness, aStats.edgeSharpness, 1)), + ); + } + return lastStats; + } + + function metricPill(name, value) { + const item = el('div', '', 'isp-scope-metric'); + item.append(el('span', name), el('strong', value)); + return item; + } + + // Curtain pointer dragging + let dragging = false; + const updateFromClientX = clientX => { + const rect = splitStage.getBoundingClientRect(); + if (!rect.width) return; + setPosition(((clientX - rect.left) / rect.width) * 100); + }; + + splitStage.addEventListener('pointerdown', event => { + if (event.button !== 0 && event.pointerType === 'mouse') return; + dragging = true; + splitStage.setPointerCapture?.(event.pointerId); + updateFromClientX(event.clientX); + }); + splitStage.addEventListener('pointermove', event => { + if (dragging) updateFromClientX(event.clientX); + if (loupeEnabled && beforeSource && afterSource) { + drawLoupe(event.clientX, event.clientY); + } + }); + const stopDrag = () => { dragging = false; }; + splitStage.addEventListener('pointerup', stopDrag); + splitStage.addEventListener('pointercancel', stopDrag); + splitStage.addEventListener('pointerleave', () => { + dragging = false; + loupeEl.hidden = true; + }); + + handle.addEventListener('keydown', event => { + const step = event.shiftKey ? 1 : 5; + if (event.key === 'ArrowLeft') { event.preventDefault(); setPosition(pos - step); } + else if (event.key === 'ArrowRight') { event.preventDefault(); setPosition(pos + step); } + else if (event.key === 'Home') { event.preventDefault(); setPosition(0); } + else if (event.key === 'End') { event.preventDefault(); setPosition(100); } + }); + + function drawLoupe(clientX, clientY) { + const rect = splitStage.getBoundingClientRect(); + if (!rect.width || !rect.height) return; + const u = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)); + const v = Math.max(0, Math.min(1, (clientY - rect.top) / rect.height)); + const isCanvas = afterSource instanceof HTMLCanvasElement; + const nw = isCanvas ? afterSource.width : afterSource.naturalWidth; + const nh = isCanvas ? afterSource.height : afterSource.naturalHeight; + if (!nw || !nh) return; + + const zoom = 2.5; + const size = loupeCanvas.width; + const sw = (size / zoom) * (nw / rect.width); + const sh = (size / zoom) * (nh / rect.height); + const sx = Math.max(0, Math.min(nw - sw, u * nw - sw / 2)); + const sy = Math.max(0, Math.min(nh - sh, v * nh - sh / 2)); + + const ctx = loupeCanvas.getContext('2d'); + ctx.clearRect(0, 0, size, size); + // Left half = Baseline 2.5x + ctx.save(); + ctx.beginPath(); + ctx.rect(0, 0, size / 2, size); + ctx.clip(); + ctx.drawImage(beforeSource, sx, sy, sw, sh, 0, 0, size, size); + ctx.restore(); + // Right half = Candidate 2.5x + ctx.save(); + ctx.beginPath(); + ctx.rect(size / 2, 0, size / 2, size); + ctx.clip(); + ctx.drawImage(afterSource, sx, sy, sw, sh, 0, 0, size, size); + ctx.restore(); + // Center hairline divider + ctx.fillStyle = 'rgba(255,255,255,0.92)'; + ctx.fillRect(size / 2 - 1, 0, 2, size); + + // Position loupe smartly inside stage + const lx = Math.max(8, Math.min(rect.width - size - 8, clientX - rect.left + 18)); + const ly = Math.max(8, Math.min(rect.height - size - 28, clientY - rect.top - size / 2)); + loupeEl.style.left = lx + 'px'; + loupeEl.style.top = ly + 'px'; + loupeEl.hidden = false; + } + + let imgToken = 0; + function setImages({ + beforeSrc, + afterSrc, + beforeLabel: bLabel, + afterLabel: aLabel, + beforeMeta: bMeta = '', + afterMeta: aMeta = '', + beforeAlt = '基线画面', + afterAlt = '候选画面', + }) { + const token = ++imgToken; + if (bLabel !== undefined) curBeforeLabel = bLabel; + if (aLabel !== undefined) curAfterLabel = aLabel; + curBeforeMeta = bMeta; + curAfterMeta = aMeta; + + const bImg = document.createElement('img'); + const aImg = document.createElement('img'); + bImg.className = 'isp-compare-media'; + aImg.className = 'isp-compare-media'; + bImg.alt = beforeAlt; + aImg.alt = afterAlt; + bImg.decoding = 'async'; + aImg.decoding = 'async'; + + let loaded = 0; + const onLoad = () => { + if (token !== imgToken) return; + loaded++; + syncAspectRatio(); + if (loaded >= 2 || (bImg.complete && aImg.complete)) refreshScope(); + }; + bImg.onload = onLoad; + aImg.onload = onLoad; + bImg.src = beforeSrc; + aImg.src = afterSrc; + + beforeSource = bImg; + afterSource = aImg; + syncMediaMount(); + syncLabels(); + syncToolbar(); + if (bImg.complete && aImg.complete) onLoad(); + } + + function setCanvases({ + beforeCanvas, + afterCanvas, + beforeLabel: bLabel, + afterLabel: aLabel, + beforeMeta: bMeta = '', + afterMeta: aMeta = '', + }) { + imgToken++; + if (bLabel !== undefined) curBeforeLabel = bLabel; + if (aLabel !== undefined) curAfterLabel = aLabel; + curBeforeMeta = bMeta; + curAfterMeta = aMeta; + beforeCanvas.className = 'isp-compare-media'; + afterCanvas.className = 'isp-compare-media'; + beforeSource = beforeCanvas; + afterSource = afterCanvas; + syncMediaMount(); + syncLabels(); + syncToolbar(); + refreshScope(); + } + + syncToolbar(); + return { + root, + setImages, + setCanvases, + refreshScope, + setPosition, + setMode, + getStats: () => lastStats, + }; +} diff --git a/plugins/rdk-camera-workshop/web/index.html b/plugins/rdk-camera-workshop/web/index.html index 5b9e9a9..e207049 100644 --- a/plugins/rdk-camera-workshop/web/index.html +++ b/plugins/rdk-camera-workshop/web/index.html @@ -11,91 +11,470 @@
视觉 PipelineRDK Workshop
-
+
+ + + + + +
-

RDK X5 + SONY IMX415

从相机出图到板端检测

跟着当前一步操作,保存回执后继续。

-
未开始课堂进度 · 180 分钟
+

RDK X5 + SONY IMX415

从相机出图到板端检测

按左侧流程推进,也可以直接点选任意环节查看并记录。

+
+
+ 未开始 + 课堂进度 · 180 分钟 +
+
+ + +
+
+
+ +
-
-
-

正在读取本工位进度…

+ +
+
+ +
+ + +
+
+

正在读取本实验进度…

-
Studio 工具
+
对应 Studio 工具链
- 其他工位工具与记录 + 更多课堂工具与记录 +
-
-

工位连接预检

待检查
+
+

设备连接检查

待检查

采集前检查相机服务、板卡连接和当前画面。只读取已开启的相机流。

-
+
-

本工位相机实验

+

本组相机实验

-
+

照片与三张基线图

-

-
+

+
-
+

ISP 调参 · 两轮 Gamma 与单项练习

-
+
+
+

相机参数

+
+
+
+
+
+
-

单项 ISP 实操

+

单项实操记录

-
- 讲师演示 · 现场调曝光与五项实拍 +
+ 本组离线标定 +
+

+ +
+ + +
+
+ 离线标定示例 +

正在读取示例…

+ + +
+
+ 讲师演示 · 现场调曝光与八项实拍
-

五项归档对照

+

八项归档对照

-
-

+

-

同一区域对照

+
+

同一区域对照

+
+ +
+
+
+
-
+
diff --git a/plugins/rdk-camera-workshop/web/isp-demo.mjs b/plugins/rdk-camera-workshop/web/isp-demo.mjs index c631a93..2cb8595 100644 --- a/plugins/rdk-camera-workshop/web/isp-demo.mjs +++ b/plugins/rdk-camera-workshop/web/isp-demo.mjs @@ -1,3 +1,5 @@ +import { createCompareStage } from '/image-compare.mjs'; + const demoRoot='/isp-demo/'; export async function renderIspDemo({$,element,button}) { const tabs=$('isp-demo-tabs'), panel=$('isp-demo-panel'); @@ -5,6 +7,7 @@ export async function renderIspDemo({$,element,button}) { const response=await fetch(demoRoot+'manifest.json'); if(!response.ok) throw new Error(); const {samples}=await response.json(); + const stage=createCompareStage({element,button,defaultMode:'split',showHistogram:true,showLoupe:true}); const controls=samples.map(sample=>button(sample.title,()=>select(sample),'ghost')); tabs.replaceChildren(...controls); function select(sample) { @@ -13,19 +16,21 @@ export async function renderIspDemo({$,element,button}) { control.setAttribute('aria-pressed',String(selected)); control.className='button '+(selected?'primary':'ghost'); } - const grid=element('div','','comparison-images isp-demo-pair'); - for(const [stage,label] of [['before','调前'],['after','调后']]) { - const data=sample[stage]; - const figure=element('figure','','comparison-frame'); - const img=element('img');img.src=demoRoot+data.image;img.alt=sample.title+' · '+label+'实拍'; - const caption=element('figcaption',label+'读值 · '+data.value); - caption.append(element('small',data.field+' · 回读 '+data.readbackHash.slice(0,12),'isp-demo-receipt')); - figure.append(img,caption);grid.append(figure); - } + stage.setImages({ + beforeSrc:demoRoot+sample.before.image, + afterSrc:demoRoot+sample.after.image, + beforeLabel:'调前 · '+sample.before.value, + afterLabel:'调后 · '+sample.after.value, + beforeMeta:sample.before.field+' · 回读 '+sample.before.readbackHash.slice(0,12), + afterMeta:sample.after.field+' · 回读 '+sample.after.readbackHash.slice(0,12), + beforeAlt:sample.title+' · 调前实拍', + afterAlt:sample.title+' · 调后实拍', + }); + stage.setPosition(50); const source=element('div',sample.device+' · '+sample.date+' · '+sample.source,'isp-demo-source'); const detail=element('a','下载实拍与参数索引','button plain'); detail.href=demoRoot+'manifest.json';detail.download='讲师-ISP实拍回读索引.json'; - panel.replaceChildren(element('p',sample.context,'action-copy'),grid, + panel.replaceChildren(element('p',sample.context,'action-copy'),stage.root, element('p',sample.observation,'isp-demo-observation'),source,detail); } select(samples[0]); diff --git a/plugins/rdk-camera-workshop/web/isp-demo/brightness-after.jpg b/plugins/rdk-camera-workshop/web/isp-demo/brightness-after.jpg new file mode 100644 index 0000000..6a8bf67 Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-demo/brightness-after.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/brightness-before.jpg b/plugins/rdk-camera-workshop/web/isp-demo/brightness-before.jpg new file mode 100644 index 0000000..96cf984 Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-demo/brightness-before.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/contrast-after.jpg b/plugins/rdk-camera-workshop/web/isp-demo/contrast-after.jpg index 16f3a87..8a8931e 100644 Binary files a/plugins/rdk-camera-workshop/web/isp-demo/contrast-after.jpg and b/plugins/rdk-camera-workshop/web/isp-demo/contrast-after.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/contrast-before.jpg b/plugins/rdk-camera-workshop/web/isp-demo/contrast-before.jpg index 0544c6b..906c4de 100644 Binary files a/plugins/rdk-camera-workshop/web/isp-demo/contrast-before.jpg and b/plugins/rdk-camera-workshop/web/isp-demo/contrast-before.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/exposure-after.jpg b/plugins/rdk-camera-workshop/web/isp-demo/exposure-after.jpg index d187ed8..5b9afcd 100644 Binary files a/plugins/rdk-camera-workshop/web/isp-demo/exposure-after.jpg and b/plugins/rdk-camera-workshop/web/isp-demo/exposure-after.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/exposure-before.jpg b/plugins/rdk-camera-workshop/web/isp-demo/exposure-before.jpg index 1a78cb8..c458dde 100644 Binary files a/plugins/rdk-camera-workshop/web/isp-demo/exposure-before.jpg and b/plugins/rdk-camera-workshop/web/isp-demo/exposure-before.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/gain-after.jpg b/plugins/rdk-camera-workshop/web/isp-demo/gain-after.jpg index 99b4a8d..39b9536 100644 Binary files a/plugins/rdk-camera-workshop/web/isp-demo/gain-after.jpg and b/plugins/rdk-camera-workshop/web/isp-demo/gain-after.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/gain-before.jpg b/plugins/rdk-camera-workshop/web/isp-demo/gain-before.jpg index bf6d955..5f8526b 100644 Binary files a/plugins/rdk-camera-workshop/web/isp-demo/gain-before.jpg and b/plugins/rdk-camera-workshop/web/isp-demo/gain-before.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/hue-after.jpg b/plugins/rdk-camera-workshop/web/isp-demo/hue-after.jpg new file mode 100644 index 0000000..7472d66 Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-demo/hue-after.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/hue-before.jpg b/plugins/rdk-camera-workshop/web/isp-demo/hue-before.jpg new file mode 100644 index 0000000..1659470 Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-demo/hue-before.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/manifest.json b/plugins/rdk-camera-workshop/web/isp-demo/manifest.json index 9577e5d..c44b24d 100644 --- a/plugins/rdk-camera-workshop/web/isp-demo/manifest.json +++ b/plugins/rdk-camera-workshop/web/isp-demo/manifest.json @@ -4,103 +4,127 @@ { "id": "exposure", "title": "曝光", - "context": "手动曝光,保持增益固定。", - "observation": "看灯具边缘和暗区。曝光时间改变时,要同时检查高光还有没有细节。", + "context": "固定手动增益(1.22×)与手动白平衡/CPROC,仅调整曝光时间(7.5 ms → 30.0 ms)。", + "observation": "对比中央水杯文字图案、底部书页纹理、左侧深色背包与顶棚灯带。拉长曝光时间可显著提亮暗部主体并降低噪点,但顶棚灯带高光也会更早饱和。", "device": "RDK X5 · Sony IMX415", - "source": "既有实机 AI 调试归档", - "runId": "86cbe76f-5c21-43ab-849c-6e1be20cd435", - "date": "2026-10-29", + "source": "实机桌面实景受控单变量 AE 归档", + "runId": "9ee6b2f3-f239-4ab9-a454-de7710a22d3f", + "date": "2026-12-01", "before": { "image": "exposure-before.jpg", - "imageSha256": "6a3819bc3240730bc325bcaaccd03e368e485a2ece29012e4ca9df7fc67d7a14", - "sourceImageSha256": "495a99cd4de2bd70b1a9e4281d57d4d75bc260fe17ef268575af8bedbadb6988", - "value": "30.0 ms", - "frameId": "4aca1b81-585b-4b9f-be0d-48f9c6a42635", - "readbackHash": "08e30cf9657e9ad2f066c568b1442109d35ce35078a4d4fdca4833280ac235cb", + "imageSha256": "0b957e0db409ffb78a3f2b52ebe986d1e9f86e576fe7d85e5481e52e6a92d9cf", + "sourceImageSha256": "359b3f7b23c9c349568049fb2205358db545d16e64c8f7ebb2c4c048c884ebc0", + "sourceCrop": [ + 160, + 180, + 3520, + 2070 + ], + "value": "7.5 ms", + "frameId": "4c8936d6-3783-460b-ab4e-6bdcd05c39ab", + "readbackHash": "e9d2010c8138b8e3f421dddeb02d120876335d22c66b974980b9662aea89ec62", "field": "exposureUs", - "actualValue": 30000.001192092896 + "actualValue": 7493.8274919986725 }, "after": { "image": "exposure-after.jpg", - "imageSha256": "43f86325e054e203e7ec7cb8d7aa4fbde1daadf9698b915c48adb75b5e48022a", - "sourceImageSha256": "09ce32f3de79ac5dcbfe716109b3f32fe0f1f90c820470f9399aa23109c3aad8", - "value": "20.0 ms", - "frameId": "9cbf159c-391f-43aa-b473-f11b6aef95aa", - "readbackHash": "ba8f207796fb4c7e209b4d69ead3e0c79c691d45f67358640533f17776e0bb5c", + "imageSha256": "64d376d2098cb3a1c803dd6c8676a522ad0fb7f8064c29f45db1754674a7afeb", + "sourceImageSha256": "229c3683a353d7580c04eb1abd367098cac79d3f2229c84a1daf25ab868c9215", + "sourceCrop": [ + 160, + 180, + 3520, + 2070 + ], + "value": "30.0 ms", + "frameId": "32e9d70f-9390-49f0-9047-57fd430b6579", + "readbackHash": "0eb7258eeaf415ff0c8ab92e122c35e8088c2021fa647c6b3dbb73670ea106f2", "field": "exposureUs", - "actualValue": 20000.001415610313 + "actualValue": 30000.001192092896 } }, { "id": "gain", "title": "增益", - "context": "自动曝光现场回读。这对画面也记录到了色彩处理的轻微变化。", - "observation": "放大看暗处的纹理和颗粒。要比较增益本身的影响,现场应固定曝光并比较多帧。", + "context": "固定短曝光(7.5 ms)与手动白平衡/CPROC,仅调整模拟增益(1.00× → 8.00×)。", + "observation": "打开 2.5× 放大镜对准水杯磨砂表面与背景暗区。高增益虽能把暗画面快速提亮,但会同步引入明显的传感器颗粒噪点。", "device": "RDK X5 · Sony IMX415", - "source": "既有实机 AI 调试归档", - "runId": "f8419aa7-7736-42ca-8c41-94e0fa443e83", - "date": "2026-10-28", + "source": "实机桌面实景受控单变量 Gain 归档", + "runId": "9ee6b2f3-f239-4ab9-a454-de7710a22d3f", + "date": "2026-12-01", "before": { "image": "gain-before.jpg", - "imageSha256": "28123fcf673ac532002ca18bd8e26df52b01e09ba2d199f0783dedf305043664", - "sourceImageSha256": "914c899d2227a51018dab7ad4bfc55ff33b890270ae541ec7dc141ad2ce3acc7", + "imageSha256": "9745e52e8fe078eb60434b89958bf3db44ceca29d33d75e57357dbf95022e6f8", + "sourceImageSha256": "20d79c565f615591c45f57510c47910b238e1c2337e21247ccfe5e4d302029c8", "sourceCrop": [ - 390, - 40, - 3390, - 1728 + 160, + 180, + 3520, + 2070 ], - "value": "1.0219 ×", - "frameId": "8b1bde53-e468-44fd-98e1-17f76140748e", - "readbackHash": "dec4c8dc33fa0178a9a20f65eb27a76861f5a01c652107c22337195888b20f96", + "value": "1.00 ×", + "frameId": "efc410a7-cf7a-49aa-85d5-3d0617027649", + "readbackHash": "873eb050d0544bdabdc89b563c463b9199127ed0348fcf71284ca56f24c8f533", "field": "gain", - "actualValue": 1.0218971967697144 + "actualValue": 1 }, "after": { "image": "gain-after.jpg", - "imageSha256": "96d97f39b2b17f067d431c9b2ef3172edd1450e953fc1372a4c12f69ca19ab84", - "sourceImageSha256": "3493ce1e12bc4eafe7f3ccf77889a3e846bd2cae4c91331d45cc95203f8bb2e6", + "imageSha256": "5aade47580d473c0b7908973799a7ace677f9ea6f52fee0b04f79ebc520005ea", + "sourceImageSha256": "399857b8cbaf868fbe82a1d11bceaec1b4bd632f4881acefd35a5c29415f777a", "sourceCrop": [ - 390, - 40, - 3390, - 1728 + 160, + 180, + 3520, + 2070 ], - "value": "1.1388 ×", - "frameId": "4c6cc49f-982a-4503-8039-e3920aa3954e", - "readbackHash": "078a6e4e80e570de05c02f037f0e36b46b730946d75ffde5cfc5d90273c88b49", + "value": "8.00 ×", + "frameId": "65ed1891-c503-4f46-9a14-c2f656f81a37", + "readbackHash": "5bc3c747a677fab81d7b3687ab5aeb93ef5dd67ccf5f476494288f7fbf0b4850", "field": "gain", - "actualValue": 1.1387885808944702 + "actualValue": 8 } }, { "id": "contrast", "title": "对比度", - "context": "固定手动色彩处理模式,改 CPROC 对比度。", - "observation": "看顶棚与暗处交界。对比度提高时,留意暗部或亮部是否丢掉层次。", + "context": "固定手动曝光(30.0 ms / 1.10×)与手动白平衡,仅调整 CPROC 对比度(0.45 → 1.80)。", + "observation": "观察下方实时亮度直方图宽度与画面反差。低对比度时像素缩在中间发灰,拉高对比度后暗部压实、亮部拉开,但过高会牺牲两端过渡层次。", "device": "RDK X5 · Sony IMX415", - "source": "既有实机 AI 调试归档", - "runId": "a0e4574b-5d92-4000-9a0d-8f73c84a33a2", - "date": "2026-10-29", + "source": "实机受控单变量 CPROC 归档", + "runId": "a2b3db6a-3b7e-4286-9c12-7f9df1ddffa7", + "date": "2026-12-01", "before": { "image": "contrast-before.jpg", - "imageSha256": "d049f28cb84465f1de74d5b91c5f3c720a6d080d6f1a29d7ec8b6462bc7aa2ee", - "sourceImageSha256": "c264fd306f3d8f257628c5845c76c1bc52ae62438fd174b554cf863890821656", - "value": "1", - "frameId": "d3171290-af5e-44df-ae14-88ff11733670", - "readbackHash": "51246444a941cc20ea40935ab91874bb0a02e0d6793fe687ba6e2a27f43de922", + "imageSha256": "3e9e0b5a27890c3103859f37fdcfb7a0e8c8a67f8efd66d74c48833742b8dbfb", + "sourceImageSha256": "3689f3d53b3d2861f61fb03b754ab2999d8d4cdd9182f7f498190f6f53085370", + "sourceCrop": [ + 0, + 0, + 3360, + 1890 + ], + "value": "0.45", + "frameId": "f8e725b3-b372-4098-958b-28f5a3ee1c6d", + "readbackHash": "d651cee64465f3668d8753c9c81a44162ef696d613c5d40cde42d59773e74e7d", "field": "contrast", - "actualValue": 1 + "actualValue": 0.453125 }, "after": { "image": "contrast-after.jpg", - "imageSha256": "5ffa615224277a31145ce79017ea32a6ca522259d6dc0efa01f41090ecf95342", - "sourceImageSha256": "7918dcc1b9a82303c58a2109cd9b9f535a6bb7a3dd6320488bdf83d6b13af1d4", - "value": "1.03125", - "frameId": "c6bc3da6-6fdd-4c03-89c3-0be46418c168", - "readbackHash": "9595436cf682e95ec39f50b5ac4e4eb678e960d1f59fa0d93850c6d6ad75b03e", + "imageSha256": "c8b2c459fb7225cf9f2cc7db8d37cbb063cd11e998f37b2b6bda4679889747df", + "sourceImageSha256": "1205b05b200f9eeb26d2b0e4971e3bd04ea5b34b4f7841fd43148a3d1529d4d8", + "sourceCrop": [ + 0, + 0, + 3360, + 1890 + ], + "value": "1.80", + "frameId": "1720da52-46fa-4179-b6ac-f2392e72454e", + "readbackHash": "6ba64d1da84dfbf782c396b18162b4352e83923de9e0f149f0eb3c87229bca13", "field": "contrast", - "actualValue": 1.03125 + "actualValue": 1.796875 } }, { @@ -157,44 +181,168 @@ "id": "white-balance", "title": "白平衡", "device": "RDK X5 · Sony IMX415", - "source": "既有实机 AWB 数值归档 · 纸面局部", - "date": "2026-10-19", - "receiptSha256": "c7aa5c50475f17446cf1e3bae0074e02dc1a8c7bfd61889f9dff7cd290c5f36c", - "context": "固定曝光与其他白平衡通道,观察蓝通道增益。", - "observation": "看同一张纸在调整前后的偏色。普通纸面可帮助观察,色彩验收需要标准灰卡。", + "source": "实机桌面实景受控单变量 AWB 归档", + "date": "2026-12-01", + "context": "固定手动曝光与固定红通道增益(1.86×),仅调整 AWB 蓝通道增益(3.40× → 1.35×)。", + "observation": "紧盯米白水杯和底部白纸书页从偏冷蓝变为偏暖黄,并观察下方 RGB 直方图中蓝曲线的整段左移。", "before": { "image": "white-balance-before.jpg", - "imageSha256": "0faf51c30f821ae471826eefdeae06d2f414bc8999c467700bb381c8266e060c", - "sourceImageSha256": "f074d829a74d677930c3f7d94c1edbba8195cb27e91955ed346a7957f9e76bf1", + "imageSha256": "1749dde3a72087baab76411f1c1c0b18ac93c7f4a2c6f3e3e2999a1c09a7137f", + "sourceImageSha256": "b8cc55518c45c61c37f0d23f4f2dd283d583b1963ee7ca511357a507f0f2835d", "sourceCrop": [ - 284, - 0, - 684, - 380 + 160, + 180, + 3520, + 2070 ], - "value": "2.4717 ×", - "actualValue": 2.4716796875, + "value": "3.40 ×", + "frameId": "fcdfed84-f95b-414d-bdeb-98f2ce09e211", + "readbackHash": "bacfb17c41c8b2890924d9e2e98db1a88d13dff3ce666f004a90c19e47afc16d", "field": "AWB 蓝通道增益", - "frameSha256": "933b20a62fd61481084158a4f0f05a14abc013c15b41a043035c7b78e4f04a97", - "sdkTimestampNs": "9099320854000", - "readbackHash": "31c79d5a0f6dfa6435afff4b45bc6e9f0624cfee6ed6092cfc5c3bacfd5b4475" + "actualValue": 3.400390625 }, "after": { "image": "white-balance-after.jpg", - "imageSha256": "c733e171fef81a28d0e4ff44d87a7b095aa51e725919599a9c2854ad9d1e3f7c", - "sourceImageSha256": "29a5e5c03fa4550a8b471c4d73d83713d4437af6a84483c6b009cbdd1ba289a4", + "imageSha256": "2fbe1b4135c2ba39bb8dd8a385d88bb048231d1de68def458836a10a2ae78895", + "sourceImageSha256": "93e53a4407be684141af2837af0acb7f97164e29dad1d13ea39c8518b346e531", "sourceCrop": [ - 284, - 0, - 684, - 380 + 160, + 180, + 3520, + 2070 ], - "value": "2.3730 ×", - "actualValue": 2.373046875, + "value": "1.35 ×", + "frameId": "d2404d05-1878-4f45-a191-4ad8e5bf3401", + "readbackHash": "b1addc52ce77484fde550c3c51deabc9fe0a63812aeef37453923eb013fbc833", "field": "AWB 蓝通道增益", - "frameSha256": "60028ff23048f9b9a35aa65d0a3db097098a613dd57ad84acffa367525cbd0f1", - "sdkTimestampNs": "9109154186000", - "readbackHash": "269f26d9f27453a679469b111de69d84e110238f17c192d0c463373cf559f7ad" + "actualValue": 1.349609375 + }, + "runId": "9ee6b2f3-f239-4ab9-a454-de7710a22d3f" + }, + { + "id": "brightness", + "title": "亮度", + "context": "固定手动曝光(30.0 ms / 1.22×)与手动白平衡,仅调整 CPROC 亮度偏移(-30 → +45)。", + "observation": "亮度是对整幅像素做线性加减偏移:-30 压暗暗部背包与书页,+45 抬亮暗部的同时会让黑位发灰、亮部高光裁切占比明显增加。", + "device": "RDK X5 · Sony IMX415", + "source": "实机桌面实景受控单变量 CPROC 归档", + "runId": "9ee6b2f3-f239-4ab9-a454-de7710a22d3f", + "date": "2026-12-01", + "before": { + "image": "brightness-before.jpg", + "imageSha256": "3e52c68df60bf511aa5cfdaea01073fca491c63214c54d2b389d87b10da12214", + "sourceImageSha256": "95a7af2a76dcce31aafa68ef7e448486e97992bb994cfcb8f4a89abbee61428a", + "sourceCrop": [ + 160, + 180, + 3520, + 2070 + ], + "value": "-30", + "frameId": "8a53b14a-decc-4054-9237-8d1b9576f38a", + "readbackHash": "6432a49c6a78751a687c0c5b15810457c161c51c4e15fb2f6d11c8d3478683f1", + "field": "brightness", + "actualValue": -30 + }, + "after": { + "image": "brightness-after.jpg", + "imageSha256": "6058cba14031c8199ed17278255a8ecf0ea2356a2d19b4f87a05c1e442bd5d2d", + "sourceImageSha256": "94c04ed058953030581b9614a717aacf2f225440183f05ffe7f6af73c6658dd0", + "sourceCrop": [ + 160, + 180, + 3520, + 2070 + ], + "value": "+45", + "frameId": "19358f62-d9ce-4fbf-ae1e-e7fa3092948b", + "readbackHash": "e7cdfe9ddafbc09e0aec116e0cfac333aa29c7a76e4e167f972cc3742f1d2c4f", + "field": "brightness", + "actualValue": 45 + } + }, + { + "id": "saturation", + "title": "饱和度", + "context": "固定手动曝光(30.0 ms / 1.22×)与手动白平衡,仅调整 CPROC 色彩饱和度(0.20 → 1.90)。", + "observation": "对比右侧淡黄圆点杯、绿色安全出口灯、绿植与米色水杯:亮度均值几乎不变,但色彩从近乎黑白灰变为浓郁高饱和,过高时容易出现色彩溢出。", + "device": "RDK X5 · Sony IMX415", + "source": "实机桌面实景受控单变量 CPROC 归档", + "runId": "9ee6b2f3-f239-4ab9-a454-de7710a22d3f", + "date": "2026-12-01", + "before": { + "image": "saturation-before.jpg", + "imageSha256": "9764627be9c0c0b1861776d4df54cdd639ca22851f97cc26e8d5c508f223824a", + "sourceImageSha256": "f9cbd19293053b97f9e8af5945c6d2f53fdfb216097d43022b8319e5be6503f1", + "sourceCrop": [ + 160, + 180, + 3520, + 2070 + ], + "value": "0.20", + "frameId": "5766fcf8-1c6f-4113-aba7-044d14622992", + "readbackHash": "180a0ab3d536a8ab5517d4da948955dd79edc51baee14155647c0a9b1efaa56e", + "field": "saturation", + "actualValue": 0.203125 + }, + "after": { + "image": "saturation-after.jpg", + "imageSha256": "abda7211b4c940b0276d2e62956f4b864a88ee19db8455c581c9f30d0247f0ab", + "sourceImageSha256": "3ffb326e17e47c4f22bfcf910bef39c46c5eb860c6d92d0aa824f726c9705118", + "sourceCrop": [ + 160, + 180, + 3520, + 2070 + ], + "value": "1.90", + "frameId": "140b367a-1d3e-470d-9baf-0a8603e2fa1d", + "readbackHash": "01cc40c24f9bb34927eb692673bb2aef4e1e99a5f5ef568a7438e20e82769bad", + "field": "saturation", + "actualValue": 1.8984375 + } + }, + { + "id": "hue", + "title": "色调", + "context": "固定手动曝光、手动白平衡与其他 CPROC 参数,仅旋转 CPROC 色调相位(0° → +45°)。", + "observation": "对比右侧黄杯、水杯本体、绿色标识与蓝灰背包的整幅色相偏转。色调用于校正轻微色相偏转,日常调试通常微调 ±5°~15°。", + "device": "RDK X5 · Sony IMX415", + "source": "实机桌面实景受控单变量 CPROC 归档", + "runId": "9ee6b2f3-f239-4ab9-a454-de7710a22d3f", + "date": "2026-12-01", + "before": { + "image": "hue-before.jpg", + "imageSha256": "1a6cb15977be32f4cbe321d8cae91f5570ef79f33988342b1cc3afd8f92605a7", + "sourceImageSha256": "32f1e475befe5956a81504589d39015f9c90092c9d471a6cd9d78a4d322531c1", + "sourceCrop": [ + 160, + 180, + 3520, + 2070 + ], + "value": "0°", + "frameId": "4a721679-018e-446b-b1ba-ccd120b513aa", + "readbackHash": "0eb7258eeaf415ff0c8ab92e122c35e8088c2021fa647c6b3dbb73670ea106f2", + "field": "hue", + "actualValue": 0 + }, + "after": { + "image": "hue-after.jpg", + "imageSha256": "eeab2cd8ce07eac176106dacfe86b030b5805a6e605625f9170d719d6d42a20f", + "sourceImageSha256": "a9ecd9e37d12711dc6b80ec0d80ef5a57ae36b31fc4c101a707c2cbbd6469be2", + "sourceCrop": [ + 160, + 180, + 3520, + 2070 + ], + "value": "+45°", + "frameId": "b9a1d863-0067-4d05-946c-dc8d4f157f32", + "readbackHash": "3272ccfe29bb8edbcfb6ea76ac74050b9338b7aa71749ea53903cc5d8496fc24", + "field": "hue", + "actualValue": 45 } } ] diff --git a/plugins/rdk-camera-workshop/web/isp-demo/saturation-after.jpg b/plugins/rdk-camera-workshop/web/isp-demo/saturation-after.jpg new file mode 100644 index 0000000..d265928 Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-demo/saturation-after.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/saturation-before.jpg b/plugins/rdk-camera-workshop/web/isp-demo/saturation-before.jpg new file mode 100644 index 0000000..5cacd89 Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-demo/saturation-before.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/white-balance-after.jpg b/plugins/rdk-camera-workshop/web/isp-demo/white-balance-after.jpg index e963cbf..7e4c0d3 100644 Binary files a/plugins/rdk-camera-workshop/web/isp-demo/white-balance-after.jpg and b/plugins/rdk-camera-workshop/web/isp-demo/white-balance-after.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-demo/white-balance-before.jpg b/plugins/rdk-camera-workshop/web/isp-demo/white-balance-before.jpg index 1fda539..a965c6f 100644 Binary files a/plugins/rdk-camera-workshop/web/isp-demo/white-balance-before.jpg and b/plugins/rdk-camera-workshop/web/isp-demo/white-balance-before.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-engine.mjs b/plugins/rdk-camera-workshop/web/isp-engine.mjs new file mode 100644 index 0000000..48fee0c --- /dev/null +++ b/plugins/rdk-camera-workshop/web/isp-engine.mjs @@ -0,0 +1,867 @@ +/** + * Isomorphic Zero-Dependency Linear-Light 10-Parameter ISP Engine, + * Bayer RAW Demosaic Pipeline, Objective Image Analyzer & 2-Pass Auto-ISP Solver. + * + * Runs identically in both Browser Canvas (ES Module) and Node.js MCP Server so + * AI chat renders and live Practice Lab sliders achieve bit-exact parity with + * zero Python / Pillow / native-addon requirements. + */ + +export const DEFAULT_ISP_PARAMS = Object.freeze({ + exposureEv: 0, + shadows: 0, + highlights: 0, + gamma: 1, + brightness: 0, + contrast: 1, + saturation: 1, + wbShift: 0, + denoise: 0, + sharpness: 0, +}); + +export const ISP_PARAM_BOUNDS = Object.freeze({ + exposureEv: [-2, 2], + shadows: [-100, 100], + highlights: [-100, 100], + gamma: [0.55, 1.45], + brightness: [-60, 60], + contrast: [0.5, 1.8], + saturation: [0, 2], + wbShift: [-50, 50], + denoise: [0, 1], + sharpness: [0, 2], +}); + +export const ISP_PARAM_STEPS = Object.freeze({ + exposureEv: 0.05, + shadows: 1, + highlights: 1, + gamma: 0.05, + brightness: 1, + contrast: 0.05, + saturation: 0.05, + wbShift: 1, + denoise: 0.05, + sharpness: 0.05, +}); + +export const ISP_PARAM_KEYS = Object.freeze(Object.keys(DEFAULT_ISP_PARAMS)); + +const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v); +const clampByte = (v) => (v <= 0 ? 0 : v >= 255 ? 255 : (v + 0.5) | 0); + +// Exact IEC 61966-2-1 sRGB <-> Linear RGB lookup tables +const SRGB_TO_LINEAR = new Float32Array(256); +for (let i = 0; i < 256; i++) { + const c = i / 255; + SRGB_TO_LINEAR[i] = c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); +} + +const LINEAR_LUT_SIZE = 4096; +const LINEAR_TO_SRGB = new Uint8Array(LINEAR_LUT_SIZE + 1); +for (let i = 0; i <= LINEAR_LUT_SIZE; i++) { + const lin = i / LINEAR_LUT_SIZE; + const s = lin <= 0.0031308 ? 12.92 * lin : 1.055 * Math.pow(lin, 1 / 2.4) - 0.055; + LINEAR_TO_SRGB[i] = clampByte(s * 255); +} + +function linearToSrgbFloat(lin) { + if (lin <= 0) return 0; + if (lin >= 1) return 1; + return lin <= 0.0031308 ? 12.92 * lin : 1.055 * Math.pow(lin, 1 / 2.4) - 0.055; +} + +function quantizeParam(key, raw) { + const [lo, hi] = ISP_PARAM_BOUNDS[key]; + const step = ISP_PARAM_STEPS[key]; + const clamped = clamp(Number(raw), lo, hi); + if (!Number.isFinite(clamped)) return DEFAULT_ISP_PARAMS[key]; + const snapped = Math.round(clamped / step) * step; + return Number(clamp(snapped, lo, hi).toFixed(step < 1 ? 2 : 0)); +} + +export function normalizeIspParams(input = {}, base = DEFAULT_ISP_PARAMS) { + const out = {}; + for (const key of ISP_PARAM_KEYS) { + const raw = input && Object.hasOwn(input, key) && input[key] !== undefined && input[key] !== null + ? input[key] + : (base && Object.hasOwn(base, key) ? base[key] : DEFAULT_ISP_PARAMS[key]); + out[key] = quantizeParam(key, raw); + } + return out; +} + +export function applyIspDelta(baseParams, delta = {}) { + const base = normalizeIspParams(baseParams); + const out = { ...base }; + for (const key of ISP_PARAM_KEYS) { + if (delta && Object.hasOwn(delta, key) && Number.isFinite(Number(delta[key]))) { + out[key] = quantizeParam(key, base[key] + Number(delta[key])); + } + } + return out; +} + +export function formatIspParamSummary(p) { + const n = normalizeIspParams(p); + const parts = []; + if (Math.abs(n.exposureEv) > 1e-6) parts.push((n.exposureEv > 0 ? '+' : '') + n.exposureEv.toFixed(1) + 'EV'); + if (Math.abs(n.shadows) >= 1) parts.push('暗部' + (n.shadows > 0 ? '+' : '') + Math.round(n.shadows)); + if (Math.abs(n.highlights) >= 1) parts.push('高光' + (n.highlights > 0 ? '+' : '') + Math.round(n.highlights)); + if (Math.abs(n.gamma - 1) > 1e-6) parts.push('γ' + n.gamma.toFixed(2)); + if (Math.abs(n.brightness) >= 1) parts.push('亮' + (n.brightness > 0 ? '+' : '') + Math.round(n.brightness)); + if (Math.abs(n.contrast - 1) > 1e-6) parts.push('对比' + n.contrast.toFixed(2)); + if (Math.abs(n.saturation - 1) > 1e-6) parts.push('饱和' + n.saturation.toFixed(2)); + if (Math.abs(n.wbShift) >= 1) parts.push('色温' + (n.wbShift > 0 ? '+' : '') + Math.round(n.wbShift)); + if (n.denoise > 1e-6) parts.push('降噪' + n.denoise.toFixed(2)); + if (n.sharpness > 1e-6) parts.push('锐度' + n.sharpness.toFixed(2)); + return parts.length ? parts.join(' ') : '原始未调'; +} + +// Fast separable box blur for smooth local luminance guide (WDR / LTM) +function boxBlur1D(src, dst, width, height, radius, horizontal) { + const win = radius * 2 + 1; + const inv = 1 / win; + if (horizontal) { + for (let y = 0; y < height; y++) { + const row = y * width; + let acc = src[row] * (radius + 1); + for (let k = 1; k <= radius; k++) acc += src[row + Math.min(width - 1, k)]; + for (let x = 0; x < width; x++) { + dst[row + x] = acc * inv; + const removeIdx = Math.max(0, x - radius); + const addIdx = Math.min(width - 1, x + radius + 1); + acc += src[row + addIdx] - src[row + removeIdx]; + } + } + } else { + for (let x = 0; x < width; x++) { + let acc = src[x] * (radius + 1); + for (let k = 1; k <= radius; k++) acc += src[Math.min(height - 1, k) * width + x]; + for (let y = 0; y < height; y++) { + dst[y * width + x] = acc * inv; + const removeIdx = Math.max(0, y - radius); + const addIdx = Math.min(height - 1, y + radius + 1); + acc += src[addIdx * width + x] - src[removeIdx * width + x]; + } + } + } +} + +function smoothLuminanceMap(luma, width, height) { + const n = width * height; + const r = Math.max(4, Math.min(28, Math.round(Math.min(width, height) / 22))); + const tmp = new Float32Array(n); + const out = new Float32Array(n); + boxBlur1D(luma, tmp, width, height, r, true); + boxBlur1D(tmp, out, width, height, r, false); + // Second pass approximates Gaussian blur cleanly without halos + boxBlur1D(out, tmp, width, height, r, true); + boxBlur1D(tmp, out, width, height, r, false); + return out; +} + +/** + * Core Linear-Light 10-Parameter ISP Pixel Pipeline. + * Accepts interleaved RGB (stride=3) or RGBA (stride=4) Uint8Array / Uint8ClampedArray. + * Returns same layout buffer. + */ +export function applyIspPipeline(srcBytes, width, height, rawParams = {}, stride = 3) { + const p = normalizeIspParams(rawParams); + const count = width * height; + const out = stride === 4 ? new Uint8ClampedArray(count * 4) : new Uint8Array(count * 3); + + const isIdentity = + Math.abs(p.exposureEv) < 1e-6 && + Math.abs(p.shadows) < 1e-6 && + Math.abs(p.highlights) < 1e-6 && + Math.abs(p.gamma - 1) < 1e-6 && + Math.abs(p.brightness) < 1e-6 && + Math.abs(p.contrast - 1) < 1e-6 && + Math.abs(p.saturation - 1) < 1e-6 && + Math.abs(p.wbShift) < 1e-6 && + p.denoise < 1e-6 && + p.sharpness < 1e-6; + + if (isIdentity) { + out.set(srcBytes); + return out; + } + + // Stage 1: sRGB -> Linear RGB + Linear Exposure + Linear White Balance + const evGain = Math.pow(2, p.exposureEv); + // Physical color temperature shift in linear light (spans full 2800K tungsten <-> 6500K daylight AWB!) + const wbRatio = p.wbShift / 50; // -1..+1 + const rWbRaw = Math.pow(2, wbRatio * 0.88); + const bWbRaw = Math.pow(2, -wbRatio * 1.18); + const lumaNorm = 1 / (0.2126 * rWbRaw + 0.7152 + 0.0722 * bWbRaw); + const rGain = evGain * rWbRaw * lumaNorm; + const gGain = evGain * lumaNorm; + const bGain = evGain * bWbRaw * lumaNorm; + + const linR = new Float32Array(count); + const linG = new Float32Array(count); + const linB = new Float32Array(count); + const useWdr = Math.abs(p.shadows) >= 1 || Math.abs(p.highlights) >= 1; + const lumaForWdr = useWdr ? new Float32Array(count) : null; + + for (let i = 0, o = 0; i < count; i++, o += stride) { + const r = SRGB_TO_LINEAR[srcBytes[o]] * rGain; + const g = SRGB_TO_LINEAR[srcBytes[o + 1]] * gGain; + const b = SRGB_TO_LINEAR[srcBytes[o + 2]] * bGain; + linR[i] = r; + linG[i] = g; + linB[i] = b; + if (lumaForWdr) { + // Soft perceptual log-like luminance guide for WDR mask + const y = 0.2126 * r + 0.7152 * g + 0.0722 * b; + lumaForWdr[i] = y / (1 + y * 0.35); + } + } + + // Stage 2: Edge-preserving Perceptual Bilateral 2DNR (Chroma + Luma noise reduction before tone/sharpen!) + if (p.denoise > 0.01 && width >= 3 && height >= 3) { + const strength = p.denoise; + // Perceptual-domain range sigma (gamma ~0.5) handles both dark shadows and midtones uniformly + const sigmaP = 0.065 + 0.22 * strength; + const inv2Sig2 = 1 / (2 * sigmaP * sigmaP); + const lumaBlend = 0.68 * strength; + const chromaBlend = 0.88 * strength; + const dR = new Float32Array(linR); + const dG = new Float32Array(linG); + const dB = new Float32Array(linB); + const pyPlane = new Float32Array(count); + for (let i = 0; i < count; i++) { + const y = 0.2126 * linR[i] + 0.7152 * linG[i] + 0.0722 * linB[i]; + pyPlane[i] = Math.sqrt(y > 0 ? y : 0); + } + + for (let y = 1; y < height - 1; y++) { + const row = y * width; + for (let x = 1; x < width - 1; x++) { + const idx = row + x; + const cr = linR[idx]; + const cg = linG[idx]; + const cb = linB[idx]; + const cy = 0.2126 * cr + 0.7152 * cg + 0.0722 * cb; + const cpy = pyPlane[idx]; + let wSum = 1.0; + let sR = cr, sG = cg, sB = cb, sY = cy; + + for (let dy = -1; dy <= 1; dy++) { + const nRow = (y + dy) * width; + for (let dx = -1; dx <= 1; dx++) { + if (dx === 0 && dy === 0) continue; + const nIdx = nRow + x + dx; + const diff = pyPlane[nIdx] - cpy; + const spatial = (dx === 0 || dy === 0) ? 0.9 : 0.65; + const w = spatial * Math.exp(-(diff * diff) * inv2Sig2); + const nr = linR[nIdx]; + const ng = linG[nIdx]; + const nb = linB[nIdx]; + wSum += w; + sR += nr * w; + sG += ng * w; + sB += nb * w; + sY += (0.2126 * nr + 0.7152 * ng + 0.0722 * nb) * w; + } + } + const avgR = sR / wSum, avgG = sG / wSum, avgB = sB / wSum, avgY = sY / wSum; + const targetY = cy + (avgY - cy) * lumaBlend; + const cR = (cr - cy) + ((avgR - avgY) - (cr - cy)) * chromaBlend; + const cG = (cg - cy) + ((avgG - avgY) - (cg - cy)) * chromaBlend; + const cB = (cb - cy) + ((avgB - avgY) - (cb - cy)) * chromaBlend; + dR[idx] = Math.max(0, targetY + cR); + dG[idx] = Math.max(0, targetY + cG); + dB[idx] = Math.max(0, targetY + cB); + } + } + linR.set(dR); + linG.set(dG); + linB.set(dB); + } + + // Stage 3: Local Tone Mapping / WDR (Shadows & Highlights separation) + if (useWdr && lumaForWdr) { + const smoothY = smoothLuminanceMap(lumaForWdr, width, height); + const shStrength = p.shadows / 100; // -1..+1 + const hiStrength = p.highlights / 100; // -1..+1 + for (let i = 0; i < count; i++) { + const sy = clamp(smoothY[i], 0, 1.5); + // Smooth shadow weight peaks for dark regions (sy < 0.35), vanishes in highlights + const shadowMask = Math.pow(clamp(1 - sy * 2.2, 0, 1), 1.65); + // Smooth highlight weight peaks for bright regions (sy > 0.45), vanishes in shadows + const hiMask = Math.pow(clamp((sy - 0.38) / 0.72, 0, 1), 1.5); + const gain = Math.pow(2, shStrength * 1.45 * shadowMask + hiStrength * 1.15 * hiMask); + linR[i] *= gain; + linG[i] *= gain; + linB[i] *= gain; + } + } + + // Stage 4: Soft Highlight Roll-off (Filmic shoulder above 0.88 linear so HDR preserves sky detail) + // + Linear Color Saturation + sRGB encode + Gamma/Brightness/Contrast + const sat = p.saturation; + const gamma = p.gamma; + const brightOffset = p.brightness / 255; + const contrast = p.contrast; + const hasShoulder = p.exposureEv > 0.2 || p.highlights < -10 || p.shadows > 20; + + const srgbR = new Float32Array(count); + const srgbG = new Float32Array(count); + const srgbB = new Float32Array(count); + + const shoulder = (x) => { + if (x <= 0) return 0; + if (!hasShoulder || x <= 0.85) return x > 1 ? 1 : x; + // Smooth Reinhard shoulder on [0.85, +inf) -> [0.85, 1.0) + const excess = x - 0.85; + return 0.85 + 0.15 * (excess / (excess + 0.15)); + }; + + for (let i = 0; i < count; i++) { + let r = linR[i]; + let g = linG[i]; + let b = linB[i]; + + // Linear-light saturation (preserves hue accuracy far better than sRGB saturation) + if (Math.abs(sat - 1) > 1e-6) { + const y = 0.2126 * r + 0.7152 * g + 0.0722 * b; + r = Math.max(0, y + (r - y) * sat); + g = Math.max(0, y + (g - y) * sat); + b = Math.max(0, y + (b - y) * sat); + } + + r = linearToSrgbFloat(shoulder(r)); + g = linearToSrgbFloat(shoulder(g)); + b = linearToSrgbFloat(shoulder(b)); + + if (Math.abs(gamma - 1) > 1e-6) { + r = Math.pow(r, gamma); + g = Math.pow(g, gamma); + b = Math.pow(b, gamma); + } + + if (Math.abs(contrast - 1) > 1e-6 || Math.abs(brightOffset) > 1e-6) { + r = clamp((r - 0.5) * contrast + 0.5 + brightOffset, 0, 1); + g = clamp((g - 0.5) * contrast + 0.5 + brightOffset, 0, 1); + b = clamp((b - 0.5) * contrast + 0.5 + brightOffset, 0, 1); + } + + srgbR[i] = r * 255; + srgbG[i] = g * 255; + srgbB[i] = b * 255; + } + + // Stage 5: Luma-only 3x3 Unsharp Mask (prevents color fringing!) with gentle halo clamp + if (p.sharpness > 0.005 && width >= 3 && height >= 3) { + const amount = p.sharpness; + const maxDelta = amount > 1.35 ? 95 : 42; // allows intentional over-sharpen demo at sharpness=2.0 while protecting normal tuning + const yPlane = new Float32Array(count); + for (let i = 0; i < count; i++) { + yPlane[i] = 0.299 * srgbR[i] + 0.587 * srgbG[i] + 0.114 * srgbB[i]; + } + + for (let y = 0; y < height; y++) { + const row = y * width; + const borderY = y === 0 || y === height - 1; + for (let x = 0; x < width; x++) { + const idx = row + x; + let delta = 0; + if (!borderY && x > 0 && x < width - 1) { + const blur = ( + yPlane[idx - width - 1] + 2 * yPlane[idx - width] + yPlane[idx - width + 1] + + 2 * yPlane[idx - 1] + 4 * yPlane[idx] + 2 * yPlane[idx + 1] + + yPlane[idx + width - 1] + 2 * yPlane[idx + width] + yPlane[idx + width + 1] + ) * 0.0625; + const hp = yPlane[idx] - blur; + // Coring threshold suppresses tiny noise amplification while sharpening real edges + if (Math.abs(hp) > 1.2) { + delta = clamp(hp * amount, -maxDelta, maxDelta); + } + } + const o = idx * stride; + out[o] = clampByte(srgbR[idx] + delta); + out[o + 1] = clampByte(srgbG[idx] + delta); + out[o + 2] = clampByte(srgbB[idx] + delta); + if (stride === 4) out[o + 3] = srcBytes[o + 3]; + } + } + } else { + for (let i = 0, o = 0; i < count; i++, o += stride) { + out[o] = clampByte(srgbR[i]); + out[o + 1] = clampByte(srgbG[i]); + out[o + 2] = clampByte(srgbB[i]); + if (stride === 4) out[o + 3] = srcBytes[o + 3]; + } + } + + return out; +} + +/** + * Demosaic 8/10/12/16-bit Bayer RAW into sRGB 8-bit RGB buffer + * (BLC subtraction -> Bilinear Demosaic -> sRGB encode) so real sensor RAW files + * flow directly into the 10-parameter linear ISP pipeline. + */ +export function demosaicBayerRaw(rawBuffer, { + width, + height, + pattern = 'RGGB', + bitDepth = 10, + blackLevel = 64, +} = {}) { + const w = Number(width); + const h = Number(height); + if (!Number.isInteger(w) || !Number.isInteger(h) || w < 4 || h < 4) { + throw new Error('isp_raw_invalid_dimensions'); + } + const pat = String(pattern || 'RGGB').toUpperCase(); + if (!['RGGB', 'BGGR', 'GRBG', 'GBRG'].includes(pat)) { + throw new Error('isp_raw_invalid_pattern'); + } + const bits = Number(bitDepth) || 10; + const bytes = rawBuffer instanceof Uint8Array ? rawBuffer : new Uint8Array(rawBuffer); + const count = w * h; + const is8Bit = bits <= 8 && bytes.length >= count && bytes.length < count * 2; + if (!is8Bit && bytes.length < count * 2) { + throw new Error('isp_raw_truncated'); + } + + const maxVal = (1 << bits) - 1; + const blc = Array.isArray(blackLevel) ? blackLevel : [blackLevel, blackLevel, blackLevel, blackLevel]; + const plane = new Float32Array(count); + const dv = is8Bit ? null : new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + + // Determine channel code per (y&1, x&1): 0=R, 1=Gr/Gb, 2=B + const cellChar = (y, x) => pat[((y & 1) << 1) | (x & 1)]; + const blcIdx = (y, x) => ((y & 1) << 1) | (x & 1); + + for (let y = 0; y < h; y++) { + const row = y * w; + for (let x = 0; x < w; x++) { + const idx = row + x; + const sample = is8Bit ? bytes[idx] : dv.getUint16(idx * 2, true); + const bVal = Number(blc[blcIdx(y, x)]) || 0; + const denom = Math.max(1, maxVal - bVal); + plane[idx] = clamp((sample - bVal) / denom, 0, 1); + } + } + + const rgb = new Uint8Array(count * 3); + const at = (y, x) => plane[clamp(y, 0, h - 1) * w + clamp(x, 0, w - 1)]; + + for (let y = 0; y < h; y++) { + for (let x = 0; x < w; x++) { + const ch = cellChar(y, x); + let r, g, b; + if (ch === 'R') { + r = at(y, x); + g = 0.25 * (at(y - 1, x) + at(y + 1, x) + at(y, x - 1) + at(y, x + 1)); + b = 0.25 * (at(y - 1, x - 1) + at(y - 1, x + 1) + at(y + 1, x - 1) + at(y + 1, x + 1)); + } else if (ch === 'B') { + b = at(y, x); + g = 0.25 * (at(y - 1, x) + at(y + 1, x) + at(y, x - 1) + at(y, x + 1)); + r = 0.25 * (at(y - 1, x - 1) + at(y - 1, x + 1) + at(y + 1, x - 1) + at(y + 1, x + 1)); + } else { + // Green site: check whether horizontal neighbor is R or B + g = at(y, x); + const horizIsR = cellChar(y, x + 1) === 'R'; + if (horizIsR) { + r = 0.5 * (at(y, x - 1) + at(y, x + 1)); + b = 0.5 * (at(y - 1, x) + at(y + 1, x)); + } else { + b = 0.5 * (at(y, x - 1) + at(y, x + 1)); + r = 0.5 * (at(y - 1, x) + at(y + 1, x)); + } + } + const o = (y * w + x) * 3; + rgb[o] = LINEAR_TO_SRGB[Math.round(clamp(r, 0, 1) * LINEAR_LUT_SIZE)]; + rgb[o + 1] = LINEAR_TO_SRGB[Math.round(clamp(g, 0, 1) * LINEAR_LUT_SIZE)]; + rgb[o + 2] = LINEAR_TO_SRGB[Math.round(clamp(b, 0, 1) * LINEAR_LUT_SIZE)]; + } + } + return { width: w, height: h, data: rgb }; +} + +/** + * Full objective image quality analyzer (runs on RGB stride=3 or RGBA stride=4). + */ +export function analyzeIspImage(bytes, width, height, stride = 3) { + const count = width * height; + const histY = new Uint32Array(256); + let sumR = 0, sumG = 0, sumB = 0, sumY = 0, sumY2 = 0, sumSat = 0; + let dark = 0, clip = 0; + // Bright-neutral pixels (Y in [95, 238]) give cleaner WB cast estimation than dark shadows + let midR = 0, midG = 0, midB = 0, midCount = 0; + + const yPlane = new Float32Array(count); + for (let i = 0, o = 0; i < count; i++, o += stride) { + const r = bytes[o]; + const g = bytes[o + 1]; + const b = bytes[o + 2]; + const y = 0.299 * r + 0.587 * g + 0.114 * b; + yPlane[i] = y; + const yb = clampByte(y); + histY[yb]++; + sumR += r; + sumG += g; + sumB += b; + sumY += y; + sumY2 += y * y; + const mx = r >= g && r >= b ? r : g >= b ? g : b; + const mn = r <= g && r <= b ? r : g <= b ? g : b; + sumSat += mx - mn; + if (y < 16) dark++; + if (y > 248) clip++; + if (y >= 85 && y <= 240) { + midR += r; + midG += g; + midB += b; + midCount++; + } + } + + // Percentiles p05, p50, p95 + const pct = (q) => { + const target = Math.max(1, Math.round(count * q)); + let acc = 0; + for (let v = 0; v < 256; v++) { + acc += histY[v]; + if (acc >= target) return v; + } + return 255; + }; + const p05Luma = pct(0.05); + const medianLuma = pct(0.5); + const p95Luma = pct(0.95); + const meanLuma = sumY / count; + const contrastStd = Math.sqrt(Math.max(0, sumY2 / count - meanLuma * meanLuma)); + const darkPct = (dark * 100) / count; + const clipPct = (clip * 100) / count; + const meanSat = sumSat / count; + + // Edge sharpness (Laplacian mean abs) + flat-patch noise estimate (MAD on low-gradient pixels) + let lapSum = 0; + let lapCount = 0; + let flatNoiseSum = 0; + let flatCount = 0; + const stepY = height > 360 ? 2 : 1; + const stepX = width > 480 ? 2 : 1; + for (let y = 1; y < height - 1; y += stepY) { + const row = y * width; + for (let x = 1; x < width - 1; x += stepX) { + const idx = row + x; + const c = yPlane[idx]; + const gx = Math.abs(yPlane[idx + 1] - yPlane[idx - 1]); + const gy = Math.abs(yPlane[idx + width] - yPlane[idx - width]); + const lap = Math.abs(4 * c - yPlane[idx - 1] - yPlane[idx + 1] - yPlane[idx - width] - yPlane[idx + width]); + lapSum += lap; + lapCount++; + if (gx < 12 && gy < 12) { + flatNoiseSum += lap * 0.25; + flatCount++; + } + } + } + const edgeSharpness = lapCount ? lapSum / lapCount : 0; + const noiseEstimate = flatCount ? flatNoiseSum / flatCount : 0; + + const chR = sumR / count; + const chG = sumG / count; + const chB = sumB / count; + const wbR = midCount > count * 0.04 ? midR / midCount : chR; + const wbG = midCount > count * 0.04 ? midG / midCount : chG; + const wbB = midCount > count * 0.04 ? midB / midCount : chB; + + const hazeScore = clamp( + (Math.max(0, p05Luma - 24) / 45) * 0.65 + (Math.max(0, 52 - contrastStd) / 36) * 0.35, + 0, + 1, + ); + + return { + meanLuma: Number(meanLuma.toFixed(2)), + medianLuma: Number(medianLuma.toFixed(1)), + p05Luma, + p95Luma, + dynamicRange: p95Luma - p05Luma, + contrastStd: Number(contrastStd.toFixed(2)), + darkPct: Number(darkPct.toFixed(2)), + clipPct: Number(clipPct.toFixed(2)), + meanSat: Number(meanSat.toFixed(2)), + edgeSharpness: Number(edgeSharpness.toFixed(2)), + noiseEstimate: Number(noiseEstimate.toFixed(2)), + channelMeans: [Number(chR.toFixed(1)), Number(chG.toFixed(1)), Number(chB.toFixed(1))], + wbSampleMeans: [Number(wbR.toFixed(1)), Number(wbG.toFixed(1)), Number(wbB.toFixed(1))], + wbCastIndex: Number((wbR - wbB).toFixed(1)), + hazeScore: Number(hazeScore.toFixed(2)), + }; +} + +/** + * Parse relative natural-language tweak directives (Chinese / English) into bounded deltas. + * Enables pure natural-language multi-turn refinement ("再冷一点、暗部再提一点、锐度降一点"). + */ +export function parseRelativeGoalDelta(goalText = '') { + const g = String(goalText || '').trim(); + if (!g) return {}; + const delta = {}; + const add = (k, v) => { delta[k] = (delta[k] || 0) + v; }; + + // Exposure / brightness + if (/再亮|更亮|亮一点|提亮一点|曝光高|brighter|lift exposure/i.test(g)) add('exposureEv', 0.25); + if (/暗一点|再暗|压暗|降低曝光|曝光低|darker|dimmer/i.test(g)) add('exposureEv', -0.25); + // Shadows / highlights + if (/暗部再|阴影再|暗处再|提暗部|救暗|more shadow|lift shadow/i.test(g)) add('shadows', 25); + if (/压暗部|黑位更实|暗部压|deeper black/i.test(g)) add('shadows', -20); + if (/压高光|保高光|别过曝|不过曝|防过曝|高光压|protect highlight|recover highlight/i.test(g)) add('highlights', -35); + if (/高光亮|提亮高光|brighter highlight/i.test(g)) add('highlights', 20); + // White balance + if (/再冷|更冷|冷一点|去黄|少点黄|偏冷|cooler|less yellow|less warm/i.test(g)) add('wbShift', -12); + if (/再暖|更暖|暖一点|去蓝|少点蓝|偏暖|warmer|less blue|less cool/i.test(g)) add('wbShift', 12); + // Contrast / haze + if (/去雾|去灰|更通透|反差大|对比度高|加对比|more contrast|dehaze|punchier/i.test(g)) { + add('contrast', 0.15); + add('brightness', -6); + } + if (/柔和|对比度低|减对比|发硬|softer contrast|less contrast/i.test(g)) add('contrast', -0.15); + // Saturation + if (/更鲜艳|色彩浓|加饱和|饱和度高|more vivid|more saturat/i.test(g)) add('saturation', 0.15); + if (/淡一点|自然一点|别太艳|减饱和|饱和度低|less saturat|more natural/i.test(g)) add('saturation', -0.15); + // Sharpness + if (/更清晰|再锐|加锐|锐度高|锐度加|字更清|sharper|more sharp/i.test(g)) add('sharpness', 0.25); + if (/别太锐|降锐|少锐|去白边|锐度低|锐度降|锐度减|锐度少|减锐|less sharp|softer edge/i.test(g)) add('sharpness', -0.30); + // Denoise + if (/降噪|噪点|颗粒|更干净|denoise|less noise|cleaner/i.test(g)) add('denoise', 0.25); + if (/少降噪|保留纹理|less denoise/i.test(g)) add('denoise', -0.20); + + return delta; +} + +/** + * 2-Pass Closed-Loop Auto-ISP Diagnostic Solver. + * + * Pass 1: Diagnoses physical image faults from real pixel statistics + honors natural-language goal. + * Pass 2: Renders candidate pixels, re-measures actual output telemetry, and automatically corrects + * highlight clipping, WB overshoot, residual shadow darkness, or post-lift noise explosion. + */ +export function solveAutoIsp(srcBytes, width, height, goalText = '', stride = 3) { + const goal = String(goalText || '').trim(); + const before = analyzeIspImage(srcBytes, width, height, stride); + const p = { ...DEFAULT_ISP_PARAMS }; + const defects = []; + + const wantProtectHighlights = /不过曝|别过曝|防过曝|保高光|逆光|高光|highlight|hdr|wdr/i.test(goal); + const wantLiftDarks = /暗|黑|看不清|提亮|救亮|水杯|文字|字|lowlight|dark|bright|text|clear/i.test(goal); + const wantNeutralWb = /白平衡|偏色|偏黄|偏暖|偏冷|偏蓝|还原白|中性白|white balance|wb|cast|yellow|warm|cool/i.test(goal); + const wantDehaze = /去雾|去灰|通透|发灰|发白|反差|对比|dehaze|haze|contrast/i.test(goal); + const wantSharp = /锐|清晰|细节|刻度|文字|字|sharp|detail|crisp/i.test(goal); + const wantDenoise = /降噪|噪点|颗粒|干净|denoise|noise|clean/i.test(goal); + const wantNatural = /自然|真实|克制|别太艳|natural|subtle/i.test(goal); + const wantVivid = /鲜艳|艳丽|生动|vivid|colorful/i.test(goal); + + // 1. Diagnose Backlight / High Dynamic Range vs Global Underexposure + const isBacklit = (before.darkPct >= 10 && (before.clipPct >= 1.5 || before.p95Luma >= 232)) || + (before.p95Luma >= 238 && before.p05Luma <= 20 && before.medianLuma < 95); + const isUnderexposed = !isBacklit && (before.meanLuma < 96 || before.darkPct > 18); + const isOverexposed = before.meanLuma > 185 || before.clipPct > 12; + + if (isBacklit) { + defects.push('大光比逆光(暗部压黑且亮部接近裁切)'); + p.exposureEv = -0.15; + p.highlights = -62; + p.shadows = 68; + p.gamma = 0.80; + p.contrast = 1.12; + p.saturation = 1.12; + p.denoise = 0.20; + p.sharpness = 0.35; + } else if (isUnderexposed) { + defects.push(`低照度欠曝(均亮 ${before.meanLuma},暗部 ${before.darkPct}%)`); + const deficit = clamp((122 - before.meanLuma) / 72, 0.25, 1.35); + p.exposureEv = clamp(0.45 + deficit * 0.72, 0.35, 1.35); + p.shadows = clamp(Math.round(35 + deficit * 32), 25, 78); + p.highlights = before.p95Luma > 205 || wantProtectHighlights ? -45 : -20; + p.gamma = clamp(0.88 - deficit * 0.14, 0.68, 0.90); + p.contrast = 1.12; + p.saturation = wantNatural ? 1.08 : 1.18; + p.denoise = clamp(0.18 + deficit * 0.24, 0.15, 0.48); + p.sharpness = wantSharp || wantLiftDarks ? 0.50 : 0.35; + } else if (isOverexposed) { + defects.push(`画面偏亮/过曝(均亮 ${before.meanLuma},过曝 ${before.clipPct}%)`); + p.exposureEv = -0.55; + p.highlights = -65; + p.gamma = 1.12; + p.contrast = 1.08; + } + + // 2. Diagnose Haze / Lifted Black Floor (must have low saturation too — never confuse colorful bright scenes!) + const isHazy = before.hazeScore >= 0.45 && before.p05Luma >= 34 && before.darkPct < 4 && before.meanSat < 48; + if (isHazy || wantDehaze) { + if (isHazy) defects.push(`雾感/黑位抬升(P05=${before.p05Luma},标准差 ${before.contrastStd})`); + const hPow = isHazy ? clamp(before.hazeScore, 0.5, 1.0) : 0.65; + p.brightness = Math.min(p.brightness, -Math.round(12 + hPow * 12)); + p.contrast = Math.max(p.contrast, 1.25 + hPow * 0.30); + p.gamma = isUnderexposed ? p.gamma : Math.max(p.gamma, 1.12 + hPow * 0.10); + p.saturation = Math.max(p.saturation, 1.25 + hPow * 0.18); + p.sharpness = Math.max(p.sharpness, 0.45); + } + + // 3. Diagnose White Balance Color Cast (Warm / Cool) in linear ratio domain + const [wbR, wbG, wbB] = before.wbSampleMeans; + const rbDiff = wbR - wbB; + const rgRatio = wbR / Math.max(12, wbG); + const bgRatio = wbB / Math.max(12, wbG); + const strongWarm = rbDiff > 22 && rgRatio > 1.05 && bgRatio < 0.95; + const strongCool = rbDiff < -22 && bgRatio > 1.05 && rgRatio < 0.95; + if (strongWarm || (wantNeutralWb && rbDiff > 10)) { + defects.push(`暖黄白平衡偏色(R-B=${rbDiff.toFixed(1)})`); + // Linear ratio ≈ (wbR/wbB)^2.2; wbShift linear span is 2^(2.06 * wbRatio) + const linLog2 = 2.2 * Math.log2(Math.max(1.02, wbR / Math.max(12, wbB))); + p.wbShift = clamp(-Math.round((linLog2 / 2.06) * 50), -46, -10); + if (!isHazy && !isUnderexposed) { + p.exposureEv = Math.max(p.exposureEv, 0.05); + p.contrast = Math.max(p.contrast, 1.05); + p.saturation = wantNatural ? 1.02 : 1.08; + } + } else if (strongCool || (wantNeutralWb && rbDiff < -10)) { + defects.push(`偏冷蓝白平衡偏色(R-B=${rbDiff.toFixed(1)})`); + const linLog2 = 2.2 * Math.log2(Math.max(1.02, wbB / Math.max(12, wbR))); + p.wbShift = clamp(Math.round((linLog2 / 2.06) * 50), 10, 46); + } + + // 4. Diagnose Soft Detail / Low Sharpness & High Noise + if (before.edgeSharpness < 6.0 && !isOverexposed) { + defects.push(`细节偏软(边缘锐度 ${before.edgeSharpness})`); + p.sharpness = Math.max(p.sharpness, wantSharp ? 1.05 : 0.65); + p.contrast = Math.max(p.contrast, 1.12); + p.saturation = Math.max(p.saturation, wantNatural ? 1.08 : 1.20); + } else if (wantSharp) { + defects.push('强化局部边缘清晰度(抑制过锐白边)'); + p.sharpness = Math.max(p.sharpness, 0.95); + p.contrast = Math.max(p.contrast, 1.12); + } + if (before.noiseEstimate > 4.2 || wantDenoise) { + if (before.noiseEstimate > 4.2) defects.push(`暗部/平滑区噪点偏高(${before.noiseEstimate})`); + p.denoise = Math.max(p.denoise, wantDenoise ? 0.45 : 0.30); + } + + // 5. Apply Natural-Language Goal Modifiers + if (wantProtectHighlights) { + p.highlights = Math.min(p.highlights, -60); + if (p.exposureEv > 0.70) p.exposureEv = 0.70; + } + if (wantLiftDarks && !isUnderexposed && !isBacklit) { + p.shadows = Math.max(p.shadows, 42); + p.exposureEv = Math.max(p.exposureEv, 0.35); + p.gamma = Math.min(p.gamma, 0.85); + } + if (wantVivid) p.saturation = Math.max(p.saturation, 1.30); + if (wantNatural && p.saturation > 1.15) p.saturation = 1.12; + if (!defects.length) { + defects.push('基础曝光均衡,执行轻度通透与细节微润'); + p.contrast = Math.max(p.contrast, 1.08); + p.saturation = Math.max(p.saturation, 1.08); + p.sharpness = Math.max(p.sharpness, 0.35); + } + + const pass1Params = normalizeIspParams(p); + const pass1Rgb = applyIspPipeline(srcBytes, width, height, pass1Params, stride); + const pass1Stats = analyzeIspImage(pass1Rgb, width, height, stride); + + // ── Pass 2: Closed-Loop Self-Check & Guardrail Refinement on Rendered Pixels ── + const p2 = { ...pass1Params }; + const refinements = []; + + // Guard 1: Highlight clipping protection + const clipAllowance = wantProtectHighlights ? 0.6 : 1.8; + if (pass1Stats.clipPct > before.clipPct + clipAllowance && pass1Stats.clipPct > 1.2) { + const excess = pass1Stats.clipPct - before.clipPct; + p2.exposureEv = clamp(p2.exposureEv - Math.min(0.55, 0.20 + excess * 0.06), -1.5, 1.5); + p2.highlights = clamp(p2.highlights - 28, -98, 0); + refinements.push(`二轮防过曝修正:调后高光裁切 ${pass1Stats.clipPct}% 偏高,回退曝光并加强高光保护`); + } + + // Guard 2: White balance overshoot damping + if (Math.abs(pass1Params.wbShift) >= 8) { + const flippedSign = (before.wbCastIndex > 10 && pass1Stats.wbCastIndex < -12) || + (before.wbCastIndex < -10 && pass1Stats.wbCastIndex > 12); + if (flippedSign) { + p2.wbShift = Math.round(pass1Params.wbShift * 0.72); + refinements.push(`二轮白平衡阻尼:避免色温矫枉过正(R-B ${pass1Stats.wbCastIndex}),将色温微调至 ${p2.wbShift}`); + } else if (Math.abs(before.wbCastIndex) > 30 && Math.abs(pass1Stats.wbCastIndex) > 16 && + Math.sign(before.wbCastIndex) === Math.sign(pass1Stats.wbCastIndex)) { + const nudge = Math.sign(pass1Params.wbShift) * Math.min(12, Math.round(Math.abs(pass1Stats.wbCastIndex) * 0.30)); + p2.wbShift = clamp(pass1Params.wbShift + nudge, -48, 48); + refinements.push(`二轮白平衡补正:残留色偏 R-B=${pass1Stats.wbCastIndex},继续向中性白收敛至 ${p2.wbShift}`); + } + } + + // Guard 3: Residual shadow darkness when highlight headroom remains + if ((isUnderexposed || wantLiftDarks) && pass1Stats.meanLuma < 100 && pass1Stats.clipPct <= before.clipPct + 0.5) { + p2.shadows = clamp(p2.shadows + 18, -100, 90); + p2.exposureEv = clamp(p2.exposureEv + 0.15, -2, 1.5); + refinements.push(`二轮暗部补亮:首轮均亮 ${pass1Stats.meanLuma} 仍有高光余量,继续抬升阴影与曝光`); + } + + // Guard 4: Noise spike suppression after shadow lift + if (pass1Stats.noiseEstimate > Math.max(4.5, before.noiseEstimate * 1.65)) { + p2.denoise = clamp(p2.denoise + 0.20, 0, 0.75); + p2.sharpness = clamp(p2.sharpness - 0.15, 0, 1.5); + refinements.push(`二轮噪点抑制:提暗后平滑区噪点升至 ${pass1Stats.noiseEstimate},补强 2DNR 降噪并收敛锐度`); + } + + const finalParams = normalizeIspParams(p2); + const changedInPass2 = ISP_PARAM_KEYS.some((k) => Math.abs(finalParams[k] - pass1Params[k]) > 1e-6); + const finalRgb = changedInPass2 + ? applyIspPipeline(srcBytes, width, height, finalParams, stride) + : pass1Rgb; + const afterStats = changedInPass2 ? analyzeIspImage(finalRgb, width, height, stride) : pass1Stats; + + return { + params: finalParams, + outputBytes: finalRgb, + beforeStats: before, + pass1Stats, + afterStats, + diagnosedDefects: defects, + refinements, + iterations: changedInPass2 ? 2 : 1, + }; +} + +/** + * Generate concise engineering diagnosis notes comparing before & after telemetry. + */ +export function buildIspDiagnosisNotes(before, after, params, autoMeta = null) { + const notes = []; + if (autoMeta?.diagnosedDefects?.length) { + notes.push(`自动病灶诊断:${autoMeta.diagnosedDefects.join(';')}。`); + } + if (autoMeta?.refinements?.length) { + notes.push(`闭环二轮校验:${autoMeta.refinements.join(';')}。`); + } + if (after.clipPct > before.clipPct + 2.5 && after.clipPct > 2.0) { + notes.push(`高光过曝风险:>248 裁切占比由 ${before.clipPct}% 升至 ${after.clipPct}%,建议加强高光保护(highlights < 0)或回调曝光。`); + } + if (after.darkPct < before.darkPct - 5.0) { + notes.push(`暗部细节救回:死黑占比由 ${before.darkPct}% 降至 ${after.darkPct}%,均亮由 ${before.meanLuma} 升至 ${after.meanLuma}。`); + } + if (Math.abs(before.wbCastIndex) - Math.abs(after.wbCastIndex) > 12) { + notes.push(`白平衡收敛:红蓝通道差由 ${before.wbCastIndex} 收敛到 ${after.wbCastIndex}(RGB 均值 [${after.channelMeans.join(', ')}])。`); + } + if (params.sharpness >= 1.55) { + notes.push(`过锐白边警告:当前锐度 ${params.sharpness.toFixed(2)} 偏高,请用 2.5× 放大镜核查黑白高反差边缘是否出现亮晕。`); + } else if (after.edgeSharpness > before.edgeSharpness * 1.12 && params.sharpness > 0.1) { + notes.push(`清晰度增益:边缘锐度由 ${before.edgeSharpness} 升至 ${after.edgeSharpness},同时保持噪声受控(${after.noiseEstimate})。`); + } + if (params.denoise >= 0.15 && after.noiseEstimate < before.noiseEstimate * 0.92) { + notes.push(`降噪生效:平滑区噪点估计由 ${before.noiseEstimate} 降至 ${after.noiseEstimate}。`); + } + if (!notes.length) { + notes.push(`线性域 10 参数已更新(${formatIspParamSummary(params)}),均亮 ${before.meanLuma} → ${after.meanLuma},动态范围 ${before.dynamicRange} → ${after.dynamicRange}。`); + } + return notes; +} diff --git a/plugins/rdk-camera-workshop/web/isp-example/backlight/gamma-20.jpg b/plugins/rdk-camera-workshop/web/isp-example/backlight/gamma-20.jpg new file mode 100644 index 0000000..4de44d7 Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-example/backlight/gamma-20.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-example/colorchecker/gamma-20.jpg b/plugins/rdk-camera-workshop/web/isp-example/colorchecker/gamma-20.jpg new file mode 100644 index 0000000..818dd8b Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-example/colorchecker/gamma-20.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-example/gamma-20.png b/plugins/rdk-camera-workshop/web/isp-example/gamma-20.png new file mode 100644 index 0000000..6c734fa Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-example/gamma-20.png differ diff --git a/plugins/rdk-camera-workshop/web/isp-example/hazy/gamma-20.jpg b/plugins/rdk-camera-workshop/web/isp-example/hazy/gamma-20.jpg new file mode 100644 index 0000000..e4e3f89 Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-example/hazy/gamma-20.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-example/lowlight/gamma-20.jpg b/plugins/rdk-camera-workshop/web/isp-example/lowlight/gamma-20.jpg new file mode 100644 index 0000000..79bb064 Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-example/lowlight/gamma-20.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-example/macro_detail/gamma-20.jpg b/plugins/rdk-camera-workshop/web/isp-example/macro_detail/gamma-20.jpg new file mode 100644 index 0000000..b3101c6 Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-example/macro_detail/gamma-20.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-example/scenes.json b/plugins/rdk-camera-workshop/web/isp-example/scenes.json new file mode 100644 index 0000000..ef5740c --- /dev/null +++ b/plugins/rdk-camera-workshop/web/isp-example/scenes.json @@ -0,0 +1,193 @@ +{ + "schema": "rdk.isp-example-scenes.v1", + "scenes": [ + { + "id": "lowlight", + "title": "暗光机器人工作台 · 低照度救暗练习", + "shortTitle": "暗光工作台(低照度)", + "source": "isp_teaching_reference_scene", + "badge": "典型病灶 · 暗部欠曝", + "diagnosis": "病灶:整体欠曝偏暗,开发板丝印、机械爪齿轮与彩色跳线藏在阴影里;右上台灯同时存在局部高光。", + "description": "典型低照度机器人实验台场景。练习通过曝光 EV、低 Gamma(0.65–0.80)与适度锐度把暗部硬件纹理和导线色彩救出来,同时控制暗区不发灰、右上台灯不溢出。", + "observation": "重点观察开发板芯片丝印、彩色杜邦线、机械爪齿轮与前景螺丝细节,同时盯住右上台灯高光与暗部颗粒变化。", + "placeholder": "例如:Gamma 0.70 + 曝光 +0.8 EV 后,开发板引脚、跳线颜色与机械爪结构清晰浮现,且暗部黑位扎实、台灯未大面积过曝。", + "recommendedGamma": 0.7, + "recommendedLab": { + "exposureEv": 0.75, + "shadows": 56, + "highlights": -30, + "gamma": 0.75, + "brightness": 2, + "contrast": 1.1, + "saturation": 1.15, + "wbShift": 0, + "denoise": 0.35, + "sharpness": 0.45 + }, + "recommendedNote": "推荐思路:先提曝光 +0.8 EV 与压低 Gamma 0.70 抬起阴影,再小幅补对比度 1.10 与锐度 0.35 保持机械纹理扎实。", + "captureSummary": "教学参考场景 · 16:9 暗光机器人开发台(线性低曝模拟,保留完整暗部可恢复动态范围)", + "mimeType": "image/jpeg", + "ext": "jpg", + "prefix": "/isp-example/lowlight/" + }, + { + "id": "backlight", + "title": "逆光通道机器人 · 大光比 HDR 取舍", + "shortTitle": "逆光通道(大光比)", + "source": "isp_teaching_reference_scene", + "badge": "典型病灶 · 强逆光 HDR", + "diagnosis": "病灶:门外晴空与玻璃幕墙接近过曝裁切,室内配送机器人、橙白锥桶与红色 STOP 标牌严重压暗。", + "description": "自动驾驶与移动机器人最常见的大光比逆光入口场景。练习用压低 Gamma(0.65–0.75)配合微降曝光,既救回暗处机器人和交通标识,又不把室外天空与建筑吹白。", + "observation": "对比右侧红色 STOP 标牌、配送机器人底盘、左侧锥桶与门外蓝天白云/大楼立面,观察直方图高光裁切(>248)占比。", + "placeholder": "例如:微降曝光 -0.1 EV 保住门外云层与建筑细节,同时 Gamma 0.65 让室内 STOP 牌与机器人机身清晰可辨。", + "recommendedGamma": 0.7, + "recommendedLab": { + "exposureEv": -0.25, + "shadows": 68, + "highlights": -80, + "gamma": 0.8, + "brightness": 0, + "contrast": 1.1, + "saturation": 1.12, + "wbShift": 0, + "denoise": 0.2, + "sharpness": 0.35 + }, + "recommendedNote": "推荐思路:逆光切忌猛加曝光(会把门外直接吹白),应微降曝光 -0.1 EV 守住高光,再用低 Gamma 0.65 专项提亮暗区。", + "captureSummary": "教学参考场景 · 16:9 逆光车库通道与配送机器人(大光比高动态范围模拟)", + "mimeType": "image/jpeg", + "ext": "jpg", + "prefix": "/isp-example/backlight/" + }, + { + "id": "warm_wb", + "title": "暖黄灯光桌面 · 白平衡偏色校正", + "shortTitle": "偏色桌面(白平衡)", + "source": "isp_teaching_reference_scene", + "badge": "典型病灶 · 严重偏暖黄", + "diagnosis": "病灶:2800K 暖黄光下白平衡严重失衡,纯白瓷杯、白纸笔记本与 18% 灰卡发橙发黄,蓝色积木发灰。", + "description": "含纯白瓷杯、空白纸本、18% 中性灰卡、红蓝绿黄标准积木与绿植苹果的桌面参考场景。切到「7 参数实验室」拉动白平衡冷暖,直观体会中性白与三原色如何一键回正。", + "observation": "紧盯白色咖啡杯、打开的白纸、灰卡和蓝色积木,同步看直方图红蓝通道曲线是否重新重合,避免矫枉过正变偏蓝。", + "placeholder": "例如:白平衡拉向冷色 -36 后,白杯、白纸与 18% 灰卡恢复纯正中性,蓝绿积木与红苹果色彩自然通透。", + "recommendedGamma": 0.95, + "recommendedLab": { + "exposureEv": 0.1, + "gamma": 0.95, + "brightness": 0, + "contrast": 1.05, + "saturation": 1.1, + "wbShift": -36, + "sharpness": 0.25 + }, + "recommendedNote": "推荐思路:大幅向冷色补偿白平衡 -36(压红抬蓝)即可把 18% 灰卡还原到三通道近似相等,再微调曝光与饱和度恢复通透感。", + "captureSummary": "教学参考场景 · 16:9 暖光偏色静物台(含白瓷杯、白纸、18% 灰卡与四色积木)", + "mimeType": "image/jpeg", + "ext": "jpg", + "prefix": "/isp-example/warm_wb/" + }, + { + "id": "hazy", + "title": "起雾泛白智慧仓库 · 对比度与黑位去灰", + "shortTitle": "起雾仓库(低反差)", + "source": "isp_teaching_reference_scene", + "badge": "典型病灶 · 发灰低反差", + "diagnosis": "病灶:眩光/雾气与偏高黑位导致暗部发灰(黑位抬高到 Y≈60)、画面发平,AMR 与红蓝货箱发闷寡淡。", + "description": "模拟工业通道起雾、镜头眩光或黑电平偏高导致的“发灰泛白”典型场景。练习下压亮度/拉高对比度与高 Gamma(1.15–1.30)配合饱和度,一键去灰通透。", + "observation": "观察下方亮度直方图如何从“挤在中间发平”重新拉开到两端,对比 AMR 车体黑色、黄黑地面警示线与红蓝周转箱的立体感。", + "placeholder": "例如:压低亮度 -18、拉高对比度 1.55 与 Gamma 1.20、饱和度 1.45 后,雾感明显褪去,黑位扎实且红蓝料箱鲜明。", + "recommendedGamma": 1.25, + "recommendedLab": { + "exposureEv": -0.1, + "gamma": 1.2, + "brightness": -18, + "contrast": 1.55, + "saturation": 1.45, + "wbShift": -4, + "sharpness": 0.5 + }, + "recommendedNote": "推荐思路:发灰场景核心是把抬起的黑位压回零点并拉开反差(亮度 -18 + 对比度 1.55 + Gamma 1.20),再补饱和度 1.45 与锐度 0.50。", + "captureSummary": "教学参考场景 · 16:9 智慧物流仓 AMR 通道(镜头眩光与黑位抬升发灰模拟)", + "mimeType": "image/jpeg", + "ext": "jpg", + "prefix": "/isp-example/hazy/" + }, + { + "id": "macro_detail", + "title": "多色精密零件与刻度尺 · 锐度与色彩防溢出", + "shortTitle": "细节刻度尺(锐度/色彩)", + "source": "isp_teaching_reference_scene", + "badge": "典型病灶 · 偏软待锐化", + "diagnosis": "病灶:光学低通偏软且色彩平淡;打开 2.5× 放大镜观察毫米刻度、齿轮齿面与红黑编织线,最能看出锐度收益与过锐白边光晕。", + "description": "高密度细节与高纯度五色零件近景。重点练习「锐度 USM」在 0.8–1.2 清晰化与推到 2.0 产生白边光晕(Overshoot)的边界,以及饱和度过高引发的色彩溢出。", + "observation": "开启 2.5× 放大镜对准钢尺 10–50 mm 刻度线、铝齿轮边缘与红黑编织线;分别体验锐度 1.10 的利落清晰与 2.00 的白边光晕副作用。", + "placeholder": "例如:锐度 1.10 下钢尺毫米刻度与铝齿轮拉丝质感利落清晰;继续拉到 2.00 时黑白刻度边出现明显白边光晕。", + "recommendedGamma": 0.95, + "recommendedLab": { + "exposureEv": 0, + "gamma": 0.95, + "brightness": 0, + "contrast": 1.15, + "saturation": 1.25, + "wbShift": 0, + "sharpness": 1.1 + }, + "recommendedNote": "推荐思路:锐度 1.10 搭配温和对比度 1.15 与饱和度 1.25 可同时提升钢尺刻线、金属纹理与五色积木质感,且不出现刺眼白边光晕。", + "captureSummary": "教学参考场景 · 16:9 精密零件近景(五色铝块 + 不锈钢毫米尺 + 齿轮 + 红黑编织线)", + "mimeType": "image/jpeg", + "ext": "jpg", + "prefix": "/isp-example/macro_detail/" + }, + { + "id": "colorchecker", + "title": "24 色卡与分辨率 · 定量综合参考卡", + "shortTitle": "24 色卡综合(标板)", + "source": "synthetic_studio_colorchecker", + "badge": "定量标板 · 色准 + 锐度", + "diagnosis": "基准测试卡:标准 sRGB 24 色卡 + 暗部微光字(L=18–48)+ 高光保护阶梯(L=212–252)+ 西门子分辨星 + 21 阶线性灰阶。", + "description": "用于定量验收全链路 ISP 调试效果的标准综合标板。任何参数改动都能在色块、灰阶、高光裁切、暗部文字与西门子星上得到无歧义的客观读数。", + "observation": "同时观察 24 色块肤色与中性灰是否偏色、右上暗部微光文字可辨度、高光 212–247 阶梯是否融合,以及西门子星与中文笔画边缘白边。", + "placeholder": "例如:暗部区 L=18–36 笔画清晰可辨,高光 247 阶梯未融合,24 色卡肤色与底部灰阶保持中性无偏色。", + "recommendedGamma": 0.8, + "recommendedLab": { + "exposureEv": 0.0, + "gamma": 0.85, + "brightness": 0, + "contrast": 1.1, + "saturation": 1.15, + "wbShift": 0, + "sharpness": 0.35 + }, + "recommendedNote": "推荐思路:以定量基准卡检验均衡参数——微调 Gamma 0.85 让暗部字浮现,同时确认高光 247 格不裁切、灰阶不偏色。", + "captureSummary": "高清 16:9 综合参考卡 · Macbeth 24 色卡 + 21 阶灰阶 + 西门子星 + 中文清晰度", + "mimeType": "image/jpeg", + "ext": "jpg", + "prefix": "/isp-example/colorchecker/" + }, + { + "id": "chart", + "title": "课堂合成测试卡 · Gamma 练习", + "shortTitle": "经典测试卡(兼容)", + "source": "synthetic_course_chart", + "badge": "经典测试卡 · 与对话默认一致", + "diagnosis": "经典 Gamma 专项测试卡:左侧暗部笔画 A1、右上高光保护阶梯与右下斜边刀口(与 AI 对话默认空参返回同一张卡)。", + "description": "拖动滑块对比不同 Gamma(0.55–1.45)对暗部笔画、背景细纹与亮部阶梯的影响;也可以在 Studio 对话里说「把课程示例图的 Gamma 调到 0.80」。", + "observation": "比较暗部笔画、背景细纹和亮部阶梯。", + "placeholder": "例如:Gamma 0.80 下左侧暗部笔画更清楚,同时右上高光阶梯依然可分辨。", + "recommendedGamma": 0.8, + "recommendedLab": { + "exposureEv": 0.0, + "gamma": 0.8, + "brightness": 0, + "contrast": 1.05, + "saturation": 1.1, + "wbShift": 0, + "sharpness": 0.3 + }, + "recommendedNote": "推荐思路:Gamma 0.80 提亮暗部「暗部笔画 A1」并保留右上高光阶梯层次。", + "captureSummary": "课堂标准合成测试卡(暗部文字 + 灰阶阶梯 + 细纹)", + "mimeType": "image/png", + "ext": "png", + "prefix": "/isp-example/" + } + ] +} diff --git a/plugins/rdk-camera-workshop/web/isp-example/warm_wb/gamma-20.jpg b/plugins/rdk-camera-workshop/web/isp-example/warm_wb/gamma-20.jpg new file mode 100644 index 0000000..4bc16b7 Binary files /dev/null and b/plugins/rdk-camera-workshop/web/isp-example/warm_wb/gamma-20.jpg differ diff --git a/plugins/rdk-camera-workshop/web/isp-panel.mjs b/plugins/rdk-camera-workshop/web/isp-panel.mjs index 2f5be86..1b6cfd1 100644 --- a/plugins/rdk-camera-workshop/web/isp-panel.mjs +++ b/plugins/rdk-camera-workshop/web/isp-panel.mjs @@ -1,17 +1,22 @@ const stageText={snapshot:'读取原始 ISP',saved:'原始 ISP 已保存',checking:'核对设备和当前配置', - gamma_before:'采集调整前实拍',gamma_plan:'等待 AI 生成候选',gamma_apply:'应用有界 Gamma', + gamma_before:'采集调整前实拍',gamma_plan:'AI 正在分析调前画面并生成候选',gamma_proposed:'AI 候选已就绪,等你确认',gamma_apply:'应用有界 Gamma', gamma_verify:'独立回读并采集新图',gamma_saved:'实拍与回读齐备',gamma_reloaded:'已重载并采得新帧', exposure_manual:'切换到手动曝光',exposure_before:'读取手动曝光并拍摄调前图',exposure_apply:'缩短曝光时间', exposure_verify:'独立回读曝光并拍摄调后图', - learner_ready:'已核对工位可写参数',learner_before:'采集调整前实拍',learner_apply:'写入所选单项参数', + learner_ready:'已核对相机可写参数',learner_before:'采集调整前实拍',learner_apply:'写入所选单项参数', learner_verify:'独立回读并采集调后新图',learner_saved:'单项实验已取得回读', restore:'恢复期初 ISP',readback:'独立读取当前 ISP',stop:'停止采流',stopped:'原值已恢复,采流已停止',reverted:'已恢复期初 ISP'}; const errors={ - camera_gamma_round_locked:'请先完成上一轮取舍,并核对原值恢复。每个工位最多两轮。', - camera_binding_invalid:'先关联本工位相机实验。', - camera_capture_busy:'相机正在执行本工位另一项操作。', - camera_isp_snapshot_missing:'请先保存本工位原始 ISP。', - camera_isp_snapshot_changed:'当前相机或配置发生变化。请核对工位并恢复本工位原值。', + camera_credential_missing:'已找到相机连接配置,但缺少凭据文件。请在相机插件重新配置相机凭据,再刷新。', + camera_archive_quota_full:'证据存储额度已满。请联系助教处理额度,再重试采集或生成候选。', + camera_gamma_baseline_moved:'AI 提案后,相机期初回读已改变。候选已作废,本次没有写入。请先和助教核对是否有其他工作台在使用这台相机。', + camera_gamma_proposal_changed:'本轮候选已更新。请查看当前方案后再应用。', + camera_gamma_proposal_pending:'先应用或放弃当前 Gamma 候选,再试调其他参数。', + camera_gamma_round_locked:'请先完成上一轮取舍,并核对原值恢复。每个实验最多两轮。', + camera_binding_invalid:'先关联本组相机实验。', + camera_capture_busy:'相机正在执行本组另一项操作。', + camera_isp_snapshot_missing:'请先保存相机原始 ISP。', + camera_isp_snapshot_changed:'当前相机或配置发生变化。请核对实验并恢复设备原值。', camera_isp_stream_required:'请先确认相机正在出图,再采实拍和独立回读。', camera_recovery_required:'请先核对并恢复已保存的原始 ISP。', camera_isp_restore_unconfirmed:'恢复尚未核对。请保留本轮记录,并用同一快照处理。', @@ -21,31 +26,36 @@ const errors={ vision_model_no_adjustment:'AI 本次未给出合格候选。可以修改观察目标重试,当前未增加已完成轮数。', camera_gamma_freshness_failed:'候选应用后未取得匹配的新帧。请先核对恢复。', camera_gamma_reload_required:'先取得已验证候选和恢复后实拍,再重载。', - camera_exposure_unavailable:'本工位缺少可验证的手动曝光、增益或传感器行周期。请核对相机适配器。', + camera_exposure_unavailable:'本组缺少可验证的手动曝光、增益或传感器行周期。请核对相机适配器。', camera_exposure_no_room:'手动曝光已接近该模式的最短曝光时间。增加固定光照后重新布置演示场景。', camera_exposure_freshness_failed:'未取到与曝光回读匹配的新实拍,本次对照未验收。', camera_exposure_readback_mismatch:'曝光或其他 ISP 读值与计划不符,本次对照未验收。', - camera_learner_control_unavailable:'这项参数当前不可写。重新读取工位权限后选择可写项。', - camera_learner_control_changed:'工位范围或当前值已变化。重新读取参数后再试。', - camera_learner_value_out_of_range:'候选超出工位范围或不符合步进。按界面给出的范围和步进填写。', + camera_learner_control_unavailable:'这项参数当前不可写。重新读取设备权限后选择可写项。', + camera_learner_control_changed:'设备范围或当前值已变化。重新读取参数后再试。', + camera_learner_value_out_of_range:'候选超出设备范围或不符合步进。按界面给出的范围和步进填写。', camera_learner_value_unchanged:'候选量化后与当前值相同。请选择一个可区分的值。', camera_learner_readback_mismatch:'独立回读未证实只有所选参数变化。请先恢复期初 ISP。', camera_learner_freshness_failed:'未取得与调后回读匹配的新图。请先恢复期初 ISP。', camera_learner_trial_locked:'请先核对当前单项实验的实拍和回读。', - vision_camera_control_unavailable:'此工位未确认该参数可写。请重新检查适配器和模式。', - vision_camera_control_inactive:'当前参数由自动模式接管。请使用助教准备的手动工位。', - vision_camera_control_out_of_range:'工位拒绝了这个值。先核对恢复,再检查参数范围和步进。', - camera_isp_evidence_unavailable:'暂时读不到归档图。请核对工位相机服务。', + vision_camera_control_unavailable:'此实验未确认该参数可写。请重新检查适配器和模式。', + vision_camera_control_inactive:'当前参数由自动模式接管。请使用助教准备的已设为手动模式的相机。', + vision_camera_control_out_of_range:'设备拒绝了这个值。先核对恢复,再检查参数范围和步进。', + vision_device_checks_failed:'相机采流状态检查未通过。请先确认相机已点亮并处于采流中,再重试。', + vision_device_archive_capacity:'当前实验的操作归档条数已满。请先核对 ISP 恢复与停流,再在同设备新建实验继续并保留旧归档。', + vision_device_history_capacity:'当前实验的操作历史已满。请先核对 ISP 恢复与停流,再在同设备新建实验继续并保留旧归档。', + vision_recovery_recording_failed:'板端 SDK 已确认恢复原始 ISP,但服务端写回恢复记录失败。请勿重试写入,立即联系助教核对实验记录。', + vision_device_busy:'板端相机设备正忙(本次未写入硬件)。请稍候数秒后重试。', + camera_isp_evidence_unavailable:'暂时读不到归档图。请核对相机服务。', }; -const explain=code=>errors[code]??'本工位操作未完成 · '+(code??'请刷新后重试'); +const explain=code=>errors[code]??'本组操作未完成 · '+(code??'请刷新后重试'); const names={original:'原始ISP',beforeReadback:'调前ISP回读',gammaReadback:'Gamma参数回读',decisionReadback:'取舍确认回读', - resetReadback:'下一轮前恢复回读',readback:'工位恢复回读',reloadReadback:'重载回读', + resetReadback:'下一轮前恢复回读',readback:'相机恢复回读',reloadReadback:'重载回读', before:'调前实拍',after:'调后实拍',restored:'恢复后实拍',reloaded:'重载实拍', afterReadback:'调后ISP回读',restorationReadback:'恢复期初ISP回读'}; const images=new Set(['before','after','restored','reloaded']); const previewRetryDelays=[300,900]; -const evidenceChanged='ISP 工位记录已更新,请重新下载成果包。'; -const transportError=()=>Object.assign(new Error('暂时无法读取工位数据,请重试。'),{retryable:true}); +const evidenceChanged='ISP 实验记录已更新,请重新下载成果包。'; +const transportError=()=>Object.assign(new Error('暂时无法读取实验数据,请重试。'),{retryable:true}); const receiptFields=['beforeReadback','gammaReadback','decisionReadback','resetReadback']; const roundFields=['before','after','restored',...receiptFields]; const exposureReceipts=['beforeReadback','afterReadback','restorationReadback']; @@ -57,18 +67,20 @@ const learnerEntries=(adjustment,fields)=>fields.filter(name=>adjustment[name]). const roundEntries=(round,fields)=>fields.filter(name=>round[name]).map(name=>({name,round:round.number,asset:round[name]})); const sessionEntries=(status,fields)=>fields.filter(name=>status?.[name]).map(name=>({name,asset:status[name]})); const entryKey=({name,round,scope,trial})=>`${scope==='learner'?'learner-'+trial:scope??round??0}:${name}`; +const proposalEntry=proposal=>({name:'before',scope:'gamma-proposal',asset:proposal.before}); const artifacts=status=>[...sessionEntries(status,['original','readback','reloadReadback','reloaded']), ...(status?.rounds??[]).flatMap(round=>roundEntries(round,roundFields)), ...exposureEntries(status?.exposure,['before','after',...exposureReceipts]), ...(status?.adjustments??[]).flatMap(item=>learnerEntries(item,['before','after','restored',...learnerReceipts]))]; -export function createIspPanel({key,$,element,button,openDialog,field,notify,getBinding,pick,compareFrames,onEvidenceChange}) { +export function createIspPanel({key,$,element,button,openDialog,field,notify,getBinding,showCamera,pick,compareFrames,onEvidenceChange,initialRound}) { let binding, status, posting=false, polling=false, bindingRevision=0; - let imageReads=Promise.resolve(); + let operationRevision=0, pollIssue='', renderedParameters=''; + let imageReads=Promise.resolve(), focusedRound=false; const previews=new Map(); const proofOpen=new Map(); - async function request(path='/camera/isp',body) { - const headers={'X-Workshop-Session':key,...(body?{'Content-Type':'application/json'}:{})}; + async function request(path='/camera/isp',body,background=false) { + const headers={'X-Workshop-Session':key,...(background?{'X-Workshop-Poll':'1'}:{}),...(body?{'Content-Type':'application/json'}:{})}; let response; try { response=await fetch(path,{headers,...(body?{method:'POST',body:JSON.stringify(body)}:{})}); } catch { throw transportError(); } @@ -89,7 +101,7 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get try { blob=await response.blob(); } catch { throw transportError(); } const ext=images.has(name)?(blob.type==='image/png'?'.png':'.jpg'):'.json'; - const prefix=scope==='learner'?'单项ISP-第'+trial+'次-':scope==='exposure'?'讲师-曝光-':round?'Gamma-第'+round+'轮-':'工位-'; + const prefix=scope==='learner'?'单项ISP-第'+trial+'次-':scope==='exposure'?'讲师-曝光-':round?'Gamma-第'+round+'轮-':'实验-'; return new File([blob],prefix+names[name]+ext,{type:blob.type}); } function readImage(entry,isCurrent) { @@ -138,7 +150,7 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get if(next&&next.experimentId!==binding) return; if(JSON.stringify(status)===JSON.stringify(next)) return; status=next; - const entries=new Map(artifacts(next).filter(entry=>images.has(entry.name)).map(entry=>[entryKey(entry),entry])); + const entries=new Map([...artifacts(next),...(next?.gammaProposal?[proposalEntry(next.gammaProposal)]:[])].filter(entry=>images.has(entry.name)).map(entry=>[entryKey(entry),entry])); for(const [slot,previous] of previews) if(previous.hash!==entries.get(slot)?.asset.sha256) { if(previous.url) URL.revokeObjectURL(previous.url); previews.delete(slot); @@ -152,25 +164,37 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get onEvidenceChange?.(); } async function poll() { - if(polling||posting||!key||!binding) return; + if(polling||posting||!key||!binding||document.hidden) return; const revision=bindingRevision; + const operation=operationRevision; + const current=()=>!posting&&bindingRevision===revision&&operationRevision===operation; polling=true; try { - const data=await(await request()).json(); - if(!posting&&bindingRevision===revision) apply(data.isp); - } catch {} + const data=await(await request('/camera/isp',undefined,true)).json(); + if(!current()) return; + const recovered=Boolean(pollIssue); + pollIssue=''; + if(JSON.stringify(data.isp)!==JSON.stringify(status)) apply(data.isp); + else if(recovered) render(); + } catch { + if(current()&&!pollIssue) { + pollIssue='暂时无法更新设备实验。请确认 Studio 仍在运行,再刷新状态。'; + render(); + } + } finally { polling=false; - if(bindingRevision!==revision) void poll(); + if(bindingRevision!==revision||operationRevision!==operation) void poll(); } } async function start(body) { if(posting||status?.running) return; const revision=bindingRevision; + operationRevision++; posting=true;render(); try { const {isp}=await(await request('/camera/isp',body)).json(); - if(bindingRevision===revision) apply(isp); + if(bindingRevision===revision) {pollIssue='';apply(isp);} } catch(error) { if(bindingRevision===revision) notify(error.message); } finally { @@ -183,7 +207,7 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get const exposure=status?.exposure?.recoveryPending; openDialog(final?'恢复期初 ISP 并停流':'恢复期初 ISP,继续采流',[ element('p',final?'恢复原始配置,独立回读一致后停止采流。':exposure? - '恢复期初 ISP 并独立回读。已采集的曝光证据会留在工位。': + '恢复期初 ISP 并独立回读。已采集的曝光证据会留在实验。': '独立确认恢复原值,并采一张恢复后实拍。已记录的取舍会保留。'), ],()=>start({action}),final?'恢复并停流':'恢复原值'); } @@ -194,14 +218,13 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get element('p','保持机位、光照和目标不变。只调整当前生效的 Gamma 曲线。'), guided?field('goal','选一个观察目标',{options:goals,value:goals[0][0]}): field('goal','写出你自己的观察目标',{max:180,placeholder:'例如让左侧暗部更清楚,同时保持右侧亮部细节'}), - ],({goal})=>start({action:'gamma',round:number,goal}),'生成并应用候选'); + ],({goal})=>start({action:'gamma_prepare',round:number,goal}),'让 AI 先给方案'); } - function openDecision(round) { - openDialog(`第 ${round.number} 轮 · 记录取舍`,[ + function openDecision(round,choice,label) { + openDialog(`第 ${round.number} 轮 · ${label}`,[ element('p','先看调前、调后两张实拍和参数回读,再记录你看到的改善或代价。'), - field('choice','选择',{options:[['','请选择'],['keep','保留调整'],['restore','恢复原值']]}), field('reason','写下理由',{max:180,placeholder:'例如阴影中文字更清楚,亮部仍有纹理'}), - ],({choice,reason})=>start({action:'decision',round:round.number,choice,reason}),'保存取舍并核对回读'); + ],({reason})=>start({action:'decision',round:round.number,choice,reason}),'保存取舍并核对回读'); } function imageCard(entry,value) { const {name}=entry; @@ -239,47 +262,82 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get area.append(element('summary',title),...contents); return area; } - function curvePlot(curve) { + function curvePlot(curve,preview=false) { const card=element('div','','curve-plot'); - const count=curve.changed+' 个节点有变化'+(curve.rows>1?' · 显示变化最多的第 '+curve.row+' / '+curve.rows+' 条':''); - card.append(element('strong','Gamma 曲线独立回读'),element('p',count,'action-copy')); + const count=preview?'当前曲线和第 1 条候选曲线 · 候选尚未下发':curve.changed+' 个节点有变化'+(curve.rows>1?' · 显示变化最多的第 '+curve.row+' / '+curve.rows+' 条':''); + card.append(element('strong',preview?'Gamma 候选曲线':'Gamma 曲线独立回读'),element('p',count,'action-copy')); + card.append(drawCurve([[curve.before,'#526888',[6,4]],[curve.after,'#194fc2',[]]], + (preview?'当前和候选 Gamma 曲线。':'Gamma 调前和调后的 SDK 曲线。')+count), + element('small',preview?'灰色虚线 · 当前 蓝色实线 · AI 候选':'灰色虚线 · 调前 蓝色实线 · 调后','curve-legend')); + return card; + } + function drawCurve(series,label) { const canvas=element('canvas'); canvas.width=480;canvas.height=104; canvas.setAttribute('role','img'); - canvas.setAttribute('aria-label','Gamma 调前和调后的 SDK 曲线。'+count+'。横轴为输入节点,纵轴为输出等级。'); + canvas.setAttribute('aria-label',label+'。横轴为输入节点,纵轴为输出等级。'); const context=canvas.getContext?.('2d'); if(context) { context.strokeStyle='#dce5f2'; for(const y of [8,52,96]) { context.beginPath();context.moveTo(8,y);context.lineTo(472,y);context.stroke(); } - for(const [nodes,color,pattern] of [[curve.before,'#526888',[6,4]],[curve.after,'#194fc2',[]]]) { + for(const [nodes,color,pattern] of series) { context.beginPath();context.strokeStyle=color;context.lineWidth=3;context.setLineDash(pattern); for(const [index,value] of nodes.entries()) { - const x=8+index*464/63,y=96-value*88/1023; + const x=8+index*464/(nodes.length-1),y=96-value*88/1023; if(index===0) context.moveTo(x,y); else context.lineTo(x,y); } context.stroke(); } } - card.append(canvas,element('small','灰色虚线 · 调前 蓝色实线 · 调后','curve-legend')); - return card; + return canvas; } function compareButton(prefix,labels) { const sources=['before','after'].map(name=>previews.get(prefix+':'+name)?.url); if(!compareFrames||!sources.every(Boolean)) return; return button('放大同一区域',()=>compareFrames(sources.map((src,index)=>({src,label:labels[index]}))),'ghost'); } + function proposalReasons(model,reasons) { + const box=element('div','','ai-isp-explanation'); + box.append(element('strong','AI 为什么这样调')); + if(model) box.append(element('small','本轮模型 · '+model)); + if(!reasons?.length) box.append(element('p','这次模型回执未提供文字理由,请依据曲线和画面对照判断。','action-copy')); + else for(const reason of reasons) box.append(element('p',reason,'action-copy')); + return box; + } + function proposeCard(proposal,busy) { + const box=element('div','','ai-isp-proposal'); + box.append(element('p','观察目标 · '+proposal.goal,'isp-decision')); + const pair=element('div','','ai-isp-pair'); + pair.append(imageCard(proposalEntry(proposal)),proposalReasons(proposal.model,proposal.reasons)); + box.append(pair); + if(proposal.beforeCurve?.length===64&&proposal.curve?.length===64) { + box.append(curvePlot({before:proposal.beforeCurve,after:proposal.curve},true)); + } + const bar=element('div','','button-row'); + const applyButton=button('应用本次候选并拍摄对照',()=>start({ + action:'gamma_apply',round:proposal.number,candidateId:proposal.candidateId, + }),'primary'); + const discard=button('换个观察目标',()=>start({action:'gamma_discard'}),'plain'); + applyButton.disabled=discard.disabled=busy; + bar.append(applyButton,discard);box.append(bar); + return box; + } function roundCard(number,round,done,busy) { const card=element('article','','isp-round'); + card.id='isp-gamma-round-'+number; + card.dataset.ispRound=String(number); const current=done===number-1; const head=element('div','','action-head'); - const state=round?.decision?'已验收':round?'待记录取舍':current?'待实拍与回读':'等待上一轮'; + const proposal=status?.gammaProposal?.number===number?status.gammaProposal:undefined; + const state=proposal?'AI 候选待应用':round?.decision?'已验收':round?'待记录取舍':current?'待实拍与回读':'等待上一轮'; head.append(element('h3',number===1?'第 1 轮 · 跟做':'第 2 轮 · 自主'),element('span',state,'status-tag'+(round?.decision?' ok':''))); card.append(head); card.append(element('p',round?.goal??(number===1?'选一个观察目标,跟着完成一次有界调整。':'自己写目标,再验证同一场景的画面变化。'),'action-copy')); if(!round) { + if(proposal) {card.append(proposeCard(proposal,busy));return card;} if(current&&status?.original&&!status.stop&&!status.changesActive&&!status.recoveryPending&&(status.rounds?.length??0)===number-1) { const launch=button(number===1?'开始第 1 轮跟做':'开始第 2 轮自主',()=>openTrial(number),'primary'); launch.disabled=busy;card.append(launch); @@ -290,10 +348,14 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get for(const entry of roundEntries(round,['before','after'])) frames.append(imageCard(entry)); const content=element('div'); content.append(frames); + if(round.model||round.modelReasons?.length) content.append(proposalReasons(round.model,round.modelReasons)); const actions=element('div','','button-row'); const before=previews.get(`${number}:before`)?.file, after=previews.get(`${number}:after`)?.file; if(!round.decision&&!status.stop) { - const decide=button('记录保留或恢复',()=>openDecision(round),'primary');decide.disabled=busy;actions.append(decide); + for(const [choice,label] of [['keep','保留本次调整'],['restore','恢复原值']]) { + const decide=button(label,()=>openDecision(round,choice,label),'ghost'); + decide.disabled=busy;actions.append(decide); + } } const zoom=compareButton(number,['调前实拍','调后实拍']); if(zoom) actions.append(zoom); @@ -321,7 +383,7 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get const hint=element('p',active?(stageText[status.stage]??'正在核对相机与期初配置'): demo?.recoveryPending?explain(status.error??'camera_isp_restore_unconfirmed'): demo?.error?explain(demo.error)+(demo.restorationReadback?' 已回读原值。':''): - !binding?'关联本工位相机实验并开启采流。':status?.stop?'本工位采流已停止。': + !binding?'关联本组相机实验并开启采流。':status?.stop?'本组相机采流已停止。': status?.recoveryPending?'先恢复期初 ISP。':locked?'先完成当前 Gamma 轮的取舍并恢复期初 ISP。': !status?.original?'先保存期初 ISP,再固定机位和光照。': finished?'对照同一目标的亮部细节和暗部可见度,核对两张图的增益与曝光回读。': @@ -357,23 +419,65 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get const observation={ 曝光:'观察亮部层次和暗部可见度。', 增益:'观察暗部亮度,同时检查颗粒是否增加。', + 亮度:'观察暗部是否抬升,同时留意黑位是否发灰、亮部是否过曝。', 对比度:'观察明暗是否更分明,同时检查两端细节。', + 饱和度:'观察彩色物体浓度是否自然,同时留意高饱和区域是否溢出。', + 色调:'观察整体色相是否偏转,微调校正偏色后再核对中性灰。', 锐度:'放大同一条边缘,检查笔画和光晕。', 白平衡:'观察中性白或灰是否偏色。', }; - const inactive={manual_mode:'自动模式下锁定。请使用助教准备的手动工位。', - read_only:'工位回读为只读或资格未确认。',snapshot_mismatch:'当前值无法与完整 ISP 快照对应。', + const inactive={manual_mode:'自动模式下锁定。请使用助教准备的已设为手动模式的相机。', + read_only:'设备回读为只读或资格未确认。',snapshot_mismatch:'当前值无法与完整 ISP 快照对应。', native_service_missing:'当前相机服务尚未提供单项锐度写入。'}; - const numeric=(value,unit)=>Number(value.toPrecision(9))+(unit?' '+unit:''); + const numeric=(value,unit)=>String(value)+(unit?' '+unit:''); + const readTime=value=>Number.isFinite(Date.parse(value))?new Date(value).toLocaleTimeString('zh-CN',{hour12:false}):''; + const learnerBlocked=()=>Boolean(pollIssue||status?.stop||status?.recoveryPending||status?.changesActive||status?.gammaProposal|| + status?.rounds?.at(-1)&&!status.rounds.at(-1).decision); + function lastGammaReadback() { + return artifacts(status).filter(entry=>entry.asset.curvePreview).sort((a,b)=> + (Date.parse(b.asset.recordedAt)||0)-(Date.parse(a.asset.recordedAt)||0))[0]; + } + async function showGammaCurve(entry,control) { + const revision=bindingRevision; + control.disabled=true; + try { + const receipt=JSON.parse(await (await readFile(entry)).text()); + if(bindingRevision!==revision||!control.isConnected) return; + const gamma=receipt.config?.modules?.gamma; + const nodes=gamma?.mode===0?gamma['auto_attr.curve']:gamma?.mode===1?gamma['manual_attr.curve']:undefined; + if(receipt.hash!==entry.asset.hash||!Array.isArray(nodes)||nodes.length<64||nodes.length>4096||nodes.length%64|| + nodes.some(value=>!Number.isInteger(value)||value<0||value>1023)) throw new Error('本次回读没有可核对的 Gamma 曲线。'); + const chart=element('div','','curve-plot'); + const values=element('ol','','isp-curve-nodes'); + values.start=0; + function draw(row) { + const series=nodes.slice(row*64,(row+1)*64); + chart.replaceChildren(drawCurve([[series,'#194fc2',[]]],'最近回读的 Gamma 曲线')); + values.replaceChildren(...series.map(value=>element('li',String(value)))); + } + const exact=element('details','','proof-details'); + exact.append(element('summary','查看 64 个精确节点'),values); + const body=[element('p',names[entry.name]+(readTime(receipt.recordedAt)?' · '+readTime(receipt.recordedAt):''),'action-copy')]; + if(nodes.length>64) { + const option=field('curve','自动曲线档位',{options:Array.from({length:nodes.length/64},(_,row)=>[row,'第 '+(row+1)+' 档']),value:'0'}); + option.querySelector('select').onchange=event=>draw(Number(event.currentTarget.value)); + body.push(option); + } + draw(0); + openDialog('最近回读的 Gamma 曲线',[...body,chart,exact],()=>{},'完成'); + } catch(error) { + if(bindingRevision===revision) notify(error.message); + } finally {control.disabled=false;} + } function openLearnerTrial(option) { - const {id,label,group,value,min,max,step,linePeriod,unit}=option; + const {id,label,group,value,min,max,step,linePeriod,fixedScale,log2GainSteps,unit}=option; const inputField=field('value','本轮候选值',{type:'number',value}); const input=inputField.querySelector('input'); input.min=min;input.max=max;input.step=step??'any'; + const alignHint=linePeriod?' · 按相机行周期对齐':log2GainSteps?' · 按模拟增益步进对齐':fixedScale?' · 按 AWB 定点步进对齐':step?' · 步进 '+numeric(step,unit):''; openDialog('试调'+label,[ - element('p','当前 '+numeric(value,unit)+' · 可用范围 '+numeric(min,unit)+' 至 '+numeric(max,unit)+ - (linePeriod?' · 按相机行周期对齐':step?' · 步进 '+numeric(step,unit):'')), - element('p','固定机位和光照。'+observation[group]), + element('p','当前 '+numeric(value,unit)+' · 可用范围 '+numeric(min,unit)+' 至 '+numeric(max,unit)+alignHint), + element('p','固定机位和光照。'+(observation[group]??'观察目标区域与亮暗部细节变化。')), inputField, ],({value:candidate})=>start({action:'learner_apply',field:id,expected:value,value:Number(candidate)}),'采集调前图并应用'); } @@ -385,13 +489,27 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get adjustment.restorationReadback?'已核对恢复':adjustment.after?'待取舍':'采集或验证未完成','status-tag')); card.append(title); const comparison=element('div','','comparison-images isp-pair'); - for(const entry of learnerEntries(adjustment,['before','after'])) comparison.append(imageCard(entry, - numeric(entry.name==='before'?adjustment.beforeValue:adjustment.afterValue,adjustment.unit))); + for(const entry of learnerEntries(adjustment,['before','after'])) { + const valText=adjustment.kind==='multi' + ? (entry.name==='before'?'调前实拍':'联调后实拍') + : numeric(entry.name==='before'?adjustment.beforeValue:adjustment.afterValue,adjustment.unit); + comparison.append(imageCard(entry,valText)); + } if(comparison.childElementCount) card.append(comparison); - if(adjustment.afterReadback) card.append(element('p','请求 '+numeric(adjustment.requested,adjustment.unit)+ - ' · 独立回读 '+numeric(adjustment.beforeValue,adjustment.unit)+' → '+numeric(adjustment.afterValue,adjustment.unit),'isp-decision')); + if(adjustment.afterReadback) { + if(adjustment.kind==='multi') { + const vals=Object.entries(adjustment.afterValues??adjustment.appliedValues??{}).map(([k,v])=>`${k}=${v}`).join(' · '); + const deltaText=adjustment.metricsDelta?` · 均亮 ${adjustment.metricsDelta.meanLuma>=0?'+':''}${adjustment.metricsDelta.meanLuma} · 暗部 ${adjustment.metricsDelta.darkPct>=0?'+':''}${adjustment.metricsDelta.darkPct}% · 锐度 ${adjustment.metricsDelta.edgeSharpness>=0?'+':''}${adjustment.metricsDelta.edgeSharpness}`:''; + card.append(element('p','多参数独立回读:'+vals+deltaText,'isp-decision')); + } else { + card.append(element('p','请求 '+numeric(adjustment.requested,adjustment.unit)+ + ' · 独立回读 '+numeric(adjustment.beforeValue,adjustment.unit)+' → '+numeric(adjustment.afterValue,adjustment.unit),'isp-decision')); + } + } const receipts=learnerEntries(adjustment,learnerReceipts); if(receipts.length) card.append(disclosure('learner-'+adjustment.number,'查看独立回读与哈希',receiptsList(receipts))); + if(adjustment.goal) card.append(element('p','观察目标 · '+adjustment.goal,'isp-decision')); + if(adjustment.reason) card.append(element('p','试调理由 · '+adjustment.reason,'action-copy')); if(adjustment.restored) card.append(disclosure('learner-restored-'+adjustment.number,'查看恢复后实拍', imageCard({name:'restored',scope:'learner',trial:adjustment.number,asset:adjustment.restored}))); if(adjustment.decision) card.append(element('p','取舍理由 · '+adjustment.decision.reason,'isp-decision')); @@ -399,57 +517,86 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get const zoom=compareButton('learner-'+adjustment.number,['调前实拍','调后实拍']); if(zoom) actions.append(zoom); if(canDecide) { - const control=button('记录本次保留或恢复',()=>openDialog('单项实验 · 记录取舍',[ - element('p','比对同一区域,确认独立回读,再写下观察和取舍。'), - field('choice','选择',{options:[['','请选择'],['keep','保留本次参数'],['restore','恢复期初 ISP']]}), - field('reason','理由',{max:180,placeholder:'目标区域有什么变化?是否出现副作用?'}), - ],({choice,reason})=>start({action:'learner_decision',trial:adjustment.number,choice,reason}),'保存取舍并核对回读'),'primary'); - control.disabled=busy;actions.append(control); + for(const [choice,label] of [['keep','保留本次参数'],['restore','恢复期初 ISP']]) { + const control=button(label,()=>openDialog('单项实验 · '+label,[ + element('p','比对同一区域,确认独立回读,再写下观察和取舍。'), + field('reason','理由',{max:180,placeholder:'目标区域有什么变化?是否出现副作用?'}), + ],({reason})=>start({action:'learner_decision',trial:adjustment.number,choice,reason}),'保存取舍并核对回读'),'ghost'); + control.disabled=busy;actions.append(control); + } } if(actions.childElementCount) card.append(actions); return card; } - function renderLearner(busy) { - const container=$('isp-learner-content'); + function renderParameters(busy) { + const stamp=JSON.stringify([binding,status,busy,pollIssue]); + if(stamp===renderedParameters) return; + renderedParameters=stamp; + const container=$('isp-parameters-content'); container.replaceChildren(); - const progress=element('ol','','learner-steps'); - for(const step of ['读取工位可写项','选一个参数','对照实拍与回读','记录保留或恢复']) progress.append(element('li',step)); - container.append(progress); - const help=element('p',!binding?'先关联本工位相机实验。':!status?.original?'先保存上方的期初 ISP,再读取可写参数。': - status.stop?'本工位已停流,可以查看已保存的单项证据。': - status.recoveryPending?'先恢复期初 ISP,再开启下一次实验。': - status.changesActive?'完成当前取舍。若已保留,开始下一项前请恢复期初 ISP。': - '每次只写一个数值。实际可选范围来自工位,软件支持的项目需在本工位取得实拍与回读。','action-copy'); + const options=status?.learnerOptions; + const help=element('p',pollIssue||(!binding?'先关联本组相机实验。': + status?.stop?'相机已停流。': + status?.recoveryPending?'先恢复期初 ISP,再读取可试调参数。': + status?.changesActive?'完成当前取舍并恢复期初 ISP 后,再开始下一项。': + status?.running==='learner_options'?'正在读取相机参数和范围…': + !status?.original?'先保存期初 ISP,再读取设备允许试调的数值。': + !options?'尚无本组参数回读。读取后可以核对实际值和权限。': + status.gammaProposal?errors.camera_gamma_proposal_pending: + '试调一次只应用一个参数,并保存同场景的前后实拍与独立回读。'),'action-copy'); container.append(help); - if(status?.original&&!status.stop) { + if(binding&&!status?.stop) { const actions=element('div','','button-row'); - const refresh=button('读取本工位可写参数',()=>start({action:'learner_options'}),'plain'); - refresh.disabled=Boolean(busy||status.recoveryPending||status.changesActive); + const refresh=pollIssue?button('刷新状态',poll,'ghost'):status?.original? + button(options?'重新读取参数':'读取相机参数',()=>start({action:'learner_options'}),'ghost'): + button('保存原始 ISP',()=>start({action:'save'}),'primary'); + refresh.disabled=Boolean(busy||!pollIssue&&(status?.recoveryPending||status?.changesActive)); actions.append(refresh);container.append(actions); } - if(status?.learnerOptions) { + const gamma=lastGammaReadback(); + const gammaSummary=element('div','','isp-gamma-summary'); + gammaSummary.append(element('strong','Gamma 曲线')); + if(gamma) { + const {mode,points}=gamma.asset.curvePreview; + const source=readTime(gamma.asset.recordedAt); + const curveButton=button('查看完整曲线',()=>showGammaCurve(gamma,curveButton),'plain'); + gammaSummary.append(element('p','最近回读 · '+(mode===0?'自动模式,第 1 档':'手动模式')+ + (source?' · '+source:''),'isp-parameter-status'), + element('p','节点 0 / 16 / 32 / 48 / 63 · '+points.join(' / '),'isp-parameter-status'),curveButton); + } else gammaSummary.append(element('p','等待包含 Gamma 的设备回读。','isp-parameter-status')); + container.append(gammaSummary); + if(options) { + const readAt=readTime(status.learnerOptionsReadAt); + container.append(element('p','最近读取的设备数值'+(readAt?' · '+readAt:'')+ + (pollIssue?' · 状态待重新核对':''),'isp-parameter-status')); const list=element('div','','learner-options'); - for(const [group,observe] of Object.entries(observation)) { - const options=status.learnerOptions.filter(item=>item.group===group); - const section=element('div','','learner-option'); - section.append(element('h4',group),element('p',observe,'action-copy')); - if(!options.length) section.append(element('p','工位未返回可核对的数值范围。','action-copy')); - for(const option of options) { - const row=element('div','','learner-field'); - row.append(element('strong',option.label),element('small',option.disabled?inactive[option.disabled]: - '当前 '+numeric(option.value,option.unit)+' · '+numeric(option.min,option.unit)+' 至 '+numeric(option.max,option.unit))); - if(!option.disabled) { - const adjust=button('试调'+option.label,()=>openLearnerTrial(option),'plain'); - adjust.disabled=Boolean(busy||status.recoveryPending||status.changesActive); - row.append(adjust); - } - section.append(row); + for(const option of options) { + const row=element('div','','learner-field'); + const head=element('div','','learner-field-head'); + const access=option.disabled==='manual_mode'?'模式锁定':option.disabled?'只读':learnerBlocked()?'暂缓试调':'可试调'; + head.append(element('strong',option.label),element('span',access,'status-tag'+(access==='可试调'?' ok':''))); + row.append(head,element('small','回读 '+numeric(option.value,option.unit)+' · 范围 '+ + numeric(option.min,option.unit)+' 至 '+numeric(option.max,option.unit))); + if(option.disabled) row.append(element('small',inactive[option.disabled]??'可写资格待确认。')); + else { + const adjust=button('试调'+option.label,()=>openLearnerTrial(option),'plain'); + adjust.disabled=Boolean(busy||learnerBlocked()); + row.append(adjust); } - list.append(section); + list.append(row); } + if(!options.length) list.append(element('p','设备未返回可核对的课堂参数范围。','action-copy')); container.append(list); } + const assistant=element('div','','isp-studio-help'); + assistant.append(element('p','在 Studio 说「先建议一个新曝光值,等我确认后再拍前后对照」。','action-copy')); + container.append(disclosure('studio-isp','在 Studio 对话里调参',assistant)); + } + function renderLearner(busy) { + const container=$('isp-learner-content'); + container.replaceChildren(); const records=status?.adjustments??[]; + $('isp-learner').hidden=!records.length; for(const adjustment of [...records].reverse()) { const active=status.activeAdjustment===adjustment.number; container.append(learnerResult(adjustment,busy,Boolean(active&&adjustment.after&& @@ -460,26 +607,33 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get const badge=$('isp-status'),help=$('isp-help'),summary=$('isp-detail'),actions=$('isp-actions'); const busy=posting||Boolean(status?.running); renderExposure(busy); + renderParameters(busy); renderLearner(busy); const rounds=status?.rounds??[]; const done=rounds.filter(round=>round.decision).length; badge.textContent=busy?'进行中':status?.error?'需要处理':`${done} / 2 轮已验收`; badge.className='status-tag'+(status?.error?' blocked':done===2?' ok':''); help.textContent=status?.error?explain(status.error):busy?(stageText[status?.stage]??'等待相机回执'): - !binding?'先关联本工位相机实验。':status?.stop?'原值已恢复,采流已停止。': + !binding?'先关联本组相机实验。':status?.stop?'原值已恢复,采流已停止。': !status?.original?'先保存期初 ISP。两轮都留实拍、回读和自己的判断。': rounds.at(-1)&&!rounds.at(-1).decision?'核对本轮实拍和独立回读,再选择保留或恢复。': done===1&&status.changesActive?'第 1 轮取舍已留档。先恢复期初配置,再用同一基线做第 2 轮。': + status?.gammaProposal?'查看 AI 理由和候选曲线,确认后采一组实际对照。': done===2?'两轮证据已保存。继续做盲选对照,或下载个人成果包。':'选择观察目标,开始当前轮。'; summary.replaceChildren();actions.replaceChildren(); const cards=element('div','','isp-rounds'); for(const number of [1,2]) cards.append(roundCard(number,rounds.find(round=>round.number===number),done,busy)); summary.append(cards); - if(!binding) return; - if(!status?.original) { - const save=button('保存原始 ISP',()=>start({action:'save'}),'primary');save.disabled=busy;actions.append(save);return; + if(!focusedRound&&(status?.gammaProposal?.number===initialRound||rounds.some(round=>round.number===initialRound))) { + focusedRound=true; + requestAnimationFrame(()=>$('isp-gamma-round-'+initialRound)?.scrollIntoView({block:'start'})); } - summary.append(disclosure('session','查看期初 ISP 与工位回执',receiptsList(sessionEntries(status,['original','readback','reloadReadback'])))); + if(!binding) { + if(showCamera) actions.append(button('关联本组相机实验',showCamera,'primary')); + return; + } + if(!status?.original) return; + summary.append(disclosure('session','查看期初 ISP 与实验回执',receiptsList(sessionEntries(status,['original','readback','reloadReadback'])))); if(status.reloaded) summary.append(imageCard({name:'reloaded',asset:status.reloaded})); if(status.stop) summary.append(element('p','停流回执 · '+status.stop.receiptId,'isp-decision')); if(status.comparisonIssue) summary.append(element('p','已独立回读原值,恢复后实拍仍待补。','capture-error')); @@ -499,7 +653,7 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get function syncBinding() { const id=getBinding()?.experimentId??null; if(id===binding) return; - binding=id;bindingRevision++;proofOpen.clear();apply(undefined);render();void poll(); + binding=id;bindingRevision++;pollIssue='';proofOpen.clear();apply(undefined);render();void poll(); } function evidenceIndex() { const rounds=(status?.rounds??[]).filter(round=>round.before&&round.after&&round.beforeReadback&&round.gammaReadback&&round.decision); @@ -514,5 +668,13 @@ export function createIspPanel({key,$,element,button,openDialog,field,notify,get if(!isCurrent()) throw new Error(evidenceChanged); return {receipt,files}; } - return {syncBinding,poll,evidence,evidenceIndex}; + function latestBlindPair() { + const rounds=status?.rounds??[]; + for(const round of [...rounds].reverse()) { + const before=previews.get(`${round.number}:before`)?.file; + const after=previews.get(`${round.number}:after`)?.file; + if(before&&after&&round.gammaReadback) return {round:round.number,pair:[before,after],readback:round.gammaReadback}; + } + } + return {syncBinding,poll,evidence,evidenceIndex,latestBlindPair}; } diff --git a/plugins/rdk-camera-workshop/web/preflight-panel.mjs b/plugins/rdk-camera-workshop/web/preflight-panel.mjs index 1a553cc..087f0a8 100644 --- a/plugins/rdk-camera-workshop/web/preflight-panel.mjs +++ b/plugins/rdk-camera-workshop/web/preflight-panel.mjs @@ -1,50 +1,61 @@ const checks={service:'相机服务',board:'X5 板端连接',frame:'当前画面'}; const states={waiting:'待检查',checking:'检查中',passed:'通过',blocked:'待处理'}; const fixes={ - camera_binding_required:'先在下方关联本工位相机实验,再检查 X5。', - camera_unconfigured:'在相机插件完成连接设置后重试。', - camera_configuration_invalid:'运行相机插件连接自检,核对私有连接文件。', - camera_auth_required:'确认当前身份可读取本工位相机实验。', - camera_service_unreachable:'确认本机相机服务已启动,然后重试。', + camera_credential_missing:'已找到相机连接配置,但缺少凭据文件。请在相机插件重新配置相机凭据,再刷新。', + camera_binding_required:'请选择本组相机实验,再重新检查 X5。', + camera_unconfigured:'先在相机插件设置服务地址和连接凭据,再回来检查。', + camera_configuration_invalid:'运行相机插件的连接自检,核对服务地址和私有连接配置。', + camera_auth_required:'检查 Studio 是否登录了有权访问本组实验的账号,再重新检查。', + camera_service_unreachable:'相机服务暂时连不上。若服务在本机,确认它已启动;若在远程,检查网络和服务地址。', + camera_service_error:'相机服务本次未完成检查。请运行相机插件的连接自检,再重新检查。', + camera_response_invalid:'相机服务回执不完整。请助教核对插件和相机服务版本。', camera_archive_missing:'重新选择当前身份可访问的相机实验。', - vision_device_adapter_required:'让助教确认本工位的板端适配器,再重新关联实验。', + vision_device_adapter_required:'让助教确认本组的板端适配器,再重新关联实验。', vision_device_transport_failed:'检查板卡供电、Studio 设备连接和相机服务的板端转发。', camera_capture_unconfirmed:'板端未及时响应。检查连接和转发,再重试预检。', - camera_sdk_unavailable:'让助教检查本工位 SDK 与相机模式。', + camera_sdk_unavailable:'让助教检查设备 SDK 与相机模式。', camera_recovery_required:'先用相机插件核对并恢复 ISP 与采流,再检查画面。', camera_stream_not_running:'在相机实验里点亮并打开预览,再重试。', camera_live_frame_stale:'预览帧未推进。检查当前采流后再试。', + vision_device_preview_frame_stale:'预览帧未推进。检查当前采流后再试。', camera_live_receipt_invalid:'相机服务缺少可验证的实时帧回执。请助教检查服务版本。', }; const pending={status:'waiting'}; const freshnessMs=120000; -export function createPreflightPanel({key,$,element,button,notify,getBinding,showCamera}) { +export function createPreflightPanel({key,$,element,button,notify,getBinding,showCamera,isCameraVisible}) { let binding; let observation; let posting=false; let checking=false; let expired=false; - const fresh=()=>observation?.completedAt&&Date.now()-Date.parse(observation.completedAt)!pollError&&observation?.completedAt&&Date.now()-Date.parse(observation.completedAt)=freshnessMs); - if(JSON.stringify(next)!==JSON.stringify(observation)||expired!==nextExpired) { - observation=next;expired=nextExpired;render(); + if(JSON.stringify(next)!==JSON.stringify(observation)||expired!==nextExpired||pollError) { + observation=next;expired=nextExpired;pollError=undefined;render(); } - } catch {} + } catch(error) { + if(current!==binding||posting) return; + const hint=error.message.startsWith('实验链接已失效')?error.message:'暂时读不到预检结果。确认 Studio 仍在运行,或点击“刷新状态”。'; + if(pollError!==hint) {pollError=hint;render();} + } finally {checking=false;} } async function start() { @@ -61,30 +72,38 @@ export function createPreflightPanel({key,$,element,button,notify,getBinding,sho function render() { const status=$('preflight-status'),list=$('preflight-checks'),actions=$('preflight-actions'); const busy=posting||observation?.running; - const ready=!expired&&Object.keys(checks).every(key=>observation?.checks[key]?.status==='passed'); - status.textContent=busy?'检查中':expired?'回执已过期':ready?'三项通过':observation?'查看检查结果':'待检查'; + const ready=!pollError&&!expired&&Object.keys(checks).every(key=>observation?.checks[key]?.status==='passed'); + status.textContent=pollError?'预检状态未更新':busy?'检查中':expired?'回执已过期':ready?'三项通过':observation?'查看检查结果':'待检查'; status.className='status-tag'+(ready?' ok':''); list.replaceChildren();actions.replaceChildren(); + if(pollError) { + list.append(element('p',pollError+(observation?' 下方显示上次读取的记录。':''),'preflight-error')); + actions.append(button('刷新状态',poll,'primary')); + } for(const [id,label] of Object.entries(checks)) { const result=observation?.checks[id]??pending; const card=element('article','','preflight-check'); card.append(element('h3',label),element('span',states[result.status]??states.waiting, - 'status-tag'+(result.status==='passed'&&!expired?' ok':result.status==='blocked'?' blocked':''))); + 'status-tag'+(result.status==='passed'&&!expired&&!pollError?' ok':result.status==='blocked'?' blocked':''))); if(result.code) card.append(element('p',fixes[result.code]??('检查未完成 · '+result.code),'preflight-error')); if(result.status==='passed'&&id==='board') card.append(element('p',[result.board,result.sensorModel,result.mode].filter(Boolean).join(' · '))); if(result.status==='passed'&&id==='frame') card.append(element('p',result.width+' × '+result.height+' · 已验证 SDK 帧时间推进')); - if(result.checkedAt) card.append(element('p','工位记录于 '+new Date(result.checkedAt).toLocaleTimeString('zh-CN',{hour12:false}))); + if(result.checkedAt) card.append(element('p','检查时间 '+new Date(result.checkedAt).toLocaleTimeString('zh-CN',{hour12:false}))); list.append(card); } const check=button(observation?'重新检查':'运行连接预检',start,'primary'); - check.disabled=Boolean(busy);actions.append(check); - if(!binding) actions.append(button('去关联相机实验',showCamera,'plain')); + check.disabled=Boolean(busy);if(!pollError) actions.append(check); + if(!binding&&!isCameraVisible?.()) actions.append(button('去关联相机实验',showCamera,'plain')); + else if(!busy&&!isCameraVisible?.()&&['camera_archive_missing','vision_device_adapter_required'].some(code=> + Object.values(observation?.checks??{}).some(result=>result.code===code))) { + actions.append(button('核对本组相机实验',showCamera,'plain')); + } } function syncBinding() { const next=getBinding()?.experimentId??null; - if(next===binding) return; - binding=next;observation=undefined;expired=false; + if(next===binding) {render();return;} + binding=next;observation=undefined;expired=false;pollError=undefined; render();void poll(); } - return {syncBinding,poll,receipt:()=>fresh()?observation:undefined}; + return {syncBinding,poll,render,receipt:()=>fresh()?observation:undefined}; } diff --git a/plugins/rdk-camera-workshop/web/style.css b/plugins/rdk-camera-workshop/web/style.css index d7512ec..26b3907 100644 --- a/plugins/rdk-camera-workshop/web/style.css +++ b/plugins/rdk-camera-workshop/web/style.css @@ -5,60 +5,109 @@ } *{box-sizing:border-box} body{margin:0} +[hidden]{display:none !important} button,input,select,textarea{font:inherit} button,summary{cursor:pointer} button:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible,textarea:focus-visible{outline:3px solid #5f8bed;outline-offset:3px} .top{background:#14243f;color:#f8fbff} -.top-inner,.shell{max-width:1200px;margin:auto;padding-inline:clamp(16px,4vw,52px)} -.top-inner{height:65px;display:flex;align-items:center;justify-content:space-between;gap:12px} -.brand,.top-actions,.button-row,.action-head{display:flex;align-items:center;gap:10px} -.brand strong{font-size:16px}.brand span:not(.brand-mark){font-size:12px;color:#b6c7e5;margin-left:10px} -.brand-mark{border:1px solid #819bcb;border-radius:8px;padding:3px 8px;font-size:18px;color:#b9d1ff} -.top .ghost{color:#edf5ff;background:#243959;border-color:#465c82} -.shell{padding-block:35px 62px} -.hero{display:flex;align-items:flex-end;justify-content:space-between;gap:18px;margin-bottom:26px} -.eyebrow{font-family:"IBM Plex Mono",monospace;letter-spacing:.12em;color:#3d5b8e;font-size:11px;font-weight:700;margin:0 0 10px} -h1{font-size:clamp(26px,4vw,41px);letter-spacing:-.045em;line-height:1.17;margin:0} -.lede{color:var(--muted);font-size:15px;margin:12px 0 0} -.clock{padding:12px 14px;background:#e3ecfa;border:1px solid #c9daf4;border-radius:12px;display:flex;align-items:center;gap:15px} -.clock #clock-value{display:block;font-weight:700;font-size:18px;font-variant-numeric:tabular-nums;white-space:nowrap} -.clock-label{font-size:11px;color:#445a7c;white-space:nowrap}.clock .button{font-size:12px;padding:7px 8px} -.grid{display:grid;grid-template-columns:minmax(218px, .77fr) minmax(0, 2.35fr);gap:18px;align-items:start} -.main-column{display:grid;gap:16px;min-width:0} -.box{background:var(--surface);border:1px solid var(--line);border-radius:16px;padding:22px;box-shadow:0 5px 18px rgba(29,55,97,.035);min-width:0} -.timeline{padding:18px 10px 14px} -.section-label{font-size:12px;font-weight:750;letter-spacing:.07em;color:#526888} -.timeline>.section-label{padding-left:8px;margin-bottom:14px} -.timeline ol{list-style:none;margin:0;padding:0;display:grid;gap:3px} -.timeline li{display:grid;grid-template-columns:12px 1fr;gap:8px;align-items:start;border:1px solid transparent;border-radius:9px;padding:8px;font-size:12px} -.stage-name{font-weight:640;line-height:1.5}.stage-time{display:block;color:var(--muted);font-size:11px;margin-top:2px} -.timeline li.state-current{background:#edf3ff;border-color:#cadcff;color:#1849a5} -.timeline .state-blocked{background:#fff8ec;color:#704b10}.timeline .state-evidence_recorded .marker{background:#1d795c} -.marker{width:8px;height:8px;margin-top:5px;border-radius:50%;background:#b8c7dd} +.top-inner,.shell{max-width:1200px;margin:auto;padding-inline:clamp(14px,3.5vw,44px)} +.top-inner{min-height:58px;padding-block:8px;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap} +.brand,.top-actions,.button-row,.action-head,.clock-actions,.step-head-right{display:flex;align-items:center;gap:8px} +.top-actions{flex-wrap:wrap} +.brand strong{font-size:15px}.brand span:not(.brand-mark){font-size:12px;color:#b6c7e5;margin-left:8px} +.brand-mark{border:1px solid #819bcb;border-radius:8px;padding:2px 7px;font-size:16px;color:#b9d1ff} +.top .ghost{color:#edf5ff;background:#243959;border-color:#465c82;padding:6px 10px;font-size:12px} +.top .ghost:hover{background:#2f4970} +.shell{padding-block:22px 52px} +.hero{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;margin-bottom:18px} +.eyebrow{font-family:"IBM Plex Mono",monospace;letter-spacing:.12em;color:#3d5b8e;font-size:11px;font-weight:700;margin:0 0 6px} +h1{font-size:clamp(22px,3.4vw,34px);letter-spacing:-.04em;line-height:1.18;margin:0} +.lede{color:var(--muted);font-size:14px;margin:8px 0 0} +.clock{padding:10px 12px;background:#e4edfa;border:1px solid #c9daf4;border-radius:12px;display:flex;align-items:center;gap:12px;flex:none} +.clock #clock-value{display:block;font-weight:700;font-size:17px;font-variant-numeric:tabular-nums;white-space:nowrap} +.clock-label{font-size:11px;color:#445a7c;white-space:nowrap} +.clock .button{font-size:12px;padding:7px 10px;white-space:nowrap} +.station-health{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;padding:9px 12px;margin-bottom:14px;background:var(--surface);border:1px solid var(--line);border-radius:12px;box-shadow:0 2px 10px rgba(29,55,97,.03)} +.station-health[hidden]{display:none} +.health-pills{display:flex;align-items:center;gap:6px;flex-wrap:wrap;min-width:0} +.health-pill{display:inline-flex;align-items:center;gap:6px;padding:5px 9px;border:1px solid #d4e0f2;border-radius:999px;background:#f7faff;color:var(--text);font-size:12px;font-weight:600;line-height:1.25} +.health-pill:hover{border-color:#8cb0ea;background:#edf4ff} +.health-pill i{width:7px;height:7px;border-radius:50%;flex:none;background:#99adc8} +.health-pill.ok{background:#edf9f4;border-color:#b8e3d2;color:#0e5946}.health-pill.ok i{background:#188766} +.health-pill.warn{background:#fff9eb;border-color:#ebd4a2;color:#734b0e}.health-pill.warn i{background:#c5841d} +.health-pill.blocked{background:#fff3f2;border-color:#ecc0bc;color:#8e2a23}.health-pill.blocked i{background:#c93d34} +.health-meta{display:flex;align-items:center;gap:8px;flex:none} +.health-meta .button{padding:4px 8px;font-size:12px} +.live-sync{display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:650;color:var(--muted);white-space:nowrap} +.live-sync i{width:7px;height:7px;border-radius:50%;background:#99adc8} +.live-sync.connected{color:#0e5946}.live-sync.connected i{background:#188766} +.health-diag-list{display:grid;gap:8px;margin:0} +.health-diag-item{border:1px solid var(--line);border-radius:10px;padding:10px 12px;background:#f8fbff} +.health-diag-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:4px} +.health-diag-item strong{font-size:13px}.health-diag-item p{margin:0;font-size:12px;color:var(--muted);line-height:1.55} +.grid{display:grid;grid-template-columns:minmax(228px, .78fr) minmax(0, 2.35fr);gap:18px;align-items:start} +.main-column{display:grid;gap:14px;min-width:0} +.box{background:var(--surface);border:1px solid var(--line);border-radius:16px;padding:20px;box-shadow:0 5px 18px rgba(29,55,97,.035);min-width:0} + +/* Timeline sidebar */ +.timeline{padding:14px 10px 12px} +.timeline summary{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:2px 8px;list-style:none;font-size:14px;font-weight:750;color:var(--text)} +.timeline summary::-webkit-details-marker{display:none} +.timeline-title{white-space:nowrap} +.timeline-progress{font-size:11px;font-weight:700;color:#2851a0;background:#ebf2ff;border-radius:999px;padding:2px 8px;white-space:nowrap;font-variant-numeric:tabular-nums} +.timeline-bar{height:4px;background:#e5edf8;border-radius:999px;margin:10px 8px 10px;overflow:hidden} +.timeline-bar i{display:block;height:100%;width:var(--progress,0%);background:#245cd4;border-radius:inherit;transition:width .2s ease} +.timeline ol{list-style:none;margin:0;padding:0;display:grid;gap:2px} +.timeline-parallel{margin-top:10px;padding-top:10px;border-top:1px dashed #cad7ec} +.timeline-parallel[hidden]{display:none} +.timeline-subhead{margin:0 0 6px 8px;font-size:11px;font-weight:750;letter-spacing:.06em;color:#3d5b8e} +.timeline-parallel .stage-button{background:#f7faff;border-color:#e3ecf9} +.timeline-parallel .stage-button[aria-current="location"]{background:#e7f0ff;border-color:#9fc0f6} +.stage-button{font:inherit;font-size:12px;text-align:left;color:inherit;background:transparent;width:100%;display:grid;grid-template-columns:12px minmax(0,1fr);gap:8px;align-items:start;border:1px solid transparent;border-radius:9px;padding:6px 8px;cursor:pointer} +.stage-button:hover{background:#f2f6fc} +.stage-button:focus-visible{outline:2px solid #2659c7;outline-offset:-2px} +.stage-name{display:block;font-weight:640;line-height:1.4}.stage-time{display:block;color:var(--muted);font-size:11px;margin-top:1px;font-variant-numeric:tabular-nums} +.stage-button[aria-current="location"]{background:#edf3ff;border-color:#cadcff;color:#1849a5} +.timeline .state-blocked .stage-time{color:#704b10}.timeline .state-evidence_recorded .marker{background:#1d795c} +.marker{width:8px;height:8px;margin-top:4px;border-radius:50%;background:#b8c7dd} .state-current .marker{background:#245cd4}.state-blocked .marker{background:#a56915} -.action{border-top:4px solid #2659c7}.action-head{justify-content:space-between;min-height:24px} -.focus-dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:#285ccd;margin-right:7px} -h2{line-height:1.24;margin:10px 0 8px;font-size:clamp(20px,3vw,28px);letter-spacing:-.029em} -p{line-height:1.7}.action-copy,.training p,.evidence p{font-size:14px;color:var(--muted);margin:0 0 14px} -.status-tag{display:inline-block;border-radius:6px;background:#edf3fb;color:#3b577c;font-size:11px;font-weight:700;padding:5px 8px;white-space:nowrap} + +/* Action & banners */ +.section-label{font-size:12px;font-weight:750;letter-spacing:.05em;color:#526888;display:flex;align-items:center} +.action{border-top:4px solid #2659c7}.action-head{justify-content:space-between;min-height:24px;flex-wrap:wrap} +.focus-dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:#285ccd;margin-right:7px;flex:none} +.step-head-right [hidden]{display:none} +h2{line-height:1.24;margin:8px 0 8px;font-size:clamp(19px,2.6vw,25px);letter-spacing:-.025em} +p{line-height:1.68}.action-copy,.training p,.evidence p{font-size:14px;color:var(--muted);margin:0 0 12px} +.status-tag{display:inline-block;border-radius:6px;background:#edf3fb;color:#3b577c;font-size:11px;font-weight:700;padding:4px 8px;white-space:nowrap} +#step-tag[hidden]{display:none} .status-tag.blocked{background:#fff0d6;color:var(--amber)}.status-tag.ok{background:#dff4eb;color:var(--green)} -.button{border:1px solid transparent;border-radius:8px;padding:9px 12px;font-weight:650;font-size:13px;line-height:1.25} +.button{border:1px solid transparent;border-radius:8px;padding:8px 12px;font-weight:650;font-size:13px;line-height:1.25} a.button{text-decoration:none} -.training-preflight{background:#fffaed;border:1px solid #efdbb1;border-radius:8px;padding:10px 12px;margin:0 0 14px} +.training-preflight,.route-ready-banner{background:#fffaed;border:1px solid #efdbb1;border-radius:10px;padding:10px 12px} +.training-preflight{margin:0 0 12px} .training-preflight p{color:#704b17;margin:0;font-size:13px} -.training-preflight .button-row{margin-top:5px} +.training-preflight .button-row{margin-top:6px} +.route-ready-banner{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap} +.route-ready-banner[hidden]{display:none} +.route-ready-banner strong{display:block;font-size:13px;color:#6c450d} +.route-ready-banner span{display:block;font-size:12px;color:#7a5620;margin-top:2px} .primary{background:var(--blue);color:#fff}.primary:hover{background:#153da5} -.ghost{border-color:#cbd8ed;background:#f5f8fe;color:#214476}.plain{background:transparent;color:#2851a0} -.button:disabled{opacity:.58;cursor:default} -.button-row{flex-wrap:wrap;margin-top:13px} +.ghost{border-color:#cbd8ed;background:#f5f8fe;color:#214476}.ghost:hover{background:#eaf1fd} +.plain{background:transparent;color:#2851a0;padding-inline:8px}.plain:hover{background:#f0f5fe} +.button:disabled{opacity:.52;cursor:not-allowed} +.button-row{flex-wrap:wrap;margin-top:12px} +#capture-actions:has(button){margin-bottom:12px} .tool-hint,.run-ref{display:block;border-radius:8px;padding:9px 11px;background:#f0f5fc;color:#345378;font-family:"IBM Plex Mono",monospace;font-size:11px;overflow-wrap:anywhere;margin:10px 0} -.tool-details{margin:16px 0 0;color:#345378;font-size:12px}.tool-details code{display:block;margin-top:8px;overflow-wrap:anywhere} +.tool-details{margin:14px 0 0;color:#345378;font-size:12px}.tool-details code{display:block;margin-top:8px;overflow-wrap:anywhere} .last-checked{display:block;color:var(--muted);font-size:12px;margin-bottom:8px} + +/* Comparison & camera */ .comparison-images{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px} .comparison-frame{margin:0;min-width:0;border:1px solid var(--line);border-radius:9px;overflow:hidden;background:#f0f4fa} .comparison-frame img,.comparison-placeholder{width:100%;aspect-ratio:16 / 10;display:block;object-fit:contain;background:#14243f} .comparison-placeholder{display:grid;place-items:center;background:#edf2f9;color:#50637f;font-size:13px} -.comparison-frame figcaption{display:flex;justify-content:space-between;align-items:center;min-height:42px;padding:4px 10px;font-size:13px;font-weight:650} +.comparison-frame figcaption{display:flex;justify-content:space-between;align-items:center;min-height:40px;padding:4px 10px;font-size:13px;font-weight:650} .comparison-readback{color:var(--muted);overflow-wrap:anywhere} .camera-frame-preview{display:block;width:100%;max-height:54vh;object-fit:contain;background:#14243f;border-radius:9px} .camera-summary{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin:12px 0} @@ -81,61 +130,84 @@ a.button{text-decoration:none} .preflight-check h3{margin:0 0 8px;font-size:14px} .preflight-check p{margin:8px 0 0;font-size:12px;color:var(--muted);overflow-wrap:anywhere} .preflight-check .preflight-error{color:#972e26} -@media(max-width:720px){.capture-cards{grid-template-columns:1fr}} -@media(max-width:720px){.preflight-checks{grid-template-columns:1fr}} -.action-checklist{margin:12px 0 16px;padding-left:24px;color:var(--text);font-size:14px;line-height:1.65} -.action-checklist li+li{margin-top:5px} -.fields{margin:13px 0 5px;display:grid;gap:10px;font-size:12px} +.action-checklist{margin:10px 0 14px;padding-left:22px;color:var(--text);font-size:14px;line-height:1.65} +.action-checklist li+li{margin-top:4px} +.fields{margin:12px 0 4px;display:grid;gap:10px;font-size:12px} .field{display:grid;gap:5px;color:#354a67;font-weight:650} .field input,.field select,.field textarea{min-width:0;width:100%;border:1px solid #ccd8e9;border-radius:8px;background:#fbfcff;color:var(--text);padding:8px 9px;font-size:13px;font-weight:450} -.field textarea{min-height:95px} -.milestones{display:grid;grid-template-columns:repeat(3,1fr);margin:12px 0;gap:8px} -.milestones div{background:#edf3fc;border:1px solid #d9e6f7;padding:9px;border-radius:9px} -.milestones strong,.milestones span{display:block}.milestones strong{font-size:15px;color:#234d94}.milestones span{font-size:11px;color:#465d80;margin-top:3px} +.field textarea{min-height:90px} +.field-inline-head{display:flex;align-items:center;justify-content:space-between;gap:10px} +.slider-readout{font-family:"IBM Plex Mono",monospace;font-size:15px;font-weight:700;color:var(--blue);font-variant-numeric:tabular-nums} +.practice-slider-field{margin:10px 0 12px} +.practice-slider-field input[type="range"]{padding:0;border:0;background:transparent;accent-color:var(--blue)} +.practice-scene-tabs{margin:10px 0 8px;flex-wrap:wrap;gap:6px} +.practice-presets{margin-top:8px;flex-wrap:wrap;gap:6px} +.practice-presets .button{padding:4px 10px;font-size:12px} + +/* Milestones: static neutral timeline info cards (not clickable tabs) */ +.milestones{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));margin:12px 0;gap:8px} +.milestones div{background:#f6f8fb;border:1px solid var(--line);border-left:3px solid #7d9bc9;padding:8px 10px;border-radius:8px} +.milestones strong,.milestones span{display:block}.milestones strong{font-size:14px;color:var(--text);font-variant-numeric:tabular-nums}.milestones span{font-size:11px;color:var(--muted);margin-top:2px} .detection-summary strong{margin-top:5px} + +/* Route selection cards */ .routes{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin:12px 0} -.route-card{text-align:left;border:1px solid #d3dff0;border-radius:10px;padding:10px;background:#f8fbff;color:var(--text);min-width:0} -.route-card.active{border-color:#285dcc;background:#eff5ff}.route-card:disabled{cursor:default;background:#f3f4f7} -.route-card strong{display:block;font-size:13px}.route-card small{display:block;font-size:11px;color:#4a5c75;line-height:1.55;margin-top:5px} -.route-card .status-tag{margin-top:6px}.route-heading{font-size:12px;font-weight:650;margin-bottom:5px} -.evidence details{border-top:1px solid var(--line);padding-top:11px;margin-top:15px} +.route-card{text-align:left;border:1px solid #c6d7f2;border-radius:10px;padding:11px;background:#f8fbff;color:var(--text);min-width:0;transition:border-color .15s,background .15s} +.route-card:hover:not(:disabled){border-color:#285dcc;background:#eff5ff} +.route-card.active{border:2px solid #285dcc;background:#edf4ff} +.route-card:disabled{cursor:not-allowed;opacity:.62;border-style:dashed;border-color:#ccd4e0;background:#f4f6f9} +.route-card strong{display:block;font-size:13px}.route-card small{display:block;font-size:11px;color:#4a5c75;line-height:1.5;margin-top:5px} +.route-card .status-tag{margin-top:6px}.route-heading{font-size:12px;font-weight:650;margin-bottom:5px;color:#3d5370} + +/* Evidence & delivery */ +.evidence details{border-top:1px solid var(--line);padding-top:11px;margin-top:14px} .evidence summary{font-size:12px;font-weight:700;color:#2b518a} .evidence ul,.review-list{margin:8px 0;padding-left:19px;overflow-wrap:anywhere;font-size:12px;color:#465771} -dialog{width:min(455px,calc(100% - 28px));padding:23px;border:1px solid var(--line);border-radius:15px;color:var(--text);box-shadow:0 10px 60px #0b234940} -dialog::backdrop{background:#11264888} -#notice{position:fixed;right:18px;bottom:18px;max-width:calc(100% - 36px);padding:12px 15px;border-radius:10px;background:#102748;color:#fff;font-size:13px;box-shadow:0 4px 20px #14243f33} -@media(max-width:800px){.hero{align-items:flex-start;flex-direction:column}.grid{grid-template-columns:190px minmax(0,1fr)}.box{padding:16px}.timeline{padding:13px 7px}} -@media(max-width:580px){.shell{padding-block:24px}.grid{display:flex;flex-direction:column-reverse}.grid>*{width:100%}.brand span:not(.brand-mark){display:none}.top-inner{height:55px}.top-actions{gap:5px}.top .button{font-size:12px;padding:7px 8px}.routes{grid-template-columns:1fr}.clock{width:100%;justify-content:space-between}.timeline ol{grid-template-columns:1fr 1fr}} +.attachment-hint{font-size:12px;color:var(--muted);margin:10px 0 6px} +.attachment-list{list-style:none;padding:0;margin:6px 0 12px;display:grid;gap:6px} +.attachment-list:empty{display:none} +.attachment-item{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:6px 10px;border:1px solid var(--line);border-radius:8px;background:#f8fbff;font-size:12px;color:var(--text)} +.attachment-item span{min-width:0;overflow-wrap:anywhere} +.attachment-item button{flex:none;padding:4px 8px;font-size:11px} +/* Dialogs & toast */ +dialog{width:min(460px,calc(100% - 28px));padding:22px;border:1px solid var(--line);border-radius:15px;color:var(--text);box-shadow:0 10px 60px #0b234940} +dialog::backdrop{background:#11264888} +#notice{position:fixed;right:18px;bottom:18px;max-width:calc(100% - 36px);padding:11px 15px;border-radius:10px;background:#102748;color:#fff;font-size:13px;box-shadow:0 4px 20px #14243f33;z-index:20} .robogo-parameters{max-height:46vh;overflow:auto;margin:0;padding:12px;border:1px solid var(--line);border-radius:8px;background:#f3f6fb;font-size:12px;line-height:1.5;overflow-wrap:anywhere;white-space:pre-wrap} -.isp-rounds{display:grid;gap:12px;margin:14px 0} +/* ISP & workspace */ +.isp-rounds{display:grid;gap:12px;margin:12px 0} .isp-round{padding:14px;border:1px solid var(--line,#d9e3ef);border-radius:12px;background:#f9fbff} .isp-round h3{font-size:16px;margin:0} .isp-round .action-copy{margin:8px 0} .isp-pair{grid-template-columns:repeat(2,minmax(0,1fr))} .isp-receipt small,.isp-demo-receipt{display:block;color:var(--muted);font-size:11px;overflow-wrap:anywhere} .isp-decision,.isp-demo-observation{margin:12px 0;color:#2f4e6f;font-size:13px} -.isp-demo summary{cursor:pointer;font-size:17px;font-weight:700} +.isp-demo summary{cursor:pointer;font-size:16px;font-weight:700} .isp-live{margin:14px 0} .isp-demo-archive{font-size:15px;margin:16px 0 8px} .isp-demo-pair{margin-top:12px} .isp-demo-pair figure img{width:100%;aspect-ratio:16/9;object-fit:contain;background:#192335} .isp-demo-pair figcaption{display:block;padding:9px 12px} .isp-demo-source{font-size:12px;color:var(--muted);margin-bottom:8px} -@media(max-width:540px){.isp-round{padding:10px}.isp-demo-pair figcaption{padding:6px}.isp-pair figcaption{padding:6px}} -.workspace-panels{display:grid;gap:16px;min-width:0} +.workspace-panels{display:grid;gap:14px;min-width:0} .workspace-panels:empty{display:none} -.workspace-panels>section,.workspace-panels>details{scroll-margin-top:94px} -.timeline summary,.station-tools>summary{font-size:14px;font-weight:750;color:var(--text)} -.timeline summary{padding:0 8px} -.timeline[open] summary{margin-bottom:14px} -.station-tools[open]>.workspace-panels{margin-top:16px} -.station-tools .box{box-shadow:none} +.workspace-panels>section,.workspace-panels>details{scroll-margin-top:88px} +.station-tools>summary{font-size:14px;font-weight:750;color:var(--text)} +.station-tools[open] .tool-tabs{display:flex} +.tool-tabs{display:none;flex-wrap:wrap;gap:6px;margin:12px 0 12px;padding-bottom:10px;border-bottom:1px solid var(--line)} +.tool-tab{border:1px solid #d0dcf0;border-radius:999px;background:#f6f9fe;color:#2c4b77;padding:5px 11px;font-size:12px;font-weight:650} +.tool-tab[aria-selected="true"]{background:var(--blue);border-color:var(--blue);color:#fff} +.station-tools .box{box-shadow:none;padding:16px} +.station-tools [data-tab-hidden="true"]{display:none} .connect-panels .isp-rounds,.connect-panels #isp-status{display:none} -.parallel-training{position:sticky;top:0;z-index:2;display:flex;align-items:center;justify-content:space-between; - gap:10px;padding:10px 12px;background:#f5f8ff;border:1px solid #cadcff;border-radius:10px;box-shadow:0 4px 13px #194fc212} +.parallel-training{display:flex;align-items:center;justify-content:space-between; + gap:10px;padding:10px 14px;background:#f5f8ff;border:1px solid #cadcff;border-radius:10px} +.action{border-top:4px solid #2659c7;scroll-margin-top:16px} +.route-ready-banner .button{background:#fff8e6;border-color:#d9b36c;color:#6c450d} +.route-ready-banner .button:hover{background:#ffefc9} .parallel-training[hidden]{display:none} .parallel-training div{min-width:0;overflow-wrap:anywhere} .parallel-training strong,.parallel-training span{display:block;font-size:13px} @@ -164,53 +236,356 @@ dialog.frame-dialog{width:min(960px,calc(100% - 20px));padding:16px;max-height:c .frame-controls input{width:100%;min-width:0;accent-color:var(--blue)} .board-preview img{max-height:min(52vh,440px)} .board-preview:not([hidden]){margin:0 0 8px} +#board-actions select{max-width:100%;padding:8px 9px;border:1px solid #ccd8e9;border-radius:8px;background:#fbfcff;color:var(--text)} +#board-actions + .board-preview{margin-top:12px} +.board-fixed-scene{flex-basis:100%;display:flex;gap:8px;align-items:flex-start;font-size:.9rem} +.board-fixed-scene[hidden],.board-comparison[hidden],.board-roi[hidden]{display:none} +.board-fixed-scene input{margin-top:.2rem} +.board-comparison{margin-top:16px;padding:14px;border:1px solid #ccd8e9;border-radius:12px} +.board-comparison h3{margin:0 0 6px} +.board-comparison p{margin:8px 0} +.board-comparison-images{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px} +.board-comparison-images figure{min-width:0;margin:0} +.board-comparison-images figcaption{padding:6px 0 8px} +.board-comparison-frame{position:relative;aspect-ratio:16/9;border-radius:8px;overflow:hidden;background:#202b3a} +.board-comparison-frame img{display:block;width:100%;height:100%} +.board-comparison-frame.select-region{cursor:crosshair} +.board-image-status{position:absolute;inset:0;padding:8px;color:white} +.board-roi{position:absolute;pointer-events:none;left:var(--roi-left);top:var(--roi-top);width:var(--roi-width);height:var(--roi-height);border:2px solid #ffe45d;box-shadow:0 0 0 1px #141820} +.board-comparison-tools{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin:8px 0} +.board-comparison-tools select,.board-coordinates input{max-width:100%;padding:8px;border:1px solid #ccd8e9;border-radius:8px;background:#fbfcff;color:var(--text)} +.board-coordinates{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px;margin-top:8px} +.board-coordinates label{display:grid;gap:4px} +.board-comparison-card{display:grid;gap:5px;border:1px solid #ccd8e9;border-radius:8px;padding:10px} +.board-comparison-result{margin-top:10px} .board-frame-detail{font-size:13px;color:var(--text);overflow-wrap:anywhere} #detection-title{margin:14px 0 3px;font-size:16px} #detection .detection-summary{margin-top:8px} #delivery .delivery-checklist{padding:0;list-style:none;display:grid;gap:6px} -.delivery-checklist li{display:flex;justify-content:space-between;align-items:baseline;gap:10px; - padding:8px 0;border-bottom:1px solid var(--line)} -.delivery-checklist li span{text-align:right} +.delivery-checklist li{display:flex;justify-content:space-between;align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid var(--line);flex-wrap:wrap} +.delivery-checklist-right{display:flex;align-items:center;gap:8px;flex-wrap:wrap} .evidence-ready{color:var(--green);font-weight:700} -@media(min-width:1000px){.grid>aside{position:sticky;top:12px;max-height:calc(100dvh - 24px);overflow:auto}} -@media(max-width:999px){ - .grid{display:grid;grid-template-columns:minmax(0,1fr)} - .grid>*{width:auto} - .timeline{padding:11px 10px} - .timeline ol{grid-template-columns:repeat(2,minmax(0,1fr))} - .shell{padding-top:20px} - .hero{gap:10px;margin-bottom:12px} - .hero .lede{display:none} -} -@media(min-width:600px) and (max-width:999px){ - .hero{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center} -} -@media(max-width:480px){ - .frame-controls{grid-template-columns:1fr;gap:7px} - .isp-round h3{font-size:15px} - .isp-pair figcaption{overflow-wrap:anywhere} - .delivery-checklist li{display:grid;gap:3px} - .delivery-checklist li span{text-align:left} -} .isp-learner{border-top:1px solid var(--line,#dbe3ed);margin-top:20px;padding-top:18px} -.isp-learner h3,.isp-learner h4{margin:0} -.learner-steps{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px;margin:12px 0;padding:0;list-style:none;counter-reset:learner} -.learner-steps li{padding:8px 10px;border:1px solid #d7e1ed;background:#f0f5fc;border-radius:8px;color:#203854;font-size:13px;font-weight:650} -.learner-steps li::before{counter-increment:learner;content:counter(learner) " ";color:#174fbb} -.learner-options{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin:12px 0} -.learner-option{min-width:0;padding:12px;border:1px solid #d7e1ed;border-radius:9px} -.learner-option .action-copy{margin:6px 0} -.learner-field{display:grid;justify-items:start;gap:5px;border-top:1px solid #e2e9f1;padding-top:8px;margin-top:8px;overflow-wrap:anywhere} +.isp-workspace{display:grid;gap:14px;margin-top:12px;align-items:start;grid-template-areas:"parameters" "round"} +.isp-round-workspace{grid-area:round;min-width:0} +.isp-parameters{grid-area:parameters;min-width:0;padding:14px;border:1px solid var(--line);border-radius:10px;background:#f5f8fe;overflow-wrap:anywhere;scroll-margin-top:88px} +.isp-parameters h3,.isp-learner h3{margin:0 0 8px} +.isp-parameters .action-copy{font-size:13px;margin:6px 0} +.isp-parameters .button-row,.isp-parameters .proof-details{margin-top:8px} +.isp-parameter-status{margin:6px 0;color:var(--muted);font-size:12px;font-variant-numeric:tabular-nums} +.isp-gamma-summary{margin:12px 0 0;padding-top:10px;border-top:1px solid var(--line)} +.isp-gamma-summary strong{display:block} +.isp-parameters .curve-plot{padding:8px} +.isp-curve-nodes{margin:0;padding-left:24px;display:grid;grid-template-columns:repeat(auto-fit,minmax(56px,1fr));gap:4px 8px;font:12px/1.5 "IBM Plex Mono",monospace} +.learner-options{margin:8px 0 0} +.learner-field{display:grid;justify-items:start;gap:5px;border-top:1px solid var(--line);padding-top:8px;margin-top:8px;overflow-wrap:anywhere} +.learner-field-head{display:flex;align-items:center;gap:5px 8px;flex-wrap:wrap} .learner-field small{color:var(--muted)} .learner-result{margin-top:12px} -@media(max-width:600px){.learner-options{grid-template-columns:1fr}.learner-steps{grid-template-columns:repeat(2,minmax(0,1fr))}} - +@media(min-width:740px){.isp-workspace{grid-template-columns:minmax(0,1fr) minmax(214px,30%);grid-template-areas:"round parameters"}} -.entry-choice{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:18px} +.entry-choice{display:flex;align-items:center;justify-content:space-between;gap:14px;margin-bottom:16px;padding:14px 18px} .entry-choice[hidden],.parallel-actions [hidden],.top-actions [hidden]{display:none} -.entry-choice h2{margin:0 0 4px} -.entry-choice p{margin:0} -.parallel-actions{justify-content:flex-end;flex-wrap:wrap} -.is-practice :is(#camera,#camera-preflight,#camera-capture,#camera-isp,#board,#training,#training-preflight){display:none} -@media(max-width:640px){.entry-choice{align-items:flex-start;flex-direction:column}.parallel-actions{justify-content:flex-start}} +.entry-choice .button-row{margin-top:0} +.entry-choice .button-row [hidden]{display:none} +.entry-choice h2{margin:0 0 3px;font-size:17px} +.entry-choice p{margin:0;font-size:13px} +.parallel-actions{justify-content:flex-end;flex-wrap:wrap;margin-top:0} +.is-practice :is(#camera,#camera-preflight,#camera-capture,#camera-isp,#board,#training,#training-preflight,#route-ready-banner,#station-health){display:none} +.is-practice :is(.shell>.grid,.hero,.top-actions,#isp-live-exposure,.isp-demo-archive){display:none} +.is-practice .shell{max-width:920px;padding-block:16px 32px} +#practice-content .practice-card{padding:18px 20px} +#practice-note{margin-top:12px;padding:16px 18px} +#practice-observation{min-height:66px} +#entry-practice[hidden]{display:none} + +/* Pro interactive compare stage, split curtain, 2.5x loupe, dual RGB/luma scope & 6-param ISP lab */ +.practice-mode-bar{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;margin:6px 0 10px} +.practice-stage{margin-top:10px} +.isp-compare-widget{display:grid;gap:10px;margin-top:10px} +.isp-compare-toolbar{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap} +.isp-compare-tools{display:flex;align-items:center;gap:6px;flex-wrap:wrap} +.isp-compare-tools .button{padding:5px 10px;font-size:12px} +.isp-segmented{display:inline-flex;padding:3px;border-radius:10px;background:#e6eef9;border:1px solid #cddaf0;gap:2px} +.isp-seg-btn{border:0;border-radius:7px;background:transparent;color:#35517a;font-size:12px;font-weight:650;padding:5px 11px;transition:background .15s,color .15s,box-shadow .15s} +.isp-seg-btn.active{background:#fff;color:var(--blue);box-shadow:0 1px 4px rgba(20,36,63,.12)} + +.isp-split-stage{position:relative;width:100%;aspect-ratio:16 / 9;border-radius:12px;overflow:hidden;background:#0f192b;border:1px solid #c5d4ea;user-select:none;touch-action:none;cursor:ew-resize;box-shadow:0 6px 22px rgba(20,36,63,.09)} +.isp-split-stage[hidden]{display:none} +.isp-split-layer{position:absolute;inset:0;width:100%;height:100%} +.isp-split-before{clip-path:inset(0 calc(100% - var(--split-pos, 50%)) 0 0);z-index:2} +.isp-split-after{z-index:1} +.isp-compare-media{display:block;width:100%;height:100%;object-fit:contain;pointer-events:none} +.isp-stage-badge{position:absolute;top:10px;z-index:4;padding:4px 10px;border-radius:999px;background:rgba(15,25,43,.76);backdrop-filter:blur(6px);-webkit-backdrop-filter:blur(6px);color:#f4f8ff;font-size:12px;font-weight:650;letter-spacing:.01em;border:1px solid rgba(255,255,255,.18);pointer-events:none;font-variant-numeric:tabular-nums} +.isp-stage-badge-left{left:10px} +.isp-stage-badge-right{right:10px;background:rgba(25,79,194,.86);border-color:rgba(191,219,254,.45)} +.isp-split-divider{position:absolute;top:0;bottom:0;left:var(--split-pos, 50%);width:2px;margin-left:-1px;background:#fff;box-shadow:0 0 10px rgba(10,20,38,.65);z-index:5;pointer-events:none} +.isp-split-handle{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:38px;height:38px;border-radius:50%;border:2px solid #fff;background:rgba(20,36,63,.86);color:#fff;font-size:11px;font-weight:700;display:grid;place-items:center;box-shadow:0 4px 14px rgba(10,20,38,.45);pointer-events:auto;cursor:ew-resize;transition:transform .12s ease,background .12s ease} +.isp-split-handle:hover,.isp-split-handle:focus-visible{transform:translate(-50%,-50%) scale(1.08);background:var(--blue)} +.isp-split-meta{display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;font-size:11px;color:var(--muted);padding:0 2px;font-variant-numeric:tabular-nums} +.isp-split-meta[hidden]{display:none} +.isp-side-stage[hidden]{display:none} +.isp-side-media{width:100%;aspect-ratio:16 / 9;background:#0f192b;overflow:hidden} +.isp-side-media .isp-compare-media{width:100%;height:100%;object-fit:contain} + +.isp-loupe{position:absolute;z-index:8;width:168px;border-radius:12px;overflow:hidden;border:2px solid #fff;background:#0f192b;box-shadow:0 10px 30px rgba(10,20,38,.5);pointer-events:none} +.isp-loupe[hidden]{display:none} +.isp-loupe canvas{display:block;width:168px;height:168px} +.isp-loupe-label{display:block;text-align:center;font-size:10px;font-weight:700;color:#e2ecff;background:rgba(15,25,43,.92);padding:3px 6px} + +.isp-scope-box{border:1px solid #c9d8ef;border-radius:12px;background:#f7faff;padding:10px 12px;display:grid;gap:8px} +.isp-scope-box[hidden]{display:none} +.isp-scope-head{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap} +.isp-scope-head strong{font-size:12px;color:var(--text)} +.isp-scope-legend{font-size:11px;color:var(--muted)} +.isp-scope-canvas{display:block;width:100%;height:92px;border-radius:8px;background:#0f192b} +.isp-scope-metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(128px,1fr));gap:6px} +.isp-scope-metric{background:#fff;border:1px solid var(--line);border-radius:8px;padding:6px 8px;display:grid;gap:2px} +.isp-scope-metric span{font-size:11px;color:var(--muted)} +.isp-scope-metric strong{font-size:12px;color:var(--text);font-variant-numeric:tabular-nums} + +.isp-diagnosis-callout{margin:6px 0 8px;padding:8px 11px;border-radius:9px;border:1px solid #f0d7a8;border-left:4px solid #c97a16;background:#fffaf0;color:#5c3d0e;font-size:12px;line-height:1.5;font-weight:600} +.isp-lab-panel{border:1px solid #cddbf0;border-radius:12px;background:#f6f9fe;padding:12px 14px;margin:10px 0 12px;display:grid;gap:10px} +.isp-lab-panel[hidden]{display:none} +.isp-lab-head{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap} +.isp-lab-actions{display:flex;align-items:center;gap:6px;flex-wrap:wrap} +.isp-lab-head .practice-presets{margin-top:0} +.isp-lab-head .button{padding:4px 10px;font-size:12px} +.isp-lab-layout{display:grid;grid-template-columns:minmax(0,1fr) 176px;gap:14px;align-items:start} +.isp-lab-sliders{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:9px 14px} +.isp-lab-slider{display:grid;gap:4px;font-size:12px;font-weight:650;color:#334a6b} +.isp-lab-slider-wide{grid-column:1 / -1} +.isp-lab-slider span{display:flex;justify-content:space-between;align-items:center;gap:6px} +.isp-lab-slider output{font-family:"IBM Plex Mono",monospace;font-size:12px;color:var(--blue);font-variant-numeric:tabular-nums} +.isp-lab-slider input[type="range"]{width:100%;accent-color:var(--blue);margin:0} +.isp-lab-tip{margin:0;padding:7px 10px;border-radius:8px;background:#edf4ff;border:1px solid #cfe0fa;color:#21457d;font-size:12px;line-height:1.45} +.isp-curve-mini{background:#fff;border:1px solid var(--line);border-radius:10px;padding:8px;display:grid;gap:6px;text-align:center} +.isp-curve-mini strong{font-size:12px;color:var(--text)} +.isp-curve-mini canvas{width:100%;height:auto;border-radius:6px;display:block} +.isp-curve-mini small{font-size:10px;color:var(--muted);line-height:1.35;white-space:nowrap} +.frame-dialog-actions{margin-top:0} +@media(max-width:660px){.isp-lab-layout{grid-template-columns:1fr}.isp-lab-sliders{grid-template-columns:1fr}} + +.ai-isp-proposal { display: grid; gap: 12px; margin-top: 12px; } +.ai-isp-pair { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); align-items: start; gap: 12px; } +.ai-isp-explanation { padding: 12px; border: 1px solid #c9dbf0; border-radius: 9px; background: #f0f6fd; overflow-wrap: anywhere; } +.ai-isp-explanation small { display: block; margin-top: 5px; } +.ai-isp-example { margin: 8px 0 0; padding: 8px 10px; background: #fff; border-radius: 6px; } +.station-command{display:block;white-space:pre-wrap;overflow-wrap:anywhere;font-size:.83rem;line-height:1.45} + +#calibration-demo{container-type:inline-size} +#calibration-demo [hidden]{display:none} +#calibration-demo-status{margin:12px 0} +#calibration-demo-result h3{margin:0 0 4px;font-size:17px;line-height:1.35} +#calibration-demo-result .action-copy{margin-bottom:0} +.flat-lesson{margin-top:14px} +.flat-lesson .action-head{flex-wrap:wrap;align-items:flex-start;margin-bottom:12px} +.flat-lesson .action-head .button{white-space:nowrap} +.flat-lesson-layout{display:grid;gap:10px} +.flat-compare{margin:0;min-width:0} +.flat-image{position:relative;aspect-ratio:3/2;overflow:hidden;border-radius:10px;border:1px solid #91a0b4; + background:#dbe1e9;cursor:ew-resize;touch-action:pan-y;user-select:none} +.flat-image img{position:absolute;inset:0;display:block;width:100%;height:100%;pointer-events:none} +#calibration-demo-after{clip-path:inset(0 0 0 var(--split,50%))} +.flat-image [class^="flat-label-"]{position:absolute;z-index:2;top:8px;padding:5px 7px;border-radius:5px; + background:#14243f;color:#fff;font-size:12px;font-weight:650;pointer-events:none} +.flat-label-before{left:10%}.flat-label-after{right:10%} +.flat-image.hide-before-label .flat-label-before,.flat-image.hide-after-label .flat-label-after{display:none} +.flat-divider{position:absolute;z-index:2;top:0;bottom:0;left:clamp(1px,var(--split,50%),calc(100% - 1px)); + width:2px;transform:translateX(-50%);background:#fff;box-shadow:0 0 0 1px #14243f60;pointer-events:none} +.flat-divider::after{content:'↔';position:absolute;top:50%;left:50%;display:grid;place-items:center; + width:30px;height:30px;transform:translate(-50%,-50%);border-radius:50%;border:2px solid #fff; + background:#14243f;color:#fff;font:700 18px/1 system-ui} +.flat-image:is(.hide-before-label,.hide-after-label) .flat-divider::after{top:60%} +.flat-regions{position:absolute;inset:0;pointer-events:none} +.flat-regions i{position:absolute;width:8.333%;height:12.5%;border:2px solid #fff;box-shadow:0 0 0 1px #14243f} +.flat-regions i:nth-child(1){left:0;top:0}.flat-regions i:nth-child(2){right:0;top:0} +.flat-regions i:nth-child(3){left:0;bottom:0}.flat-regions i:nth-child(4){right:0;bottom:0} +.flat-regions i:nth-child(5){left:45.833%;top:43.75%} +.flat-slider{display:grid;grid-template-columns:auto minmax(0,1fr);align-items:center;gap:10px; + min-height:42px;color:var(--muted);font-size:12px} +.flat-slider input{margin:0;width:100%;min-height:28px;accent-color:var(--blue);cursor:ew-resize} +.flat-readout{padding:12px;border-radius:10px;border:1px solid var(--line);background:#f6f9fd;min-width:0} +.flat-readout h4{margin:0 0 12px;font-size:13px} +.flat-readout p{margin:10px 0 0;color:var(--muted);font-size:12px} +.flat-measure{display:grid;gap:5px;margin-top:10px;color:#344967;font-size:13px;font-variant-numeric:tabular-nums} +.flat-measure span{display:block;height:7px;border-radius:8px;background:#dbe4f0} +.flat-measure i{display:block;width:var(--brightness,0%);height:100%;border-radius:inherit;background:#647d9e} +.flat-measure-after{color:var(--green)} +.flat-measure-after i{background:#188065} +.dark-lesson{display:grid;gap:12px;margin-top:18px;padding-top:16px;border-top:1px solid var(--line)} +.dark-lesson button{margin-top:10px} +.dark-activity{display:flex;align-items:start;gap:12px} +.dark-raw{flex:0 0 85px;margin:0} +.dark-raw figcaption{margin-top:4px;color:var(--muted);font-size:11px;text-align:center} +.dark-bayer{display:grid;aspect-ratio:1;grid-template:repeat(8,1fr)/repeat(8,1fr);gap:2px} +.dark-values{display:grid;flex:1;grid-template-columns:repeat(2,minmax(0,1fr));gap:5px;min-width:0} +.dark-value{padding:6px;border-radius:6px;font-size:11px;color:var(--text);white-space:nowrap} +.dark-value strong,.dark-value span{display:block} +.dark-value strong{font-variant-numeric:tabular-nums} +.dark-value span{margin-bottom:2px} +.bayer-r{background:#f3c5c5}.bayer-gr{background:#bee4c8}.bayer-gb{background:#cae6c2}.bayer-b{background:#c5d7f5} +.dark-value.bayer-r{background:#f9e9e9}.dark-value.bayer-gr{background:#e5f3e8} +.dark-value.bayer-gb{background:#ecf4e5}.dark-value.bayer-b{background:#e9f0fc} +#calibration-demo-calculated:empty{display:none} +.cal-demo-actions{margin:16px 0 8px} +.ccm-lesson,.awb-lesson{display:grid;gap:12px;margin-top:18px;padding-top:16px;border-top:1px solid var(--line)} +.ccm-lesson-layout,.awb-lesson-layout{display:grid;gap:12px;align-items:start} +.ccm-card-wrap{min-width:0} +.ccm-grid{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:5px;padding:8px;border-radius:10px;background:#1d2430;border:1px solid #2d3848} +.ccm-patch{position:relative;aspect-ratio:1;border-radius:5px;overflow:hidden;border:1px solid rgba(255,255,255,.16);background:var(--after)} +.ccm-patch::before{content:'';position:absolute;inset:0;background:var(--before);clip-path:polygon(0 0,52% 0,0 52%);opacity:.96} +.ccm-patch::after{content:'';position:absolute;left:0;top:0;width:54%;height:54%;border-bottom:1px solid rgba(255,255,255,.45);transform:rotate(-45deg);transform-origin:top right;pointer-events:none} +.ccm-readout{padding:11px;border-radius:10px;border:1px solid var(--line);background:#f6f9fd;min-width:0} +.ccm-readout h4{margin:0 0 8px;font-size:13px} +.awb-swatches{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} +.awb-swatch-box{display:grid;gap:6px;padding:8px;border:1px solid var(--line);border-radius:9px;background:#fff;text-align:center} +.awb-swatch{display:block;height:52px;border-radius:6px;border:1px solid rgba(20,36,63,.16);transition:background-color .18s ease} +.awb-swatch-box small{color:var(--muted);font-size:11px;line-height:1.35} +.awb-gains-wrap{padding:10px 12px;border-radius:9px;border:1px solid var(--line);background:#f6f9fd;min-width:0} +@container (min-width:540px) { + .flat-lesson-layout{grid-template-columns:minmax(0,1.7fr) minmax(155px,1fr);align-items:start;gap:12px} + .dark-lesson{grid-template-columns:minmax(0,1fr) minmax(215px,1fr)} + .ccm-lesson-layout{grid-template-columns:minmax(0,1.25fr) minmax(210px,1fr)} + .awb-lesson-layout{grid-template-columns:minmax(0,1fr) minmax(220px,1fr)} + #calibration-demo-calculated{grid-column:1/-1} +} + +#calibration-workbench{container-type:inline-size} +#calibration-workbench [hidden]{display:none} +#calibration-workbench :is(h3,h4){margin:0} +#calibration-workbench h3{font-size:15px} +#calibration-workbench h4{font-size:14px} +#calibration-workbench code{overflow-wrap:anywhere;word-break:break-word} +#calibration-workbench .button-row{margin-top:8px;gap:6px} +#calibration-workbench .action-copy{margin:0} +.calibration-bar{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:12px 0;min-height:34px} +.calibration-bar .button{white-space:nowrap} +#calibration-status[data-tone=error],.calibration-task-error{color:#972e26} +#calibration-status[data-tone=success]{color:var(--green)} +.calibration-shell{display:grid;gap:12px} +.calibration-overview-bar{display:grid;gap:8px;padding:10px 12px;border:1px solid var(--line);border-radius:10px;background:#f7faff} +.calibration-engines{display:flex;flex-wrap:wrap;align-items:center;gap:6px} +.calibration-engine-pill{display:inline-flex;align-items:center;gap:5px;padding:3px 8px;border-radius:999px;font-size:11px;font-weight:600;border:1px solid var(--line);background:#fff;color:var(--muted)} +.calibration-engine-pill.ok{border-color:#9dd6c4;background:#ebf9f4;color:#11644e} +.calibration-engine-pill i{width:6px;height:6px;border-radius:50%;background:currentColor} +.calibration-pipeline{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px} +@container (min-width:520px){.calibration-pipeline{grid-template-columns:repeat(4,minmax(0,1fr))}} +.calibration-stage-btn{display:grid;gap:2px;padding:7px 8px;border:1px solid var(--line);border-radius:8px;background:#fff;text-align:left;cursor:pointer;font:inherit;color:var(--text);transition:border-color .15s,background .15s} +.calibration-stage-btn:hover{border-color:#8faee8;background:#f2f6ff} +.calibration-stage-btn.is-active{border-color:var(--blue);background:#eaf1ff;box-shadow:inset 0 0 0 1px var(--blue)} +.calibration-stage-btn strong{font-size:12px;line-height:1.3} +.calibration-stage-btn span{font-size:11px;color:var(--muted)} +.calibration-stage-btn.is-done span{color:var(--green);font-weight:600} +.calibration-create-head{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:8px} +.calibration-engine-field{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--muted)} +.calibration-engine-field select{padding:4px 8px;border:1px solid var(--line);border-radius:7px;background:#fff;font-size:12px;color:var(--text)} +.calibration-stage-panel{display:grid;gap:10px} +.calibration-stage-panel .field{margin-block:6px} +.calibration-form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} +.calibration-bl-head{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:12px;font-weight:600;color:var(--text);margin-top:4px} +.calibration-bl-head .button{padding:3px 8px;font-size:11px;min-height:auto} +.calibration-bl-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px} +.calibration-bl-grid .field{margin-block:0;font-size:11px} +.calibration-bl-grid input{padding:5px 6px;font-size:12px} +.calibration-inline-form{padding:8px 10px;border:1px dashed var(--line);border-radius:8px;background:#fafcff} +.calibration-awb-groups{display:grid;gap:8px} +.calibration-awb-group{padding:9px;border:1px solid var(--line);border-radius:9px;background:#f9fbff;display:grid;gap:6px} +.calibration-awb-group-head{display:flex;align-items:center;justify-content:space-between;gap:6px;font-size:12px;font-weight:650} +.calibration-awb-group-head .button{padding:2px 7px;font-size:11px;min-height:auto} +.calibration-roi-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:5px} +.calibration-roi-grid .field{margin-block:0;font-size:11px} +.calibration-roi-grid input{padding:4px 5px;font-size:12px} +.calibration-layout{display:grid;gap:14px} +.calibration-column{display:grid;align-content:start;gap:10px;min-width:0} +.calibration-column + .calibration-column{border-top:1px solid var(--line);padding-top:14px} +@container (min-width:600px){ + .calibration-layout{grid-template-columns:minmax(0,1.12fr) minmax(0,1fr);gap:18px} + .calibration-column + .calibration-column{border-top:0;border-left:1px solid var(--line);padding:0 0 0 18px} +} +.calibration-empty{background:#f4f7fb;border:1px solid var(--line);border-radius:9px;padding:12px} +#calibration-workbench .calibration-small,.calibration-task-error{font-size:12px;line-height:1.5;margin:5px 0 0} +.calibration-small{color:var(--muted);overflow-wrap:anywhere} +#calibration-dark-form .field{margin-block:12px} +.calibration-samples{display:grid;gap:6px;margin-top:8px;max-height:270px;overflow:auto;padding:2px 4px 2px 2px;scrollbar-gutter:stable} +.calibration-sample,.calibration-check{display:flex;align-items:flex-start;gap:8px;min-width:0;font-size:13px;line-height:1.5;overflow-wrap:anywhere} +.calibration-sample{border:1px solid var(--line);border-radius:8px;background:#f8fbff;padding:8px;cursor:pointer} +.calibration-sample:has(input:checked){border-color:#91afe8;background:#edf3ff} +.calibration-sample:has(input:disabled:not(:checked)){color:var(--muted);background:#f5f7fa} +.calibration-sample:focus-within{outline:2px solid #5f8bed;outline-offset:-2px} +.calibration-sample-info{flex:1;min-width:0} +.calibration-sample-name{display:flex;justify-content:space-between;align-items:baseline;gap:6px} +.calibration-sample-name code{flex:none;color:var(--muted);font-size:10px} +.calibration-sample small{display:block;color:var(--muted);font-size:11px} +.calibration-check{margin-bottom:12px} +.calibration-sample input,.calibration-check input{flex:none;margin:3px 0 0;accent-color:var(--blue)} +.calibration-extra{margin:0;padding-top:8px;border-top:1px solid var(--line)} +.calibration-extra>summary{overflow-wrap:anywhere} +.calibration-extra[open]>.action-copy,.calibration-extra form,.calibration-extra form .button{margin-top:8px} +#calibration-tasks{display:grid;gap:7px;max-height:370px;overflow:auto;padding:2px 3px 2px 2px} +.calibration-task{border:1px solid var(--line);border-radius:9px;padding:10px;min-width:0} +.calibration-task.is-selected{border-color:#91afe8;background:#f6f9ff} +.calibration-task-head{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:5px} +#calibration-outcome:not(:empty){padding:12px;border:1px solid #cbdcf4;border-radius:10px;background:#f7faff;min-width:0} +#calibration-outcome:empty{display:none} +#calibration-outcome h4{font-size:15px;margin-bottom:8px} +.calibration-channels{display:grid;gap:7px;margin:0} +.calibration-channel-row{display:grid;grid-template-columns:24px minmax(20px,1fr) auto;align-items:center;gap:8px;font-size:13px} +.calibration-channel-row dt{font-weight:650} +.calibration-channel-row dd{margin:0;min-width:56px;text-align:right} +.calibration-channel-row small{display:block;color:var(--muted);font-size:10px} +.calibration-channel-meter,.calibration-channel-meter span{display:block;height:7px;border-radius:4px} +.calibration-channel-meter{background:#e7edf8} +.calibration-channel-meter span{background:#4674bf} +.calibration-channel-meter [data-channel=R]{background:#b95759} +.calibration-channel-meter [data-channel=Gr],.calibration-channel-meter [data-channel=Gb]{background:#2c826e} +.calibration-numeric,.calibration-table,.calibration-gradient-label{font-variant-numeric:tabular-nums} +.calibration-heatmaps{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:7px} +.calibration-heatmap{margin:0;border:1px solid var(--line);padding:5px;border-radius:8px;background:#fff;min-width:0} +.calibration-heatmap figcaption{display:flex;flex-wrap:wrap;justify-content:space-between;gap:2px;font-size:11px;padding:1px 2px 5px} +.calibration-heatmap canvas{display:block;width:100%;height:auto;max-height:84px;object-fit:contain;image-rendering:pixelated;background:#edf3fc;border-radius:3px} +.calibration-gradient-label{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--muted);margin-top:7px} +.calibration-gradient-label span:nth-child(2){height:6px;flex:1;border-radius:5px;background:linear-gradient(90deg,#1c3e74,#fcae37)} +.calibration-table{width:100%;border-collapse:collapse;table-layout:fixed;font-size:12px;text-align:right} +.calibration-table :is(th,td){padding:6px 3px;border-bottom:1px solid var(--line);overflow-wrap:anywhere} +.calibration-table :is(th,td):first-child{width:34%;text-align:left} +.calibration-table thead{color:var(--muted)} +.calibration-matrix tbody td{background:#edf3fc} +.calibration-matrix tbody tr:nth-child(1) td:nth-child(2),.calibration-matrix tbody tr:nth-child(2) td:nth-child(3),.calibration-matrix tbody tr:nth-child(3) td:nth-child(4){background:#e2ebfb;font-weight:650} +.calibration-statistics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px;margin:8px 0} +.calibration-statistics div{background:#e9f0fb;border-radius:7px;padding:7px;font-size:11px} +.calibration-statistics dd{margin:3px 0 0;font-size:14px;font-weight:650;font-variant-numeric:tabular-nums} + +/* Clean 3-tier responsive breakpoints */ +@media(min-width:1000px){ + .grid>aside{position:sticky;top:12px;max-height:calc(100dvh - 24px);overflow:auto} +} +@media(max-width:999px){ + .grid{grid-template-columns:minmax(0,1fr)} + .shell{padding-top:16px} + .hero{flex-direction:column;align-items:stretch;gap:10px;margin-bottom:14px} + .hero .lede{display:none} + .clock{justify-content:space-between} + .box{padding:16px} + .timeline{padding:10px} + .timeline summary::before{content:'▸';margin-right:4px;color:#3d5b8e} + .timeline[open] summary::before{content:'▾'} + .timeline ol{grid-template-columns:repeat(2,minmax(0,1fr))} +} +@media(max-width:720px){ + .capture-cards,.preflight-checks,.routes,.milestones,.frame-controls,.ai-isp-pair{grid-template-columns:1fr} +} +@media(max-width:639px){ + .brand span:not(.brand-mark){display:none} + .top-actions{gap:5px} + .station-health{padding:8px 10px;gap:8px} + .health-pill{font-size:11px;padding:4px 8px} + .entry-choice{align-items:flex-start;flex-direction:column} + .parallel-actions{justify-content:flex-start} + #practice-content .comparison-images{grid-template-columns:1fr} + .board-comparison-images,.board-coordinates{gap:8px;grid-template-columns:repeat(2,minmax(0,1fr))} + .board-comparison,.isp-round{padding:10px} + .isp-demo-pair figcaption,.isp-pair figcaption{padding:6px;overflow-wrap:anywhere} + .delivery-checklist li{align-items:flex-start;flex-direction:column;gap:4px} +} diff --git a/plugins/rdk-camera-workshop/web/zip.mjs b/plugins/rdk-camera-workshop/web/zip.mjs index cbe5414..d42fce6 100644 --- a/plugins/rdk-camera-workshop/web/zip.mjs +++ b/plugins/rdk-camera-workshop/web/zip.mjs @@ -1,14 +1,21 @@ // Stored ZIP records and CRC checksums. Input paths are chosen by the workbench. +const crcTable=(()=>{ + const table=new Uint32Array(256); + for (let i=0;i<256;i++) { + let c=i; + for (let bit=0;bit<8;bit++) c=(c>>>1)^((c&1)?0xedb88320:0); + table[i]=c>>>0; + } + return table; +})(); + export function storedZip(entries) { const encoder=new TextEncoder(); const chunks=[], directory=[]; let offset=0, directorySize=0; function crc32(bytes) { let crc=0xffffffff; - for (const value of bytes) { - crc^=value; - for(let bit=0;bit<8;bit++) crc=(crc>>>1)^((crc&1)?0xedb88320:0); - } + for (let i=0;i>>8); return (crc^0xffffffff)>>>0; } for (const [path,bytes] of entries) { diff --git a/tests/camera-studio/classroom.mjs b/tests/camera-studio/classroom.mjs index 665dc73..18a9156 100644 --- a/tests/camera-studio/classroom.mjs +++ b/tests/camera-studio/classroom.mjs @@ -9,21 +9,32 @@ export async function classroom(url) { const page=await browser.newPage(); const errors=[];page.on('pageerror',e=>errors.push(e.message)); await page.goto(url); - await page.locator('#entry-continue').waitFor(); - assert.match(await page.locator('#entry-title').textContent(),/已有课堂工位/); - await page.locator('#entry-practice').click(); - await page.waitForFunction(()=>document.querySelector('#entry-title')?.textContent==='独立练习'); - await page.locator('#entry-practice').click(); - const options=page.locator('#isp-demo-tabs button'); - assert.equal(await options.count(),5); - for(const item of await options.all()){ + // Since 1.5.13 a retained station opens directly and the practice lab is entered from the top bar. + await page.locator('#top-practice').waitFor(); + assert.equal(await page.locator('#entry-choice').isHidden(),true); + assert.ok((await page.locator('#step-title').textContent()).trim()); + await page.locator('#top-practice').click(); + await page.waitForFunction(()=>document.querySelector('#entry-title')?.textContent==='ISP 图像调试实验室'); + const scenes=page.locator('#practice-scenes button'); + assert.equal(await scenes.count(),7); + for(const item of await scenes.all()){ await item.click(); assert.equal(await item.getAttribute('aria-pressed'),'true'); } + await page.waitForTimeout(1500); + // The linear ISP lab must paint its before/after images, not only expose controls. + const painted=await page.evaluate(()=>[...document.querySelectorAll('canvas')].filter(c=>c.getBoundingClientRect().width>0).map(c=>{ + const off=document.createElement('canvas');off.width=32;off.height=32;const g=off.getContext('2d');g.drawImage(c,0,0,32,32);const d=g.getImageData(0,0,32,32).data;const set=new Set();for(let i=0;i>3)+','+(d[i+1]>>3)+','+(d[i+2]>>3));return set.size;})); + assert.ok(painted.filter(colors=>colors>=32).length>=2,`expected painted lab images, got ${JSON.stringify(painted)}`); + assert.equal(await page.locator('#practice-lab-controls input[type=range]').count(),10); + for(const mode of ['practice-mode-gamma','practice-mode-lab']){ + await page.locator('#'+mode).click(); + assert.equal(await page.locator('#'+mode).getAttribute('aria-pressed'),'true'); + } await page.locator('#entry-continue').click(); - await page.waitForURL(url);await page.locator('#entry-continue').click(); + await page.waitForFunction(()=>document.querySelector('#entry-choice')?.hidden===true); assert.ok((await page.locator('#step-title').textContent()).trim()); assert.deepEqual(errors,[]); - console.log('Verified resume, independent practice, five ISP samples and return to original station'); + console.log('Verified direct station resume, ISP lab with seven scenes and painted before/after images, both practice modes and return to original station'); }finally{await browser.close();} } diff --git a/tests/camera-studio/smoke.mjs b/tests/camera-studio/smoke.mjs index bdee3be..f67152e 100644 --- a/tests/camera-studio/smoke.mjs +++ b/tests/camera-studio/smoke.mjs @@ -64,7 +64,8 @@ assert.ok(available.tools.some(t=>t.name==='vision_connection_status')); assert.equal(value(status).code,'camera_bridge_unconfigured'); const name='rdk-vision-workshop'; const [catalog,plan]=rpc(name,[['tools/list',{}],call('vision_course_plan')]); -assert.equal(catalog.tools.length,10);assert.equal(value(plan).totalMinutes,180); +// 1.5.13 exposes sixteen course tools; the packaged declaration must list exactly those tools. +assert.equal(catalog.tools.length,16);assert.deepEqual(catalog.tools.map(t=>t.name).sort(),Object.keys(map[name].permissions.tools).sort());assert.equal(value(plan).totalMinutes,180); // A retained 1.5.6 station is copied once. Its original ledger must remain independent. const worker=realpathSync(path.join(installed,'mcp/workbench-session.mjs')); const scope=createHash('sha256').update(worker+'|persistent-workbench').digest('hex').slice(0,32);