diff --git a/plugins/rdk-camera-workshop/.mcp.json b/plugins/rdk-camera-workshop/.mcp.json index a1f0daa..aaf89e3 100644 --- a/plugins/rdk-camera-workshop/.mcp.json +++ b/plugins/rdk-camera-workshop/.mcp.json @@ -3,7 +3,8 @@ "rdk-camera-workshop": { "transport": "stdio", "command": "node", - "args": ["mcp/bridge.mjs"] + "args": ["mcp/bridge.mjs"], + "env": { "RDK_CAMERA_WORKSHOP_ONBOARDING": "1" } } } } diff --git a/plugins/rdk-vision-workshop/device/x5-station-bridge.py b/plugins/rdk-vision-workshop/device/x5-station-bridge.py index d55b37e..8d27e67 100644 --- a/plugins/rdk-vision-workshop/device/x5-station-bridge.py +++ b/plugins/rdk-vision-workshop/device/x5-station-bridge.py @@ -37,8 +37,18 @@ def client(options): host = config['sshHost'] if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,119}', host): raise ValueError('invalid_station_ssh_alias') - command = ['python3', config['boardBridge'], 'board', '--config', - config['boardConfig'], '--run-id', run_id, '--model-hash', model] + use_sudo = config.get('useSudo', False) + if not isinstance(use_sudo, bool): + raise ValueError('invalid_station_sudo_flag') + ssh_port = config.get('sshPort') + if ssh_port is not None and (type(ssh_port) is not int or not 1 <= ssh_port <= 65535): + raise ValueError('invalid_station_ssh_port') + board_python = config.get('boardPython', '/usr/bin/python3' if use_sudo else 'python3') + if not isinstance(board_python, str) or not re.fullmatch(r'(?:/[A-Za-z0-9._-]+)+|python3(?:\.[0-9]+)?', board_python): + raise ValueError('invalid_station_board_python') + command = (['sudo', '-n'] if use_sudo else []) + [ + board_python, config['boardBridge'], 'board', '--config', + config['boardConfig'], '--run-id', run_id, '--model-hash', model] approved = os.environ.get('RDK_COURSE_APPROVED_ISP') if os.environ.get('RDK_COURSE_COMPARE_ISP') == '1': if not approved: @@ -46,7 +56,8 @@ def client(options): command.append('--comparison') with Path(approved).open('rb') if approved else nullcontext(subprocess.DEVNULL) as document: ssh_config = ['-F', config['sshConfig']] if config.get('sshConfig') else [] - ssh = [config.get('sshExecutable', 'ssh'), *ssh_config, '-T', '-o', 'BatchMode=yes', '-o', + ssh_port_args = ['-p', str(ssh_port)] if ssh_port is not None else [] + ssh = [config.get('sshExecutable', 'ssh'), *ssh_config, *ssh_port_args, '-T', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes', '-o', 'ConnectTimeout=6', host, shlex.join(command)] with subprocess.Popen(ssh, stdin=document, stdout=subprocess.PIPE) as process: try: diff --git a/plugins/rdk-vision-workshop/mcp/camera-source.mjs b/plugins/rdk-vision-workshop/mcp/camera-source.mjs index 998fd86..56c4086 100644 --- a/plugins/rdk-vision-workshop/mcp/camera-source.mjs +++ b/plugins/rdk-vision-workshop/mcp/camera-source.mjs @@ -431,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=>{ @@ -440,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|| @@ -454,7 +466,7 @@ export function createCameraSource(configFile=process.env.RDK_CAMERA_WORKSHOP_CO 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=typeof candidate.model==='string'?candidate.model.replace(/[\u0000-\u001f\u007f]/gu,' ').trim().slice(0,100):undefined; + 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, diff --git a/plugins/rdk-vision-workshop/mcp/isp-example.mjs b/plugins/rdk-vision-workshop/mcp/isp-example.mjs index eee0f86..b484b0e 100644 --- a/plugins/rdk-vision-workshop/mcp/isp-example.mjs +++ b/plugins/rdk-vision-workshop/mcp/isp-example.mjs @@ -221,14 +221,33 @@ export function findLatestChatAttachment( 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) continue; - const val = obj[key]; + 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 (typeof val !== 'number' || !Number.isFinite(val) || val < lo || val > hi) { + 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; } } @@ -236,15 +255,24 @@ function validateDeltaMap(delta) { if (!delta || typeof delta !== 'object' || Array.isArray(delta)) { throw withHint('invalid_arguments', 'delta 必须为对象,例如 { wbShift: -10, sharpness: -0.2 }。'); } - for (const [key, val] of Object.entries(delta)) { + 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 (typeof val !== 'number' || !Number.isFinite(val) || Math.abs(val) > span) { + 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; } } @@ -359,9 +387,14 @@ export function ispExample(args = {}, context = {}) { throw withHint('invalid_arguments', 'scene、imagePath、useWorkbenchImage 与 useLatestAttachment 请只传其中一个。'); } - // Validate explicit parameters & delta early - validateParamMap(args); - if (args.delta !== undefined) validateDeltaMap(args.delta); + // 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); @@ -520,21 +553,24 @@ export function ispExample(args = {}, context = {}) { ((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 || args.delta !== undefined || (!preset && !hasExplicitNumericParams && Boolean(goal))), + (action !== 'auto' || (args.inheritCurrent === true && hasExplicitDelta)) && + (args.inheritCurrent === true || hasExplicitDelta || (!preset && !hasExplicitNumericParams && Boolean(goal))), ); const wantAutoSolve = - action === 'auto' || - args.mode === 'auto' || - preset === 'auto' || - (!preset && !hasExplicitNumericParams && !args.delta && !shouldInheritParams && Boolean(goal)); + !shouldInheritParams && ( + action === 'auto' || + args.mode === 'auto' || + preset === 'auto' || + (!preset && !hasExplicitNumericParams && !hasExplicitDelta && Boolean(goal)) + ); let params; let afterRgb; diff --git a/plugins/rdk-vision-workshop/mcp/release-regressions.test.mjs b/plugins/rdk-vision-workshop/mcp/release-regressions.test.mjs index 5e28a59..881d696 100644 --- a/plugins/rdk-vision-workshop/mcp/release-regressions.test.mjs +++ b/plugins/rdk-vision-workshop/mcp/release-regressions.test.mjs @@ -703,7 +703,17 @@ test('linkage polish: exposureTrial avoids probe, restoreOriginalIsp handles arc assert.equal(tokenCount,2); }); -test('linkage polish: calibration AWB handoff/ROI/spread, server hints, symlink rejection, SKILL tool_search and timeout',async t=>{ +test('continuous ISP edits apply string deltas to the current settings despite a conflicting auto action',()=>{ + const args={scene:'lowlight',action:'auto',inheritCurrent:true,delta:{wbShift:'-12'}}; + const workbenchPractice={state:{scene:'lowlight',params:{wbShift:5,brightness:16}}}; + const result=ispExample(args,{workbenchPractice}); + assert.equal(result.status.parameters.wbShift,-7); + assert.equal(result.status.parameters.brightness,16); + assert.equal(args.delta.wbShift,'-12'); + assert.throws(()=>ispExample({...args,delta:{wbShift:'NaN'}},{workbenchPractice}),/invalid_arguments/); +}); + +test('linkage polish: calibration AWB handoff/ROI/spread, server hints, symlink rejection, SKILL MCP discovery and timeout',async t=>{ const expId=randomUUID(),taskId=randomUUID(); const rawIds=[randomUUID(),randomUUID(),randomUUID(),randomUUID(),randomUUID(),randomUUID()]; @@ -750,10 +760,11 @@ test('linkage polish: calibration AWB handoff/ROI/spread, server hints, symlink assert.throws(()=>ispExample({imagePath:linkIn}),/invalid_arguments/); assert.throws(()=>ispExample({scene:'lowlight',preset:'lowlight_rescue',outputPath:linkOut}),/invalid_arguments/); - // 6. SKILL.md uses tool_search (never discover_configured_tools) and .mcp.json has 120s timeout. + // 6. SKILL.md names the configured vision MCP search tools and .mcp.json has 120s timeout. const skillText=await readFile(new URL('../skills/rdk-vision-workshop/SKILL.md',import.meta.url),'utf8'); - assert.match(skillText,/tool_search/); - assert.doesNotMatch(skillText,/discover_configured_tools/); + assert.match(skillText,/`mcp__rdk-vision-workshop__search`/); + assert.match(skillText,/`mcp__rdk-camera-workshop__search`/); + assert.doesNotMatch(skillText,/先调用一次 `tool_search`/); const mcpCfg=JSON.parse(await readFile(new URL('../.mcp.json',import.meta.url),'utf8')); assert.ok(mcpCfg.mcpServers['rdk-vision-workshop'].requestTimeoutMs>=120000); }); diff --git a/plugins/rdk-vision-workshop/mcp/workbench.mjs b/plugins/rdk-vision-workshop/mcp/workbench.mjs index 862d91e..5eb260f 100644 --- a/plugins/rdk-vision-workshop/mcp/workbench.mjs +++ b/plugins/rdk-vision-workshop/mcp/workbench.mjs @@ -119,15 +119,35 @@ function readDeveloperMachineProfile(file=process.env.RDK_VISION_COURSE_DEVMACHI } catch {return {status:'invalid'};} } -export async function startWorkbench(input={}, port=0, cameraSource=createCameraSource(), { +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; } @@ -169,7 +189,8 @@ export async function startWorkbench(input={}, port=0, cameraSource=createCamera 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 boardLauncher=createBoardLauncher(undefined,{onChange:()=>emitEvent('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; diff --git a/plugins/rdk-vision-workshop/skills/rdk-vision-workshop/SKILL.md b/plugins/rdk-vision-workshop/skills/rdk-vision-workshop/SKILL.md index 4a9f216..7aa84aa 100644 --- a/plugins/rdk-vision-workshop/skills/rdk-vision-workshop/SKILL.md +++ b/plugins/rdk-vision-workshop/skills/rdk-vision-workshop/SKILL.md @@ -14,7 +14,7 @@ enabled: true 本课程依据 [飞书方案](https://horizonrobotics.feishu.cn/docx/UdhhdVXYXoPLgfxmZ32cJBSAnRb)。课程执行方法见 [操作稿](references/course-runbook.md),实机交接见 [检测交接](references/tuning-handoff.md)。 -0. **工具发现(Studio 延迟挂载)**:调用任何 `vision_course_*` 或 `vision_*` 工具前,若当前轮次工具列表中尚未出现目标工具,先调用一次 `tool_search` 检索并加载 `rdk-vision-workshop`(涉及真机底层控制、AI 自动调试或标定上板时一并加载 `rdk-camera-workshop`),避免直调未挂载工具造成空跑。 +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` 即可触发宿主挂载。 ## 双插件意图分流与防误调矩阵 @@ -25,7 +25,7 @@ enabled: true | 课堂拍照、三张基线图(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_*` | 需先用 `tool_search` 加载 `rdk-camera-workshop`;写设备操作按权限确认 | +| 底层 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 或板端工具执行当前一步。实际工具缺失时指出哪项配置或操作需要用户或助教处理。不要把课程工具的规划回执当成执行回执。 diff --git a/plugins/vision-workshop-packages/manifest.json b/plugins/vision-workshop-packages/manifest.json index 76460a8..040a118 100644 --- a/plugins/vision-workshop-packages/manifest.json +++ b/plugins/vision-workshop-packages/manifest.json @@ -15,15 +15,15 @@ { "kind": "studio", "name": "RDK Camera AI", - "version": "1.3.0", - "bytes": 163823, - "sha256": "1ca77a4d9632ed115a0826808286ad73a39b1ed08a84ce401dafcf67b6e9a880", + "version": "1.5.13", + "bytes": 1800525, + "sha256": "50e0cee7ede51d180d008fbda5ca201857369a349be9f5487dae98a4b37c28bf", "requirements": [ "Node.js 22+", "RDK Studio 1.4+ 或兼容 MCP 宿主", - "d-obs 相机服务访问权限(用户自备凭据文件)", - "已登记的开发板与相机适配器(服务端配置)" + "已配置 d-obs 相机连接时支持一键点亮建基线与真机前后对照看图;免接相机即可运行 10 参数线性域 ISP、2-Pass Auto-ISP、Bayer RAW 与 7 场景离线标定", + "仅训练路径需要 RoboGO 账号与匹配的训练资源" ] } ] -} \ No newline at end of file +} diff --git a/plugins/vision-workshop-packages/studio.zip b/plugins/vision-workshop-packages/studio.zip index b202283..160d572 100644 Binary files a/plugins/vision-workshop-packages/studio.zip and b/plugins/vision-workshop-packages/studio.zip differ diff --git a/server/monitoring/vision-workshop-routes.ts b/server/monitoring/vision-workshop-routes.ts index 7816935..ea9bbfc 100644 --- a/server/monitoring/vision-workshop-routes.ts +++ b/server/monitoring/vision-workshop-routes.ts @@ -5,6 +5,7 @@ import path from 'node:path'; import { z, ZodError } from 'zod'; import { requireVisionWorkshopAccess, requireVisionWorkshopUploadAccess, visionWorkshopOwner, visionWorkshopDevices } from './vision-workshop-access.js'; import { requireOpsMutationGuard } from './observability-route-kit.js'; +import { gammaCanonicalStrength } from './vision-workshop-gamma-transform.js'; import { VisionWorkshopService, VisionWorkshopError, buildVisionHandbook, imageDimensions, visionWorkshopLimitsFromEnv, type VisionExperiment, type VisionJsonObject, type VisionRawMetadata, type VisionRawSample, type VisionProcessedImage, type VisionCameraFrame, type VisionDeviceCapability, type VisionCapabilities } from './vision-workshop-service.js'; import { generateVisionIspCandidate, visionModelEnabled, type VisionModelInput, type VisionIspCandidate } from './vision-workshop-model.js'; import { analyzeVisionRaw } from './vision-workshop-raw.js'; @@ -67,6 +68,11 @@ const classroomSharpnessInput = z.object({ baselineId: id, baselineHash: z.string().regex(/^[a-f0-9]{64}$/), frameId: id, path: z.enum(classroomSharpnessPaths), value: z.number().finite(), }).strict(); +const classroomGammaPath = '/modules/gamma/auto_attr.curve'; +const classroomGammaInput = z.object({ + baselineId: id, baselineHash: z.string().regex(/^[a-f0-9]{64}$/), frameId: id, + goal: goalSchema.optional(), strength: z.number().finite().positive().max(0.99).optional(), +}).strict(); const candidateInput = z.object({ goal: goalSchema.optional(), frameIds: z.array(id).min(1).max(16).refine(values => new Set(values).size === values.length).optional(), targetAnalysisFrameId: id.optional() }).strict(); const resultInput = z.object({ sampleId: id, candidateId: id.optional(), filename: z.string().max(200).optional(), mimeType: z.enum(['image/png', 'image/jpeg']).optional() }).strict(); const rawMetadataInput = z.object({ scene: z.string().trim().min(1).max(120), width: z.number().int(), height: z.number().int(), bitDepth: z.union([z.literal(8), z.literal(10), z.literal(12), z.literal(14), z.literal(16)]), bayer: z.enum(['RGGB', 'BGGR', 'GRBG', 'GBRG']), packing: z.enum(['unpacked16le', 'mipi-raw10', 'mipi-raw12']), stride: z.number().int(), blackLevel: z.number().int(), whiteLevel: z.number().int(), exposureUs: z.number().finite().optional(), gain: z.number().finite().optional() }).strict(); @@ -278,7 +284,7 @@ export function registerVisionWorkshopRoutes(router: Router, options: Options = }); get('/capabilities', async (req, res) => { const experimentCreationCapacity = await service().experimentCreationCapacity(visionWorkshopOwner(req)).catch(() => undefined); - res.json({ ok: true, contract: VISION_WORKSHOP_CONTRACT, ...runtimeCapabilities(req), experimentCreationCapacity, classroomSharpnessCandidate: true, mcpEndpoint: VISION_WORKSHOP_MCP, + res.json({ ok: true, contract: VISION_WORKSHOP_CONTRACT, ...runtimeCapabilities(req), experimentCreationCapacity, classroomSharpnessCandidate: true, ...(options.localOperatorLogin ? { classroomGammaCandidate: true } : {}), mcpEndpoint: VISION_WORKSHOP_MCP, atomicOperations: [...Object.keys(VISION_WORKSHOP_OPERATIONS), ...Object.keys(VISION_CALIBRATION_OPERATIONS)], knowledge: { status: 'available', contract: VISION_KNOWLEDGE_CONTRACT, searchPath: VISION_WORKSHOP_API + '/knowledge' }, binaryUpload: { rawHeader: 'x-vision-sample', imageHeader: 'x-vision-result', type: 'application/octet-stream', metadataEncoding: 'encodeURIComponent(JSON.stringify(metadata))' } }); }); get('/experiment-capacity', async (req, res) => { @@ -417,6 +423,43 @@ export function registerVisionWorkshopRoutes(router: Router, options: Options = }); res.status(201).json({ ok: true, candidate }); }); + if (options.localOperatorLogin) { + post('/experiments/:id/classroom-gamma-candidate', async (req, res) => { + const input = classroomGammaInput.parse(req.body); + const owner = visionWorkshopOwner(req); + const experiment = await service().getExperiment(owner, String(req.params.id)); + const baseline = experiment.baseline; + if (!experiment.targetId || !baseline || baseline.id !== input.baselineId || baseline.hash !== input.baselineHash) + throw new VisionWorkshopError('vision_baseline_changed', 'Use the current verified camera baseline', 409); + const gammaRule = baseline.rules.find(rule => rule.path === classroomGammaPath && rule.transform?.kind === 'x5-common-auto-gamma-band-v1'); + if (baseline.tuning.kind !== 'x5-hbn-isp-v2' || !gammaRule || !gammaRule.step || gammaRule.step <= 0) + throw new VisionWorkshopError('vision_camera_control_unavailable', 'Bounded classroom Gamma transform is not available in this baseline', 409); + const frame = experiment.cameraFrames.find(item => item.id === input.frameId); + if (!frame || frame.source !== 'runner' || frame.adapterId !== experiment.targetId || frame.tuningHash !== baseline.hash || frame.mimeType !== 'image/png') + throw new VisionWorkshopError('vision_matching_frame_required', 'Use a current PNG camera frame of this baseline', 409); + const stored = await service().readCameraFrame(owner, experiment.id, frame.id); + const statistics = analyzeVisionProcessedPng(stored.data); + const step = gammaRule.step; + const minStrength = step; + const maxStrength = gammaRule.max; + const goalText = input.goal ?? experiment.goal ?? ''; + let desired = input.strength; + if (desired === undefined) { + let ratio = 0.50; + if (statistics.meanLuma < 95 || statistics.nearBlackRatio > 0.15) ratio = 0.35; + else if (statistics.meanLuma > 145 || /对比|发灰|清晰|笔画|文字/.test(goalText)) ratio = 0.65; + if (/柔和|轻微|保护暗部/.test(goalText)) ratio = Math.min(ratio, 0.35); + desired = minStrength + (maxStrength - minStrength) * ratio; + } + const clamped = Math.min(maxStrength, Math.max(minStrength, gammaCanonicalStrength(desired, step))); + const reason = `本地帧亮度分析(均亮 ${statistics.meanLuma.toFixed(1)},近黑 ${(statistics.nearBlackRatio * 100).toFixed(1)}%)生成的有界 Gamma 建议(强度 ${clamped}),无需外接模型网关;请结合前后实拍与独立回读判断保留或恢复。`; + const candidate = await service().createCandidate(owner, experiment.id, { + source: 'manual', baselineId: baseline.id, baselineHash: baseline.hash, frameIds: [frame.id], sampleIds: [], + patches: [{ path: classroomGammaPath, value: clamped, reason }], + }); + res.status(201).json({ ok: true, candidate }); + }); + } post('/experiments/:id/candidates', async (req, res) => { const input = candidateInput.parse(req.body ?? {}); const owner = visionWorkshopOwner(req); const experimentId = String(req.params.id); const experiment = await service().getExperiment(owner, experimentId); if (!experiment.baseline) throw new VisionWorkshopError('vision_baseline_required', 'Import a validated baseline before generating candidates', 409); diff --git a/tools/package-vision-distribution.mts b/tools/package-vision-distribution.mts index 7cd5b4d..b179bc9 100644 --- a/tools/package-vision-distribution.mts +++ b/tools/package-vision-distribution.mts @@ -25,8 +25,8 @@ import { visionCrc32 } from '../server/monitoring/vision-workshop-export.js'; const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); export const CAMERA_ID = 'rdk-camera-workshop'; export const COURSE_ID = 'rdk-vision-workshop'; -export const DEFAULT_STUDIO_VERSION = '1.5.11'; -export const DEFAULT_CLASSROOM_VERSION = '1.5.9-rc.27'; +export const DEFAULT_STUDIO_VERSION = '1.5.13'; +export const DEFAULT_CLASSROOM_VERSION = '1.5.9-rc.28'; const MAX_PACKAGE_BYTES = 32 * 1024 * 1024; const SEMVER_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/; const SECRET_PATTERN = @@ -546,7 +546,7 @@ export async function verifySingleArchive( const mcpJson = JSON.parse(extracted.get(`${prefix}.mcp.json`)!.toString('utf8')) as { mcpServers: Record< string, - { args: string[]; requestTimeoutMs?: number; permissions?: { default?: string; tools?: Record } } + { args: string[]; env?: Record; requestTimeoutMs?: number; permissions?: { default?: string; tools?: Record } } >; }; if (pluginJson.name !== CAMERA_ID) throw new Error(`Unexpected plugin.json name: ${pluginJson.name}`); @@ -595,7 +595,8 @@ export async function verifySingleArchive( { HOME: homeDir, USERPROFILE: homeDir, - RDK_CAMERA_WORKSHOP_ONBOARDING: '1', + // Launch exactly as the packaged .mcp.json declares, so the shipped configuration is what gets verified. + ...(mcpJson.mcpServers[CAMERA_ID].env ?? {}), RDK_CAMERA_WORKSHOP_CONFIG: path.join(homeDir, 'missing-connection.json'), }, ); @@ -831,7 +832,7 @@ function parseCli(argv: string[]) { console.log( [ 'Usage:', - ' npm run vision:package -- [--output ] [--studio-version 1.5.11] [--classroom-version 1.5.9-rc.27] [--lesson-html ]', + ' npm run vision:package -- [--output ] [--studio-version 1.5.13] [--classroom-version 1.5.9-rc.28] [--lesson-html ]', ' npm run vision:verify -- [--dir ]', ].join('\n'), ); diff --git a/tools/package-vision-distribution.test.mts b/tools/package-vision-distribution.test.mts index e3df0ef..aa6384c 100644 --- a/tools/package-vision-distribution.test.mts +++ b/tools/package-vision-distribution.test.mts @@ -42,8 +42,10 @@ test('packageVisionDistribution builds studio.zip & classroom.zip directly from const studioZip = await readFile(path.join(out, 'studio.zip')); const entries = extractZipEntries(studioZip); const mcpJson = JSON.parse(entries.get('rdk-camera-workshop/.mcp.json')!.toString('utf8')) as { - mcpServers: Record } }>; + mcpServers: Record; permissions?: { tools?: Record } }>; }; + // The packaged launch configuration must keep the onboarding diagnostics that the README contract describes. + assert.equal(mcpJson.mcpServers['rdk-camera-workshop']?.env?.RDK_CAMERA_WORKSHOP_ONBOARDING, '1'); assert.equal(mcpJson.mcpServers['rdk-camera-workshop']?.permissions?.tools?.vision_camera_bringup_flow, 'approval'); assert.equal(mcpJson.mcpServers['rdk-camera-workshop']?.permissions?.tools?.vision_ai_debug_preview, 'readonly'); assert.equal(mcpJson.mcpServers['rdk-camera-workshop']?.permissions?.tools?.vision_camera_frame_preview, 'readonly'); diff --git a/tools/package-vision-quickstart.mjs b/tools/package-vision-quickstart.mjs new file mode 100644 index 0000000..a8358b3 --- /dev/null +++ b/tools/package-vision-quickstart.mjs @@ -0,0 +1,261 @@ +#!/usr/bin/env node +/** + * Package a self-contained, zero-node_modules quickstart bundle for trainees + * using a stock official RDKOS 3.5.0 RDK X5 board. + */ +import { createHash } from 'node:crypto'; +import { execFileSync } from 'node:child_process'; +import { existsSync, realpathSync } from 'node:fs'; +import { chmod, copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + +const BOARD_TOOL_FILES = [ + 'vision-x5-board-bootstrap.py', + 'vision-x5-preflight.py', + 'vision-x5-camera.py', + 'vision-x5-frame.py', + 'vision-x5-isp.py', + 'vision-x5-bpu-preview.py', + 'vision-x5-calibration.py', + 'vision-camera-systemd.py', +]; + +const NATIVE_SOURCE_FILES = [ + 'x5_camera_backend.c', + 'x5_camera_backend.h', + 'x5_isp_modules.inc.c', + 'x5_isp_module_control.inc.c', + 'x5_isp_replay.inc.c', + 'x5_isp_feedback.inc.c', + 'x5_gpio_permission_wait.c', + 'x5_factory_profiles.c', + 'Makefile', + 'README.md', + 'LICENSE', +]; + +const COURSE_DEVICE_FILES = [ + 'x5-course-detect.py', + 'x5-station-bridge.py', +]; + +function parseArgs(argv) { + const options = { + outDir: path.join(ROOT, 'output', 'vision-workshop-quickstart'), + precompiledDir: undefined, + courseAssetsDir: undefined, + classroomConfig: undefined, + clean: true, + }; + for (let i = 0; i < argv.length; i += 1) { + const flag = argv[i]; + const next = () => { + if (i + 1 >= argv.length) throw new Error(`missing_value:${flag}`); + i += 1; + return argv[i]; + }; + if (flag === '--out-dir') options.outDir = path.resolve(next()); + else if (flag === '--precompiled-dir') options.precompiledDir = path.resolve(next()); + else if (flag === '--course-assets-dir') options.courseAssetsDir = path.resolve(next()); + else if (flag === '--classroom-config') options.classroomConfig = path.resolve(next()); + else if (flag === '--no-clean') options.clean = false; + else if (!flag.startsWith('-')) options.outDir = path.resolve(flag); + else throw new Error(`unknown_flag:${flag}`); + } + return options; +} + +async function copyTree(from, to) { + await mkdir(to, { recursive: true }); + for (const entry of await readdir(from, { withFileTypes: true })) { + if (entry.name === '__pycache__' || entry.name.endsWith('.pyc') || entry.name.startsWith('.')) continue; + if (entry.isSymbolicLink()) throw new Error(`symlink_not_allowed:${path.join(from, entry.name)}`); + const src = path.join(from, entry.name); + const dst = path.join(to, entry.name); + if (entry.isDirectory()) await copyTree(src, dst); + else if (entry.isFile()) await copyFile(src, dst); + } +} + +export async function packageQuickstart(options) { + const outDir = path.resolve(options.outDir); + const esbuildBin = path.join(ROOT, 'node_modules', '.bin', process.platform === 'win32' ? 'esbuild.cmd' : 'esbuild'); + await stat(esbuildBin); + + if (options.clean) { + await rm(outDir, { recursive: true, force: true }); + } + const runtimeDir = path.join(outDir, 'runtime'); + const payloadDir = path.join(outDir, 'board-payload'); + const nativeDir = path.join(payloadDir, 'vision-x5-native'); + await mkdir(runtimeDir, { recursive: true }); + await mkdir(nativeDir, { recursive: true }); + + // 1. Bundle vision-workshop-local.mts into a single zero-dependency ESM file. + const bundleOut = path.join(runtimeDir, 'vision-workshop-local.mjs'); + execFileSync(esbuildBin, [ + path.join(ROOT, 'tools', 'vision-workshop-local.mts'), + '--bundle', + '--platform=node', + '--target=node22', + '--format=esm', + '--banner:js=import { createRequire as __rdkCreateRequire } from "node:module"; const require = __rdkCreateRequire(import.meta.url);', + `--outfile=${bundleOut}`, + ], { cwd: ROOT, stdio: 'pipe' }); + + // 2. Copy quickstart launcher and minimal board payload. + await copyFile(path.join(ROOT, 'tools', 'vision-workshop-quickstart.mjs'), path.join(outDir, 'vision-workshop-quickstart.mjs')); + for (const name of BOARD_TOOL_FILES) { + await copyFile(path.join(ROOT, 'tools', name), path.join(payloadDir, name)); + } + for (const name of NATIVE_SOURCE_FILES) { + const src = path.join(ROOT, 'tools', 'vision-x5-native', name); + try { + await stat(src); + await copyFile(src, path.join(nativeDir, name)); + } catch (error) { + if (name !== 'LICENSE' || error.code !== 'ENOENT') throw error; + } + } + for (const name of COURSE_DEVICE_FILES) { + await copyFile(path.join(ROOT, 'plugins', 'rdk-vision-workshop', 'device', name), path.join(payloadDir, name)); + } + + if (options.precompiledDir) { + for (const name of ['libvision_x5_native.so', 'libvision_x5_gpio_permission_wait.so']) { + const src = path.join(options.precompiledDir, name); + try { + await stat(src); + await copyFile(src, path.join(payloadDir, name)); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + } + } + let presetCourseAssets = { bundled: false }; + if (options.courseAssetsDir) { + const source = options.courseAssetsDir; + const model = await readFile(path.join(source, 'preset-model.bin')); + const profile = JSON.parse(await readFile(path.join(source, 'model-profile.json'), 'utf8')); + const modelSha256 = createHash('sha256').update(model).digest('hex'); + if (!model.length || profile.sha256 !== modelSha256) throw new Error('preset_model_sha256_mismatch'); + for (const asset of ['course-static.jpg', 'model-zoo/ultralytics_yolo_det.py']) { + if (!(await stat(path.join(source, asset))).isFile()) throw new Error('missing_course_asset:' + asset); + } + await copyTree(source, path.join(payloadDir, 'course')); + presetCourseAssets = { + bundled: true, + modelFile: 'board-payload/course/preset-model.bin', + modelBytes: model.length, + modelSha256, + }; + } + if (options.classroomConfig) { + await copyFile(options.classroomConfig, path.join(outDir, 'classroom.json')); + } + + // 3. Emit cross-platform one-click wrapper scripts (start / status / stop) and README. + const unixWrapper = cmd => [ + '#!/usr/bin/env bash', + 'set -euo pipefail', + 'DIR="$(cd "$(dirname "$0")" && pwd)"', + `exec node "$DIR/vision-workshop-quickstart.mjs" ${cmd} "$@"`, + '', + ].join('\n'); + const winWrapper = cmd => [ + '@echo off', + 'setlocal', + 'set "DIR=%~dp0"', + `node "%DIR%vision-workshop-quickstart.mjs" ${cmd} %*`, + 'if errorlevel 1 pause', + '', + ].join('\r\n'); + for (const [name, cmd] of [ + ['start-workshop.sh', 'start'], + ['start-workshop.command', 'start'], + ['status-workshop.sh', 'status'], + ['stop-workshop.sh', 'stop'], + ]) { + const target = path.join(outDir, name); + await writeFile(target, unixWrapper(cmd), { mode: 0o755 }); + if (process.platform !== 'win32') await chmod(target, 0o755); + } + for (const [name, cmd] of [ + ['start-workshop.bat', 'start'], + ['status-workshop.bat', 'status'], + ['stop-workshop.bat', 'stop'], + ]) { + await writeFile(path.join(outDir, name), winWrapper(cmd)); + } + + const exampleClassroom = { + _comment: '组织方在发包前按需重命名为 classroom.json;请勿将真实 API Key 提交至公开仓库。', + model: { + baseUrl: 'https://your-classroom-gateway.example.com/v1', + apiKey: 'REPLACE_WITH_TEMPORARY_CLASSROOM_KEY', + model: 'qwen-vl-max', + }, + robogoProfilePath: './training-profile.json', + }; + await writeFile(path.join(outDir, 'classroom.example.json'), JSON.stringify(exampleClassroom, null, 2) + '\n'); + + const readme = [ + '# RDK 视觉 Pipeline Workshop · 官方镜像一键启动包', + '', + '适用于烧录了**官方 RDKOS 3.5.0** 镜像的 RDK X5 + IMX415 开发板,无需定制母盘、无需板卡联网、无需额外配置模型 Key。', + '', + '## 定版课程主线(统一预置模型优先,数据集重训为进阶选做)', + '', + '- **主线(必做,控制变量验证 ISP 效果)**:带课程资产的启动包内置通过校验的 **X5 INT8 预置检测模型**(`board-payload/course/preset-model.bin` + `model-profile.json` + `course-static.jpg` + `model-zoo/ultralytics_yolo_det.py`)。学员先在 RDK Studio 体验有状态**自然语言连续 10 参数图片 ISP 调参**,再完成真机点亮、三联基线、两轮 Gamma(免外部 Key)与单项 ISP 实操,最后用**同一个预置模型**对比「原始 ISP vs 调优后 ISP」的 BPU 实时检测效果,零重训即可直观验收 ISP 收益。', + '- **进阶 / 异步选做(数据集重训 A 路径)**:如需新增自定义物体类别或完整体验训练量化链路,可在主线完成后通过 RoboGO 异步训练并 PTQ 量化成 X5 INT8 `.bin` 上板对比,不阻塞课堂主线节奏。', + '', + '## 学员 3 步开始', + '', + '1. 断电接好 IMX415(支持 CSI0 / CSI2 自动探测),上电并用 Type-C 数据线(默认 `192.168.128.10`)或网线连上电脑。', + '2. 在电脑本机运行启动脚本(首次连接如需登录,请输入自己的板卡密码;准备就绪后转入后台):', + ' - macOS / Linux:`./start-workshop.sh`(查看状态 `./status-workshop.sh`,课后停止 `./stop-workshop.sh`;局域网 IP 加 `--host <板卡IP>`)', + ' - Windows:双击 `start-workshop.bat`(查状态 `status-workshop.bat`,停止 `stop-workshop.bat`)', + '3. 打开 **RDK Studio**(已启用 RDK Camera AI / 视觉 Workshop 插件),工作台将**自动绑定默认实验并自动发现一键预置 BPU 检测**,直接对话输入:', + ' > 开始视觉 Workshop,请先调用 mcp__rdk-vision-workshop__vision_course_view 打开课堂工作台。', + '', + ' Studio 1.7.0 选中板卡时,若右侧面板加载失败,从对话结果中打开原始工作台链接。', + '', + '## 内置免配置特性', + '', + '- **带课程资产的包可运行预置 X5 INT8 模型**:同步至板端后自动生成 `board-launcher.json`,工作台一键运行 BPU 静态样张 + 实拍流检测并核验 SHA-256。', + '- **自然语言连续 ISP 图片调参**:免接相机即可对 7 套内置病灶场景或任意本地图片连续多轮对话调优(自动继承前序参数、支持 `delta` 相对增量、`undo` 一键撤回与保参高清导出)。', + '- **CSI 口与 Lane 自动探测**:自动识别 IMX415 接在 CSI0(2-lane)还是 CSI2(4-lane),无需手动记参数。', + '- **免模型 Key 实机 Gamma**:未配置外部模型网关时,实机两轮 Gamma 自动使用本地帧亮度分析生成有界曲线,零 Key 分发负担。', + '- **工作台自动发现 & 实时进度反馈**:自动读取默认实验 ID 与 `board-launcher.json`,预检与 4K 采图实时展示耗时计数。', + '', + '预置 BPU 检测依赖板卡账号已有的 systemd 与非交互运行权限。启动时的检测就绪回执会显示权限或资产缺项。', + '', + ].join('\n'); + await writeFile(path.join(outDir, 'README.md'), readme); + + // 4. Write manifest with SHA-256 of the standalone runtime bundle and preset course assets. + const bundleBytes = await readFile(bundleOut); + const manifest = { + schema: 'rdk.vision-workshop-quickstart.v1', + bundleFile: 'runtime/vision-workshop-local.mjs', + bundleBytes: bundleBytes.length, + bundleSha256: createHash('sha256').update(bundleBytes).digest('hex'), + presetCourseAssets, + }; + await writeFile(path.join(outDir, 'MANIFEST.json'), JSON.stringify(manifest, null, 2) + '\n'); + return { outDir, ...manifest }; +} + +const entryFile = process.argv[1]; +if (entryFile && existsSync(entryFile) && import.meta.url === pathToFileURL(realpathSync(entryFile)).href) { + const opts = parseArgs(process.argv.slice(2)); + packageQuickstart(opts).then(result => { + console.log(JSON.stringify(result, null, 2)); + }).catch(error => { + console.error(error.message); + process.exitCode = 1; + }); +} diff --git a/tools/vision-course-preset/model-profile.json b/tools/vision-course-preset/model-profile.json new file mode 100644 index 0000000..7eaf217 --- /dev/null +++ b/tools/vision-course-preset/model-profile.json @@ -0,0 +1,36 @@ +{ + "schema": "rdk.vision-course-model-profile.v1", + "name": "course-yolov8s-a2_bayese_640x640_nv12.bin", + "sha256": "59dd362fb5d2369168b8f43bca4c465ef1590cc6d8deb3e122370bb842243fd8", + "precision": "INT8", + "architecture": "bayes-e", + "classes": [ + "park", + "qrcode", + "obstacle" + ], + "input": { + "name": "images", + "width": 640, + "height": 640, + "type": "NV12", + "resize": "direct" + }, + "decoder": { + "type": "ultralytics_yolov8_6head", + "heads": [ + { "name": "output0", "shape": [1, 80, 80, 3] }, + { "name": "326", "shape": [1, 80, 80, 64] }, + { "name": "334", "shape": [1, 40, 40, 3] }, + { "name": "342", "shape": [1, 40, 40, 64] }, + { "name": "350", "shape": [1, 20, 20, 3] }, + { "name": "358", "shape": [1, 20, 20, 64] } + ] + }, + "provenance": { + "runId": "job-c2c5897c2ad3", + "openExplorer": "1.2.8", + "mapper": "1.24.3", + "verifiedAt": "2026-11-22T21:49:27+08:00" + } +} diff --git a/tools/vision-course-preset/model-zoo/ultralytics_yolo_det.py b/tools/vision-course-preset/model-zoo/ultralytics_yolo_det.py new file mode 100644 index 0000000..630b4fd --- /dev/null +++ b/tools/vision-course-preset/model-zoo/ultralytics_yolo_det.py @@ -0,0 +1,291 @@ +# Copyright (c) 2025 D-Robotics Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Ultralytics YOLO Detection Runtime Wrapper. + +This module implements the maintained Python detection wrapper for the +`ultralytics_yolo` sample on `RDK X5`. It is used by all supported detection +families in this sample: + + - YOLOv5u + - YOLOv8 + - YOLOv9 + - YOLOv10 + - YOLO11 + - YOLO12 + - YOLO13 + +All detection models exported for this sample use the same fixed output +protocol on X5: + + - output[0]: stride-8 classification logits + - output[1]: stride-8 DFL box tensor + - output[2]: stride-16 classification logits + - output[3]: stride-16 DFL box tensor + - output[4]: stride-32 classification logits + - output[5]: stride-32 DFL box tensor + +The wrapper keeps the sample responsibilities clear: + + - preprocessing: convert one BGR image into packed NV12 input + - forward: invoke `hbm_runtime` + - postprocessing: decode boxes, apply class-wise NMS, and scale the + results back to the original image +""" + +import os +import sys +import time +import logging +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Tuple + +import hbm_runtime +import numpy as np + +sys.path.append(os.path.abspath("../../../../../")) + +import utils.py_utils.postprocess as post_utils +import utils.py_utils.preprocess as pre_utils + + +logger = logging.getLogger("Ultralytics_YOLO") + + +@dataclass +class UltralyticsYOLODetectConfig: + """Configuration used by the detection wrapper. + + Args: + model_path: Path to the X5 `.bin` model. + classes_num: Number of categories predicted by the model. + score_thres: Confidence threshold used before NMS. + nms_thres: IoU threshold used by class-wise NMS. + reg: Number of DFL bins for one box edge. + resize_type: Resize policy, `0` for direct resize and `1` for + letterbox. + strides: Feature strides used by the three detection heads. + """ + + model_path: str + classes_num: int = 80 + score_thres: float = 0.25 + nms_thres: float = 0.70 + reg: int = 16 + resize_type: int = 1 + strides: List[int] = field(default_factory=lambda: [8, 16, 32]) + + +class UltralyticsYOLODetect: + """Detection wrapper built on top of `hbm_runtime`. + + This wrapper owns one BPU model instance and exposes a consistent + `predict()` interface used by `main.py`. + """ + + def __init__(self, config: UltralyticsYOLODetectConfig): + """Initialize the runtime wrapper and decoding metadata. + + Args: + config: Detection runtime configuration for the current model. + """ + self.cfg = config + self.conf_thres_raw = -np.log(1.0 / self.cfg.score_thres - 1.0) + self.weights_static = np.arange(self.cfg.reg, dtype=np.float32)[None, None, :] + + t0 = time.time() + self.model = hbm_runtime.HB_HBMRuntime(self.cfg.model_path) + logger.info("\033[1;31mLoad Model time = %.2f ms\033[0m", 1000 * (time.time() - t0)) + + self.model_name = self.model.model_names[0] + self.input_names = self.model.input_names[self.model_name] + self.output_names = self.model.output_names[self.model_name] + self.input_shapes = self.model.input_shapes[self.model_name] + + input_shape = self.input_shapes[self.input_names[0]] + if input_shape[1] == 3: + self.input_h = input_shape[2] + self.input_w = input_shape[3] + else: + self.input_h = input_shape[1] + self.input_w = input_shape[2] + + def set_scheduling_params( + self, + priority: Optional[int] = None, + bpu_cores: Optional[list] = None, + ) -> None: + """Set optional BPU scheduling parameters. + + Args: + priority: Runtime priority used by `hbm_runtime`. + bpu_cores: BPU core list used by the model scheduler. + """ + kwargs = {} + if priority is not None: + kwargs["priority"] = {self.model_name: priority} + if bpu_cores is not None: + kwargs["bpu_cores"] = {self.model_name: bpu_cores} + if kwargs: + self.model.set_scheduling_params(**kwargs) + + def pre_process( + self, + img: np.ndarray, + resize_type: Optional[int] = None, + ) -> Dict[str, Dict[str, np.ndarray]]: + """Convert one BGR image into packed NV12 model input. + + Args: + img: Input BGR image loaded by OpenCV. + resize_type: Optional resize policy override. + + Returns: + The nested input tensor dictionary required by `HB_HBMRuntime.run`. + """ + t0 = time.time() + resize_type = self.cfg.resize_type if resize_type is None else resize_type + + resized = pre_utils.resized_image(img, self.input_w, self.input_h, resize_type) + y, uv = pre_utils.bgr_to_nv12_planes(resized) + packed_nv12 = np.concatenate([y.reshape(-1), uv.reshape(-1)]).astype(np.uint8) + + logger.info("\033[1;31mPre-process time = %.2f ms\033[0m", 1000 * (time.time() - t0)) + return {self.model_name: {self.input_names[0]: packed_nv12}} + + def forward(self, input_tensor: Dict[str, Dict[str, np.ndarray]]) -> Dict[str, Dict[str, np.ndarray]]: + """Run BPU inference for one input image. + + Args: + input_tensor: Input tensor dictionary returned by `pre_process`. + + Returns: + Raw output tensors indexed by model name and output name. + """ + t0 = time.time() + outputs = self.model.run(input_tensor) + logger.info("\033[1;31mForward time = %.2f ms\033[0m", 1000 * (time.time() - t0)) + return outputs + + def post_process( + self, + outputs: Dict[str, Dict[str, np.ndarray]], + ori_img_w: int, + ori_img_h: int, + score_thres: Optional[float] = None, + nms_thres: Optional[float] = None, + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """Decode detection tensors into final sample results. + + Args: + outputs: Raw runtime outputs returned by `forward`. + ori_img_w: Original image width. + ori_img_h: Original image height. + score_thres: Optional score threshold override. + nms_thres: Optional NMS threshold override. + + Returns: + A tuple containing: + - bounding boxes in `(x1, y1, x2, y2)` format + - confidence scores + - class ids + """ + t0 = time.time() + score_thres = self.cfg.score_thres if score_thres is None else score_thres + nms_thres = self.cfg.nms_thres if nms_thres is None else nms_thres + conf_thres_raw = -np.log(1.0 / score_thres - 1.0) + raw_outputs = outputs[self.model_name] + + detections = [] + for level_index, stride in enumerate(self.cfg.strides): + base_idx = level_index * 2 + cls_output = raw_outputs[self.output_names[base_idx]].reshape(-1, self.cfg.classes_num) + box_output = raw_outputs[self.output_names[base_idx + 1]] + + scores, cls_ids, valid_indices = post_utils.filter_classification(cls_output, conf_thres_raw) + if valid_indices.size == 0: + continue + + grid_size = self.input_h // stride + boxes = post_utils.decode_boxes( + box_output, + valid_indices, + grid_size, + stride, + self.weights_static, + ) + detections.append(np.hstack([boxes, scores[:, None], cls_ids[:, None].astype(np.float32)])) + + if not detections: + return ( + np.empty((0, 4), dtype=np.float32), + np.empty((0,), dtype=np.float32), + np.empty((0,), dtype=np.int32), + ) + + dets = np.concatenate(detections, axis=0).astype(np.float32) + final_boxes = [] + final_scores = [] + final_cls_ids = [] + for cls_id in np.unique(dets[:, 5].astype(np.int32)): + cls_dets = dets[dets[:, 5] == cls_id] + keep = post_utils.NMS(cls_dets[:, :4], cls_dets[:, 4], cls_dets[:, 5], nms_thres) + if not keep: + continue + + kept = cls_dets[keep] + boxes = post_utils.scale_coords_back( + kept[:, :4].copy(), + ori_img_w, + ori_img_h, + self.input_w, + self.input_h, + self.cfg.resize_type, + ) + final_boxes.append(boxes.astype(np.float32)) + final_scores.append(kept[:, 4].astype(np.float32)) + final_cls_ids.append(kept[:, 5].astype(np.int32)) + + logger.info("\033[1;31mPost Process time = %.2f ms\033[0m", 1000 * (time.time() - t0)) + if not final_boxes: + return ( + np.empty((0, 4), dtype=np.float32), + np.empty((0,), dtype=np.float32), + np.empty((0,), dtype=np.int32), + ) + + return ( + np.concatenate(final_boxes, axis=0), + np.concatenate(final_scores, axis=0), + np.concatenate(final_cls_ids, axis=0), + ) + + def predict(self, img: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """Run the full detection pipeline on one image. + + Args: + img: One BGR image in OpenCV format. + + Returns: + Detection results in `(boxes, scores, cls_ids)` format. + """ + ori_img_h, ori_img_w = img.shape[:2] + input_tensor = self.pre_process(img) + outputs = self.forward(input_tensor) + return self.post_process(outputs, ori_img_w, ori_img_h) + + def __call__(self, img: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """Provide function-style inference for one image.""" + return self.predict(img) diff --git a/tools/vision-course-preset/model-zoo/utils/__init__.py b/tools/vision-course-preset/model-zoo/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tools/vision-course-preset/model-zoo/utils/py_utils/__init__.py b/tools/vision-course-preset/model-zoo/utils/py_utils/__init__.py new file mode 100644 index 0000000..6122a84 --- /dev/null +++ b/tools/vision-course-preset/model-zoo/utils/py_utils/__init__.py @@ -0,0 +1,9 @@ +# flake8: noqa: F401 +# flake8: noqa: F403 + +# from .preprocess import * +# from .postprocess import * +from .visualize import * +# from .inspect import * +from .file_io import * +# from .nn_math import * diff --git a/tools/vision-course-preset/model-zoo/utils/py_utils/file_io.py b/tools/vision-course-preset/model-zoo/utils/py_utils/file_io.py new file mode 100644 index 0000000..2081ad2 --- /dev/null +++ b/tools/vision-course-preset/model-zoo/utils/py_utils/file_io.py @@ -0,0 +1,168 @@ +# Copyright (c) 2025 D-Robotics Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# flake8: noqa: E501 + + +""" +file_io: File and resource I/O utilities. + +This module defines a collection of helper functions for interacting with +files and external resources. It serves as a common utility layer for +handling file existence checks, resource loading, and basic data access, +and is intended to be reused across different samples and runtimes. + +Key Features: + - Provide unified interfaces for file and resource access. + - Encapsulate common file-related operations to reduce duplication. + - Remain independent of specific models or tasks. + +Typical Usage: + >>> from file_io import download_model_if_needed + >>> download_model_if_needed(model_path, download_url) + +Notes: + - This module focuses on general-purpose I/O utilities and should not + include algorithm-specific or business-specific logic. + - New file or resource related helpers should follow the same design + principles and be added to this module when appropriate. +""" + + +import os +import ast +import json +import cv2 +import numpy as np + +def download_model_if_needed(model_path: str, download_url: str) -> None: + """Ensure that the model file exists locally, downloading it if necessary. + + If the model file specified by `model_path` does not exist, this function + downloads it from the given URL and saves it to the target location. + + Args: + model_path: Full local path where the model file should be saved. + download_url: URL used to download the model file. + + Returns: + None + + Raises: + RuntimeError: If the download fails or the model file does not exist + after the download attempt. + """ + # Return immediately if the model file already exists + if os.path.exists(model_path): + print(f"Model already exists: {model_path}") + return + + # Extract directory and filename from the target model path + dirname = os.path.dirname(model_path) + filename = os.path.basename(model_path) + + print(f"File {model_path} does not exist. Downloading model '{filename}'...") + + # Create the directory if it does not already exist + os.makedirs(dirname, exist_ok=True) + + print(f"Downloading from: {download_url}") + print(f"Saving to: {model_path}") + + # Execute the wget command to download the model file + cmd = f"wget -c {download_url} -O {model_path}" + ret = os.system(cmd) + + # Validate whether the download was successful + if ret != 0 or not os.path.exists(model_path): + raise RuntimeError(f"Failed to download model from {download_url}") + + +def load_image(img_path: str) -> np.ndarray: + """Load an image from a file path using OpenCV. + + The image is loaded in BGR color format, which is the default format + used by OpenCV. + + Args: + img_path: Path to the image file. + + Returns: + The loaded image as a NumPy array in BGR format. + + Raises: + FileNotFoundError: If the image cannot be loaded from the given path. + """ + img = cv2.imread(img_path) + if img is None: + raise FileNotFoundError(f"Image file '{img_path}' not found.") + return img + + +def load_class_names(path: str) -> list: + """Load class names from a label file. + + Each line in the file is treated as a single class name. Empty lines + are ignored. + + Args: + path: Path to the label file. Each non-empty line contains one + class name. + + Returns: + A list of class name strings. + """ + with open(path, 'r') as f: + # Strip whitespace and filter out empty lines + class_names = [line.strip() for line in f.readlines() if line.strip()] + return class_names + + +def load_imagenet_labels(path: str) -> dict: + """Load ImageNet labels from a file. + + This function attempts to load labels that might be stored as a Python + dictionary string (e.g., "{0: 'label'}") or as a plain text file where + each line corresponds to a label index. + + Args: + path: Path to the label file. + + Returns: + A dictionary mapping class indices (int) to label strings. + Returns an empty dictionary if loading fails or file not found. + """ + if not os.path.exists(path): + return {} + + try: + with open(path, 'r', encoding='utf-8') as f: + content = f.read().strip() + + if content.startswith('{') or content.startswith('['): + try: + parsed = json.loads(content) + except Exception: + parsed = ast.literal_eval(content) + + if isinstance(parsed, dict): + return {int(k): v for k, v in parsed.items()} + if isinstance(parsed, list): + return {i: str(label) for i, label in enumerate(parsed)} + + # Fallback: assume one label per line + return {i: line.strip() for i, line in enumerate(content.split('\n')) if line.strip()} + except Exception as e: + print(f"Warning: Failed to load ImageNet labels from {path}: {e}") + return {} diff --git a/tools/vision-course-preset/model-zoo/utils/py_utils/inspect.py b/tools/vision-course-preset/model-zoo/utils/py_utils/inspect.py new file mode 100644 index 0000000..7a19dab --- /dev/null +++ b/tools/vision-course-preset/model-zoo/utils/py_utils/inspect.py @@ -0,0 +1,238 @@ +# Copyright (c) 2025 D-Robotics Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# flake8: noqa: E501 + +""" +inspect: Runtime and system inspection utilities. + +This module provides helper functions for inspecting runtime and system-level +information at execution time. It is primarily used to query platform metadata +and to introspect loaded models, exposing detailed information for debugging, +verification, and demonstration purposes. + +Key Features: + - Query basic system or platform identification information. + - Inspect runtime-managed models and print detailed metadata. + - Assist developers in understanding model inputs, outputs, and scheduling + configurations. + +Typical Usage: + >>> from inspect import get_soc_name + >>> soc = get_soc_name() + + >>> from inspect import print_model_info + >>> print_model_info(models) + +Notes: + - This module is intended for inspection, debugging, and informational + purposes only, and should not be relied on for performance-critical logic. + - The output format is human-readable and may change as inspection + requirements evolve. +""" + + +def get_soc_name() -> str: + """Get the SoC (System-on-Chip) name of the current device. + + The SoC name is read from the system file + `/sys/class/boardinfo/soc_name`. If the file cannot be read, a default + value is returned. + + Returns: + The SoC name as a string. Returns `"s100"` if reading the system + information fails. + """ + soc_path = "/sys/class/boardinfo/soc_name" + try: + # Attempt to read the SoC name from the system information file + with open(soc_path, "r") as f: + # Strip trailing whitespace and return the content + return f.read().strip() + except Exception: + # Return a default SoC name when the system file cannot be read + return "s100" + + +def print_model_info(models: object) -> None: + + """Print detailed input and output tensor information for all models. + + This utility function prints comprehensive metadata for each model + managed by the runtime, including: + + - Model names and total model count + - Input tensor information: + - Names, shapes, data types + - Quantization parameters + - Strides and descriptions + - Output tensor information: + - Names, shapes, data types + - Quantization parameters + - Strides and descriptions + - Model-level and HBM-level descriptions + - Runtime scheduling parameters (priority, BPU cores, etc.) + + Args: + models: Runtime model container object that provides model metadata + such as inputs, outputs, quantization info, and scheduling + parameters. + + Returns: + None + """ + # 1. Model Name List + print("=== Model Name List ===") + model_names = models.model_names + print(model_names) + + # 2. Total Number of Models + print("\n=== Model Count ===") + print(models.model_count) + + # 3. Input Count per Model + print("\n=== Input Counts ===") + input_counts = models.input_counts + for model, count in input_counts.items(): + print(f"{model}: {count}") + + # 4. Input Names per Model + print("\n=== Input Names ===") + input_names = models.input_names + for model, inputs in input_names.items(): + print(f"{model}:") + for name in inputs: + print(f" - {name}") + + # 5. Input Tensor Shapes + print("\n=== Input Tensor Shapes ===") + input_shapes = models.input_shapes + for model, inputs in input_shapes.items(): + print(f"{model}:") + for name, shape in inputs.items(): + print(f" {name} -> shape: {shape}") + + # 6. Input Tensor Data Types + print("\n=== Input Tensor Types ===") + input_types = models.input_dtypes + for model, inputs in input_types.items(): + print(f"{model}:") + for name, dtype in inputs.items(): + print(f" {name} -> dtype: {dtype.name}") + + # 7. Input Quantization Information + print("\n=== Input Quantization Info ===") + input_quanti_info = models.input_quants + for model, inputs in input_quanti_info.items(): + print(f"{model}:") + for name, info in inputs.items(): + print(f" {name}:") + print(f" quanti_type: {info.quant_type.name}") + print(f" quantize_axis: {info.axis}") + print(f" scale_data: {info.scale.tolist()}") + print(f" zero_point_data: {info.zero_point.tolist()}") + + # 8. Input Tensor Stride + print("\n=== Input Tensor Stride ===") + input_strides = models.input_strides + for model, inputs in input_strides.items(): + print(f"{model}:") + for name, stride in inputs.items(): + print(f" {name} -> stride: {stride}") + + # 9. Input Descriptions + input_descs = models.input_descs + for model, inputs in input_descs.items(): + for name, desc in inputs.items(): + print(f"[Input] {model}.{name} desc: {desc}") + + print("\n================ OUTPUT TESTS ================\n") + + # 1. Output Count per Model + print("=== Output Counts ===") + output_counts = models.output_counts + for model, count in output_counts.items(): + print(f"{model}: {count}") + + # 2. Output Names per Model + print("\n=== Output Names ===") + output_names = models.output_names + for model, outputs in output_names.items(): + print(f"{model}:") + for name in outputs: + print(f" - {name}") + + # 3. Output Tensor Shapes + print("\n=== Output Tensor Shapes ===") + output_shapes = models.output_shapes + for model, outputs in output_shapes.items(): + print(f"{model}:") + for name, shape in outputs.items(): + print(f" {name} -> shape: {shape}") + + # 4. Output Tensor Data Types + print("\n=== Output Tensor Types ===") + output_types = models.output_dtypes + for model, outputs in output_types.items(): + print(f"{model}:") + for name, dtype in outputs.items(): + print(f" {name} -> dtype: {dtype.name}") + + # 5. Output Quantization Information + print("\n=== Output Quantization Info ===") + output_quanti = models.output_quants + for model, outputs in output_quanti.items(): + print(f"{model}:") + for name, info in outputs.items(): + print(f" {name}:") + print(f" quanti_type: {info.quant_type.name}") + print(f" quantize_axis: {info.axis}") + print(f" scale_data: {info.scale}") + print(f" zero_point_data: {info.zero_point}") + + # 6. Output Tensor Stride + print("\n=== Output Tensor Stride ===") + output_stride = models.output_strides + for model, outputs in output_stride.items(): + print(f"{model}:") + for name, stride in outputs.items(): + print(f" {name} -> stride: {stride}") + + # 7. Output Descriptions + output_descs = models.output_descs + for model, outputs in output_descs.items(): + for name, desc in outputs.items(): + print(f"[Output] {model}.{name} desc: {desc}") + + # Get and Print Model Description Info + print("\nModel Description:") + model_desc = models.model_descs + for model_name, desc in model_desc.items(): + print(f" - {model_name}: {desc}") + + # Get and Print HBM Description Info + print("\nHBM Description:") + hbm_desc = models.hbm_descs + for file_name, desc in hbm_desc.items(): + print(f" - {file_name}: {desc}") + + # Get and PrintScheduling Params + print("\n=== Scheduling Parameters ===") + sched_params = models.sched_params + for model_name, sched in sched_params.items(): + print(f"{model_name}:") + print(f" priority : {sched.priority}") + print(f" customId : {sched.customId}") + print(f" bpu_cores : {sched.bpu_cores}") + print(f" deviceId : {sched.deviceId}") diff --git a/tools/vision-course-preset/model-zoo/utils/py_utils/nn_math.py b/tools/vision-course-preset/model-zoo/utils/py_utils/nn_math.py new file mode 100644 index 0000000..855bc1e --- /dev/null +++ b/tools/vision-course-preset/model-zoo/utils/py_utils/nn_math.py @@ -0,0 +1,60 @@ +# Copyright (c) 2025 D-Robotics Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# flake8: noqa: E501 + +import cv2 +import numpy as np + +""" +nn_math: Lightweight neural network math utilities. + +This module provides small, reusable numerical helpers commonly used in +neural network preprocessing or postprocessing, such as activation functions +and simple normalization operations. The implementations are framework-agnostic +and intended for clarity and portability. +""" + + +def sigmoid(x: np.ndarray) -> np.ndarray: + """Compute the sigmoid activation function. + + Applies the sigmoid function element-wise to the input NumPy array. + + Args: + x: Input NumPy array. + + Returns: + A NumPy array with the sigmoid function applied element-wise. + """ + return 1.0 / (1.0 + cv2.exp(-x)) + + +def zscore_normalize_lastdim(x: np.ndarray) -> np.ndarray: + """Normalize the input array along the last dimension using z-score. + + This function performs standard score normalization (z-score) on the + last dimension of the input array, resulting in zero mean and unit + variance for each vector. + + Args: + x: Input NumPy array with shape `(..., channels)`. + + Returns: + A NumPy array where each vector along the last dimension is + normalized to have mean 0 and variance 1. + """ + mean = np.mean(x, axis=-1, keepdims=True) # Compute mean per sample + var = np.var(x, axis=-1, keepdims=True) # Compute variance per sample + return np.squeeze((x - mean) / np.sqrt(var + 1e-5)) # Z-score normalization diff --git a/tools/vision-course-preset/model-zoo/utils/py_utils/postprocess.py b/tools/vision-course-preset/model-zoo/utils/py_utils/postprocess.py new file mode 100644 index 0000000..612d2e6 --- /dev/null +++ b/tools/vision-course-preset/model-zoo/utils/py_utils/postprocess.py @@ -0,0 +1,804 @@ +# Copyright (c) 2025 D-Robotics Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# flake8: noqa: E501 + +""" +postprocess: Postprocessing utilities for vision model outputs. + +This module provides reusable postprocessing helpers to convert raw model +outputs into task-level results, including coordinate scaling, quantization +recovery, prediction filtering, and optional decoding for different output +types. It is designed to be shared across multiple samples and runtimes. + +Key Features: + - Recover/rescale results back to the original image space. + - Dequantize and decode raw outputs into usable representations. + - Apply common filtering and suppression strategies (e.g., NMS). + - Provide optional utilities for masks, keypoints, and geometric handling. + +Notes: + - The module focuses on generic postprocessing building blocks; task- or + model-specific policies should be implemented at the sample level. + - Output formats and helper coverage may evolve as new models are added. +""" + + +import cv2 +import numpy as np +from hbm_runtime import QuantParams +try: + from scipy.special import softmax +except ImportError: + def softmax(x: np.ndarray, axis: int = -1) -> np.ndarray: + shifted = x - np.max(x, axis=axis, keepdims=True) + exps = np.exp(shifted) + return exps / np.sum(exps, axis=axis, keepdims=True) + + +def sigmoid(x: np.ndarray) -> np.ndarray: + """Apply the sigmoid activation function element-wise. + + Args: + x: Input tensor in logit space. + + Returns: + Tensor converted to probability space. + """ + return 1.0 / (1.0 + np.exp(-x)) + + +def recover_to_original_size(img: np.ndarray, + orig_w: int, + orig_h: int, + resize_type: int = 1) -> np.ndarray: + """Restore a resized image back to its original size. + + This function reverses the resizing operation applied during preprocessing. + It supports both direct resizing and letterbox-based resizing with padding + removal. + + Args: + img: Input image array with shape `(H, W, C)` after preprocessing. + orig_w: Original image width. + orig_h: Original image height. + resize_type: Resize strategy used during preprocessing. + - 0: Direct resize. + - 1: Letterbox resize with padding. + + Returns: + The image resized back to shape `(orig_h, orig_w, C)`. + + Raises: + ValueError: If an invalid `resize_type` is provided. + """ + h, w = img.shape[:2] # current size after preprocess + + if resize_type == 0: + # Resize directly to original dimensions + img_resized = cv2.resize(img, (orig_w, orig_h), + interpolation=cv2.INTER_NEAREST) + elif resize_type == 1: + # Remove padding and resize back from letterbox + scale = min(h / orig_h, w / orig_w) + new_w, new_h = int(orig_w * scale), int(orig_h * scale) + + pad_w = w - new_w + pad_h = h - new_h + left = pad_w // 2 + top = pad_h // 2 + + # Crop out the letterbox padding + cropped = img[top:top + new_h, left:left + new_w] + + # Resize cropped region to original size + img_resized = cv2.resize(cropped, (orig_w, orig_h), + interpolation=cv2.INTER_NEAREST) + else: + raise ValueError(f"Invalid resize_type: {resize_type}, must be 0 or 1") + + return img_resized + + +def dequantize_tensor(q_tensor: np.ndarray, quant_info: QuantParams) -> np.ndarray: + """Dequantize a quantized tensor to floating-point values. + + This function converts a quantized tensor (e.g., int8 or uint8) into + floating-point values using the provided quantization parameters. + Both per-tensor and per-channel dequantization are supported. + + Args: + q_tensor: Quantized input tensor. + quant_info: Quantization parameters including scale, zero point, + quantization axis, and quantization type. + + Returns: + A float32 NumPy array containing the dequantized tensor values. + """ + quant_type = quant_info.quant_type + quant_type_name = getattr(quant_type, "name", str(quant_type)) + if quant_type_name not in ("SCALE", "1"): + return q_tensor + + zero_point = quant_info.zero_point.astype(np.float32) + if zero_point.size == 0: + zero_point = np.zeros((1,), dtype=np.float32) + + if quant_info.scale.ndim == 0 or q_tensor.ndim == 1 or quant_info.scale.size == 1: + # Per-tensor dequantization + return (q_tensor.astype(np.float32) - zero_point.reshape(-1)[0]) * quant_info.scale + else: + # Per-channel dequantization + shape = [1] * q_tensor.ndim + shape[quant_info.axis] = -1 + scale = quant_info.scale.reshape(shape) + if zero_point.size == 1: + zero_point = np.zeros_like(scale, dtype=np.float32) + else: + zero_point = zero_point.reshape(shape) + return (q_tensor.astype(np.float32) - zero_point.astype(np.float32)) * scale + + +def dequantize_outputs(outputs: dict, quan_infos: dict) -> dict: + """Dequantize a dictionary of quantized model outputs. + + This function applies tensor dequantization to each model output using + its corresponding quantization parameters and returns the results as + floating-point tensors. + + Args: + outputs: Dictionary mapping output tensor names to quantized tensors. + quan_infos: Dictionary mapping output tensor names to their + corresponding quantization parameters. + + Returns: + A dictionary mapping output tensor names to dequantized float32 + NumPy arrays. + """ + fp32_outputs = {} + for name, output in outputs.items(): + quant_info = quan_infos[name] + fp32_outputs[name] = dequantize_tensor(output, quant_info) + return fp32_outputs + + +def scale_coords_back(xyxy: np.ndarray, + img_w: int, + img_h: int, + input_w: int, + input_h: int, + resize_type: int = 1) -> np.ndarray: + """Map bounding box coordinates back to the original image scale. + + This function converts bounding box coordinates from the resized + (model input) image space back to the original image resolution. + Both direct resize and letterbox resize strategies are supported. + + Args: + xyxy: Bounding boxes with shape `(N, 4)` in the resized image space, + formatted as `(xmin, ymin, xmax, ymax)`. + img_w: Original image width. + img_h: Original image height. + input_w: Network input width. + input_h: Network input height. + resize_type: Resize strategy used during preprocessing. + - 0: Direct resize. + - 1: Letterbox resize with padding. + + Returns: + Bounding boxes rescaled to the original image dimensions with + shape `(N, 4)`. + + Raises: + ValueError: If an invalid `resize_type` is provided. + """ + if resize_type == 0: + # Direct resize + scale_x = img_w / input_w + scale_y = img_h / input_h + xyxy[:, [0, 2]] *= scale_x + xyxy[:, [1, 3]] *= scale_y + elif resize_type == 1: + # Letterbox resize + scale = min(input_w / img_w, input_h / img_h) + pad_w = (input_w - img_w * scale) / 2 + pad_h = (input_h - img_h * scale) / 2 + xyxy[:, [0, 2]] = (xyxy[:, [0, 2]] - pad_w) / scale + xyxy[:, [1, 3]] = (xyxy[:, [1, 3]] - pad_h) / scale + else: + raise ValueError("resize_type must be 0 (resize) or 1 (letterbox)") + + # Clamp coordinates within valid image bounds + xyxy[:, [0, 2]] = np.clip(xyxy[:, [0, 2]], 0, img_w) + xyxy[:, [1, 3]] = np.clip(xyxy[:, [1, 3]], 0, img_h) + + return xyxy + + +def NMS(xyxy: np.ndarray, + score: np.ndarray, + cls: np.ndarray, + iou_thresh: float = 0.45) -> list: + """Perform class-wise Non-Maximum Suppression (NMS). + + This function applies Non-Maximum Suppression independently for each + class. For each class, bounding boxes are sorted by confidence score, + and boxes with an Intersection over Union (IoU) greater than the given + threshold are suppressed. + + Args: + xyxy: Bounding boxes with shape `(N, 4)`, formatted as + `(xmin, ymin, xmax, ymax)`. + score: Confidence scores for each bounding box with shape `(N,)`. + cls: Class IDs for each bounding box with shape `(N,)`. + iou_thresh: IoU threshold used to suppress overlapping boxes. + + Returns: + A list of indices corresponding to the bounding boxes that are kept + after Non-Maximum Suppression. + """ + keep = [] + for c in np.unique(cls): + idx = np.where(cls == c)[0] + x1, y1, x2, y2 = xyxy[idx].T + area = (x2 - x1) * (y2 - y1) + order = score[idx].argsort()[::-1] # Sort by descending score + + while order.size > 0: + i = order[0] + keep.append(idx[i]) + # Compute IoU with remaining boxes + xx1 = np.maximum(x1[i], x1[order[1:]]) + yy1 = np.maximum(y1[i], y1[order[1:]]) + xx2 = np.minimum(x2[i], x2[order[1:]]) + yy2 = np.minimum(y2[i], y2[order[1:]]) + inter = np.clip(xx2 - xx1, 0, None) * np.clip(yy2 - yy1, 0, None) + iou = inter / (area[i] + area[order[1:]] - inter + 1e-9) + + # Keep boxes with IoU below threshold + order = order[1:][iou < iou_thresh] + + return keep + + +def xywh_to_xyxy(xywh: np.ndarray) -> np.ndarray: + """Convert bounding boxes from center format to corner format. + + This function converts bounding boxes from + `(center_x, center_y, width, height)` format to + `(x1, y1, x2, y2)` format, where `(x1, y1)` is the top-left corner + and `(x2, y2)` is the bottom-right corner. + + Args: + xywh: Bounding boxes with shape `(N, 4)` in + `(center_x, center_y, width, height)` format. + + Returns: + Bounding boxes with shape `(N, 4)` in `(x1, y1, x2, y2)` format. + """ + x1y1 = xywh[:, :2] - xywh[:, 2:] / 2 + x2y2 = xywh[:, :2] + xywh[:, 2:] / 2 + return np.hstack([x1y1, x2y2]) + + +def filter_classification(cls_output: np.ndarray, conf_thres_raw: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Filter classification outputs using a raw confidence threshold. + + This function selects classification predictions whose maximum logit + value exceeds a given threshold, then computes sigmoid confidence + scores for the selected predictions. + + Args: + cls_output: Classification logits with shape `(N, C)`, where `N` + is the number of predictions and `C` is the number of classes. + conf_thres_raw: Threshold applied to the maximum logit value + (before sigmoid). + + Returns: + A tuple containing: + - scores: Sigmoid confidence scores of the selected predictions. + - ids: Class indices of the selected predictions. + - valid_indices: Indices of the selected predictions in the + original input array. + """ + cls_output = cls_output.reshape(-1, cls_output.shape[-1]) + max_scores = np.max(cls_output, axis=1) + valid_indices = np.flatnonzero(max_scores >= conf_thres_raw) + ids = np.argmax(cls_output[valid_indices], axis=1) + # Apply sigmoid + scores = sigmoid(max_scores[valid_indices]) + return scores, ids, valid_indices + + +def decode_ltrb_boxes(anchor: np.ndarray, + box_output: np.ndarray, + stride: int) -> np.ndarray: + """Decode anchor-relative LTRB regression outputs to `xyxy` boxes. + + This helper converts YOLO-style left, top, right, and bottom distances + predicted on a feature grid into corner-format boxes in the model input + coordinate system. + + Args: + anchor: Grid center coordinates with shape `(N, 2)` in `(x, y)` format. + box_output: Box regression outputs with shape `(N, 4)` formatted as + `(left, top, right, bottom)`. + stride: Feature stride used to project the grid coordinates back to the + input image scale. + + Returns: + A NumPy array with shape `(N, 4)` in `(x1, y1, x2, y2)` format. + """ + x1y1 = anchor - box_output[:, :2] + x2y2 = anchor + box_output[:, 2:] + return np.hstack([x1y1, x2y2]) * stride + + +def filter_mces(mces_output: np.ndarray, valid_indices: np.ndarray) -> np.ndarray: + """Extract MCES features for selected predictions. + + This function selects MCES feature vectors corresponding to the given + valid prediction indices. + + Args: + mces_output: MCES output tensor, where the last dimension represents + the feature dimension. + valid_indices: Indices of valid predictions to be selected. + + Returns: + A NumPy array of shape `(K, D)` containing the filtered MCES features, + where `K = len(valid_indices)` and `D` is the feature dimension. + """ + mces_output = mces_output.reshape(-1, mces_output.shape[-1]) + mces = mces_output[valid_indices, :] + return mces + + +def filter_predictions(pred: np.ndarray, score_thres: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Filter detection predictions by confidence threshold. + + This function combines objectness scores and class probabilities to + compute final confidence scores, then filters out predictions whose + confidence is below the given threshold. + + Args: + pred: Prediction tensor with shape `(N, 5 + C)`, formatted as + `[x, y, w, h, objectness, class_probs...]`. + score_thres: Confidence threshold applied to + `(objectness * class_probability)`. + + Returns: + A tuple containing: + - xyxy: Filtered bounding boxes with shape `(Nf, 4)` in + `(x1, y1, x2, y2)` format. + - score: Confidence scores of the filtered predictions with + shape `(Nf,)`. + - cls: Class indices of the filtered predictions with + shape `(Nf,)`. + """ + xywh = pred[:, :4] + + # Combine objectness and class scores + conf_all = pred[:, 4:5] * pred[:, 5:] + cls = conf_all.argmax(axis=1) + score = conf_all[np.arange(len(pred)), cls] + mask = score > score_thres + xyxy = xywh_to_xyxy(xywh[mask]) + return xyxy, score[mask], cls[mask] + + +def gen_anchor(grid_size: int) -> np.ndarray: + """Generate anchor center positions on a square grid. + + This function generates evenly spaced anchor center coordinates for a + square grid of size `grid_size x grid_size`. The centers are placed at + half-integer positions (e.g., 0.5, 1.5, ...) along both axes. + + Args: + grid_size: Size of the square grid (e.g., `80` for an `80 x 80` grid). + + Returns: + A NumPy array of shape `(N, 2)` containing anchor center coordinates + in `(x, y)` format, where `N = grid_size * grid_size`. + """ + x = np.tile(np.linspace(0.5, grid_size - 0.5, grid_size), reps=grid_size) + y = np.repeat(np.linspace(0.5, grid_size - 0.5, grid_size), grid_size) + return np.stack([x, y], axis=1) + + +def decode_boxes(boxes_output: np.ndarray, + valid_indices: np.ndarray, + grid_size: int, + stride: int, + weights_static: np.ndarray) -> np.ndarray: + """Decode bounding boxes from distributional predictions. + + This function decodes bounding box coordinates from distribution-based + regression outputs (e.g., 16-bin discrete distributions per side). + It applies softmax to each distribution, computes the expected offsets, + and converts them into bounding boxes in `(x1, y1, x2, y2)` format. + + Args: + boxes_output: Bounding box output tensor with shape `(N, 4 * 16)`, + representing discrete distributions for left, top, right, and + bottom offsets. + valid_indices: Indices of valid predictions to be decoded. + grid_size: Feature map grid size (e.g., width or height of the grid). + stride: Downsampling factor used to map grid coordinates to the + original image scale. + weights_static: Discrete location weights used to compute expectations + (e.g., values from `0` to `15`). + + Returns: + A NumPy array of shape `(M, 4)` containing decoded bounding boxes in + `(x1, y1, x2, y2)` format, where `M = len(valid_indices)`. + """ + bboxes = boxes_output.reshape(-1, boxes_output.shape[-1]) + bboxes_float32 = bboxes[valid_indices] + # Softmax over 16 bins per LTRB side and apply expectation + ltrb = np.sum(softmax(bboxes_float32.reshape(-1, 4, 16), axis=2) * + weights_static, axis=2) + anchor = gen_anchor(grid_size)[valid_indices] + x1y1 = anchor - ltrb[:, 0:2] + x2y2 = anchor + ltrb[:, 2:4] + return np.hstack([x1y1, x2y2]) * stride + + +def decode_masks(mces: np.ndarray, + boxes: np.ndarray, + protos: np.ndarray, + input_w: int, + input_h: int, + mask_w: int, + mask_h: int, + mask_thresh: float = 0.5) -> list[np.ndarray]: + """Decode instance segmentation masks. + + This function generates instance-level binary masks by linearly combining + mask prototype features with per-instance mask coefficients (MCES). + The resulting masks are cropped according to the corresponding bounding + boxes and binarized using a threshold. + + Args: + mces: Mask coefficients for each detection with shape `(M, C)`. + boxes: Bounding boxes with shape `(M, 4)` in `(x1, y1, x2, y2)` format. + protos: Mask prototype feature map with shape `(H, W, C)`. + input_w: Width of the input image. + input_h: Height of the input image. + mask_w: Width of the mask prototype feature map. + mask_h: Height of the mask prototype feature map. + mask_thresh: Threshold used to binarize the decoded masks. + + Returns: + A list of binary mask arrays, where each element has shape `(H_i, W_i)` + corresponding to one detected instance. + """ + masks = [] + x_scale = mask_w / input_w + y_scale = mask_h / input_h + + for i, (x1, y1, x2, y2) in enumerate(boxes): + # Crop proto features using scaled coordinates + x1_corp = int(x1 * x_scale) + y1_corp = int(y1 * y_scale) + x2_corp = int(x2 * x_scale) + y2_corp = int(y2 * y_scale) + + proto_crop = protos[y1_corp:y2_corp, x1_corp:x2_corp, :] # (H, W, C) + mc = mces[i] + # Linear combination and thresholding + mask = (np.sum(proto_crop * mc[np.newaxis, np.newaxis, :], axis=2) + > mask_thresh).astype(np.uint8) + masks.append(mask) + + return masks + + +def decode_kpts(kpts_output: np.ndarray, + valid_indices: np.ndarray, + grid_size: int, + stride: int, + anchor: np.ndarray = None) -> tuple[np.ndarray, np.ndarray]: + """Decode keypoint coordinates from model output. + + This function decodes keypoint predictions from the model output tensor + into pixel coordinates using anchor points and the given stride. Each + keypoint consists of `(x, y, score)` values. + + Args: + kpts_output: Keypoint output tensor with shape `(N, 17 * 3)`, where + each keypoint is represented by `(x, y, score)`. + valid_indices: Indices of valid predictions to be decoded. + grid_size: Size of the feature map grid. + stride: Downsampling factor used to map grid coordinates to the + original image scale (e.g., 8, 16, 32). + anchor: Optional anchor center coordinates with shape `(M, 2)`. + If `None`, anchor points are generated automatically based on + `grid_size`. + + Returns: + A tuple containing: + - kpts_xy: Keypoint pixel coordinates with shape `(M, 17, 2)`. + - kpts_score: Keypoint confidence scores with shape `(M, 17, 1)`. + """ + kpts_output = kpts_output.reshape(-1, kpts_output.shape[-1]) + kpts = kpts_output[valid_indices].reshape(-1, 17, 3) # (M, 17, 3) + + if anchor is None: + anchor = gen_anchor(grid_size)[valid_indices] # (M, 2) + + # Decode x, y using anchor and stride + kpts_xy = (kpts[:, :, :2] * 2.0 + (anchor[:, None, :] - 0.5)) * stride + + # Extract score without activation (or apply sigmoid optionally) + kpts_score = kpts[:, :, 2:3] + + return kpts_xy, kpts_score + + +def decode_layer(feat: np.ndarray, + stride: int, + anchor: np.ndarray, + classes_num: int = 80) -> np.ndarray: + """Decode a single feature layer from the detection head. + + This function decodes the raw output tensor of one detection layer into + bounding box predictions in the original image scale. The decoded output + includes bounding box center coordinates, width and height, objectness + score, and per-class confidence scores. + + Args: + feat: Raw model output tensor with shape + `(1, na, h, w, 5 + classes_num)`, where `na` is the number of anchors. + stride: Stride of the feature layer relative to the input image. + anchor: Anchor sizes for this feature layer with shape `(na, 2)`, + formatted as `(width, height)`. + classes_num: Number of object classes. + + Returns: + A NumPy array of shape `(N, 5 + classes_num)` containing decoded + predictions, where `N = na * h * w`. + """ + _, _, h, w, _ = feat.shape # h/w: feature map size + + # Create coordinate grid of shape (1, 1, h, w, 2) + grid_y, grid_x = np.mgrid[0:h, 0:w] + grid = np.stack((grid_x, grid_y), axis=-1)[None, None] + + # batch sigmoid + feat_sig = sigmoid(feat[..., :5 + classes_num]) + + # Decode center offsets (dx, dy) and size (dw, dh) + dxdy = feat_sig[..., :2] + dwdh = feat_sig[..., 2:4] + obj = feat_sig[..., 4:5] + cls = feat_sig[..., 5:] + + # Compute center coordinates in original image scale + xy = (dxdy * 2. - 0.5 + grid) * stride + + # Compute width/height from anchor sizes + wh = (dwdh * 2.) ** 2 * anchor[:, None, None, :] + + # Construct final output tensor (xywh + obj + class scores) + out = np.empty((*xy.shape[:-1], 5 + classes_num), dtype=np.float32) + out[..., 0:2] = xy + out[..., 2:4] = wh + out[..., 4:5] = obj + out[..., 5:] = cls + + return out.reshape(-1, 5 + classes_num) + + +def decode_outputs(output_names: list[str], + fp32_outputs: dict[str, np.ndarray], + strides: list[int], + anchors: list[np.ndarray], + classes_num: int = 80) -> np.ndarray: + """Decode all feature maps from the model output. + + This function iterates over all detection heads, reshapes and reorders + the raw output tensors, decodes each feature map using its corresponding + stride and anchor configuration, and concatenates the results into a + single prediction tensor. + + Args: + output_names: List of output tensor names corresponding to detection heads. + fp32_outputs: Dictionary mapping output tensor names to FP32 NumPy arrays + produced by the model. + strides: List of stride values for each detection head. + anchors: List of anchor arrays for each detection head, where each element + has shape `(na, 2)`. + classes_num: Number of object classes. + + Returns: + A NumPy array of shape `(N, 5 + classes_num)` containing all decoded + predictions, where `N` is the total number of predictions across + all detection heads. + """ + decoded = [] + for i, key in enumerate(output_names): + out = fp32_outputs[key] + h, w = out.shape[1:3] + # Reshape and transpose to (1, na, h, w, c) + feat = out.reshape(1, h, w, 3, 5 + classes_num).transpose(0, 3, 1, 2, 4) + decoded.append(decode_layer(feat, strides[i], anchors[i], classes_num)) + return np.concatenate(decoded, axis=0) + + +def get_bounding_boxes(dilated_polys: list[np.ndarray], min_area: float) -> list[np.ndarray]: + """Extract minimum-area bounding boxes from polygon contours. + + This function computes the minimum-area bounding rectangle for each + polygon contour and filters out boxes whose area is smaller than the + specified threshold. + + Args: + dilated_polys: List of polygon contours. Each element is a NumPy array + with shape `(N, 1, 2)`. + min_area: Minimum area threshold used to filter out small bounding boxes. + + Returns: + A list of bounding boxes. Each bounding box is a NumPy array with + shape `(4, 2)` and integer coordinates. + """ + boxes_list = [] + for cnt in dilated_polys: + if cv2.contourArea(cnt) < min_area: + continue # Skip small contours + rect = cv2.minAreaRect(cnt) + box = cv2.boxPoints(rect).astype(np.int_) + boxes_list.append(box) + return boxes_list + + +def resize_masks_to_boxes(masks: list[np.ndarray], + boxes: list[tuple[float, float, float, float]], + img_w: int, img_h: int, + interpolation: int = cv2.INTER_LANCZOS4, + do_morph: bool = True) -> list[np.ndarray]: + """Resize binary masks to fit inside their corresponding bounding boxes. + + This function resizes each binary mask to match the size of its + corresponding bounding box. Optionally, a morphological open operation + can be applied to smooth the resized masks. + + Args: + masks: List of binary mask arrays with shape `(H, W)` and dtype + `uint8`. + boxes: List of bounding boxes in `(x1, y1, x2, y2)` format. + img_w: Width of the original image. + img_h: Height of the original image. + interpolation: OpenCV interpolation method used for resizing. + do_morph: Whether to apply a morphological open operation to smooth + the resized masks. + + Returns: + A list of resized binary masks, each cropped to the size of its + corresponding bounding box. + """ + resized_masks = [] + for mask, (x1, y1, x2, y2) in zip(masks, boxes): + # Clamp coordinates to image bounds + x1, y1 = max(int(x1), 0), max(int(y1), 0) + x2, y2 = min(int(x2), img_w), min(int(y2), img_h) + + target_w = max(x2 - x1, 1) + target_h = max(y2 - y1, 1) + + resized = cv2.resize(mask, (target_w, target_h), interpolation=interpolation) + + if do_morph: + # Apply morphological filtering + resized = cv2.morphologyEx(resized, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8)) + + resized_masks.append(resized) + + return resized_masks + + +def scale_keypoints_to_original_image(kpts_xy: np.ndarray, + kpts_score: np.ndarray, + img_w: int, img_h: int, + input_w: int, input_h: int, + resize_type: int = 1) -> tuple[np.ndarray, np.ndarray]: + """Scale keypoints back to the original image coordinates. + + This function maps keypoint coordinates from the model input space back + to the original image resolution. Both direct resize and letterbox resize + strategies are supported. + + Args: + kpts_xy: Keypoint coordinates with shape `(M, 17, 2)` in the model + input space. + kpts_score: Keypoint confidence scores with shape `(M, 17, 1)`. + img_w: Width of the original image. + img_h: Height of the original image. + input_w: Width of the model input. + input_h: Height of the model input. + resize_type: Resize strategy used during preprocessing. + - 0: Direct resize. + - 1: Letterbox resize with padding. + + Returns: + A tuple containing: + - scaled_kpts: Keypoints scaled to the original image coordinates + with shape `(M, 17, 2)`. + - kpts_score: Keypoint confidence scores with shape `(M, 17, 1)`. + """ + scaled_kpts = kpts_xy.copy() + + if resize_type == 0: + scale_x = img_w / input_w + scale_y = img_h / input_h + scaled_kpts[..., 0] *= scale_x + scaled_kpts[..., 1] *= scale_y + + elif resize_type == 1: + scale = min(input_w / img_w, input_h / img_h) + pad_w = (input_w - img_w * scale) / 2 + pad_h = (input_h - img_h * scale) / 2 + scaled_kpts[..., 0] = (scaled_kpts[..., 0] - pad_w) / scale + scaled_kpts[..., 1] = (scaled_kpts[..., 1] - pad_h) / scale + + else: + raise ValueError("resize_type must be 0 or 1") + + # Clip to image bounds + scaled_kpts[..., 0] = np.clip(scaled_kpts[..., 0], 0, img_w) + scaled_kpts[..., 1] = np.clip(scaled_kpts[..., 1], 0, img_h) + + return scaled_kpts, kpts_score + + +def crop_and_rotate_image(img: np.ndarray, box: np.ndarray) -> np.ndarray: + """Crop and rotate a region from an image using a rotated bounding box. + + This function extracts a rotated rectangular region defined by a + four-point bounding box. It applies a perspective transformation to + obtain an upright cropped image and optionally rotates the result + based on the bounding box angle. + + Args: + img: Input image array with shape `(H, W, C)` and dtype `uint8`. + box: Rotated bounding box represented as a four-point array with + shape `(4, 2)`. + + Returns: + A NumPy array representing the cropped and rotated image region. + """ + rect = cv2.minAreaRect(box) + box = cv2.boxPoints(rect).astype(np.intp) + width = int(rect[1][0]) + height = int(rect[1][1]) + angle = rect[2] + + src_pts = box.astype("float32") + dst_pts = np.array([[0, height - 1], + [0, 0], + [width - 1, 0], + [width - 1, height - 1]], dtype="float32") + + # Apply perspective transform + M = cv2.getPerspectiveTransform(src_pts, dst_pts) + warped = cv2.warpPerspective(img, M, (width, height)) + + # Rotate if angle is large + if angle >= 45: + rotated = cv2.rotate(warped, cv2.ROTATE_90_CLOCKWISE) + else: + rotated = warped + + print("width:", rotated.shape[1], "height:", rotated.shape[0]) + return rotated diff --git a/tools/vision-course-preset/model-zoo/utils/py_utils/preprocess.py b/tools/vision-course-preset/model-zoo/utils/py_utils/preprocess.py new file mode 100644 index 0000000..41fabee --- /dev/null +++ b/tools/vision-course-preset/model-zoo/utils/py_utils/preprocess.py @@ -0,0 +1,229 @@ +# Copyright (c) 2025 D-Robotics Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# flake8: noqa: E501 + +""" +preprocess: Preprocessing utilities for vision model inputs. + +This module provides reusable preprocessing helpers to convert raw inputs +into model-ready representations, including image resizing strategies and +format conversions. It is designed to be shared across multiple samples and +runtimes to keep preprocessing consistent and easy to maintain. + +Key Features: + - Convert between common image formats and planar representations. + - Resize inputs with optional aspect-ratio preservation (e.g., letterbox). + - Split and manipulate NV12 data into components suitable for inference. + +Notes: + - The module focuses on generic preprocessing building blocks; task- or + model-specific preprocessing policies should be implemented at the + sample level. + - Helper coverage may evolve as new input formats and models are added. +""" + + +import cv2 +import numpy as np + + +def bgr_to_nv12_planes(image: np.ndarray) -> tuple: + """Convert a BGR image to NV12 format (Y and UV planes). + + This function converts a BGR image into NV12 format by first transforming + it into planar YUV420 (I420) format and then interleaving the U and V + planes to form the UV plane. + + Args: + image: Input BGR image as a NumPy array with shape `(H, W, 3)`. + + Returns: + A tuple containing: + - y: Y plane with shape `(1, H, W, 1)`. + - uv: UV plane with shape `(1, H/2, W/2, 2)`. + """ + height, width = image.shape[:2] + area = height * width + + # Convert to planar YUV I420 format + yuv420p = cv2.cvtColor(image, cv2.COLOR_BGR2YUV_I420) + yuv420p = yuv420p.reshape((area * 3 // 2,)) + + # Extract Y, U, V planes + y = yuv420p[:area].reshape((height, width)) + u = yuv420p[area:area + area // 4].reshape((height // 2, width // 2)) + v = yuv420p[area + area // 4:].reshape((height // 2, width // 2)) + + # Interleave U and V to form UV plane + uv = np.stack((u, v), axis=-1) + + # Add batch and channel dimensions + y = y[np.newaxis, :, :, np.newaxis] + uv = uv[np.newaxis, :, :, :] + + return y, uv + + +def resized_image(img: np.ndarray, input_W: int, input_H: int, + resize_type: int = 1, + interpolation=cv2.INTER_NEAREST) -> np.ndarray: + """Resize an image using direct resize or letterbox strategy. + + This function resizes the input image to the target resolution required + by the model. It supports either direct resizing or letterbox resizing + with padding to preserve the aspect ratio. + + Args: + img: Input image array with shape `(H, W, 3)`. + input_W: Target image width. + input_H: Target image height. + resize_type: Resize strategy used during preprocessing. + - 0: Direct resize. + - 1: Letterbox resize with padding to preserve aspect ratio. + interpolation: OpenCV interpolation method used for resizing. + + Returns: + The resized image with shape `(input_H, input_W, 3)`. + + Raises: + ValueError: If an invalid `resize_type` is provided. + """ + img_h, img_w = img.shape[:2] + + if resize_type == 0: # Direct resize + resized = cv2.resize(img, (input_W, input_H), interpolation=interpolation) + elif resize_type == 1: # Letterbox resize (preserve aspect ratio) + scale = min(input_H / img_h, input_W / img_w) + new_w, new_h = int(img_w * scale), int(img_h * scale) + resized = cv2.resize(img, (new_w, new_h)) + + pad_w = input_W - new_w + pad_h = input_H - new_h + left, right = pad_w // 2, pad_w - pad_w // 2 + top, bottom = pad_h // 2, pad_h - pad_h // 2 + + # Pad image with gray (127,127,127) + resized = cv2.copyMakeBorder(resized, top, bottom, left, right, + borderType=cv2.BORDER_CONSTANT, + value=(127, 127, 127)) + else: + raise ValueError(f"Invalid resize_type: {resize_type}, must be 0 or 1") + + return resized + + +def split_nv12_bytes(nv12_bytes: bytes, width: int, height: int) -> tuple: + """Split raw NV12 bytes into Y and UV planes. + + This function parses a raw NV12-encoded byte stream and separates it + into the Y (luma) plane and the interleaved UV (chroma) plane. + + Args: + nv12_bytes: Raw NV12-encoded byte stream. + width: Image width. + height: Image height. + + Returns: + A tuple containing: + - y: Y plane with shape `(H, W)` and dtype `uint8`. + - uv: Interleaved UV plane with shape `(H/2, W)` and dtype `uint8`. + """ + y_size = width * height + uv_size = y_size // 2 + nv12_array = np.frombuffer(nv12_bytes, dtype=np.uint8) + + y = nv12_array[:y_size].reshape((height, width)) + uv = nv12_array[y_size:y_size + uv_size].reshape((height // 2, width)) + + return y, uv + + +def letterbox_resize_gray(gray_img: np.ndarray, target_w: int, target_h: int) -> np.ndarray: + """Resize a grayscale image using letterbox (aspect-ratio preserving) strategy. + + This function resizes a grayscale image while preserving its aspect ratio, + then pads the resized image with a constant gray value to match the target + resolution. + + Args: + gray_img: Input grayscale image with shape `(H, W)`. + target_w: Target image width. + target_h: Target image height. + + Returns: + The resized and padded grayscale image with shape + `(target_h, target_w)`. + """ + h, w = gray_img.shape + scale = min(target_w / w, target_h / h) + new_w, new_h = int(w * scale), int(h * scale) + resized = cv2.resize(gray_img, (new_w, new_h)) + + pad_w = target_w - new_w + pad_h = target_h - new_h + top, bottom = pad_h // 2, pad_h - pad_h // 2 + left, right = pad_w // 2, pad_w - pad_w // 2 + + # Pad with value 127 (gray) + padded = cv2.copyMakeBorder(resized, top, bottom, left, right, + borderType=cv2.BORDER_CONSTANT, value=127) + return padded + + +def resize_nv12_yuv(y: np.ndarray, uv: np.ndarray, + target_h: int = 672, target_w: int = 672, + keep_ratio: bool = True) -> tuple: + """Resize the Y and UV planes of an NV12 image to a target resolution. + + This function resizes the luma (Y) and chroma (UV) planes of an NV12 image. + When `keep_ratio` is enabled, letterbox resizing is applied to preserve + the original aspect ratio; otherwise, direct resizing is used. + + Args: + y: Y (luma) plane with shape `(H, W)`. + uv: Interleaved UV (chroma) plane with shape `(H/2, W)`. + target_h: Target image height. + target_w: Target image width. + keep_ratio: Whether to preserve the aspect ratio using letterbox + resizing. If `False`, direct resizing is applied. + + Returns: + A tuple containing: + - y_resized: Resized Y plane with shape `(target_h, target_w)`. + - uv_resized: Resized UV plane with shape + `(target_h/2, target_w/2, 2)`. + """ + # Resize Y + if keep_ratio: + y_resized = letterbox_resize_gray(y, target_w, target_h) + else: + y_resized = cv2.resize(y, (target_w, target_h)) + + # Split UV into U and V components + u = uv[:, 0::2] + v = uv[:, 1::2] + + # Resize U and V separately + if keep_ratio: + u_resized = letterbox_resize_gray(u, target_w // 2, target_h // 2) + v_resized = letterbox_resize_gray(v, target_w // 2, target_h // 2) + else: + u_resized = cv2.resize(u, (target_w // 2, target_h // 2)) + v_resized = cv2.resize(v, (target_w // 2, target_h // 2)) + + # Re-stack into UV plane + uv_resized = np.stack((u_resized, v_resized), axis=-1) + + return y_resized, uv_resized diff --git a/tools/vision-course-preset/model-zoo/utils/py_utils/visualize.py b/tools/vision-course-preset/model-zoo/utils/py_utils/visualize.py new file mode 100644 index 0000000..604c8b5 --- /dev/null +++ b/tools/vision-course-preset/model-zoo/utils/py_utils/visualize.py @@ -0,0 +1,241 @@ +# Copyright (c) 2025 D-Robotics Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +visualize: Visualization utilities for model results. + +This module provides reusable helpers for rendering model outputs onto images +and logging detailed results. It includes generic drawing functions and +specific wrappers for the YOLO26 model series. +""" + +import cv2 +import numpy as np +import logging +import math + +# Use a consistent logger +logger = logging.getLogger("YOLO26") + +# List of predefined RGB color tuples used for bounding box visualization. +rdk_colors = [ + (56, 56, 255), (151, 157, 255), (31, 112, 255), (29, 178, 255), + (49, 210, 207), (10, 249, 72), (23, 204, 146), (134, 219, 61), + (52, 147, 26), (187, 212, 0), (168, 153, 44), (255, 194, 0), + (147, 69, 52), (255, 115, 100), (236, 24, 0), (255, 56, 132), + (133, 0, 82), (255, 56, 203), (200, 149, 255), (199, 55, 255)] + +# Standard human pose skeleton structure (COCO format) +COCO_SKELETON = [ + [16, 14], [14, 12], [17, 15], [15, 13], [12, 13], [6, 12], [7, 13], [6, 7], + [6, 8], [7, 9], [8, 10], [9, 11], [2, 3], [1, 2], [1, 3], [2, 4], [3, 5], + [4, 6], [5, 7] +] + + +# ============================================================================== +# 1. Generic Drawing Functions (Numpy Array Based) +# ============================================================================== + +def draw_boxes(image: np.ndarray, boxes: np.ndarray, cls_ids: np.ndarray, + scores: np.ndarray, class_names: list, colors: list) -> np.ndarray: + """Draw bounding boxes with class names and scores.""" + for box, cls_id, score in zip(boxes, cls_ids, scores): + x1, y1, x2, y2 = map(int, box) + color = colors[cls_id % len(colors)] + name = class_names[cls_id] if cls_id < len(class_names) else str(cls_id) + label = f"{name} {score:.2f}" + + cv2.rectangle(image, (x1, y1), (x2, y2), color, thickness=2) + cv2.putText(image, label, (x1, max(y1 - 5, 0)), + fontFace=cv2.FONT_HERSHEY_SIMPLEX, + fontScale=0.5, color=color, thickness=1) + return image + + +def draw_detection_results(image: np.ndarray, boxes: np.ndarray, cls_ids: np.ndarray, + scores: np.ndarray, class_names: list, + colors: list = rdk_colors) -> np.ndarray: + """Log and draw detection results from `(boxes, scores, cls_ids)` arrays.""" + for box, cls_id, score in zip(boxes, cls_ids, scores): + x1, y1, x2, y2 = map(int, box) + name = class_names[cls_id] if cls_id < len(class_names) else str(cls_id) + logger.info(f"({x1}, {y1}, {x2}, {y2}) -> {name}: {score:.2f}") + return draw_boxes(image, boxes, cls_ids, scores, class_names, colors) + + +def draw_masks(image: np.ndarray, boxes: np.ndarray, masks: list, + cls_ids: list, colors: list, alpha: float = 0.3) -> None: + """Overlay semi-transparent instance masks.""" + for class_id, box, mask in zip(cls_ids, boxes, masks): + x1, y1, x2, y2 = map(int, box) + if mask.size == 0 or x2 <= x1 or y2 <= y1: + continue + + region = image[y1:y2, x1:x2] + mask_area = mask.astype(bool) + if not np.any(mask_area): + continue + + color = colors[class_id % len(colors)] + color_patch = np.zeros(region.shape, dtype=np.uint8) + color_patch[:] = color + + region[mask_area] = ( + (1 - alpha) * region[mask_area] + alpha * color_patch[mask_area] + ).astype(np.uint8) + + +def draw_rotated_boxes(img: np.ndarray, rrects: list, ids: list, scores: list, + class_names: list, colors: list, thickness: int = 2) -> np.ndarray: + """Draw rotated bounding boxes (OBB).""" + for rrect, cid, score in zip(rrects, ids, scores): + cx, cy, w, h, a = rrect + pts = cv2.boxPoints(((cx, cy), (w, h), a * 180 / math.pi)).astype(np.int32) + color = colors[cid % len(colors)] + name = class_names[cid] if cid < len(class_names) else str(cid) + label = f"{name}: {score:.2f}" + + cv2.drawContours(img, [pts], 0, color, thickness) + lx, ly = pts[0] + (lw, lh), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1) + cv2.rectangle(img, (lx, ly - lh - 5), (lx + lw, ly), color, cv2.FILLED) + cv2.putText(img, label, (lx, ly - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1) + return img + + +def draw_pose(img: np.ndarray, boxes: np.ndarray, kpts: np.ndarray, + skeleton: list = COCO_SKELETON, kpt_conf_thres: float = 0.5, + scores: np.ndarray = None, class_ids: np.ndarray = None, + colors: list = rdk_colors) -> np.ndarray: + """Draw pose estimation results.""" + if scores is None: scores = np.ones(len(boxes)) + if class_ids is None: class_ids = np.zeros(len(boxes), dtype=int) + + for i in range(len(boxes)): + x1, y1, x2, y2 = map(int, boxes[i]) + color = colors[class_ids[i] % len(colors)] + cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2) # Pose boxes usually green + + label = f"person: {scores[i]:.2f}" + (lw, lh), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1) + cv2.rectangle(img, (x1, y1 - lh - 10), (x1 + lw, y1), (0, 255, 0), cv2.FILLED) + cv2.putText(img, label, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1) + + for x, y, conf in kpts[i]: + if conf >= kpt_conf_thres: + cv2.circle(img, (int(x), int(y)), 3, (0, 0, 255), -1) + + for sk in skeleton: + idx1, idx2 = sk[0] - 1, sk[1] - 1 + if idx1 < len(kpts[i]) and idx2 < len(kpts[i]): + p1, p2 = kpts[i][idx1], kpts[i][idx2] + if p1[2] >= kpt_conf_thres and p2[2] >= kpt_conf_thres: + cv2.line(img, (int(p1[0]), int(p1[1])), (int(p2[0]), int(p2[1])), (255, 0, 0), 1) + return img + + +def draw_classification(img: np.ndarray, results: list, labels: dict, + pos: tuple = (10, 30), scale: float = 0.8, + color: tuple = (0, 255, 0), thickness: int = 2) -> np.ndarray: + """Draw Top-K results on image.""" + for i, (cid, score) in enumerate(results): + label_str = labels.get(cid, str(cid)) if isinstance(labels, dict) else labels[cid] if cid < len(labels) else str(cid) + text = f"Rank {i+1}: Class {cid} ({label_str}) | Score: {score:.4f}" + cv2.putText(img, text, (pos[0], pos[1] + i * 30), cv2.FONT_HERSHEY_SIMPLEX, scale, color, thickness) + return img + + +# ============================================================================== +# 2. YOLO26 Specific Wrappers (Result Dict/Tuple Based + Logging) +# ============================================================================== + +def draw_detect_yolo26(img: np.ndarray, boxes: np.ndarray, cls_ids: np.ndarray, + scores: np.ndarray, class_names: list, + colors: list = rdk_colors) -> np.ndarray: + """Draw YOLO26 detection results from `(boxes, scores, cls_ids)` arrays.""" + return draw_detection_results(img, boxes, cls_ids, scores, class_names, colors) + + +def draw_seg_yolo26(img: np.ndarray, results: list, class_names: list, + colors: list = rdk_colors) -> np.ndarray: + """Draw YOLO26 segmentation results and log details.""" + if not results: return img + + boxes, ids, scores = [], [], [] + for r in results: + x1, y1, x2, y2 = map(int, r['box']) + cid, score = int(r['id']), r['score'] + name = class_names[cid] if cid < len(class_names) else str(cid) + logger.info(f"({x1}, {y1}, {x2}, {y2}) -> {name}: {score:.2f}") + + boxes.append([x1, y1, x2, y2]) + ids.append(cid) + scores.append(score) + + if r['mask'].size == 0: + continue + + mask = r['mask'].astype(bool) + if mask.shape[:2] != img.shape[:2]: + full_mask = np.zeros(img.shape[:2], dtype=bool) + h = min(mask.shape[0], img.shape[0]) + w = min(mask.shape[1], img.shape[1]) + full_mask[:h, :w] = mask[:h, :w] + mask = full_mask + + color = np.array(colors[cid % len(colors)], dtype=np.uint8) + color_patch = np.zeros_like(img, dtype=np.uint8) + color_patch[:] = color + img[mask] = ((1 - 0.3) * img[mask] + 0.3 * color_patch[mask]).astype(np.uint8) + + draw_boxes(img, np.array(boxes), np.array(ids), np.array(scores), class_names, colors) + return img + + +def draw_obb_yolo26(img: np.ndarray, results: list, class_names: list, + colors: list = rdk_colors) -> np.ndarray: + """Draw YOLO26 OBB results and log details.""" + if not results: return img + + rrects, ids, scores = [], [], [] + for r in results: + cid, score = int(r['id']), r['score'] + name = class_names[cid] if cid < len(class_names) else str(cid) + logger.info(f"{name}: {score:.2f} | Angle: {r['rrect'][4] * 180 / math.pi:.1f} deg") + rrects.append(r['rrect']); ids.append(cid); scores.append(score) + + return draw_rotated_boxes(img, rrects, ids, scores, class_names, colors) + + +def draw_pose_yolo26(img: np.ndarray, results: list, skeleton: list = COCO_SKELETON, + kpt_conf_thres: float = 0.5) -> np.ndarray: + """Draw YOLO26 pose results and log details.""" + if not results: return img + + boxes, kpts, scores = [], [], [] + for r in results: + x1, y1, x2, y2 = map(int, r['box']) + logger.info(f"({x1}, {y1}, {x2}, {y2}) -> person: {r['score']:.2f}") + boxes.append(r['box']); kpts.append(r['kpts']); scores.append(r['score']) + + return draw_pose(img, np.array(boxes), np.array(kpts), skeleton, kpt_conf_thres, scores=np.array(scores)) + + +def draw_cls_yolo26(img: np.ndarray, results: list, labels: dict) -> np.ndarray: + """Log YOLO26 classification results (returns image unchanged).""" + for i, (cid, score) in enumerate(results): + label_str = labels.get(cid, str(cid)) if isinstance(labels, dict) else labels[cid] if cid < len(labels) else str(cid) + logger.info(f"Rank {i+1}: Class {cid} ({label_str}) | Score: {score:.4f}") + return img diff --git a/tools/vision-workshop-local.mts b/tools/vision-workshop-local.mts index 660e7e0..2add18a 100644 --- a/tools/vision-workshop-local.mts +++ b/tools/vision-workshop-local.mts @@ -24,7 +24,7 @@ if (config.adminCredentialFile !== undefined) { } // Trusted optional dependency paths, never accepted from a task/tool argument. if (config.calibration) { - for (const [key, env] of Object.entries({ ispstudioRoot: 'RDK_VISION_ISPSTUDIO_ROOT', ispcalRepository: 'RDK_VISION_ISPCAL_REPOSITORY', pythonExecutable: 'RDK_VISION_CALIBRATION_PYTHON' })) { + for (const [key, env] of Object.entries({ ispstudioRoot: 'RDK_VISION_ISPSTUDIO_ROOT', ispcalRepository: 'RDK_VISION_ISPCAL_REPOSITORY', pythonExecutable: 'RDK_VISION_CALIBRATION_PYTHON', scriptPath: 'RDK_VISION_CALIBRATION_SCRIPT_PATH' })) { if (config.calibration[key] !== undefined) { if (typeof config.calibration[key] !== 'string' || !path.isAbsolute(config.calibration[key]) || /[\x00-\x1f\x7f]/.test(config.calibration[key])) throw new Error('Invalid calibration dependency path'); process.env[env] = config.calibration[key]; diff --git a/tools/vision-workshop-quickstart.mjs b/tools/vision-workshop-quickstart.mjs new file mode 100644 index 0000000..30641fa --- /dev/null +++ b/tools/vision-workshop-quickstart.mjs @@ -0,0 +1,1113 @@ +#!/usr/bin/env node +/** + * One-command quickstart for the RDK Vision Pipeline Workshop on a stock official + * RDKOS 3.5.0 RDK X5 board. + * + * Works both inside the d-obs source tree and inside a standalone packaged + * quickstart bundle (zero git clone / zero node_modules on the trainee's PC). + */ +import { createHash, randomBytes } from 'node:crypto'; +import { spawn, spawnSync } from 'node:child_process'; +import { closeSync, existsSync, openSync, realpathSync } from 'node:fs'; +import { chmod, copyFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'; +import { createServer } from 'node:net'; +import { homedir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url)); +const SSH_ALIAS = 'rdk-x5-workshop'; + +const BOARD_TOOL_FILES = [ + 'vision-x5-board-bootstrap.py', + 'vision-x5-preflight.py', + 'vision-x5-camera.py', + 'vision-x5-frame.py', + 'vision-x5-isp.py', + 'vision-x5-bpu-preview.py', + 'vision-x5-calibration.py', + 'vision-camera-systemd.py', +]; + +const NATIVE_SOURCE_FILES = [ + 'x5_camera_backend.c', + 'x5_camera_backend.h', + 'x5_isp_modules.inc.c', + 'x5_isp_module_control.inc.c', + 'x5_isp_replay.inc.c', + 'x5_isp_feedback.inc.c', + 'x5_gpio_permission_wait.c', + 'x5_factory_profiles.c', + 'Makefile', + 'README.md', +]; + +const COURSE_DEVICE_FILES = [ + 'x5-course-detect.py', + 'x5-station-bridge.py', +]; + +const REMOTE_SYNC_SCRIPT = ` +import base64, hashlib, json, os, sys +from pathlib import Path + +payload = json.load(sys.stdin) +root = Path(payload["installDir"]).expanduser().resolve() +root.mkdir(parents=True, exist_ok=True) +written = [] +for entry in payload["files"]: + rel = entry["path"] + if rel.startswith("/") or ".." in Path(rel).parts: + raise ValueError("invalid_relative_path:" + rel) + raw = base64.b64decode(entry["base64"], validate=True) + if hashlib.sha256(raw).hexdigest() != entry["sha256"]: + raise ValueError("payload_sha256_mismatch:" + rel) + target = root / rel + target.parent.mkdir(parents=True, exist_ok=True) + tmp = target.with_suffix(target.suffix + ".part") + tmp.write_bytes(raw) + os.chmod(tmp, int(entry.get("mode", 0o644))) + tmp.replace(target) + written.append(rel) +print(json.dumps({"ok": True, "installDir": str(root), "count": len(written)})) +`.trim(); + +export function usageText() { + return [ + 'RDK 视觉 Pipeline Workshop · 官方镜像一键初始化与启动工具', + '', + '用法:', + ' node vision-workshop-quickstart.mjs [start|status|stop] [选项]', + '', + '子命令:', + ' start (默认) 一键配置板端与本机服务,后台常驻后自动退出(不占窗口)', + ' status 检查后台隧道、本机相机后端与板端连通状态', + ' stop 停止后台本机相机后端与 SSH 隧道', + '', + '常用选项:', + ' --host 板卡地址(默认 192.168.128.10,Type-C 默认地址)', + ' --user 板卡 SSH 用户(默认 sunrise)', + ' --ssh-port 板卡 SSH 端口(默认 22)', + ' --csi-port IMX415 所接 CSI 口(默认 auto 自动探测,回退 CSI2)', + ' --lanes IMX415 MIPI lane 数(默认 auto 自动探测,回退 4-lane)', + ' --camera-port 板端相机 loopback 端口(默认 3217)', + ' --local-port 本机轻量相机服务端口(默认 4310)', + ' --install-dir 板端安装目录(默认 /home//.rdk-vision-workshop)', + ' --service-mode auto | systemd | user-process(默认 auto)', + ' --classroom-config 课堂配置 JSON(可含 model / robogoProfile / courseAssets)', + ' --model-url Gamma 候选模型网关 Base URL(覆盖课堂配置)', + ' --model-key Gamma 候选模型 API Key(或通过 RDK_VISION_AI_KEY 传入)', + ' --model-name Gamma 候选模型名称', + ' --skip-board-push 跳过板端推包与安装,直接复用板端现有服务并重建隧道', + ' --rebuild-native 强制在板端重新编译原生 C 库', + ' --allow-unconnected-camera 允许未接 IMX415 时继续完成预演部署', + ' --force-config 如已存在非本脚本生成的 connection.json,备份后覆盖', + ' --foreground 前台驻留(默认后台常驻后退出,方便在终端或 Studio 里跑完即用)', + ' --check-only 完成初始化与自检后停止并退出', + ' --json 配合 status 输出 JSON', + ' --help 显示帮助', + ].join('\n'); +} + +export function parseArgs(argv) { + const options = { + command: 'start', + host: '192.168.128.10', + user: 'sunrise', + sshPort: 22, + csiPort: 'auto', + lanes: 'auto', + cameraPort: 3217, + localPort: 4310, + installDir: undefined, + serviceMode: 'auto', + classroomConfig: undefined, + modelUrl: process.env.RDK_VISION_AI_URL || undefined, + modelKey: process.env.RDK_VISION_AI_KEY || undefined, + modelName: process.env.RDK_VISION_AI_MODEL || undefined, + configDir: path.join(homedir(), '.config', 'rdk-vision-workshop', 'quickstart'), + cameraConfig: process.env.RDK_CAMERA_WORKSHOP_CONFIG || path.join(homedir(), '.config', 'rdk-camera-workshop', 'connection.json'), + robogoProfilePath: process.env.RDK_VISION_ROBOGO_TRAINING_PROFILE || path.join(homedir(), '.config', 'rdk-vision-workshop', 'training-profile.json'), + skipBoardPush: false, + rebuildNative: false, + allowUnconnectedCamera: false, + forceConfig: false, + foreground: false, + checkOnly: false, + json: false, + help: false, + }; + const intFlag = (name, value, min, max) => { + const parsed = Number(value); + if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max) { + throw new Error(`invalid_flag:${name}`); + } + return parsed; + }; + let startIndex = 0; + if (argv[0] && ['start', 'status', 'stop'].includes(argv[0])) { + options.command = argv[0]; + startIndex = 1; + } + for (let i = startIndex; i < argv.length; i += 1) { + const flag = argv[i]; + const next = () => { + if (i + 1 >= argv.length) throw new Error(`missing_flag_value:${flag}`); + i += 1; + return argv[i]; + }; + if (flag === '--help' || flag === '-h') options.help = true; + else if (flag === '--host') options.host = next(); + else if (flag === '--user') options.user = next(); + else if (flag === '--ssh-port') options.sshPort = intFlag(flag, next(), 1, 65535); + else if (flag === '--csi-port') { + const raw = next(); + if (raw === 'auto') options.csiPort = 'auto'; + else { + const value = intFlag(flag, raw, 0, 2); + if (value !== 0 && value !== 2) throw new Error('invalid_flag:--csi-port'); + options.csiPort = value; + } + } else if (flag === '--lanes') { + const raw = next(); + if (raw === 'auto') options.lanes = 'auto'; + else { + const value = intFlag(flag, raw, 2, 4); + if (value !== 2 && value !== 4) throw new Error('invalid_flag:--lanes'); + options.lanes = value; + } + } else if (flag === '--camera-port') options.cameraPort = intFlag(flag, next(), 1024, 65535); + else if (flag === '--local-port') options.localPort = intFlag(flag, next(), 1024, 65535); + else if (flag === '--install-dir') options.installDir = next(); + else if (flag === '--service-mode') { + const mode = next(); + if (!['auto', 'systemd', 'user-process'].includes(mode)) throw new Error('invalid_flag:--service-mode'); + options.serviceMode = mode; + } else if (flag === '--classroom-config') options.classroomConfig = path.resolve(next()); + else if (flag === '--model-url') options.modelUrl = next(); + else if (flag === '--model-key') options.modelKey = next(); + else if (flag === '--model-name') options.modelName = next(); + else if (flag === '--config-dir') options.configDir = path.resolve(next()); + else if (flag === '--camera-config') options.cameraConfig = path.resolve(next()); + else if (flag === '--skip-board-push') options.skipBoardPush = true; + else if (flag === '--rebuild-native') options.rebuildNative = true; + else if (flag === '--allow-unconnected-camera') options.allowUnconnectedCamera = true; + else if (flag === '--force-config') options.forceConfig = true; + else if (flag === '--foreground') options.foreground = true; + else if (flag === '--background' || flag === '--daemon') options.foreground = false; + else if (flag === '--check-only') options.checkOnly = true; + else if (flag === '--json') options.json = true; + else throw new Error(`unknown_flag:${flag}`); + } + if (!/^[A-Za-z0-9._:-]{1,128}$/.test(options.host)) throw new Error('invalid_flag:--host'); + if (!/^[a-z_][a-z0-9_-]{0,31}$/.test(options.user)) throw new Error('invalid_flag:--user'); + if (!options.installDir) { + options.installDir = options.user === 'root' ? '/opt/rdk-vision-workshop' : `/home/${options.user}/.rdk-vision-workshop`; + } + if (!options.installDir.startsWith('/') || options.installDir.includes('..')) { + throw new Error('invalid_flag:--install-dir'); + } + return options; +} + +export async function fileExists(target) { + try { + await stat(target); + return true; + } catch { + return false; + } +} + +export async function resolveRuntimeLayout(scriptDir = SCRIPT_DIR) { + const portableServer = path.join(scriptDir, 'runtime', 'vision-workshop-local.mjs'); + const portablePayload = path.join(scriptDir, 'board-payload'); + if (await fileExists(portableServer) && await fileExists(portablePayload)) { + const defaultClassroom = path.join(scriptDir, 'classroom.json'); + return { + mode: 'portable', + root: scriptDir, + serverCommand: [process.execPath, portableServer], + boardPayloadDir: portablePayload, + calibrationScriptPath: path.join(portablePayload, 'vision-x5-calibration.py'), + stationBridgeClientPath: path.join(portablePayload, 'x5-station-bridge.py'), + defaultClassroomConfig: (await fileExists(defaultClassroom)) ? defaultClassroom : undefined, + }; + } + const repoRoot = path.resolve(scriptDir, '..'); + const repoServer = path.join(repoRoot, 'tools', 'vision-workshop-local.mts'); + if (await fileExists(repoServer)) { + return { + mode: 'repo', + root: repoRoot, + serverCommand: [process.execPath, '--import', 'tsx', repoServer], + toolsDir: path.join(repoRoot, 'tools'), + deviceDir: path.join(repoRoot, 'plugins', 'rdk-vision-workshop', 'device'), + calibrationScriptPath: path.join(repoRoot, 'tools', 'vision-x5-calibration.py'), + stationBridgeClientPath: path.join(repoRoot, 'plugins', 'rdk-vision-workshop', 'device', 'x5-station-bridge.py'), + defaultClassroomConfig: undefined, + }; + } + throw new Error('quickstart_runtime_layout_not_found'); +} + +export async function writePrivateFile(filePath, content, mode = 0o600) { + const dir = path.dirname(filePath); + await mkdir(dir, { recursive: true, mode: 0o700 }); + if (process.platform !== 'win32') { + await chmod(dir, 0o700).catch(() => {}); + } + const tmp = `${filePath}.${process.pid}.${Date.now()}.tmp`; + await writeFile(tmp, content, { mode }); + if (process.platform !== 'win32') { + await chmod(tmp, mode); + } + await rename(tmp, filePath); +} + +export function buildAdapterRecord(bootstrapReceipt, localCameraPort, boardToken) { + const caps = bootstrapReceipt.capabilities ?? {}; + const operations = Array.isArray(caps.operations) && caps.operations.length + ? caps.operations + : ['probe', 'pipeline_validate']; + const record = { + id: 'rdk-x5-imx415-quickstart', + label: `RDK X5 + IMX415 (${bootstrapReceipt.sensorConfig || '4lane'} CSI${bootstrapReceipt.csiPort ?? 2})`, + board: 'RDK X5', + sensorVendor: 'Sony', + sensorModel: 'IMX415', + sdkVersion: bootstrapReceipt.sdkVersion, + cameraInterface: 'MIPI CSI-2', + cameraMode: bootstrapReceipt.cameraMode, + operations, + url: `http://127.0.0.1:${localCameraPort}`, + token: boardToken, + }; + const hasPreviewOps = ['preview_start', 'preview_frame', 'preview_stop'].every(op => operations.includes(op)); + if (hasPreviewOps && Array.isArray(caps.previewModes) && caps.previewModes.length) { + record.previewModes = caps.previewModes; + } + return record; +} + +export function buildWorkbenchConfig({ localPort, stateDir, adminCredentialFile, adapter, model, calibrationScriptPath }) { + const config = { + port: localPort, + stateDir, + adminCredentialFile, + adapters: [adapter], + }; + if (model && model.baseUrl && model.apiKey && model.model) { + config.model = { baseUrl: model.baseUrl, apiKey: model.apiKey, model: model.model }; + } + if (calibrationScriptPath) { + config.calibration = { scriptPath: calibrationScriptPath }; + } + return config; +} + +export function buildCameraConnectionConfig(localPort, adminCredentialFile) { + return { + url: `http://127.0.0.1:${localPort}/api/ops/vision-workshop/mcp`, + auth: { type: 'admin', credentialFile: adminCredentialFile }, + }; +} + +export function buildBoardLauncherConfigs({ + archiveRoot, + experimentId, + detectionReceipt, + sshAlias, + sshConfigPath, + sshPort, + stationBridgeClientPath, + pythonExecutable, +}) { + if (!detectionReceipt?.ready || !detectionReceipt.presetModelSha256) { + return null; + } + if (!pythonExecutable) { + const names = process.platform === 'win32' ? ['python', 'python3'] : ['python3']; + for (const name of names) { + const probe = spawnSync(name, ['-c', 'import sys; print(sys.executable)'], { encoding: 'utf8', timeout: 5000 }); + const candidate = probe.stdout?.trim(); + if (probe.status === 0 && candidate && path.isAbsolute(candidate)) { + pythonExecutable = candidate; + break; + } + } + } + if (!pythonExecutable || !path.isAbsolute(pythonExecutable)) throw new Error('local_python3_required_for_bpu_detection'); + const clientConfig = { + sshHost: sshAlias, + sshConfig: sshConfigPath, + ...(sshPort && sshPort !== 22 ? { sshPort } : {}), + boardBridge: detectionReceipt.boardBridge, + boardConfig: detectionReceipt.boardConfig, + ...(detectionReceipt.useSudo ? { useSudo: true, boardPython: '/usr/bin/python3' } : {}), + }; + const presetClientPath = path.join(archiveRoot, 'preset-client.json'); + const launcherConfig = { + archiveRoot, + experimentId, + profiles: { + B: { + executable: pythonExecutable, + args: [stationBridgeClientPath, 'client', '--config', presetClientPath], + modelSha256: detectionReceipt.presetModelSha256, + supportsApprovedIsp: true, + supportsIspComparison: true, + }, + }, + }; + return { clientConfig, presetClientPath, launcherConfig }; +} + +export async function collectBoardPayloadFiles(layout, classroom = {}) { + const entries = []; + const addFile = async (diskPath, relPath, mode = 0o644) => { + const raw = await readFile(diskPath); + entries.push({ + path: relPath.split(path.sep).join('/'), + mode, + sha256: createHash('sha256').update(raw).digest('hex'), + base64: raw.toString('base64'), + }); + }; + const addTree = async (dirPath, relPrefix) => { + const items = (await readdir(dirPath, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name)); + for (const item of items) { + if (item.name === '__pycache__' || item.name.endsWith('.pyc') || item.name.startsWith('.')) continue; + const full = path.join(dirPath, item.name); + const rel = relPrefix ? `${relPrefix}/${item.name}` : item.name; + if (item.isDirectory()) { + await addTree(full, rel); + } else if (item.isFile()) { + const execBit = item.name.endsWith('.py') || item.name.endsWith('.sh') || item.name.endsWith('.so') ? 0o755 : 0o644; + await addFile(full, rel, execBit); + } + } + }; + + if (layout.mode === 'portable') { + await addTree(layout.boardPayloadDir, ''); + } else { + for (const file of BOARD_TOOL_FILES) { + await addFile(path.join(layout.toolsDir, file), file, 0o755); + } + for (const file of NATIVE_SOURCE_FILES) { + const full = path.join(layout.toolsDir, 'vision-x5-native', file); + if (await fileExists(full)) { + await addFile(full, `vision-x5-native/${file}`, 0o644); + } + } + for (const file of COURSE_DEVICE_FILES) { + await addFile(path.join(layout.deviceDir, file), file, 0o755); + } + } + + // Optional organizer-supplied precompiled .so binaries and preset course model assets. + if (classroom.precompiledNativeDir && await fileExists(classroom.precompiledNativeDir)) { + for (const name of ['libvision_x5_native.so', 'libvision_x5_gpio_permission_wait.so']) { + const candidate = path.join(classroom.precompiledNativeDir, name); + if (await fileExists(candidate)) { + await addFile(candidate, name, 0o755); + } + } + } + if (classroom.courseAssetsDir && await fileExists(classroom.courseAssetsDir)) { + await addTree(classroom.courseAssetsDir, 'course'); + } + return entries; +} + +async function reserveFreeLocalPort(preferredPort) { + const tryListen = port => new Promise(resolve => { + const server = createServer(); + server.once('error', () => resolve(null)); + server.listen(port, '127.0.0.1', () => { + const chosen = server.address().port; + server.close(() => resolve(chosen)); + }); + }); + return (await tryListen(preferredPort)) ?? (await tryListen(0)); +} + +function runCommandSync(cmd, args, options = {}) { + const result = spawnSync(cmd, args, { encoding: 'utf8', ...options }); + if (result.error) { + throw new Error(`${cmd}_exec_failed:${result.error.message}`); + } + return result; +} + +async function ensureLocalSshSetup({ configDir, host, user, sshPort }) { + await mkdir(configDir, { recursive: true, mode: 0o700 }); + const keyPath = path.join(configDir, 'id_ed25519'); + const pubKeyPath = `${keyPath}.pub`; + const knownHostsPath = path.join(configDir, 'known_hosts'); + const sshConfigPath = path.join(configDir, 'ssh_config'); + + if (!(await fileExists(keyPath))) { + const gen = runCommandSync('ssh-keygen', ['-t', 'ed25519', '-N', '', '-C', 'rdk-vision-workshop', '-f', keyPath]); + if (gen.status !== 0) { + throw new Error(`ssh_keygen_failed:${(gen.stderr || '').trim()}`); + } + } + if (process.platform !== 'win32') { + await chmod(keyPath, 0o600).catch(() => {}); + } + + // Pin the board's host key for strict host key checking. + const scan = runCommandSync('ssh-keyscan', ['-p', String(sshPort), '-T', '5', host]); + if (scan.status !== 0 || !scan.stdout.trim()) { + throw new Error(`board_ssh_unreachable:${host}:${sshPort}(请确认 X5 已上电、Type-C/网线已接通且 SSH 可达)`); + } + await writePrivateFile(knownHostsPath, scan.stdout.trim() + '\n', 0o600); + + const quoteIfSpace = value => (value.includes(' ') ? `"${value}"` : value); + const sshConfigText = [ + `Host ${SSH_ALIAS}`, + ` HostName ${host}`, + ` User ${user}`, + ` Port ${sshPort}`, + ` IdentityFile ${quoteIfSpace(keyPath)}`, + ' IdentitiesOnly yes', + ` UserKnownHostsFile ${quoteIfSpace(knownHostsPath)}`, + ' StrictHostKeyChecking yes', + ' ServerAliveInterval 15', + ' ServerAliveCountMax 3', + ' ConnectTimeout 8', + '', + ].join('\n'); + await writePrivateFile(sshConfigPath, sshConfigText, 0o600); + + // Test passwordless login; if not yet authorized, authorize once interactively. + const probe = runCommandSync('ssh', ['-F', sshConfigPath, '-o', 'BatchMode=yes', SSH_ALIAS, 'true']); + if (probe.status !== 0) { + const pubKey = (await readFile(pubKeyPath, 'utf8')).trim(); + console.log(`\n[1/5] 首次连接 ${user}@${host},将自动配置免密登录(若提示输入板卡密码,官方镜像默认一般为 sunrise 或 root)...`); + const authCmd = 'mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys'; + const copy = spawnSync('ssh', ['-F', sshConfigPath, '-o', 'PubkeyAuthentication=no', SSH_ALIAS, authCmd], { + input: pubKey + '\n', + stdio: ['pipe', 'inherit', 'inherit'], + }); + if (copy.status !== 0) { + throw new Error('board_ssh_key_install_failed'); + } + const recheck = runCommandSync('ssh', ['-F', sshConfigPath, '-o', 'BatchMode=yes', SSH_ALIAS, 'true']); + if (recheck.status !== 0) { + throw new Error('board_ssh_batch_auth_failed'); + } + } + return { sshConfigPath, knownHostsPath, keyPath }; +} + +function pushFilesToBoard({ sshConfigPath, installDir, files }) { + const body = JSON.stringify({ installDir, files }); + const res = runCommandSync('ssh', ['-F', sshConfigPath, '-T', '-o', 'BatchMode=yes', SSH_ALIAS, 'python3', '-c', REMOTE_SYNC_SCRIPT], { + input: body, + maxBuffer: 128 * 1024 * 1024, + }); + if (res.status !== 0) { + throw new Error(`board_payload_sync_failed:${(res.stderr || res.stdout || '').trim()}`); + } + return JSON.parse(res.stdout.trim()); +} + +function runRemoteBoardBootstrap({ sshConfigPath, options, boardToken }) { + const remoteScript = `${options.installDir}/vision-x5-board-bootstrap.py`; + const args = [ + 'python3', remoteScript, + '--install-dir', options.installDir, + '--lanes', String(options.lanes), + '--csi-port', String(options.csiPort), + '--port', String(options.cameraPort), + '--camera-user', options.user, + '--ssh-user', options.user, + '--service-mode', options.serviceMode, + '--token-stdin', + ]; + if (options.rebuildNative) args.push('--rebuild-native'); + if (options.allowUnconnectedCamera) args.push('--allow-unconnected-camera'); + + const res = runCommandSync('ssh', ['-F', sshConfigPath, '-T', '-o', 'BatchMode=yes', SSH_ALIAS, ...args], { + input: JSON.stringify({ token: boardToken }) + '\n', + maxBuffer: 16 * 1024 * 1024, + }); + let receipt; + try { + receipt = JSON.parse((res.stdout || '').trim()); + } catch { + throw new Error(`board_bootstrap_invalid_output:${(res.stderr || res.stdout || '').slice(-500)}`); + } + if (res.status !== 0 || !receipt.ok) { + const details = receipt.errors ? receipt.errors.map(item => `${item.code}: ${item.message}`).join(';') : (receipt.error || res.stderr); + throw new Error(`board_bootstrap_failed:${details}`); + } + return receipt; +} + +async function waitForHttpJson(url, headers, timeoutMs = 12000) { + const deadline = Date.now() + timeoutMs; + let lastError = 'timeout'; + while (Date.now() < deadline) { + try { + const response = await fetch(url, { headers, signal: AbortSignal.timeout(2500) }); + const data = await response.json(); + if (response.ok && data?.ok === true) return data; + lastError = `http_${response.status}`; + } catch (error) { + lastError = error.message; + } + await new Promise(resolve => setTimeout(resolve, 250)); + } + throw new Error(`endpoint_not_ready:${url}:${lastError}`); +} + +export function isPidAlive(pid) { + if (!Number.isSafeInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (error) { + return error?.code === 'EPERM'; + } +} + +export function stopPid(pid) { + if (!isPidAlive(pid)) return false; + try { + process.kill(pid, 'SIGTERM'); + return true; + } catch { + return false; + } +} + +export async function readRuntimeState(configDir) { + const file = path.join(configDir, 'runtime.json'); + if (!(await fileExists(file))) return null; + try { + return JSON.parse(await readFile(file, 'utf8')); + } catch { + return null; + } +} + +export async function stopQuickstartRuntime(configDir) { + const runtime = await readRuntimeState(configDir); + const stopped = { workbench: false, tunnel: false }; + if (runtime) { + stopped.workbench = stopPid(runtime.workbenchPid); + stopped.tunnel = stopPid(runtime.tunnelPid); + // Give processes a brief moment to release loopback ports cleanly. + if (stopped.workbench || stopped.tunnel) { + await new Promise(resolve => setTimeout(resolve, 350)); + } + await rm(path.join(configDir, 'runtime.json'), { force: true }); + } + return { hadRuntime: Boolean(runtime), stopped }; +} + +export async function inspectQuickstartStatus(configDir) { + const runtime = await readRuntimeState(configDir); + if (!runtime) { + return { running: false, reason: 'not_started' }; + } + const workbenchAlive = isPidAlive(runtime.workbenchPid); + const tunnelAlive = runtime.tunnelPid ? isPidAlive(runtime.tunnelPid) : false; + let mcpHealthy = false; + let deviceAdapters = 0; + let toolCount = 0; + if (workbenchAlive && runtime.localPort && runtime.adminCredentialFile && await fileExists(runtime.adminCredentialFile)) { + try { + const adminToken = (await readFile(runtime.adminCredentialFile, 'utf8')).trim(); + const mcpUrl = `http://127.0.0.1:${runtime.localPort}/api/ops/vision-workshop/mcp`; + const headers = { 'content-type': 'application/json', 'x-admin-token': adminToken, 'x-rdk-ops-action': 'observability' }; + const listRes = await fetch(mcpUrl, { + method: 'POST', headers, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list', params: {} }), + signal: AbortSignal.timeout(3000), + }); + if (listRes.ok) { + const listed = await listRes.json(); + toolCount = Array.isArray(listed?.result?.tools) ? listed.result.tools.length : 0; + } + const statusRes = await fetch(mcpUrl, { + method: 'POST', headers, body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'vision_workshop_runtime_status', arguments: {} } }), + signal: AbortSignal.timeout(3000), + }); + if (statusRes.ok) { + const rpc = await statusRes.json(); + const parsed = JSON.parse(rpc.result.content[0].text); + const data = parsed.data ?? parsed; + mcpHealthy = data?.contract === 'rdk.vision-workshop.v1'; + deviceAdapters = Array.isArray(data?.deviceAdapters) ? data.deviceAdapters.length : 0; + } + } catch { + mcpHealthy = false; + } + } + let tunnelHealthy = false; + if (tunnelAlive && runtime.localCameraPort && runtime.boardTokenFile && await fileExists(runtime.boardTokenFile)) { + try { + const boardToken = (await readFile(runtime.boardTokenFile, 'utf8')).trim(); + const capRes = await fetch(`http://127.0.0.1:${runtime.localCameraPort}/capabilities`, { + headers: { Authorization: `Bearer ${boardToken}` }, + signal: AbortSignal.timeout(2500), + }); + tunnelHealthy = capRes.ok; + } catch { + tunnelHealthy = false; + } + } + const running = workbenchAlive && mcpHealthy && (!runtime.tunnelPid || (tunnelAlive && tunnelHealthy)); + return { + running, + workbenchAlive, + mcpHealthy, + tunnelAlive, + tunnelHealthy, + toolCount, + deviceAdapters, + localPort: runtime.localPort, + localCameraPort: runtime.localCameraPort, + boardHost: runtime.boardHost, + boardUser: runtime.boardUser, + experimentId: runtime.experimentId, + cameraConfig: runtime.cameraConfig, + launcherPath: runtime.launcherPath, + startedAt: runtime.startedAt, + logs: runtime.logs, + }; +} + +async function startSshTunnel({ sshConfigPath, localCameraPort, boardCameraPort, boardToken, logPath, detached }) { + const logFd = detached ? openSync(logPath, 'a', 0o600) : null; + let child; + let stderr = ''; + try { + child = spawn('ssh', [ + '-F', sshConfigPath, + '-N', + '-o', 'BatchMode=yes', + '-o', 'ExitOnForwardFailure=yes', + '-L', `127.0.0.1:${localCameraPort}:127.0.0.1:${boardCameraPort}`, + SSH_ALIAS, + ], detached + ? { detached: true, windowsHide: true, stdio: ['ignore', logFd, logFd] } + : { stdio: ['ignore', 'ignore', 'pipe'] }); + } finally { + if (logFd !== null) closeSync(logFd); + } + if (!detached && child.stderr) { + child.stderr.on('data', chunk => { stderr += chunk; }); + } + try { + const capabilities = await waitForHttpJson( + `http://127.0.0.1:${localCameraPort}/capabilities`, + { Authorization: `Bearer ${boardToken}` }, + 12000, + ); + if (detached) child.unref(); + return { child, pid: child.pid, capabilities }; + } catch (error) { + stopPid(child.pid); + const tail = detached && await fileExists(logPath) ? (await readFile(logPath, 'utf8')).slice(-400).trim() : stderr.trim(); + throw new Error(`ssh_tunnel_failed:${error.message}:${tail}`); + } +} + +export async function startLocalWorkbench({ layout, workbenchConfigPath, localPort, adminToken, logPath, detached }) { + const [command, ...baseArgs] = layout.serverCommand; + const logFd = detached ? openSync(logPath, 'a', 0o600) : null; + let child; + let stdout = ''; + let stderr = ''; + try { + child = spawn(command, [...baseArgs, workbenchConfigPath], detached + ? { detached: true, windowsHide: true, stdio: ['ignore', logFd, logFd] } + : { stdio: ['ignore', 'pipe', 'pipe'] }); + } finally { + if (logFd !== null) closeSync(logFd); + } + if (!detached) { + child.stdout?.on('data', chunk => { stdout += chunk; }); + child.stderr?.on('data', chunk => { stderr += chunk; }); + } + const mcpUrl = `http://127.0.0.1:${localPort}/api/ops/vision-workshop/mcp`; + const rpc = async (id, method, params) => { + const res = await fetch(mcpUrl, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-admin-token': adminToken, + 'x-rdk-ops-action': 'observability', + }, + body: JSON.stringify({ jsonrpc: '2.0', id, method, params }), + signal: AbortSignal.timeout(4000), + }); + if (!res.ok) throw new Error(`local_workbench_mcp_http_${res.status}`); + return res.json(); + }; + const deadline = Date.now() + 15000; + let listed; + while (Date.now() < deadline) { + if (child.exitCode !== null) break; + try { + listed = await rpc(1, 'tools/list', {}); + if (Array.isArray(listed?.result?.tools)) break; + } catch { + // Wait for listener boot + } + await new Promise(resolve => setTimeout(resolve, 120)); + } + if (!Array.isArray(listed?.result?.tools)) { + stopPid(child.pid); + const tail = detached && await fileExists(logPath) + ? (await readFile(logPath, 'utf8')).slice(-500).replaceAll(adminToken, '[redacted]').trim() + : stderr.replaceAll(adminToken, '[redacted]').trim(); + throw new Error(`local_workbench_start_failed:${tail || stdout.slice(-200).trim()}`); + } + const toolCount = listed.result.tools.length; + const statusRes = await rpc(2, 'tools/call', { name: 'vision_workshop_runtime_status', arguments: {} }); + const parsedStatus = JSON.parse(statusRes.result.content[0].text); + if (detached) child.unref(); + return { child, pid: child.pid, toolCount, runtimeStatus: parsedStatus.data ?? parsedStatus }; +} + +async function ensureDefaultExperiment({ localPort, adminToken, adapter }) { + const base = `http://127.0.0.1:${localPort}/api/ops/observability/vision-workshop`; + const headers = { + 'x-admin-token': adminToken, + 'content-type': 'application/json', + 'x-rdk-ops-action': 'observability', + }; + const listRes = await fetch(`${base}/experiments?view=index&limit=30`, { headers }); + if (listRes.ok) { + const payload = await listRes.json(); + const existing = (payload.experiments ?? []).find(item => item.targetId === adapter.id); + if (existing?.id) return existing.id; + } + const createRes = await fetch(`${base}/experiments`, { + method: 'POST', + headers, + body: JSON.stringify({ + title: `RDK X5 + IMX415 视觉 Workshop (${adapter.cameraMode})`, + goal: '完成相机点亮、三图基线采集、两轮 Gamma 与单项 ISP 调优、重载恢复及板端 BPU 检测', + board: adapter.board, + sensorVendor: adapter.sensorVendor, + sensorModel: adapter.sensorModel, + sdkVersion: adapter.sdkVersion, + cameraInterface: adapter.cameraInterface, + cameraMode: adapter.cameraMode, + targetId: adapter.id, + }), + }); + if (!createRes.ok) { + const errText = await createRes.text(); + throw new Error(`default_experiment_create_failed:${createRes.status}:${errText.slice(0, 200)}`); + } + const created = await createRes.json(); + return created.experiment.id; +} + +async function writeCameraConnectionSafely({ cameraConfigPath, connectionConfig, forceConfig }) { + if (await fileExists(cameraConfigPath)) { + let existing; + try { + existing = JSON.parse(await readFile(cameraConfigPath, 'utf8')); + } catch { + existing = null; + } + const isManagedLocal = typeof existing?.url === 'string' && existing.url.startsWith('http://127.0.0.1:') && existing.auth?.type === 'admin'; + if (!isManagedLocal && !forceConfig) { + throw new Error(`existing_camera_connection_preserved:${cameraConfigPath}(检测到已有远端或自定义配置,如需备份并切换为本机快速启动,请附加 --force-config)`); + } + if (!isManagedLocal && forceConfig) { + await copyFile(cameraConfigPath, `${cameraConfigPath}.bak.${Date.now()}`); + } + } + await writePrivateFile(cameraConfigPath, JSON.stringify(connectionConfig, null, 2) + '\n', 0o600); +} + +async function loadClassroomConfig(layout, explicitPath) { + const target = explicitPath || layout.defaultClassroomConfig; + if (!target) return {}; + const data = JSON.parse(await readFile(target, 'utf8')); + const baseDir = path.dirname(target); + const resolveOpt = value => (typeof value === 'string' ? (path.isAbsolute(value) ? value : path.resolve(baseDir, value)) : undefined); + return { + ...data, + precompiledNativeDir: resolveOpt(data.precompiledNativeDir), + courseAssetsDir: resolveOpt(data.courseAssetsDir), + robogoProfilePath: resolveOpt(data.robogoProfilePath), + }; +} + +export async function runQuickstart(argv = process.argv.slice(2)) { + const majorNode = Number(process.versions.node.split('.')[0]); + if (majorNode < 22) { + throw new Error(`node_22_required:当前 Node ${process.versions.node},请升级至 Node >= 22`); + } + const options = parseArgs(argv); + if (options.help) { + console.log(usageText()); + return 0; + } + if (options.command === 'stop') { + const result = await stopQuickstartRuntime(options.configDir); + if (options.json) { + console.log(JSON.stringify({ ok: true, ...result }, null, 2)); + } else { + console.log(result.hadRuntime ? '✅ 已停止本机相机后端与板端 SSH 隧道。' : 'ℹ️ 当前没有正在运行的 Workshop 后台服务。'); + } + return 0; + } + if (options.command === 'status') { + const status = await inspectQuickstartStatus(options.configDir); + if (options.json) { + console.log(JSON.stringify(status, null, 2)); + } else if (status.running) { + console.log(`✅ Workshop 环境正常运行中`); + console.log(` 板卡 : ${status.boardUser}@${status.boardHost}`); + console.log(` 本机相机后端: http://127.0.0.1:${status.localPort}/ops-observability/vision-workshop (工具数: ${status.toolCount}, 适配器: ${status.deviceAdapters})`); + console.log(` 默认实验 ID : ${status.experimentId}`); + console.log(` MCP 配置 : ${status.cameraConfig}`); + } else { + console.log(`⚠️ Workshop 环境未就绪 (${status.reason || 'tunnel_or_workbench_down'})`); + if (status.logs) console.log(` 日志: ${status.logs.tunnel} | ${status.logs.workbench}`); + } + return status.running ? 0 : 1; + } + + // Stop any stale previous quickstart background instance before starting a fresh one. + await stopQuickstartRuntime(options.configDir); + + const layout = await resolveRuntimeLayout(SCRIPT_DIR); + const classroom = await loadClassroomConfig(layout, options.classroomConfig); + const model = { + baseUrl: options.modelUrl || classroom.model?.baseUrl, + apiKey: options.modelKey || classroom.model?.apiKey, + model: options.modelName || classroom.model?.model, + }; + const detached = !options.foreground && !options.checkOnly; + const tunnelLogPath = path.join(options.configDir, 'tunnel.log'); + const workbenchLogPath = path.join(options.configDir, 'workbench.log'); + + const csiLabel = options.csiPort === 'auto' ? 'CSI自动探测' : `CSI${options.csiPort}`; + const laneLabel = options.lanes === 'auto' ? 'lane自动探测' : `${options.lanes}-lane`; + console.log(`=== RDK 视觉 Pipeline Workshop 一键初始化 (${layout.mode === 'portable' ? '便携包模式' : '源码仓库模式'}) ===`); + console.log(`目标板卡: ${options.user}@${options.host}:${options.sshPort} | IMX415 (${csiLabel}, ${laneLabel})`); + + const { sshConfigPath } = await ensureLocalSshSetup({ + configDir: options.configDir, + host: options.host, + user: options.user, + sshPort: options.sshPort, + }); + + const boardTokenPath = path.join(options.configDir, 'board-camera-token'); + let boardToken; + if (options.skipBoardPush && await fileExists(boardTokenPath)) { + boardToken = (await readFile(boardTokenPath, 'utf8')).trim(); + } + if (!boardToken || boardToken.length < 24) { + boardToken = randomBytes(24).toString('hex'); + await writePrivateFile(boardTokenPath, boardToken + '\n', 0o600); + } + + let bootstrapReceipt; + if (!options.skipBoardPush) { + console.log('[2/5] 正在推送板端轻量工具包(离线模式,不需要板卡联网)...'); + const files = await collectBoardPayloadFiles(layout, classroom); + const synced = pushFilesToBoard({ sshConfigPath, installDir: options.installDir, files }); + console.log(` 已同步 ${synced.count} 个文件至板端 ${synced.installDir}`); + + console.log('[3/5] 正在板端执行官方镜像预检、原生库就绪检查与相机服务启动...'); + bootstrapReceipt = runRemoteBoardBootstrap({ sshConfigPath, options, boardToken }); + console.log(` 板端相机服务就绪 (${bootstrapReceipt.daemon.mode}, SDK: ${bootstrapReceipt.sdkVersion}, 原生库: ${bootstrapReceipt.native.source})`); + for (const warning of bootstrapReceipt.warnings ?? []) { + console.log(` ⚠️ 提示 [${warning.code}]: ${warning.message}`); + } + } else { + console.log('[2/5] 已跳过板端推包,直接连接板端现有服务...'); + const fallbackLanes = options.lanes === 'auto' ? 4 : options.lanes; + const fallbackCsi = options.csiPort === 'auto' ? 2 : options.csiPort; + bootstrapReceipt = { + sdkVersion: 'RDKOS 3.5.0', + cameraMode: `3840x2160-linear-RAW10-30fps-${fallbackLanes}lane`, + sensorConfig: `imx415-30fps-${fallbackLanes}lane`, + csiPort: fallbackCsi, + capabilities: {}, + detection: { ready: false }, + }; + } + + const localCameraPort = await reserveFreeLocalPort(options.cameraPort); + const localWorkbenchPort = await reserveFreeLocalPort(options.localPort); + if (!localCameraPort || !localWorkbenchPort) { + throw new Error('local_port_allocation_failed'); + } + + console.log(`[4/5] 正在建立 SSH 隧道 (127.0.0.1:${localCameraPort} → 板端 127.0.0.1:${options.cameraPort}) 并启动本机轻量相机后端...`); + const tunnel = await startSshTunnel({ + sshConfigPath, + localCameraPort, + boardCameraPort: options.cameraPort, + boardToken, + logPath: tunnelLogPath, + detached, + }); + bootstrapReceipt.capabilities = tunnel.capabilities; + + const adminToken = randomBytes(24).toString('hex'); + const adminCredentialFile = path.join(options.configDir, 'local-admin-token'); + const workbenchConfigPath = path.join(options.configDir, 'workbench.json'); + const stateDir = path.join(options.configDir, 'workbench-state'); + await mkdir(stateDir, { recursive: true, mode: 0o700 }); + await writePrivateFile(adminCredentialFile, adminToken + '\n', 0o600); + + const adapter = buildAdapterRecord(bootstrapReceipt, localCameraPort, boardToken); + const workbenchConfig = buildWorkbenchConfig({ + localPort: localWorkbenchPort, + stateDir, + adminCredentialFile, + adapter, + model: model.baseUrl && model.apiKey && model.model ? model : undefined, + calibrationScriptPath: (await fileExists(layout.calibrationScriptPath)) ? layout.calibrationScriptPath : undefined, + }); + await writePrivateFile(workbenchConfigPath, JSON.stringify(workbenchConfig, null, 2) + '\n', 0o600); + + const workbench = await startLocalWorkbench({ + layout, + workbenchConfigPath, + localPort: localWorkbenchPort, + adminToken, + logPath: workbenchLogPath, + detached, + }); + + const cleanup = () => { + stopPid(workbench.pid); + stopPid(tunnel.pid); + }; + + try { + console.log('[5/5] 正在自动写入插件连接配置、初始化默认实验并自检...'); + const connectionConfig = buildCameraConnectionConfig(localWorkbenchPort, adminCredentialFile); + await writeCameraConnectionSafely({ + cameraConfigPath: options.cameraConfig, + connectionConfig, + forceConfig: options.forceConfig, + }); + + const experimentId = await ensureDefaultExperiment({ localPort: localWorkbenchPort, adminToken, adapter }); + + if (classroom.robogoProfilePath && await fileExists(classroom.robogoProfilePath)) { + const profileText = await readFile(classroom.robogoProfilePath, 'utf8'); + await writePrivateFile(options.robogoProfilePath, profileText, 0o600); + } + + const archiveRoot = path.join(options.configDir, 'board-archives'); + await mkdir(archiveRoot, { recursive: true, mode: 0o700 }); + const launcher = buildBoardLauncherConfigs({ + archiveRoot, + experimentId, + detectionReceipt: bootstrapReceipt.detection, + sshAlias: SSH_ALIAS, + sshConfigPath, + sshPort: options.sshPort, + stationBridgeClientPath: layout.stationBridgeClientPath, + }); + let launcherPath; + if (launcher) { + await writePrivateFile(launcher.presetClientPath, JSON.stringify(launcher.clientConfig, null, 2) + '\n', 0o600); + launcherPath = path.join(options.configDir, 'board-launcher.json'); + await writePrivateFile(launcherPath, JSON.stringify(launcher.launcherConfig, null, 2) + '\n', 0o600); + } + + const runtimeMeta = { + tunnelPid: tunnel.pid, + workbenchPid: workbench.pid, + localPort: localWorkbenchPort, + localCameraPort, + boardHost: options.host, + boardUser: options.user, + experimentId, + cameraConfig: options.cameraConfig, + adminCredentialFile, + boardTokenFile: boardTokenPath, + ...(launcherPath ? { launcherPath } : {}), + startedAt: new Date().toISOString(), + logs: { tunnel: tunnelLogPath, workbench: workbenchLogPath }, + }; + if (detached) { + await writePrivateFile(path.join(options.configDir, 'runtime.json'), JSON.stringify(runtimeMeta, null, 2) + '\n', 0o600); + } + + console.log('\n============================================================'); + console.log('✅ 初始化完成,全部链路已连通!'); + console.log(` 本机相机后端: http://127.0.0.1:${localWorkbenchPort}/ops-observability/vision-workshop`); + console.log(` MCP 连接配置: ${options.cameraConfig}(已自动写入,发现 ${workbench.toolCount} 个工具)`); + console.log(` 默认实验 ID : ${experimentId}(打开课堂工作台后自动绑定,无需手动选择)`); + console.log(` 板端相机能力: ${adapter.operations.length} 项原子操作${adapter.previewModes ? `,预览模式: ${adapter.previewModes.join('/')}` : ''}`); + if (!workbenchConfig.model) { + console.log(' ✅ 实机两轮 Gamma 已启用内置本地亮度分析候选,无需额外配置模型 Key。'); + } + if (!launcherPath && bootstrapReceipt.detection?.reason) { + console.log(` 预置 BPU 检测尚未就绪:${bootstrapReceipt.detection.reason}`); + } + if (launcherPath) { + console.log(` ✅ 一键 BPU 检测已自动登记(工作台自动发现 ${launcherPath},无需手动配置环境变量)`); + } + console.log('\n下一步:打开 RDK Studio(确保已启用 RDK Camera AI / 视觉 Workshop 插件),在对话中输入:'); + console.log(' 「开始视觉 Workshop,请先调用 mcp__rdk-vision-workshop__vision_course_view 打开课堂工作台」'); + console.log('============================================================'); + + if (options.checkOnly) { + cleanup(); + return 0; + } + + if (detached) { + console.log('ℹ️ 后台服务与板端隧道已就绪,可以关闭本终端;查看状态运行 status,结束课程运行 stop。'); + return 0; + } + + console.log('服务正在前台保持运行(关闭本窗口或按 Ctrl+C 将优雅停止隧道与本机服务)...'); + await new Promise(resolve => { + const stop = () => { + console.log('\n正在关闭本机服务与板端 SSH 隧道...'); + cleanup(); + resolve(); + }; + process.once('SIGINT', stop); + process.once('SIGTERM', stop); + tunnel.child.once('exit', code => { + console.error(`\n⚠️ SSH 隧道意外断开 (exit=${code}),正在停止本机服务...`); + cleanup(); + resolve(); + }); + workbench.child.once('exit', code => { + console.error(`\n⚠️ 本机相机后端意外退出 (exit=${code}),正在关闭 SSH 隧道...`); + cleanup(); + resolve(); + }); + }); + return 0; + } catch (error) { + cleanup(); + throw error; + } +} + +const entryFile = process.argv[1]; +if (entryFile && existsSync(entryFile) && import.meta.url === pathToFileURL(realpathSync(entryFile)).href) { + runQuickstart().then(code => { + process.exitCode = code; + }).catch(error => { + console.error(`\n❌ 启动失败: ${error.message}`); + process.exitCode = 1; + }); +} diff --git a/tools/vision-workshop-quickstart.test.mjs b/tools/vision-workshop-quickstart.test.mjs new file mode 100644 index 0000000..8d80e8e --- /dev/null +++ b/tools/vision-workshop-quickstart.test.mjs @@ -0,0 +1,493 @@ +import assert from 'node:assert/strict'; +import { spawn, spawnSync } from 'node:child_process'; +import { once } from 'node:events'; +import { createHash } from 'node:crypto'; +import { cp, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'; +import { createServer } from 'node:http'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import { createBoardLauncher } from '../plugins/rdk-vision-workshop/mcp/board-launcher.mjs'; +import { packageQuickstart } from './package-vision-quickstart.mjs'; +import { + buildAdapterRecord, + buildBoardLauncherConfigs, + buildCameraConnectionConfig, + buildWorkbenchConfig, + collectBoardPayloadFiles, + inspectQuickstartStatus, + isPidAlive, + parseArgs, + resolveRuntimeLayout, + startLocalWorkbench, + stopQuickstartRuntime, + writePrivateFile, +} from './vision-workshop-quickstart.mjs'; + +test('parseArgs validates subcommands, flags and official image defaults', () => { + const defaults = parseArgs([]); + assert.equal(defaults.command, 'start'); + assert.equal(defaults.foreground, false); + assert.equal(defaults.host, '192.168.128.10'); + assert.equal(defaults.user, 'sunrise'); + assert.equal(defaults.csiPort, 'auto'); + assert.equal(defaults.lanes, 'auto'); + assert.equal(defaults.installDir, '/home/sunrise/.rdk-vision-workshop'); + + const statusCmd = parseArgs(['status', '--json']); + assert.equal(statusCmd.command, 'status'); + assert.equal(statusCmd.json, true); + + const stopCmd = parseArgs(['stop']); + assert.equal(stopCmd.command, 'stop'); + + const custom = parseArgs(['start', '--host', '10.0.0.8', '--user', 'root', '--csi-port', '0', '--lanes', '2', '--service-mode', 'user-process', '--foreground']); + assert.equal(custom.host, '10.0.0.8'); + assert.equal(custom.installDir, '/opt/rdk-vision-workshop'); + assert.equal(custom.csiPort, 0); + assert.equal(custom.lanes, 2); + assert.equal(custom.serviceMode, 'user-process'); + assert.equal(custom.foreground, true); + + assert.throws(() => parseArgs(['--csi-port', '1']), /invalid_flag:--csi-port/); + assert.throws(() => parseArgs(['--lanes', '3']), /invalid_flag:--lanes/); + assert.throws(() => parseArgs(['--host', 'bad host;rm']), /invalid_flag:--host/); +}); + +test('buildBoardLauncherConfigs satisfies createBoardLauncher contract', async t => { + const root = await mkdtemp(path.join(tmpdir(), 'qs-launcher-')); + t.after(() => rm(root, { recursive: true, force: true })); + const archiveRoot = path.join(root, 'archives'); + const experimentId = '2dd7c9bf-bcf9-48f0-89bf-14c0b1c747a4'; + const modelSha256 = 'b'.repeat(64); + const built = buildBoardLauncherConfigs({ + archiveRoot, + experimentId, + detectionReceipt: { + ready: true, + presetModelSha256: modelSha256, + boardBridge: '/home/sunrise/.rdk-vision-workshop/x5-station-bridge.py', + boardConfig: '/home/sunrise/.rdk-vision-workshop/private/board-preset-config.json', + useSudo: true, + }, + sshAlias: 'rdk-x5-workshop', + sshConfigPath: path.join(root, 'ssh_config'), + sshPort: 22, + stationBridgeClientPath: path.join(root, 'x5-station-bridge.py'), + pythonExecutable: process.execPath, + }); + assert.ok(built); + assert.equal(built.clientConfig.useSudo, true); + assert.equal(built.clientConfig.boardPython, '/usr/bin/python3'); + await writePrivateFile(built.presetClientPath, JSON.stringify(built.clientConfig, null, 2) + '\n', 0o600); + const launcherPath = path.join(root, 'board-launcher.json'); + await writePrivateFile(launcherPath, JSON.stringify(built.launcherConfig, null, 2) + '\n', 0o600); + + const launcher = createBoardLauncher(launcherPath); + const status = launcher.status({ path: 'B', modelHash: modelSha256, experimentId, available: true }); + assert.equal(status.ready, true); + assert.equal(status.reason, undefined); +}); + +test('packaged quickstart bundle runs vision-workshop-local standalone with zero node_modules', { timeout: 30000 }, async t => { + const tmpRoot = await mkdtemp(path.join(tmpdir(), 'vision-qs-portable-')); + t.after(() => rm(tmpRoot, { recursive: true, force: true })); + + const outDir = path.join(tmpRoot, 'quickstart-bundle'); + const courseAssetsDir = path.join(tmpRoot, 'course'); + await cp(new URL('./vision-course-preset', import.meta.url), courseAssetsDir, { recursive: true }); + const model = Buffer.from('test-only model bytes'); + const modelSha256 = createHash('sha256').update(model).digest('hex'); + await writeFile(path.join(courseAssetsDir, 'preset-model.bin'), model); + await writeFile(path.join(courseAssetsDir, 'model-profile.json'), JSON.stringify({ sha256: modelSha256 })); + await writeFile(path.join(courseAssetsDir, 'course-static.jpg'), Buffer.from('test-only image bytes')); + const pkg = await packageQuickstart({ outDir, clean: true, courseAssetsDir }); + assert.equal(pkg.schema, 'rdk.vision-workshop-quickstart.v1'); + assert.ok(pkg.bundleBytes > 10000); + + const linkedBundle = path.join(tmpRoot, 'linked-bundle'); + await symlink(outDir, linkedBundle, process.platform === 'win32' ? 'junction' : 'dir'); + const help = spawnSync(process.execPath, [path.join(linkedBundle, 'vision-workshop-quickstart.mjs'), 'start', '--help'], { encoding: 'utf8' }); + assert.equal(help.status, 0, help.stderr); + assert.match(help.stdout, /--help/); + + // Verify portable runtime layout & board payload collection inside the standalone directory + const layout = await resolveRuntimeLayout(outDir); + assert.equal(layout.mode, 'portable'); + const payloadFiles = await collectBoardPayloadFiles(layout); + assert.ok(payloadFiles.some(item => item.path === 'vision-x5-board-bootstrap.py')); + assert.ok(payloadFiles.some(item => item.path === 'vision-x5-camera.py')); + assert.ok(payloadFiles.some(item => item.path === 'vision-x5-native/Makefile')); + assert.ok(payloadFiles.some(item => item.path === 'x5-course-detect.py')); + assert.ok(payloadFiles.some(item => item.path === 'x5-station-bridge.py')); + assert.equal(pkg.presetCourseAssets?.bundled, true); + assert.equal(pkg.presetCourseAssets?.modelSha256, modelSha256); + assert.ok(payloadFiles.some(item => item.path === 'course/preset-model.bin' && item.sha256 === pkg.presetCourseAssets.modelSha256)); + assert.ok(payloadFiles.some(item => item.path === 'course/model-profile.json')); + assert.ok(payloadFiles.some(item => item.path === 'course/course-static.jpg')); + assert.ok(payloadFiles.some(item => item.path === 'course/model-zoo/ultralytics_yolo_det.py')); + assert.ok(payloadFiles.some(item => item.path === 'course/model-zoo/utils/py_utils/postprocess.py')); + + // Start a mock loopback board camera daemon + const boardToken = 'fixture-board-token-0123456789abcdef'; + const boardServer = createServer((req, res) => { + if (req.headers.authorization !== 'Bearer ' + boardToken) { + res.writeHead(401, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ ok: false, error: 'unauthorized' })); + return; + } + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ ok: true, operations: ['probe', 'pipeline_validate', 'bringup'], previewModes: ['camera'] })); + }); + boardServer.listen(0, '127.0.0.1'); + await once(boardServer, 'listening'); + t.after(() => new Promise(resolve => boardServer.close(resolve))); + const boardPort = boardServer.address().port; + + // Pick a free local workbench port + const probeSocket = createServer(); + probeSocket.listen(0, '127.0.0.1'); + await once(probeSocket, 'listening'); + const localPort = probeSocket.address().port; + await new Promise(resolve => probeSocket.close(resolve)); + + const adminToken = 'fixture-admin-token-0123456789abcdef'; + const adminCredentialFile = path.join(tmpRoot, 'admin-token'); + const workbenchConfigPath = path.join(tmpRoot, 'workbench.json'); + const stateDir = path.join(tmpRoot, 'state'); + await writePrivateFile(adminCredentialFile, adminToken + '\n', 0o600); + + const adapter = buildAdapterRecord({ + sdkVersion: 'RDKOS 3.5.0 / multimedia 3.0.5 / dev 3.0.4', + cameraMode: '3840x2160-linear-RAW10-30fps-4lane', + sensorConfig: 'imx415-30fps-4lane', + csiPort: 2, + capabilities: { operations: ['probe', 'pipeline_validate', 'bringup', 'preview_start', 'preview_frame', 'preview_stop'], previewModes: ['camera'] }, + }, boardPort, boardToken); + assert.deepEqual(adapter.previewModes, ['camera']); + + const minimalAdapter = buildAdapterRecord({ + sdkVersion: 'RDKOS 3.5.0', + cameraMode: '3840x2160-linear-RAW10-30fps-4lane', + capabilities: { operations: ['probe', 'pipeline_validate'], previewModes: ['camera'] }, + }, boardPort, boardToken); + assert.equal(minimalAdapter.previewModes, undefined); + + const workbenchConfig = buildWorkbenchConfig({ + localPort, + stateDir, + adminCredentialFile, + adapter, + calibrationScriptPath: layout.calibrationScriptPath, + }); + await writePrivateFile(workbenchConfigPath, JSON.stringify(workbenchConfig, null, 2) + '\n', 0o600); + + // Spawn ONLY the bundled runtime/vision-workshop-local.mjs from tmpRoot (completely outside repo/node_modules!) + const [command, ...args] = layout.serverCommand; + const child = spawn(command, [...args, workbenchConfigPath], { + cwd: tmpRoot, + stdio: ['ignore', 'pipe', 'pipe'], + }); + t.after(() => { + if (child.exitCode === null) child.kill('SIGTERM'); + }); + + let stdout = ''; + let stderr = ''; + child.stdout.on('data', chunk => { stdout += chunk; }); + child.stderr.on('data', chunk => { stderr += chunk; }); + + const deadline = Date.now() + 10000; + while (!stdout.includes('Camera workbench:')) { + if (child.exitCode !== null || Date.now() > deadline) { + throw new Error(`Bundled workbench failed to start: ${stderr}`); + } + await new Promise(resolve => setTimeout(resolve, 40)); + } + + const connection = buildCameraConnectionConfig(localPort, adminCredentialFile); + const connectionPath = path.join(tmpRoot, 'connection.json'); + await writePrivateFile(connectionPath, JSON.stringify(connection, null, 2) + '\n', 0o600); + + // Verify the real rdk-camera-workshop MCP bridge + doctor validates all 8 workflow chains against the zero-node_modules bundle. + const { doctor } = await import('../plugins/rdk-camera-workshop/mcp/setup.mjs'); + const report = await doctor(connectionPath); + assert.equal(report.status, 'connected'); + assert.equal(report.runtime, 'validated'); + assert.equal(report.capabilities.contract, 'rdk.vision-workshop.v1'); + assert.equal(report.capabilities.configuredDeviceAdapters, 1); + for (const [chainName, chain] of Object.entries(report.chains)) { + assert.equal(chain.status, 'ready', `chain ${chainName} should be ready`); + } + + const credential = (await readFile(connection.auth.credentialFile, 'utf8')).trim(); + const mcpRes = await fetch(connection.url, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'x-admin-token': credential, + 'x-rdk-ops-action': 'observability', + }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'vision_workshop_runtime_status', arguments: {} } }), + }); + assert.equal(mcpRes.status, 200); + const rpcBody = await mcpRes.json(); + const statusPayload = JSON.parse(rpcBody.result.content[0].text); + const data = statusPayload.data ?? statusPayload; + assert.equal(data.contract, 'rdk.vision-workshop.v1'); + assert.equal(data.deviceAdapters.length, 1); + assert.equal(data.deviceAdapters[0].id, 'rdk-x5-imx415-quickstart'); + assert.equal(data.deviceAdapters[0].sensorModel, 'IMX415'); + assert.equal(data.classroomGammaCandidate, true); +}); + +test('workbench auto-discovers active quickstart experimentId from runtime.json', async t => { + const root = await mkdtemp(path.join(tmpdir(), 'qs-wb-autodiscover-')); + t.after(() => rm(root, { recursive: true, force: true })); + const runtimePath = path.join(root, 'runtime.json'); + const expId = '2dd7c9bf-bcf9-48f0-89bf-14c0b1c747a4'; + await writePrivateFile(runtimePath, JSON.stringify({ + workbenchPid: process.pid, + experimentId: expId, + localPort: 4310, + }, null, 2) + '\n', 0o600); + const oldEnv = process.env.RDK_VISION_COURSE_QUICKSTART_RUNTIME; + process.env.RDK_VISION_COURSE_QUICKSTART_RUNTIME = runtimePath; + t.after(() => { + if (oldEnv === undefined) delete process.env.RDK_VISION_COURSE_QUICKSTART_RUNTIME; + else process.env.RDK_VISION_COURSE_QUICKSTART_RUNTIME = oldEnv; + }); + const { startWorkbench } = await import('../plugins/rdk-vision-workshop/mcp/workbench.mjs'); + const wb = await startWorkbench({}, 0); + t.after(() => new Promise(resolve => wb.server.close(resolve))); + const url = new URL(wb.url); + const res = await fetch(new URL('/session', url), { headers: { 'X-Workshop-Session': url.hash.slice(1) } }); + const payload = await res.json(); + assert.equal(payload.resume.camera?.experimentId, expId); +}); + +test('keyless classroom-gamma-candidate generates bounded Gamma curve from real PNG stats without model key', { timeout: 25000 }, async t => { + const { createHash } = await import('node:crypto'); + const { deflateSync } = await import('node:zlib'); + const tmpRoot = await mkdtemp(path.join(tmpdir(), 'qs-keyless-gamma-')); + t.after(() => rm(tmpRoot, { recursive: true, force: true })); + const outDir = path.join(tmpRoot, 'bundle'); + await packageQuickstart({ outDir, clean: true }); + const layout = await resolveRuntimeLayout(outDir); + + // Build a tiny valid 4x4 RGB PNG + const crcTable = new Uint32Array(256).map((_, n) => { + let c = n; + for (let k = 0; k < 8; k += 1) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1); + return c >>> 0; + }); + const crc32 = buf => { + let c = 0xffffffff; + for (const b of buf) c = crcTable[(c ^ b) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; + }; + const chunk = (type, data) => { + const tbuf = Buffer.from(type, 'ascii'); + const len = Buffer.alloc(4); len.writeUInt32BE(data.length, 0); + const crc = Buffer.alloc(4); crc.writeUInt32BE(crc32(Buffer.concat([tbuf, data])), 0); + return Buffer.concat([len, tbuf, data, crc]); + }; + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(4, 0); ihdr.writeUInt32BE(4, 4); ihdr[8] = 8; ihdr[9] = 2; + const rows = Buffer.concat(Array.from({ length: 4 }, () => Buffer.from([0, ...Array(12).fill(120)]))); + const pngBytes = Buffer.concat([ + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), + chunk('IHDR', ihdr), + chunk('IDAT', deflateSync(rows)), + chunk('IEND', Buffer.alloc(0)), + ]); + const pngSha = createHash('sha256').update(pngBytes).digest('hex'); + + const sourceCurve = Array.from({ length: 64 }, (_, i) => Math.round((i / 63) * 1023)); + const fullCurve = Array.from({ length: 20 }, () => sourceCurve).flat(); + const gainGrid = Array.from({ length: 20 }, (_, i) => (i + 1) * 10); + const snapshotId = 'a'.repeat(32); + const layoutHash = 'b'.repeat(64); + const baselineTuning = { + kind: 'x5-hbn-isp-v2', + snapshotId, + layoutHash, + modules: { gamma: { mode: 0, 'auto_attr.auto_level': 20, 'auto_attr.gain': gainGrid, 'auto_attr.curve': fullCurve } }, + }; + const baselineHash = createHash('sha256').update(JSON.stringify(baselineTuning)).digest('hex'); + + const boardToken = 'fixture-gamma-board-token-0123456789'; + const boardServer = createServer((req, res) => { + let body = ''; + req.on('data', c => { body += c; }); + req.on('end', () => { + const task = JSON.parse(body || '{}'); + res.writeHead(200, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ + ok: true, + contract: 'rdk.vision-device-runner.v1', + operation: task.operation, + jobId: task.context.jobId, + result: { + filename: 'before.png', + mimeType: 'image/png', + contentBase64: pngBytes.toString('base64'), + sha256: pngSha, + width: 4, + height: 4, + tuningHash: baselineHash, + capturedAt: new Date().toISOString(), + evidence: { sdkTimestampNs: '1000001' }, + }, + })); + }); + }); + boardServer.listen(0, '127.0.0.1'); + await once(boardServer, 'listening'); + t.after(() => new Promise(resolve => boardServer.close(resolve))); + const boardPort = boardServer.address().port; + + const sock = createServer(); sock.listen(0, '127.0.0.1'); await once(sock, 'listening'); + const localPort = sock.address().port; await new Promise(resolve => sock.close(resolve)); + const adminToken = 'fixture-gamma-admin-token-0123456789'; + const adminFile = path.join(tmpRoot, 'admin'); + const cfgFile = path.join(tmpRoot, 'wb.json'); + await writePrivateFile(adminFile, adminToken + '\n', 0o600); + const adapter = buildAdapterRecord({ + sdkVersion: 'RDKOS 3.5.0', + cameraMode: '3840x2160-linear-RAW10-30fps-4lane', + capabilities: { operations: ['probe', 'capture_frame', 'tuning_get', 'apply_tuning'] }, + }, boardPort, boardToken); + await writePrivateFile(cfgFile, JSON.stringify(buildWorkbenchConfig({ + localPort, stateDir: path.join(tmpRoot, 'state'), adminCredentialFile: adminFile, adapter, + }), null, 2) + '\n', 0o600); + + const wb = await startLocalWorkbench({ + layout, workbenchConfigPath: cfgFile, localPort, adminToken, + logPath: path.join(tmpRoot, 'wb.log'), detached: true, + }); + t.after(() => stopQuickstartRuntime(tmpRoot)); + await writePrivateFile(path.join(tmpRoot, 'runtime.json'), JSON.stringify({ workbenchPid: wb.pid }), 0o600); + + const api = `http://127.0.0.1:${localPort}/api/ops/observability/vision-workshop`; + const headers = { 'content-type': 'application/json', 'x-admin-token': adminToken, 'x-rdk-ops-action': 'observability' }; + const exp = (await (await fetch(`${api}/experiments`, { + method: 'POST', headers, + body: JSON.stringify({ + title: 'Keyless Gamma Test', goal: '提升暗部文字对比度', + board: adapter.board, sensorVendor: adapter.sensorVendor, sensorModel: adapter.sensorModel, + sdkVersion: adapter.sdkVersion, cameraInterface: adapter.cameraInterface, cameraMode: adapter.cameraMode, + targetId: adapter.id, + }), + })).json()).experiment; + const baselineRes = await (await fetch(`${api}/experiments/${exp.id}/baseline`, { + method: 'POST', headers, + body: JSON.stringify({ + config: baselineTuning, + rules: [{ + path: '/modules/gamma/auto_attr.curve', label: 'Gamma', min: 0, max: 0.9, step: 0.05, + transform: { kind: 'x5-common-auto-gamma-band-v1', lower: 160, upper: 552, activeRows: 20, sourceCurve, gainGrid, snapshotId, layoutHash }, + }], + }), + })).json(); + assert.equal(baselineRes.ok, true); + const capRes = await (await fetch(`${api}/experiments/${exp.id}/device/capture_frame`, { + method: 'POST', headers, body: JSON.stringify({ scene: '测试文字' }), + })).json(); + assert.equal(capRes.ok, true); + const frameId = capRes.asset?.id ?? capRes.frame?.id; + assert.ok(frameId); + + // 1. Confirm /candidates returns 503 vision_model_disabled when no model key configured + const modelDisabled = await fetch(`${api}/experiments/${exp.id}/candidates`, { + method: 'POST', headers, body: JSON.stringify({ frameIds: [frameId], goal: '提升文字对比' }), + }); + assert.equal(modelDisabled.status, 503); + assert.equal((await modelDisabled.json()).error, 'vision_model_disabled'); + + // 2. Confirm keyless /classroom-gamma-candidate succeeds cleanly and modifies ONLY gamma curve + const gammaRes = await fetch(`${api}/experiments/${exp.id}/classroom-gamma-candidate`, { + method: 'POST', headers, + body: JSON.stringify({ baselineId: baselineRes.baseline.id, baselineHash: baselineRes.baseline.hash, frameId, goal: '提升文字对比' }), + }); + assert.equal(gammaRes.status, 201); + const gammaBody = await gammaRes.json(); + assert.equal(gammaBody.ok, true); + assert.equal(gammaBody.candidate.source, 'manual'); + assert.notEqual(gammaBody.candidate.hash, baselineHash); + assert.equal(gammaBody.candidate.patches[0].path, '/modules/gamma/auto_attr.curve'); + assert.match(gammaBody.candidate.patches[0].reason, /无需外接模型网关/); +}); + +test('detached background start/status/stop lifecycle works cleanly on standalone bundle', { timeout: 30000 }, async t => { + const tmpRoot = await mkdtemp(path.join(tmpdir(), 'vision-qs-detached-')); + t.after(() => rm(tmpRoot, { recursive: true, force: true })); + + const outDir = path.join(tmpRoot, 'bundle'); + await packageQuickstart({ outDir, clean: true }); + const layout = await resolveRuntimeLayout(outDir); + + const probeSocket = createServer(); + probeSocket.listen(0, '127.0.0.1'); + await once(probeSocket, 'listening'); + const localPort = probeSocket.address().port; + await new Promise(resolve => probeSocket.close(resolve)); + + const configDir = path.join(tmpRoot, 'cfg'); + const adminToken = 'fixture-detached-admin-0123456789abcdef'; + const adminCredentialFile = path.join(configDir, 'admin-token'); + const workbenchConfigPath = path.join(configDir, 'workbench.json'); + const workbenchLogPath = path.join(configDir, 'workbench.log'); + await writePrivateFile(adminCredentialFile, adminToken + '\n', 0o600); + const adapter = buildAdapterRecord({ + sdkVersion: 'RDKOS 3.5.0 / multimedia 3.0.5 / dev 3.0.4', + cameraMode: '3840x2160-linear-RAW10-30fps-4lane', + capabilities: { operations: ['probe', 'pipeline_validate'] }, + }, 3217, 'fixture-board-token-0123456789abcdef'); + const workbenchConfig = buildWorkbenchConfig({ + localPort, + stateDir: path.join(configDir, 'state'), + adminCredentialFile, + adapter, + }); + await writePrivateFile(workbenchConfigPath, JSON.stringify(workbenchConfig, null, 2) + '\n', 0o600); + + const started = await startLocalWorkbench({ + layout, + workbenchConfigPath, + localPort, + adminToken, + logPath: workbenchLogPath, + detached: true, + }); + t.after(() => stopQuickstartRuntime(configDir)); + assert.ok(started.pid > 0); + assert.ok(started.toolCount >= 20); + + await writePrivateFile(path.join(configDir, 'runtime.json'), JSON.stringify({ + workbenchPid: started.pid, + localPort, + adminCredentialFile, + boardHost: '192.168.128.10', + boardUser: 'sunrise', + experimentId: '2dd7c9bf-bcf9-48f0-89bf-14c0b1c747a4', + cameraConfig: path.join(configDir, 'connection.json'), + startedAt: new Date().toISOString(), + }, null, 2) + '\n', 0o600); + + const live = await inspectQuickstartStatus(configDir); + assert.equal(live.running, true); + assert.equal(live.workbenchAlive, true); + assert.equal(live.mcpHealthy, true); + assert.equal(live.deviceAdapters, 1); + + const stopped = await stopQuickstartRuntime(configDir); + assert.equal(stopped.hadRuntime, true); + assert.equal(stopped.stopped.workbench, true); + await new Promise(resolve => setTimeout(resolve, 250)); + assert.equal(isPidAlive(started.pid), false); + + const afterStop = await inspectQuickstartStatus(configDir); + assert.equal(afterStop.running, false); + assert.equal(afterStop.reason, 'not_started'); +}); diff --git a/tools/vision-x5-board-bootstrap.py b/tools/vision-x5-board-bootstrap.py new file mode 100644 index 0000000..a9a9596 --- /dev/null +++ b/tools/vision-x5-board-bootstrap.py @@ -0,0 +1,826 @@ +#!/usr/bin/env python3 +"""Bootstrap an official RDKOS 3.5.0+ RDK X5 board for the Vision Pipeline Workshop. + +Designed to run directly on a stock official RDKOS 3.5.0 X5 board (offline, no apt +install required), either invoked over SSH by vision-workshop-quickstart.mjs or +manually on the board. Never modifies system SDK packages or vendor drivers. +""" +import argparse +import ctypes +import hashlib +import importlib.util +import json +import os +from pathlib import Path +import platform +import pwd +import re +import secrets +import shutil +import subprocess +import sys +import time +import urllib.error +import urllib.request + + +SCHEMA = "rdk.vision-x5-board-bootstrap.v1" +DEFAULT_VP_SENSOR_DIRS = ( + "/app/multimedia_samples/vp_sensors", + "/app/platform_samples/vp_sensors", +) +DEFAULT_TUNING_CANDIDATES = ( + "/usr/hobot/lib/sensor/imx415_tuning.json", + "/usr/hobot/bin/imx415_tuning.json", +) +DEFAULT_LIBVPF = "/usr/hobot/lib/libvpf.so.1" +DEFAULT_LIBCAM = "/usr/hobot/lib/libcam.so.1" +DEFAULT_IMX415_DRIVER = "/usr/hobot/lib/sensor/libimx415.so.1.0.0" +DEFAULT_SERVICE_NAME = "rdk-camera-workshop.service" + + +def load_sibling(name): + path = Path(__file__).resolve().with_name(name + ".py") + spec = importlib.util.spec_from_file_location(name.replace("-", "_"), path) + if spec is None or spec.loader is None: + raise RuntimeError(f"sibling_module_missing:{name}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def sha256_file(path): + file = Path(path) + if not file.is_file(): + return None + digest = hashlib.sha256() + with file.open("rb") as handle: + for chunk in iter(lambda: handle.read(65536), b""): + digest.update(chunk) + return digest.hexdigest() + + +def is_aarch64_elf(path): + file = Path(path) + if not file.is_file(): + return False + try: + header = file.read_bytes()[:20] + except OSError: + return False + if len(header) < 20 or header[:4] != b"\x7fELF" or header[4] != 2 or header[5] not in (1, 2): + return False + order = "little" if header[5] == 1 else "big" + return int.from_bytes(header[18:20], order) == 183 + + +def detect_sdk_version(preflight): + facts = preflight.get("facts", {}) + sdk = facts.get("sdk", preflight.get("sdk", {})) + os_version = ( + facts.get("vendorRosPrerequisites", {}).get("rdkosVersion") + or (sdk.get("releaseFiles") or [{}])[0].get("versionTokens", [None])[0] + or facts.get("system", {}).get("VERSION_ID") + ) + packages = {row["name"]: row.get("version") for row in sdk.get("packages", [])} + mm = packages.get("hobot-multimedia") + mm_dev = packages.get("hobot-multimedia-dev") + parts = [] + if os_version: + parts.append(f"RDKOS {os_version}") + if mm: + parts.append(f"multimedia {mm.split('-')[0]}") + if mm_dev: + parts.append(f"dev {mm_dev.split('-')[0]}") + if parts: + return " / ".join(parts)[:120] + return "RDKOS 3.5.0-unverified" + + +def detect_imx415_topology(preflight, explicit_csi="auto", explicit_lanes="auto"): + """Auto-detect CSI port (0 or 2) and MIPI lane count (2 or 4) from sysfs/DT facts.""" + facts = preflight.get("facts", {}) + dt = facts.get("deviceTree", {}) + i2c = facts.get("i2c", {}) + bound_clients = [c for c in i2c.get("clients", []) if c.get("imx415") and c.get("driver")] + bound_buses = {c.get("bus") for c in bound_clients if isinstance(c.get("bus"), int)} + + detected_csi = None + detected_lanes = None + evidence = [] + + # 1. Check vcon connector nodes matching the bound IMX415 I2C bus. + for node in dt.get("csi", []): + props = node.get("connectorProperties") or {} + node_path = (node.get("path") or "").lower() + bus_vals = props.get("bus") or [] + rx_vals = props.get("rxPhy") or [] + if bound_buses and any(b in bound_buses for b in bus_vals): + for rx in rx_vals: + if rx in (0, 2): + detected_csi = rx + evidence.append(f"vcon_bus_match:{node_path}->csi{rx}") + break + if detected_csi is None: + m = re.search(r"vcon[@_]?([02])\b", node_path) + if m: + detected_csi = int(m.group(1)) + evidence.append(f"vcon_path_match:{node_path}->csi{detected_csi}") + for ep in node.get("endpoints", []): + dl = ep.get("dataLanes") or [] + if len(dl) in (2, 4) and detected_lanes is None and (detected_csi is not None or f"csi{detected_csi}" in node_path): + detected_lanes = len(dl) + evidence.append(f"csi_endpoint_lanes:{len(dl)}") + + # 2. Check IMX415 sensor DT nodes for explicit data-lanes and csi/vcon hints. + for sensor in dt.get("sensors", []): + status = (sensor.get("status") or "okay").lower() + if status == "disabled": + continue + spath = (sensor.get("path") or "").lower() + for ep in sensor.get("endpoints", []): + dl = ep.get("dataLanes") or [] + if len(dl) in (2, 4): + detected_lanes = len(dl) + evidence.append(f"sensor_endpoint_lanes:{len(dl)}") + break + if detected_csi is None: + m = re.search(r"(?:csi|mipi|vcon)[@_ -]?([02])\b", spath) + if m: + detected_csi = int(m.group(1)) + evidence.append(f"sensor_path_hint:{spath}->csi{detected_csi}") + + # 3. Fallback heuristic from RDK X5 standard I2C-to-CSI mapping if DT lacked vcon properties. + if detected_csi is None and len(bound_buses) == 1: + bus = next(iter(bound_buses)) + if bus == 0: + detected_csi = 0 + evidence.append("i2c_bus0_hint->csi0") + elif bus in (2, 4): + detected_csi = 2 + evidence.append(f"i2c_bus{bus}_hint->csi2") + + csi_port = int(explicit_csi) if str(explicit_csi) in ("0", "2") else (detected_csi if detected_csi in (0, 2) else 2) + lanes = int(explicit_lanes) if str(explicit_lanes) in ("2", "4") else (detected_lanes if detected_lanes in (2, 4) else 4) + source = ( + "explicit" + if str(explicit_csi) != "auto" and str(explicit_lanes) != "auto" + else ("auto-detected" if evidence else "default-fallback") + ) + return { + "csiPort": csi_port, + "lanes": lanes, + "source": source, + "evidence": evidence, + } + + +def check_preflight_compatibility(preflight, allow_unconnected=False): + errors = [] + warnings = [] + sdk = preflight.get("facts", {}).get("sdk", preflight.get("sdk", {})) + checks = {row["name"]: row for row in preflight.get("checks", [])} + compat = sdk.get("nativeAdapterCompatibility", {}) + if compat.get("status") == "incompatible": + errors.append({ + "code": "unsupported_sdk_upgrade_to_rdkos_3_5_0", + "message": "当前板端 SDK 头文件缺少新版 CPROC/EE/2DNR/3DNR 接口(常见于 RDKOS 3.1.1),请升级烧录官方 RDKOS 3.5.0 镜像。", + }) + if not checks.get("native_sdk_files", {}).get("passed"): + errors.append({ + "code": "native_sdk_libraries_missing", + "message": "板端未检测到 AArch64 多媒体 SDK 动态库(libvpf/libcam/libhbmem),请确认烧录的是官方 RDKOS 3.5.0 X5 镜像。", + }) + if not checks.get("imx415_driver_registered", {}).get("passed"): + entry = { + "code": "imx415_not_detected", + "message": "未在内核 I2C 设备中发现已绑定驱动的 IMX415,请断电检查 MIPI 排线朝向与 CSI 接口连接。", + } + if allow_unconnected: + warnings.append(entry) + else: + errors.append(entry) + elif not checks.get("imx415_expected_i2c_address", {}).get("passed"): + warnings.append({ + "code": "imx415_unexpected_i2c_address", + "message": "已发现 IMX415 但 I2C 地址不是默认的 0x1a,请核对模组与设备树。", + }) + return errors, warnings + + +def check_bpu_python_runtime(): + modules = {} + for name in ("cv2", "numpy", "hbm_runtime"): + modules[name] = importlib.util.find_spec(name) is not None + return {"ready": all(modules.values()), "modules": modules} + + +def resolve_vp_sensor_dir(explicit=None, root="/"): + candidates = [explicit] if explicit else list(DEFAULT_VP_SENSOR_DIRS) + root_path = Path(root) + for item in candidates: + if not item: + continue + physical = root_path / item.lstrip("/") if root != "/" else Path(item) + if (physical / "vp_sensors.h").is_file() and (physical / "imx415" / "linear_3840x2160_raw10_30fps_4lane.c").is_file(): + return str(Path(item)) + return None + + +def probe_native_library_abi(library_path): + try: + lib = ctypes.CDLL(str(library_path)) + lib.x5w_abi_version.restype = ctypes.c_uint32 + abi = int(lib.x5w_abi_version()) + has_receiver_policy = hasattr(lib, "x5w_open_with_receiver_policy") + return abi == 2, abi, has_receiver_policy, None + except (OSError, AttributeError) as exc: + return False, None, False, str(exc) + + +def ensure_native_libraries(install_dir, rebuild=False, vp_sensor_dir=None, dry_run=False): + install_path = Path(install_dir) + native_so = install_path / "libvision_x5_native.so" + gpio_shim = install_path / "libvision_x5_gpio_permission_wait.so" + native_src = install_path / "vision-x5-native" + + if not rebuild and is_aarch64_elf(native_so): + if dry_run: + return { + "source": "precompiled", + "nativeLibrary": str(native_so), + "gpioShim": str(gpio_shim) if is_aarch64_elf(gpio_shim) else None, + "hasReceiverPolicy": True, + } + ok, abi, has_receiver_policy, error = probe_native_library_abi(native_so) + if ok: + return { + "source": "precompiled", + "abi": abi, + "nativeLibrary": str(native_so), + "gpioShim": str(gpio_shim) if is_aarch64_elf(gpio_shim) else None, + "hasReceiverPolicy": has_receiver_policy, + } + # Precompiled binary failed to load against this image; fall back to local build. + rebuild_reason = f"precompiled_load_failed:{error}" + else: + rebuild_reason = "rebuild_requested" if rebuild else "precompiled_missing" + + if dry_run: + return { + "source": "build_required", + "reason": rebuild_reason, + "nativeLibrary": str(native_so), + "gpioShim": str(gpio_shim), + "vpSensorDir": resolve_vp_sensor_dir(vp_sensor_dir), + "hasReceiverPolicy": True, + } + + if not (native_src / "Makefile").is_file(): + raise RuntimeError(f"native_source_missing_for_build:{rebuild_reason}") + vp_dir = resolve_vp_sensor_dir(vp_sensor_dir) + if not vp_dir: + raise RuntimeError("vp_sensor_dir_not_found") + if shutil.which("make") is None or (shutil.which("cc") is None and shutil.which("gcc") is None): + raise RuntimeError("native_build_toolchain_missing") + + command = [ + "make", "-C", str(native_src), "all", + f"VP_SENSOR_DIR={vp_dir}", + "SDK_INCLUDE=/usr/include", + "SDK_LIBDIR=/usr/hobot/lib", + ] + completed = subprocess.run(command, capture_output=True, text=True, timeout=180) + if completed.returncode != 0: + tail = (completed.stderr or completed.stdout or "")[-600:] + raise RuntimeError(f"native_build_failed:{tail}") + + built_native = native_src / "build" / "libvision_x5_native.so" + built_shim = native_src / "build" / "libvision_x5_gpio_permission_wait.so" + if not built_native.is_file(): + raise RuntimeError("native_build_artifact_missing") + shutil.copy2(built_native, native_so) + os.chmod(native_so, 0o755) + copied_shim = None + if built_shim.is_file(): + shutil.copy2(built_shim, gpio_shim) + os.chmod(gpio_shim, 0o755) + copied_shim = str(gpio_shim) + ok, abi, has_receiver_policy, error = probe_native_library_abi(native_so) + if not ok: + raise RuntimeError(f"built_native_abi_invalid:{error}") + return { + "source": "compiled", + "reason": rebuild_reason, + "abi": abi, + "vpSensorDir": vp_dir, + "nativeLibrary": str(native_so), + "gpioShim": copied_shim, + "hasReceiverPolicy": has_receiver_policy, + } + + +def build_camera_config( + *, + token, + sdk_version, + lanes, + csi_port, + port, + native_library, + state_dir, + root="/", + gpio_shim=None, + enable_gpio_wait=True, + has_receiver_policy=True, + camera_mode=None, +): + if lanes not in (2, 4): + raise ValueError("invalid_lanes") + if csi_port not in (0, 2): + raise ValueError("invalid_csi_port") + sensor_config = f"imx415-30fps-{lanes}lane" + resolved_mode = camera_mode or f"3840x2160-linear-RAW10-30fps-{lanes}lane" + root_path = Path(root) + + def path_in_root(logical): + return root_path / logical.lstrip("/") if root != "/" else Path(logical) + + config = { + "token": token, + "board": "RDK X5", + "sensorModel": "IMX415", + "sensorVendor": "Sony", + "sdkVersion": sdk_version, + "cameraInterface": "MIPI CSI-2", + "cameraMode": resolved_mode, + "sensorConfig": sensor_config, + "csiPort": csi_port, + "nativeLibrary": str(native_library), + "port": port, + "stateDir": str(state_dir), + "colorMatrix": "bt709", + "colorRange": "limited", + "blackLevel": 0, + "whiteLevel": 1023, + "discardFrames": 5, + "ispFieldPolicies": { + "gamma.auto_attr.curve": { + "min": 0, + "max": 1023, + "evidenceRef": "X5 IMX415 classroom Gamma AUTO table policy (bootstrap)", + }, + "gamma.manual_attr.curve": { + "min": 0, + "max": 1023, + "evidenceRef": "X5 IMX415 classroom Gamma MANUAL table policy (bootstrap)", + }, + }, + "gammaBandTransform": { + "lower": 160, + "upper": 552, + "maxStrength": 0.9, + "step": 0.05, + "evidenceRef": "X5 IMX415 classroom bounded Gamma transform policy (bootstrap)", + }, + } + + for candidate in DEFAULT_TUNING_CANDIDATES: + if path_in_root(candidate).is_file(): + config["effectLibrary"] = candidate + break + + # Enable host-2 4-lane GPIO351 udev race protection automatically when all + # hash-bound binaries are present on this official RDKOS 3.5.0 image. + if enable_gpio_wait and has_receiver_policy and lanes == 4 and csi_port == 2 and gpio_shim: + driver_sha = sha256_file(path_in_root(DEFAULT_IMX415_DRIVER)) + libcam_sha = sha256_file(path_in_root(DEFAULT_LIBCAM)) + shim_sha = sha256_file(gpio_shim) + if driver_sha and libcam_sha and shim_sha: + config["receiverCompatibility"] = { + "kind": "imx415-host2-stop-check-v1", + "sdkVersion": sdk_version, + "cameraMode": resolved_mode, + "sensorConfig": sensor_config, + "csiPort": csi_port, + "driverSha256": driver_sha, + "evidenceRef": "Official RDKOS 3.5.0 X5 IMX415 host-2 4-lane receiver compatibility (bootstrap)", + } + config["gpioPermissionWait"] = { + "kind": "imx415-host2-gpio351-3000ms-v1", + "sdkVersion": sdk_version, + "cameraMode": resolved_mode, + "sensorConfig": sensor_config, + "csiPort": csi_port, + "libcamSha256": libcam_sha, + "shimSha256": shim_sha, + "evidenceRef": "Official RDKOS 3.5.0 non-root GPIO351 permission wait (bootstrap)", + } + + return config + + +def write_private_json(path, payload, uid=None, gid=None): + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + temporary = target.with_suffix(target.suffix + ".tmp") + fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(payload, handle, ensure_ascii=False, indent=2) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + if uid is not None and gid is not None and os.geteuid() == 0: + os.chown(temporary, uid, gid) + os.chmod(temporary, 0o600) + temporary.replace(target) + except BaseException: + temporary.unlink(missing_ok=True) + raise + + +def fetch_capabilities(port, token, timeout_sec=12.0): + deadline = time.monotonic() + timeout_sec + last_error = "capabilities_unreachable" + url = f"http://127.0.0.1:{port}/capabilities" + while time.monotonic() < deadline: + request = urllib.request.Request(url, headers={"Authorization": "Bearer " + token}) + try: + with urllib.request.urlopen(request, timeout=3) as response: + data = json.loads(response.read().decode("utf-8")) + if response.status == 200 and data.get("ok") is True: + return data + last_error = f"unexpected_capabilities_status:{response.status}" + except (urllib.error.URLError, TimeoutError, OSError, json.JSONDecodeError) as exc: + last_error = str(exc) + time.sleep(0.25) + raise RuntimeError(f"camera_daemon_capabilities_failed:{last_error}") + + +def check_pending_recovery(state_dir, reset_state=False): + journal = Path(state_dir) / "isp-write.json" + if not journal.is_file(): + return + try: + state = json.loads(journal.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + if reset_state: + journal.unlink(missing_ok=True) + return + raise RuntimeError("existing_isp_journal_unreadable") + if state.get("cleanupRequired") or state.get("outcome") in ("pending", "unconfirmed", "confirmed"): + if not reset_state: + raise RuntimeError("previous_camera_recovery_required") + journal.unlink(missing_ok=True) + + +def run_privileged(command): + if os.geteuid() == 0: + return subprocess.run(command, capture_output=True, text=True, check=False) + return subprocess.run(["sudo", "-n", *command], capture_output=True, text=True, check=False) + + +def can_use_systemd(): + if shutil.which("systemctl") is None or not Path("/run/systemd/system").is_dir(): + return False + probe = run_privileged(["systemctl", "show-environment"]) + return probe.returncode == 0 + + +def start_camera_daemon(*, install_dir, config_path, state_dir, camera_user, service_mode, service_name, port, token): + camera_script = str(Path(install_dir) / "vision-x5-camera.py") + if service_mode == "auto": + service_mode = "systemd" if can_use_systemd() else "user-process" + + if service_mode == "systemd": + systemd_tool = load_sibling("vision-camera-systemd") + unit_text = systemd_tool.render_unit(camera_user, camera_script, str(config_path), "/usr/bin/python3") + unit_file = Path("/etc/systemd/system") / service_name + tmp_unit = Path(state_dir) / (service_name + ".tmp") + tmp_unit.write_text(unit_text, encoding="utf-8") + try: + install = run_privileged(["install", "-m", "0644", "-o", "root", "-g", "root", str(tmp_unit), str(unit_file)]) + if install.returncode != 0: + raise RuntimeError(f"systemd_unit_install_failed:{install.stderr.strip()}") + finally: + tmp_unit.unlink(missing_ok=True) + for op in (["systemctl", "daemon-reload"], ["systemctl", "enable", service_name], ["systemctl", "restart", service_name]): + res = run_privileged(op) + if res.returncode != 0: + raise RuntimeError(f"systemd_{op[1]}_failed:{res.stderr.strip()}") + active = run_privileged(["systemctl", "is-active", service_name]) + if active.returncode != 0: + raise RuntimeError(f"systemd_service_inactive:{active.stdout.strip() or active.stderr.strip()}") + capabilities = fetch_capabilities(port, token) + return {"mode": "systemd", "serviceName": service_name, "capabilities": capabilities} + + # Lightweight user-process mode (no root/systemd required). + pid_file = Path(state_dir) / "daemon.pid" + if pid_file.is_file(): + try: + old_pid = int(pid_file.read_text(encoding="utf-8").strip()) + os.kill(old_pid, 15) + time.sleep(0.6) + except (ValueError, ProcessLookupError, PermissionError): + pass + log_path = Path(state_dir) / "daemon.log" + with log_path.open("ab") as log_handle: + proc = subprocess.Popen( + [sys.executable, camera_script, "--config", str(config_path)], + stdin=subprocess.DEVNULL, + stdout=log_handle, + stderr=log_handle, + start_new_session=True, + ) + pid_file.write_text(str(proc.pid) + "\n", encoding="utf-8") + os.chmod(pid_file, 0o600) + try: + capabilities = fetch_capabilities(port, token) + except Exception: + if proc.poll() is None: + proc.terminate() + raise + return {"mode": "user-process", "pid": proc.pid, "logFile": str(log_path), "capabilities": capabilities} + + +def configure_course_detection(*, install_dir, camera_config_path, camera_user, ssh_user, service_name, service_mode, dry_run=False): + install_path = Path(install_dir) + course_dir = install_path / "course" + model_path = course_dir / "preset-model.bin" + profile_path = course_dir / "model-profile.json" + static_image = course_dir / "course-static.jpg" + model_zoo = course_dir / "model-zoo" + runner = install_path / "x5-course-detect.py" + bridge = install_path / "x5-station-bridge.py" + camera_module = install_path / "vision-x5-camera.py" + + required = [model_path, profile_path, static_image, model_zoo / "ultralytics_yolo_det.py", runner, bridge, camera_module] + missing = [str(item.relative_to(install_path)) for item in required if not item.exists()] + if missing: + return {"ready": False, "reason": "course_assets_incomplete", "missing": missing} + + model_sha = sha256_file(model_path) + profile = json.loads(profile_path.read_text(encoding="utf-8")) + if profile.get("sha256") != model_sha: + return {"ready": False, "reason": "preset_model_sha256_mismatch", "expected": profile.get("sha256"), "actual": model_sha} + + run_root = install_path / "private" / "course-runs" + board_config_path = install_path / "private" / "board-preset-config.json" + board_config = { + "model": str(model_path), + "profile": str(profile_path), + "staticImage": str(static_image), + "modelZoo": str(model_zoo), + "cameraModule": str(camera_module), + "cameraConfig": str(camera_config_path), + "runner": str(runner), + "runRoot": str(run_root), + "cameraService": service_name, + "cameraUser": camera_user, + "seconds": 25, + } + + if not dry_run: + if service_mode != "systemd": + return {"ready": False, "reason": "bpu_detection_requires_systemd"} + if ssh_user != "root": + current_account = pwd.getpwuid(os.geteuid()).pw_name + if current_account != ssh_user or shutil.which("sudo") is None: + return {"ready": False, "reason": "bpu_detection_sudo_unavailable"} + check = subprocess.run( + ["sudo", "-n", "-l", "--", "/usr/bin/python3", str(bridge), "board", + "--config", str(board_config_path), "--run-id", "00000000-0000-0000-0000-000000000000", + "--model-hash", model_sha, "--comparison"], + capture_output=True, check=False, + ) + if check.returncode != 0: + return {"ready": False, "reason": "bpu_detection_sudo_unavailable"} + run_root.mkdir(parents=True, exist_ok=True) + os.chmod(run_root, 0o700) + try: + pw = pwd.getpwnam(camera_user) + if os.geteuid() == 0: + os.chown(run_root, pw.pw_uid, pw.pw_gid) + write_private_json(board_config_path, board_config, pw.pw_uid, pw.pw_gid) + except KeyError: + write_private_json(board_config_path, board_config) + + return { + "ready": True, + "presetModelSha256": model_sha, + "boardBridge": str(bridge), + "boardConfig": str(board_config_path), + "runRoot": str(run_root), + "useSudo": service_mode == "systemd" and ssh_user != "root", + } + + +def read_token_from_stdin(): + if sys.stdin.isatty(): + return None + raw = sys.stdin.read(65536).strip() + if not raw: + return None + try: + parsed = json.loads(raw) + if isinstance(parsed, dict) and isinstance(parsed.get("token"), str): + return parsed["token"].strip() + except json.JSONDecodeError: + pass + return raw + + +def run_bootstrap(args): + install_dir = Path(args.install_dir).resolve() + private_dir = install_dir / "private" + state_dir = private_dir / "camera-state" + config_path = private_dir / "x5-camera.json" + + preflight_mod = load_sibling("vision-x5-preflight") + preflight = preflight_mod.collect_preflight(args.root) + errors, warnings = check_preflight_compatibility(preflight, allow_unconnected=args.allow_unconnected_camera) + bpu_runtime = check_bpu_python_runtime() + if not bpu_runtime["ready"]: + warnings.append({ + "code": "bpu_python_runtime_incomplete", + "message": "板端 Python 缺少部分 BPU 推理依赖(cv2/numpy/hbm_runtime),拍照与 ISP 调参不受影响,但 BPU 检测需补齐依赖。", + "modules": bpu_runtime["modules"], + }) + + if not args.plan_only and args.root == "/" and platform.machine() != "aarch64": + errors.append({ + "code": "x5_aarch64_runtime_required", + "message": f"当前机器架构为 {platform.machine()},必须在 RDK X5 (aarch64) 板端运行。", + }) + + if errors: + return 2, { + "schema": SCHEMA, + "ok": False, + "stage": "preflight", + "errors": errors, + "warnings": warnings, + "sdkVersion": detect_sdk_version(preflight), + "bpuRuntime": bpu_runtime, + } + + sdk_version = args.sdk_version or detect_sdk_version(preflight) + topology = detect_imx415_topology(preflight, explicit_csi=args.csi_port, explicit_lanes=args.lanes) + resolved_csi = topology["csiPort"] + resolved_lanes = topology["lanes"] + token = read_token_from_stdin() if args.token_stdin else None + if not token and config_path.is_file() and not args.rotate_token: + try: + existing = json.loads(config_path.read_text(encoding="utf-8")) + if isinstance(existing.get("token"), str) and len(existing["token"]) >= 24: + token = existing["token"] + except (OSError, json.JSONDecodeError): + pass + if not token: + token = secrets.token_hex(24) + + native_info = ensure_native_libraries( + install_dir, + rebuild=args.rebuild_native, + vp_sensor_dir=args.vp_sensor_dir, + dry_run=args.plan_only, + ) + + camera_config = build_camera_config( + token=token, + sdk_version=sdk_version, + lanes=resolved_lanes, + csi_port=resolved_csi, + port=args.port, + native_library=native_info["nativeLibrary"], + state_dir=state_dir, + root=args.root, + gpio_shim=native_info.get("gpioShim"), + enable_gpio_wait=not args.no_gpio_wait, + has_receiver_policy=native_info.get("hasReceiverPolicy", False), + camera_mode=args.camera_mode, + ) + + camera_mod = load_sibling("vision-x5-camera") + camera_mod.validate_config(camera_config) + + if args.plan_only: + detection = configure_course_detection( + install_dir=install_dir, + camera_config_path=config_path, + camera_user=args.camera_user, + ssh_user=args.ssh_user, + service_name=args.service_name, + service_mode=args.service_mode, + dry_run=True, + ) + redacted_config = {k: ("" if k == "token" else v) for k, v in camera_config.items()} + return 0, { + "schema": SCHEMA, + "ok": True, + "stage": "plan_only", + "sdkVersion": sdk_version, + "topology": topology, + "warnings": warnings, + "bpuRuntime": bpu_runtime, + "native": native_info, + "cameraConfig": redacted_config, + "detection": detection, + } + + private_dir.mkdir(parents=True, exist_ok=True) + state_dir.mkdir(parents=True, exist_ok=True) + os.chmod(private_dir, 0o700) + os.chmod(state_dir, 0o700) + check_pending_recovery(state_dir, reset_state=args.reset_state) + + uid = gid = None + try: + pw = pwd.getpwnam(args.camera_user) + uid, gid = pw.pw_uid, pw.pw_gid + if os.geteuid() == 0: + os.chown(private_dir, uid, gid) + os.chown(state_dir, uid, gid) + except KeyError: + pass + + write_private_json(config_path, camera_config, uid, gid) + daemon = start_camera_daemon( + install_dir=install_dir, + config_path=config_path, + state_dir=state_dir, + camera_user=args.camera_user, + service_mode=args.service_mode, + service_name=args.service_name, + port=args.port, + token=token, + ) + detection = configure_course_detection( + install_dir=install_dir, + camera_config_path=config_path, + camera_user=args.camera_user, + ssh_user=args.ssh_user, + service_name=args.service_name, + service_mode=daemon["mode"], + dry_run=False, + ) + return 0, { + "schema": SCHEMA, + "ok": True, + "stage": "ready", + "installDir": str(install_dir), + "configPath": str(config_path), + "stateDir": str(state_dir), + "port": args.port, + "sdkVersion": sdk_version, + "cameraMode": camera_config["cameraMode"], + "sensorConfig": camera_config["sensorConfig"], + "csiPort": camera_config["csiPort"], + "topology": topology, + "native": native_info, + "daemon": {k: v for k, v in daemon.items() if k != "capabilities"}, + "capabilities": daemon["capabilities"], + "bpuRuntime": bpu_runtime, + "detection": detection, + "warnings": warnings, + } + + +def parse_args(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--install-dir", default=str(Path(__file__).resolve().parent)) + parser.add_argument("--root", default="/", help="Inspect a sysroot fixture instead of / (for --plan-only testing).") + parser.add_argument("--lanes", choices=("auto", "2", "4"), default="auto") + parser.add_argument("--csi-port", choices=("auto", "0", "2"), default="auto") + parser.add_argument("--port", type=int, default=3217) + parser.add_argument("--sdk-version", default=None) + parser.add_argument("--camera-mode", default=None) + parser.add_argument("--camera-user", default=os.environ.get("SUDO_USER") or os.environ.get("USER") or "sunrise") + parser.add_argument("--ssh-user", default=os.environ.get("SUDO_USER") or os.environ.get("USER") or "sunrise") + parser.add_argument("--service-mode", choices=("auto", "systemd", "user-process"), default="auto") + parser.add_argument("--service-name", default=DEFAULT_SERVICE_NAME) + parser.add_argument("--vp-sensor-dir", default=None) + parser.add_argument("--rebuild-native", action="store_true") + parser.add_argument("--no-gpio-wait", action="store_true") + parser.add_argument("--token-stdin", action="store_true", help="Read private loopback token from stdin.") + parser.add_argument("--rotate-token", action="store_true") + parser.add_argument("--reset-state", action="store_true") + parser.add_argument("--allow-unconnected-camera", action="store_true") + parser.add_argument("--plan-only", action="store_true") + return parser.parse_args(argv) + + +def main(argv=None): + args = parse_args(argv) + try: + code, receipt = run_bootstrap(args) + except Exception as exc: + code = 1 + receipt = {"schema": SCHEMA, "ok": False, "stage": "error", "error": str(exc)} + sys.stdout.write(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n") + return code + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/vision-x5-board-bootstrap.test.py b/tools/vision-x5-board-bootstrap.test.py new file mode 100644 index 0000000..d45371f --- /dev/null +++ b/tools/vision-x5-board-bootstrap.test.py @@ -0,0 +1,261 @@ +#!/usr/bin/env python3 +"""Unit tests for vision-x5-board-bootstrap.py and x5-station-bridge.py extensions.""" +import hashlib +import importlib.util +import json +from pathlib import Path +import struct +import subprocess +import sys +import tempfile +import unittest + +TOOLS_DIR = Path(__file__).resolve().parent +ROOT_DIR = TOOLS_DIR.parent + + +def load_module(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def fake_aarch64_elf(payload=b"fixture"): + # Minimal 64-bit little-endian AArch64 (machine=183) ELF header + header = bytearray(64) + header[0:4] = b"\x7fELF" + header[4] = 2 # 64-bit + header[5] = 1 # little-endian + struct.pack_into("