Spaces:
Running
Running
sync processor from GitLab 2bbf9fe: UMI SLAM 动作模块、批次指纹与设备进度、导出/路由/前端更新
Browse filesFiles changed (21)
- processor/README.md+49-47
- processor/app/api/worker.py+84-26
- processor/app/batch_fingerprint.pyAdded+194
- processor/app/device_progress.pyAdded+218
- processor/app/lerobot_export.py+341-25
- processor/app/localstore.py+269-35
- processor/app/processing/modules/lerobot_export.py+20-2
- processor/app/processing/modules/umi_slam_action.pyAdded+192
- processor/app/project_dataset.py+203-18
- processor/app/routes/devices.py+55-8
- processor/app/routes/export.py+9-2
- processor/app/routes/session.py+38
- processor/app/routes/video.py+196-34
- processor/app/umi_slam_action.pyAdded+269
- processor/tests/test_batch_fingerprint.pyAdded+181
- processor/tests/test_device_task_progress.pyAdded+181
- processor/tests/test_lerobot_export.pyAdded+105
- processor/tests/test_tactile_decode.py+146-1
- processor/tests/test_umi_slam_action.pyAdded+369
- processor/web/static/js/player.js+72-98
- processor/web/templates/index.html+1-1
123155 unmodified lines15916016116216316416516616716816917079 unmodified lines2502512522532542552562572582592602612622632642652662672682692702712722731 unmodified line275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306127 unmodified lines434435436437438439440441442443444445446447448449450# processor[English](README.md) | [中文](README.zh-CN.md)155 unmodified lines### Video sources| Type | Example source name | Description || --- | --- | --- || Mono RGB | `head_rgb` | Regular RGB video || Metric depth | `head_depth` | Independent metric-depth video || Stereo RGB | `stereo_left_rgb`, `stereo_right_rgb` | Left and right RGB videos || Stereo depth | `stereo_depth` | Independent depth video |RGB and Depth are always stored as independent streams. A depth-only stream is never treated asRGB and is never duplicated alongside the RGB stream.79 unmodified lines#### Capture modules (Input)| Frontend module | Inputs | Outputs | Purpose and rules || --- | --- | --- | --- || `RGB Camera` | None | `RGB Video` | Mono RGB video. The device is selected from the current project's data; blank means auto-match. || `RGB-D Camera` | None | `RGB Video`, `Depth` | Emits RGB and real depth streams from the same device; Depth can connect only to a depth input. || `Stereo RGB Camera` | None | `Left RGB Video`, `Right RGB Video` | Stereo RGB input. Connecting one side creates the corresponding left/right relationship. || `Stereo RGB-D Camera` | None | `Left RGB Video`, `Right RGB Video`, `Depth` | Stereo RGB plus real depth; Depth is used by RGB-D 3D processing. || `Glove Sensor` | None | `Glove Sensor Data` | Pressure, joint, or glove sensor data; no video output. It can connect directly to quality review. |#### Video and keypoint processing modules (Process)| Frontend module | Inputs | Outputs | Purpose and rules || --- | --- | --- | --- || `Human Annotation` | `RGB Video` | `Annotation` | Frame-level manual annotation on RGB video. || `AI Annotation` | `RGB Video` | `Annotation` | Video/segment annotation through a local or API VLM; API is recommended for deployment. || `RGB_TO_2D_BareHand` | `RGB Video` | `Hand 2D` | Bare-hand 2D keypoints. `Spatial` is display-only and exports no metric 3D. || `RGB_TO_2D_BlackGlove` | `RGB Video` | `Hand 2D` | Black-glove 2D keypoints. Without Depth, it does not calculate metric 3D. || `RGB-D_3D_BareHand` | `RGB Video`, `Depth` | `Hand 3D` | Metric 3D bare-hand keypoints from RGB and real Depth; a missing branch is skipped. || `RGB-D_3D_BlackGlove` | `RGB Video`, `Depth` | `Hand 3D` | Metric 3D black-glove keypoints from RGB and real Depth; it does not search the disk or fall back to RGB estimation. |`MediaPipe Hand` remains available for historical workflows and backend compatibility but is hiddenfrom the new-workflow palette. All nodes provide hover text describing their purpose and accepted1 unmodified line#### Review modules (Review)| Frontend module | Inputs | Outputs | Purpose and rules || --- | --- | --- | --- || `Human Review` | `Review Target` | `Reviewed Data` | Human inspection of video, keypoints, or annotation results before downstream processing. || `AI Quality Review` | `Quality Review Target` | `Reviewed Data` | Checks video decoding, frame continuity, black screens, freezes, annotation coverage, and sensor data. |#### Export modules (Export)| Frontend module | Inputs | Outputs | Purpose and rules || --- | --- | --- | --- || `LeRobot Export` | `Exportable Data` | `Dataset` | Exports LeRobot v2.1 or v3.0; the version is selected on the node. || `HDF5 Export` | `Exportable Data` | `Dataset` | Exports HDF5 with the configured compression parameters. |#### Workflow Studio UI components<details><summary>Click to expand: frontend component reference</summary>| UI component | Function || --- | --- || `NodePalette` | Displays Input, Process, Review, and Export categories; supports search, category collapse, and hover descriptions. || `WorkflowCanvas` | Supports drag-and-drop node creation, typed-port connections, node movement, selection, zoom, grid snapping, and minimap navigation. || `WorkflowNode` | Renders the card title, ports, project device selector/input, `Spatial` button, and API settings button. || `WorkflowDrawer` | Lists workflows, creates new workflows, loads workflows, and refreshes project-specific input sources. || `PipelineToolbar` | Provides New, Save, Save As, workflow JSON Export, and Run actions; the yellow dot indicates unsaved changes. || `NodeSettingsModal` | Configures AI Annotation API vendor, model, endpoint, and key fields. || `DeletableEdge` | Renders data connections; a selected edge can be deleted. |Device selection is always scoped to the current project. A new empty workflow does not display adevice from another project. After data is uploaded, each card's selector shows only real sources127 unmodified linesConfiguration is stored in `processor/.env` or environment variables and must not becommitted:| Setting | Purpose || --- | --- || `STORAGE_DIR` | Root directory for data and system state || `STORAGE_BACKEND` | `local` or `sftp` || `SFTP_*` | Remote data directory and SSH connection settings || `API_KEY` | API key for the capture client and protected endpoints || `WORKER_API_KEY` | API key used by the Worker to claim and return jobs || `JWT_SECRET` | Secret used to sign Web login sessions || `UPLOAD_STAGING_DIR` | Local staging directory for upload archives || `HOST` / `PORT` | Web/API listen address and port || `PUBLIC_BASE_URL` | Public service URL |See [`.env.example`](.env.example) for the complete template. Production environments must userandom secrets and restrict `.env` permissions. Never put passwords, tokens, API keys, or database12345155 unmodified lines16116216316416516616716816917017117279 unmodified lines2522532542552562572582592602612622632642652662672682692702712722732742751 unmodified line277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308127 unmodified lines436437438439440441442443444445446447448449450451452# processor[English](README.md) | [中文](README.zh-CN.md)155 unmodified lines### Video sources| Type | Example source name | Description || ------------ | ----------------------------------------- | ------------------------------ || Mono RGB | `head_rgb` | Regular RGB video || Metric depth | `head_depth` | Independent metric-depth video || Stereo RGB | `stereo_left_rgb`, `stereo_right_rgb` | Left and right RGB videos || Stereo depth | `stereo_depth` | Independent depth video |RGB and Depth are always stored as independent streams. A depth-only stream is never treated asRGB and is never duplicated alongside the RGB stream.79 unmodified lines#### Capture modules (Input)| Frontend module | Inputs | Outputs | Purpose and rules || ----------------------- | ------ | -------------------------------------------------- | -------------------------------------------------------------------------------------------------- || `RGB Camera` | None | `RGB Video` | Mono RGB video. The device is selected from the current project's data; blank means auto-match. || `RGB-D Camera` | None | `RGB Video`, `Depth` | Emits RGB and real depth streams from the same device; Depth can connect only to a depth input. || `Stereo RGB Camera` | None | `Left RGB Video`, `Right RGB Video` | Stereo RGB input. Connecting one side creates the corresponding left/right relationship. || `Stereo RGB-D Camera` | None | `Left RGB Video`, `Right RGB Video`, `Depth` | Stereo RGB plus real depth; Depth is used by RGB-D 3D processing. || `Glove Sensor` | None | `Glove Sensor Data` | Pressure, joint, or glove sensor data; no video output. It can connect directly to quality review. |#### Video and keypoint processing modules (Process)| Frontend module | Inputs | Outputs | Purpose and rules || ------------------------ | ------------------------ | -------------- | -------------------------------------------------------------------------------------------------------------------- || `Human Annotation` | `RGB Video` | `Annotation` | Frame-level manual annotation on RGB video. || `AI Annotation` | `RGB Video` | `Annotation` | Video/segment annotation through a local or API VLM; API is recommended for deployment. || `RGB_TO_2D_BareHand` | `RGB Video` | `Hand 2D` | Bare-hand 2D keypoints.`Spatial` is display-only and exports no metric 3D. || `RGB_TO_2D_BlackGlove` | `RGB Video` | `Hand 2D` | Black-glove 2D keypoints. Without Depth, it does not calculate metric 3D. || `RGB-D_3D_BareHand` | `RGB Video`, `Depth` | `Hand 3D` | Metric 3D bare-hand keypoints from RGB and real Depth; a missing branch is skipped. || `RGB-D_3D_BlackGlove` | `RGB Video`, `Depth` | `Hand 3D` | Metric 3D black-glove keypoints from RGB and real Depth; it does not search the disk or fall back to RGB estimation. |`MediaPipe Hand` remains available for historical workflows and backend compatibility but is hiddenfrom the new-workflow palette. All nodes provide hover text describing their purpose and accepted1 unmodified line#### Review modules (Review)| Frontend module | Inputs | Outputs | Purpose and rules || --------------------- | ------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------ || `Human Review` | `Review Target` | `Reviewed Data` | Human inspection of video, keypoints, or annotation results before downstream processing. || `AI Quality Review` | `Quality Review Target` | `Reviewed Data` | Checks video decoding, frame continuity, black screens, freezes, annotation coverage, and sensor data. |#### Export modules (Export)| Frontend module | Inputs | Outputs | Purpose and rules || ------------------ | ------------------- | ----------- | ------------------------------------------------------------------ || `LeRobot Export` | `Exportable Data` | `Dataset` | Exports LeRobot v2.1 or v3.0; the version is selected on the node. || `HDF5 Export` | `Exportable Data` | `Dataset` | Exports HDF5 with the configured compression parameters. |#### Workflow Studio UI components<details><summary>Click to expand: frontend component reference</summary>| UI component | Function || --------------------- | ------------------------------------------------------------------------------------------------------------------------------------ || `NodePalette` | Displays Input, Process, Review, and Export categories; supports search, category collapse, and hover descriptions. || `WorkflowCanvas` | Supports drag-and-drop node creation, typed-port connections, node movement, selection, zoom, grid snapping, and minimap navigation. || `WorkflowNode` | Renders the card title, ports, project device selector/input,`Spatial` button, and API settings button. || `WorkflowDrawer` | Lists workflows, creates new workflows, loads workflows, and refreshes project-specific input sources. || `PipelineToolbar` | Provides New, Save, Save As, workflow JSON Export, and Run actions; the yellow dot indicates unsaved changes. || `NodeSettingsModal` | Configures AI Annotation API vendor, model, endpoint, and key fields. || `DeletableEdge` | Renders data connections; a selected edge can be deleted. |Device selection is always scoped to the current project. A new empty workflow does not display adevice from another project. After data is uploaded, each card's selector shows only real sources127 unmodified linesConfiguration is stored in `processor/.env` or environment variables and must not becommitted:| Setting | Purpose || ---------------------- | ------------------------------------------------------ || `STORAGE_DIR` | Root directory for data and system state || `STORAGE_BACKEND` | `local` or `sftp` || `SFTP_*` | Remote data directory and SSH connection settings || `API_KEY` | API key for the capture client and protected endpoints || `WORKER_API_KEY` | API key used by the Worker to claim and return jobs || `JWT_SECRET` | Secret used to sign Web login sessions || `UPLOAD_STAGING_DIR` | Local staging directory for upload archives || `HOST` / `PORT` | Web/API listen address and port || `PUBLIC_BASE_URL` | Public service URL |See [`.env.example`](.env.example) for the complete template. Production environments must userandom secrets and restrict `.env` permissions. Never put passwords, tokens, API keys, or database
21 unmodified lines2223242526272830 unmodified lines59606162636465666710 unmodified lines7879808182838497 unmodified lines18218318418518618713 unmodified lines20120220320420520620720820921021121221321421521635 unmodified lines252253254255256257258259260261262263264265266267268269270271272137 unmodified lines41041141241341441521 unmodified linesfrom app.config import settingsfrom app.localstore import (list_runs, get_run, save_run, get_episode,set_episode_status, list_exceptions, delete_exception,update_run_if_owned, save_annotations,)30 unmodified linesasync def claim_job(body: dict, _: str = Depends(verify_worker_api_key)):"""Worker 轮询领取任务:queued 或租约过期的 running。"""now = _now()runs = list_runs()candidate = Nonefor r in sorted(runs, key=lambda r: r.get("created_at") or ""):status = r.get("status")if status in ("queued", "pending"):candidate = r10 unmodified linesif candidate is None:return Response(status_code=204)run = candidaterun["status"] = "running"run["worker_id"] = body.get("worker_id")run["lease_token"] = uuid.uuid4().hex97 unmodified linespassdef prepare_episode_input_cache(episode_id: str, batch_dir: Path | None = None) -> Path:"""Build a local immutable input archive for a workflow batch.13 unmodified lineszip_path, stamp_path = _input_zip_cache_paths(str(episode_id))with _INPUT_ZIP_LOCK:if zip_path.is_file() and _input_zip_stamp_matches(stamp_path, batch_dir):return zip_pathtmp = tempfile.NamedTemporaryFile(prefix=f"egodata-input-{episode_id}-", suffix=".zip",dir=str(_worker_tmp_root()), delete=False,)tmp.close()try:with zipfile.ZipFile(tmp.name, "w", allowZip64=True) as archive:canonical_episode = Noneif (batch_dir / "meta" / "episodes").is_dir():from app.project_dataset import episode_row, episode_files35 unmodified lineselse zipfile.ZIP_DEFLATED)archive.write(path, str(arcname), compress_type=compression)except Exception:_remove_later(tmp.name)raisetry:_input_zip_cache_dir().mkdir(parents=True, exist_ok=True)shutil.move(tmp.name, str(zip_path))stamp_path.write_text(json.dumps(_input_zip_stamp(batch_dir)), encoding="utf-8")_evict_input_zip_cache()except Exception:_remove_later(tmp.name)raisereturn zip_path@router.get("/jobs/{run_id}/input")137 unmodified linesfinally:shutil.rmtree(staging_dir, ignore_errors=True)def mark_completed(current: dict) -> None:current["status"] = "completed"current["finished_at"] = finished_at21 unmodified lines2223242526272830 unmodified lines596061626364656667686910 unmodified lines80818283848586878897 unmodified lines18618718818919019119219319419519619719819920020120220320420520620720820921021121221321421513 unmodified lines22923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427535 unmodified lines311312313314315316317318319320137 unmodified lines45845946046146246346446546646746846947047147247321 unmodified linesfrom app.config import settingsfrom app.localstore import (list_runs, list_run_summaries, get_run, save_run, get_episode,set_episode_status, list_exceptions, delete_exception,update_run_if_owned, save_annotations,)30 unmodified linesasync def claim_job(body: dict, _: str = Depends(verify_worker_api_key)):"""Worker 轮询领取任务:queued 或租约过期的 running。"""now = _now()# Scan summaries, not full records: this endpoint is polled every few# seconds and reading every historical run on each poll is what saturated# the API process. Only the winner gets its full payload loaded.candidate = Nonefor r in sorted(list_run_summaries(), key=lambda r: r.get("created_at") or ""):status = r.get("status")if status in ("queued", "pending"):candidate = r10 unmodified linesif candidate is None:return Response(status_code=204)# Reload the full record before mutating — save_run replaces the whole# document, so writing the summary back would drop the run's payload.run = get_run(str(candidate.get("id"))) or dict(candidate)run["status"] = "running"run["worker_id"] = body.get("worker_id")run["lease_token"] = uuid.uuid4().hex97 unmodified linespassdef _zip_data_parquets_readable(archive_path: Path) -> bool:"""包内 ``data/*.parquet`` 是否都能读出 footer。NAS/SSHFS 偶尔返回被截断的内容,而 ``archive.write`` 会把它原样打进包。这种包一旦缓存下来就会**永久**生效:worker 解压后读到的副本本身就是坏的,重试也救不回来 —— 表现为``ArrowInvalid: Parquet magic bytes not found in footer``。只读 schema(footer)不做全量解码,代价很小。"""try:import pyarrow.parquet as pqwith zipfile.ZipFile(archive_path) as archive:for info in archive.infolist():name = info.filenameif not (name.startswith("data/") and name.endswith(".parquet")):continuewith archive.open(info) as handle:pq.read_schema(handle)return Trueexcept Exception:return Falsedef prepare_episode_input_cache(episode_id: str, batch_dir: Path | None = None) -> Path:"""Build a local immutable input archive for a workflow batch.13 unmodified lineszip_path, stamp_path = _input_zip_cache_paths(str(episode_id))with _INPUT_ZIP_LOCK:# 缓存命中也要校验:戳只看 meta/info.json,而合并只重写 data parquet# —— 戳因此可能在内容已变时仍判为新鲜,把早先固化的坏包一直发出去。# 读 footer 很便宜,换掉「坏包只能用一次才知道」的被动局面。if (zip_path.is_file()and _input_zip_stamp_matches(stamp_path, batch_dir)and _zip_data_parquets_readable(zip_path)):return zip_path# 截断的网络读入不该被缓存:校验失败就重打,连续失败才报错。# 打包本身很便宜(本地 zip),代价远低于把坏包固化进缓存。packaged: str | None = Nonefor attempt in range(3):packaged = _build_input_zip(episode_id, batch_dir)if _zip_data_parquets_readable(Path(packaged)):break_remove_later(packaged)packaged = Noneprint(f"[Worker] input archive unreadable, rebuilding "f"({attempt + 1}/3): {episode_id}")if packaged is None:raise RuntimeError(f"Input archive for {episode_id} stays unreadable after 3 attempts "f"(source on the storage mount may be corrupt)")_input_zip_cache_dir().mkdir(parents=True, exist_ok=True)shutil.move(packaged, str(zip_path))stamp_path.write_text(json.dumps(_input_zip_stamp(batch_dir)), encoding="utf-8")_evict_input_zip_cache()return zip_pathdef _build_input_zip(episode_id: str, batch_dir: Path) -> str:"""把一集的 canonical 文件打成 zip,返回临时包路径。"""tmp = tempfile.NamedTemporaryFile(prefix=f"egodata-input-{episode_id}-", suffix=".zip",dir=str(_worker_tmp_root()), delete=False,)tmp.close()try:with zipfile.ZipFile(tmp.name, "w", allowZip64=True) as archive:canonical_episode = Noneif (batch_dir / "meta" / "episodes").is_dir():from app.project_dataset import episode_row, episode_files35 unmodified lineselse zipfile.ZIP_DEFLATED)archive.write(path, str(arcname), compress_type=compression)except Exception:_remove_later(tmp.name)raisereturn tmp.name@router.get("/jobs/{run_id}/input")137 unmodified linesfinally:shutil.rmtree(staging_dir, ignore_errors=True)# 合并刚重写了该集的 data parquet,而 Worker 输入包的「新鲜度戳」只看# meta/info.json —— 合并不碰那个文件,戳因此不变,坏包会被一直复用。# 实测后果:包内 parquet 被截断(ArrowInvalid: Parquet magic bytes not# found in footer),节点每次都以「列不可读」跳过,且重试无用(解压出来的# 副本本身就是坏的)。这里主动清掉,下一次运行会重新打包。try:clear_input_zip_cache(str(run.get("episode_id") or ""))except Exception:pass # 清缓存失败不影响本次结果,下次打包仍会走戳校验def mark_completed(current: dict) -> None:current["status"] = "completed"current["finished_at"] = finished_at
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194"""批次内容指纹 — 识别"换个包名重传同一份数据"。
采集端偶尔会把已经上传过的录制再推一遍,但**包名变了**(例如重装、重开 App 后本地去重标记丢失,或包名规则从序号变成时间戳)。此时``session.py`` 的 ``incoming_name in existing_ids`` 判不出重复,同一份数据就会被当成新批次追加,审核页出现两条一模一样的数据,导出也会重复计一份(实测:UMIGripper_AI 的 4 组批次视频字节级相同、parquet 除 ``episode_index`` 外逐值相同)。
本模块给出一个与**包名无关**的内容身份:
- 每个视频文件的 md5(按 source_key 排序) - canonical data parquet 的内容哈希(排除 ``episode_index`` —— 同一次录制被追加成不同 episode 时,只有这一列会变)
合成为一个短字符串 key,存到 ``state/batch_fingerprints.json``。上传时先算新批次的 key,再按项目查表:命中且目标 episode 仍然存在,就判定为重复上传。
**失败一律放行**:算不出指纹、索引读不到、目标 episode 已被删除 ——任一情况都按"新批次"正常入库(即本模块不存在时的行为),绝不因为指纹机制本身的问题丢数据。"""
from __future__ import annotations
import hashlibimport jsonimport threadingfrom pathlib import Pathfrom typing import Any
from app.localstore import STATE_ROOT
INDEX_PATH = STATE_ROOT / "batch_fingerprints.json"_LOCK = threading.Lock()
# 视频按块读;读取量固定,不随文件大小膨胀。_CHUNK = 1 << 20
def _file_md5(path: Path) -> str | None: digest = hashlib.md5() try: with open(path, "rb") as handle: for block in iter(lambda: handle.read(_CHUNK), b""): digest.update(block) except OSError: return None return digest.hexdigest()
def _parquet_content_hash(path: Path) -> str | None: """canonical data parquet 的内容哈希,排除 ``episode_index``。
``episode_index`` 是同一次录制被追加成不同 episode 时唯一会变的列, 必须排除,否则重复上传算不出相同的 key。用 Arrow IPC 序列化取字节: 对嵌套 list 列(手套 250x250x3 力矩阵、手部关键点)比对 pandas 的 hash 更稳,且与行序无关的假设更少 —— 这里行序本身就是内容的一部分。 """ try: import pyarrow as pa import pyarrow.parquet as pq except ImportError: return None try: table = pq.read_table(path) if "episode_index" in table.column_names: table = table.drop_columns(["episode_index"]) sink = pa.BufferOutputStream() with pa.ipc.new_stream(sink, table.schema) as writer: writer.write_table(table) return hashlib.md5(sink.getvalue().to_pybytes()).hexdigest() except Exception: return None
def compute_fingerprint(root: Path) -> str | None: """Staging 目录(已 normalize)的内容指纹;算不出返回 None。""" root = Path(root) parts: list[str] = []
videos_root = root / "videos" if videos_root.is_dir(): from app.lerobot_v21 import iter_video_streams
entries: list[tuple[str, str]] = [] for source, path in iter_video_streams(videos_root): digest = _file_md5(Path(path)) if digest is None: return None entries.append((str(source), digest)) if not entries: return None parts.append("|".join(f"v:{s}={d}" for s, d in sorted(entries)))
data_files = sorted( path for path in (root / "data").rglob("*.parquet") if path.is_file() and "/meta/" not in path.as_posix().casefold() ) if not data_files: return None digest = _parquet_content_hash(data_files[0]) if digest is None: return None parts.append(f"d:{digest}")
return ";".join(parts)
def _read_index() -> dict[str, dict[str, str]]: try: value = json.loads(INDEX_PATH.read_text(encoding="utf-8")) except (OSError, ValueError): return {} return value if isinstance(value, dict) else {}
def _write_index(index: dict) -> None: try: INDEX_PATH.parent.mkdir(parents=True, exist_ok=True) temporary = INDEX_PATH.with_suffix(".json.tmp") temporary.write_text( json.dumps(index, ensure_ascii=False, indent=2), encoding="utf-8") temporary.replace(INDEX_PATH) except OSError: pass
def lookup_duplicate(project_folder: str, fingerprint: str | None, live_ids: set[str]) -> str | None: """返回与本次上传内容相同的、且**仍然存在**的 episode_id。
``live_ids`` 来自当前项目数据集的实际扫描结果:索引里指向已删除 episode 的陈旧条目在这里被自然过滤掉,因此"删除后重新上传同一条 录制"仍会正常入库,不会被误判成重复。 """ if not fingerprint: return None with _LOCK: index = _read_index() entries = index.get(str(project_folder)) if not isinstance(entries, dict): return None episode_id = entries.get(str(fingerprint)) if not episode_id: return None return str(episode_id) if str(episode_id) in live_ids else None
def record_fingerprint(project_folder: str, fingerprint: str | None, episode_id: str) -> None: """记录已提交批次的内容指纹(失败静默:只是失去一次去重机会)。""" if not fingerprint: return with _LOCK: index = _read_index() if not isinstance(index, dict): index = {} entries = index.get(str(project_folder)) if not isinstance(entries, dict): entries = {} entries[str(fingerprint)] = str(episode_id) # 同一 episode 换内容(同名重传)时清掉它名下的旧指纹,避免 # 索引里留下永远指不到实际内容的条目。 for key in [k for k, v in entries.items() if str(v) == str(episode_id) and k != str(fingerprint)]: entries.pop(key, None) index[str(project_folder)] = entries _write_index(index)
def forget_fingerprint(episode_id: str) -> None: """批次被删除后清除其指纹条目。""" target = str(episode_id) with _LOCK: index = _read_index() changed = False for entries in index.values(): if not isinstance(entries, dict): continue for key in [k for k, v in entries.items() if str(v) == target]: entries.pop(key, None) changed = True if changed: _write_index(index)
def describe(project_folder: str) -> dict[str, Any]: """诊断用:该项目已记录的内容指纹。""" with _LOCK: index = _read_index() entries = index.get(str(project_folder)) return entries if isinstance(entries, dict) else {}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218"""采集端任务进度上报账本 —— 本地 JSON 存储(无数据库)。
为什么要这个账本:``GET /device/tasks`` 原先把「项目目录下的 session 数」当采集进度,而 session 是**上传**的产物。采集端本身在「录制完成」时就已经把增量上报上来(见采集端 ``core/task_record.py`` 的分账模型),于是同一条数据被算两次——录制一次、上传一次。2026-09-10 现场:UMIGripper_AI 本机录了 12 条、服务器上 16 个 session,界面显示 28/20,两边的数都不可信。
现在的口径:
项目进度 = 各设备上报的录制完成数之和
只有**从未收到过上报**的项目才回退到 session 计数,这样升级前就存在的历史项目不会突然归零;某个项目一旦有设备上报,它就固定按上报口径走(上传不再改变它,采集端录一条 +1)。
幂等:采集端用 ``session_id = "{device}:{task_id}:{水位}"`` 标识一次增量,同一 (task_id, device_name, session_id) 只计一次 —— 网络抖动重试、程序被杀后重放同一个水位,都不会重复计数。
文件: ``data/state/device_task_progress.json``
{"tasks": {"<task_id>": { "devices": {"<device_name>": { "count": 12, "sessions": ["EGO_001:<task_id>:0", ...], # 已计入的幂等键 "updated_at": "2026-09-10T02:11:39+00:00"}}, "updated_at": "..."}}, "updated_at": "..."}"""
from __future__ import annotations
import jsonimport threadingfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Iterable
# 读-改-写必须串行:uvicorn 单进程多线程,两个设备同时上报时不能丢增量_LOCK = threading.RLock()
PROGRESS_FILE_NAME = "device_task_progress.json"
# 单次上报上限:采集端 flush 的是「本机未同步增量」,正常是 1~几十;# 超过这个数说明上报方数据脏了,直接拒绝而不是把进度顶飞。MAX_INCREMENT = 100000
_MAX_FIELD = 200 # task_id / device_name / session_id 的长度上限
def _progress_file(path: Path | None = None) -> Path: if path is not None: return Path(path) from app.localstore import STATE_ROOT return STATE_ROOT / PROGRESS_FILE_NAME
def _now() -> str: return datetime.now(timezone.utc).isoformat()
def _read(path: Path | None = None) -> dict: try: data = json.loads(_progress_file(path).read_text(encoding="utf-8")) except Exception: return {"tasks": {}} if not isinstance(data, dict): return {"tasks": {}} tasks = data.get("tasks") if not isinstance(tasks, dict): data["tasks"] = {} return data
def _write(data: dict, path: Path | None = None) -> None: target = _progress_file(path) target.parent.mkdir(parents=True, exist_ok=True) tmp = target.with_suffix(target.suffix + ".tmp") tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8") tmp.replace(target)
def _clean(value, limit: int = _MAX_FIELD) -> str: return str(value or "").strip()[:limit]
def reported_totals(path: Path | None = None) -> dict[str, int]: """各任务的上报聚合数。**只含收到过上报的任务** —— 没上报过的项目不在 这里,调用方据此回退到 session 计数。""" out: dict[str, int] = {} with _LOCK: data = _read(path) for task_id, entry in (data.get("tasks") or {}).items(): if not isinstance(entry, dict): continue total = 0 for dev in (entry.get("devices") or {}).values(): if isinstance(dev, dict): total += int(dev.get("count") or 0) out[str(task_id)] = total return out
def reported_total(task_id: str, path: Path | None = None) -> int | None: """单个任务的上报聚合数;从未上报过返回 None。""" return reported_totals(path).get(str(task_id))
def needs_session_fallback(projects: list[dict], reported: dict[str, int]) -> bool: """是否还有项目需要 session 计数兜底。
全都有上报时调用方可跳过目录扫描(远程存储上的一次全量遍历)。 """ return any(str(p.get("id") or "") not in reported for p in projects)
def resolve_count(project: dict, reported: dict[str, int], sessions: int) -> tuple[int, str]: """单个项目的 (current_count, 口径)。
有上报 → 上报聚合数(录制口径,上传不再影响它); 没有 → session 数(升级前的历史项目不归零)。 """ pid = str(project.get("id") or "") if pid in reported: return int(reported[pid]), "reported" return int(sessions or 0), "sessions"
def apply_increment(task_id: str, device_name: str, session_id: str, increment: int, path: Path | None = None) -> dict: """把一次上报落账,返回该任务的最新聚合数。
幂等:同一 (task_id, device_name, session_id) 第二次进来只读取不累加 (``applied`` 为 False),采集端重试因此安全。 """ task_id = _clean(task_id) device_name = _clean(device_name) session_id = _clean(session_id) with _LOCK: data = _read(path) tasks = data.setdefault("tasks", {}) entry = tasks.setdefault(task_id, {"devices": {}}) if not isinstance(entry.get("devices"), dict): entry["devices"] = {} dev = entry["devices"].setdefault( device_name, {"count": 0, "sessions": []}) sessions = dev.get("sessions") if not isinstance(sessions, list): sessions = dev["sessions"] = [] applied = False if session_id not in sessions: dev["count"] = int(dev.get("count") or 0) + int(increment) sessions.append(session_id) dev["updated_at"] = _now() entry["updated_at"] = dev["updated_at"] data["updated_at"] = dev["updated_at"] applied = True total = sum(int(d.get("count") or 0) for d in entry["devices"].values() if isinstance(d, dict)) if applied: _write(data, path) return {"total": total, "applied": applied, "device_count": int(dev.get("count") or 0), "device": device_name, "task_id": task_id}
def apply_report(body: dict, known_task_ids: Iterable[str] | None = None, path: Path | None = None) -> dict: """校验并落账一次上报,返回响应体(路由直接回给采集端)。
Raises: ValueError: 参数缺失/非法/任务不存在 —— 调用方转 HTTP 400。
刻意**不返回 404**:采集端把 404 当成「后端还没实现该端点」并永久降级 (``_progress_supported = False``),此后整机所有任务都不再上报。参数错 与未知任务都属于「这次请求有问题」,用 400 表达即可。 """ if not isinstance(body, dict): raise ValueError("body must be a JSON object") task_id = _clean(body.get("task_id")) device_name = _clean(body.get("device_name")) session_id = _clean(body.get("session_id")) if not task_id: raise ValueError("task_id required") if not device_name: raise ValueError("device_name required") if not session_id: raise ValueError("session_id required (idempotency key)")
raw = body.get("increment", 0) if isinstance(raw, bool): raise ValueError("increment must be an integer") try: increment = int(raw) except (TypeError, ValueError): raise ValueError("increment must be an integer") if increment < 0: raise ValueError("increment must be >= 0") if increment > MAX_INCREMENT: raise ValueError(f"increment too large (max {MAX_INCREMENT})")
if known_task_ids is not None and task_id not in set(known_task_ids): raise ValueError(f"unknown task_id: {task_id}")
result = apply_increment(task_id, device_name, session_id, increment, path) return { "ok": True, "task_id": task_id, "device_name": device_name, "applied": result["applied"], "increment": increment, # 采集端读这个字段当后端权威数 —— 必须是 int(布尔会被 isinstance 放行) "completed_count": int(result["total"]), "updated_at": _now(), }128 unmodified lines129130131132133134135136137130 unmodified lines2682692702712722732748 unmodified lines283284285286287288289290291292293294295296297298299300301302303304305306307378 unmodified lines68668768868969069169269311 unmodified lines705706707708709710711347 unmodified lines10591060106110621063106410651066106710681069107010711072107310741 unmodified line107610771078107910801081108217 unmodified lines1100110111021103110411051106555 unmodified lines16621663166416651666166716681669167078 unmodified lines174917501751175217531754175535 unmodified lines1791179217931794179517961797227 unmodified lines2025202620272028202920302031203220332034266 unmodified lines23012302230323042305230634 unmodified lines234123422343234423452346128 unmodified linesif not np.isfinite(num).any():continueq = _quantiles(num)stats[col] = {"dtype": "float32" if np.issubdtype(s.dtype, np.floating) else "int64","shape": [1],"mean": float(np.nanmean(num)),"std": float(np.nanstd(num)),"min": float(np.nanmin(num)),130 unmodified lines}continuesamples: list = []for vpath in videos:cap = cv2.VideoCapture(str(vpath))if not cap.isOpened():8 unmodified linesif not ok:breakif read_idx % step == 0 and frame.ndim == 3:samples.append(frame.astype(np.float32)[..., :channels] / 255.0)read_idx += 1cap.release()if not samples:continuestack = np.stack(samples) # (T, H, W, C)per_channel = stack.reshape(-1, stack.shape[-1])def _nested(vals):return [[[float(v)] for v in vals]]q = np.percentile(per_channel, [1, 10, 50, 90, 99], axis=0)stats[vkey] = {"min": _nested(per_channel.min(axis=0)),"max": _nested(per_channel.max(axis=0)),"mean": _nested(per_channel.mean(axis=0)),"std": _nested(per_channel.std(axis=0)),"q01": _nested(q[0]), "q10": _nested(q[1]),"q50": _nested(q[2]), "q90": _nested(q[3]),"q99": _nested(q[4]),"count": [int(per_channel.shape[0] * per_channel.shape[1])],}except Exception:pass378 unmodified linesdef _read_sensor_rows(session_dir: Path,episode_id: str | None = None) -> dict[int, dict]:"""Merge independently stored glove/action parquet rows by frame_index."""rows: dict[int, dict] = {}try:import pyarrow.parquet as pq11 unmodified linesand path.name != f"episode_{episode_index:06d}.parquet"):continuetry:table = pq.read_table(path)names = table.schema.namesif "frame_index" not in names:continue347 unmodified linesreturn "float32"def _pad_variable_columns(rows: list[dict],nan_fill: float = float("nan")) -> int:"""IMU 变长列固定长度化(官方加载器不支持变长:list<int64> 对声明int64[1] 实测 cast 失败)。返回补齐后的每帧样本数 cap。- observation.imu:每样本 6 维 → 展平为 cap*6(nan_fill 补尾)- observation.imu_ts_ns:补 0 到 cap无 IMU 列时返回 3(不影响任何声明)。"""import numpy as npimu_cap = 3for row in rows:for key in ("observation.imu", "observation.imu_ts_ns"):1 unmodified lineif isinstance(value, (list, tuple)):imu_cap = max(imu_cap, len(value))if not any("observation.imu" in row for row in rows):return imu_capfor row in rows:imu = row.get("observation.imu")if isinstance(imu, (list, tuple)):17 unmodified linesif isinstance(ts, (list, tuple)):row["observation.imu_ts_ns"] = ([int(v) for v in ts] + [0] * (imu_cap - len(ts)))[:imu_cap]return imu_capdef _propagated_hand_sets(source_row: dict) -> tuple[set[str], set[str], dict[str, set[str]]]:555 unmodified lineshand_3d_right_paths: list[str] | None = None,version: str = "v3.0",hand_3d_unit: str | None = None,progress_callback=None) -> Path:"""Build a LeRobot dataset (``version`` = "v2.1" | "v3.0").Depth sources are exported as their preview video (``is_depth_map``)plus the per-frame ``observation.depth.<source>.valid`` marker; theoriginal 16-bit PNG sequence stays in the session directory and is not78 unmodified lines# 本集实际导出的每路视频(帧数, fps) → episodes parquet 的# videos/<key>/from_timestamp 映射(官方 v3 加载器按时间戳定位帧)episode_video_meta: dict[str, tuple[int, float]] = {}sensor_rows = _read_sensor_rows(session_dir, episode_id)annotation_map, annotation_defs, _skipped_candidates = _annotation_maps(episode_id)description = str(episode.get("project") or "").strip()35 unmodified lines/ f"observation.images.{source_key}")output_video = destination / f"file-{out_episode_index:03d}.mp4"destination.mkdir(parents=True, exist_ok=True)shutil.copy2(source, output_video)total_videos += 1probed_count, probed_fps, width, height = _probe_video(source)episode_video_meta[f"observation.images.{source_key}"] = (227 unmodified linesexcept Exception:pass # 进度回调失败不影响导出本身# 变长异步传感器列固定长度化:官方加载器不支持变长列(实测# list<int64> 对声明 int64[1] 直接 cast 失败)。取全数据集最大# 样本数补齐,声明 shape 同步为固定长度,变长语义保留在 note。imu_cap = _pad_variable_columns(rows, nan_fill=0.0 if is_v2 else float("nan"))# 收敛:删恒定哨兵垃圾列(全程 NaN/-1/0/空串 → 数据从未写入)。266 unmodified linesimport numpy as nparr = np.asarray(value)shape = list(arr.shape) if arr.ndim else [1]if key in ("observation.tactile.left", "observation.tactile.right"):features[key] = {"dtype": "float32", "shape": [256],34 unmodified lines"shape": shape}if junk_cols:features = {k: v for k, v in features.items() if k not in junk_cols}# 深度有效帧标记列(行循环写入,不声明会导致官方加载器读不完整)for depth_key in sorted(depth_source_keys):key = f"observation.depth.{depth_key}.valid"128 unmodified lines129130131132133134135136137138139130 unmodified lines2702712722732742752762772782792802812822832842852862872882892902918 unmodified lines300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343378 unmodified lines72272372472572672772872973073173273373473511 unmodified lines747748749750751752753754755756757758759347 unmodified lines110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271 unmodified line132913301331133213331334133517 unmodified lines1353135413551356135713581359555 unmodified lines19151916191719181919192019211922192319241925192619271928192978 unmodified lines20082009201020112012201320142015201635 unmodified lines2052205320542055205620572058227 unmodified lines228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318266 unmodified lines2585258625872588258925902591259225932594259534 unmodified lines263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662128 unmodified linesif not np.isfinite(num).any():continueq = _quantiles(num)# 只写数值统计量。不要再加 dtype/shape 之类的元数据字段:官方# 加载器会把 stats 里的每一项都转成张量做归一化,字符串字段直接# 崩在 torch.from_numpy(np.ndarray of type numpy.str_)。官方数据集# 的 stats 也只有 min/max/mean/std/count。stats[col] = {"mean": float(np.nanmean(num)),"std": float(np.nanstd(num)),"min": float(np.nanmin(num)),130 unmodified lines}continue# 增量累积:全部集的采样帧若一次性留在内存里会爆 —— 960×1280# 的一帧 float32 是 14.75MB,34 集 × 约 200 采样帧 ≈ 100GB。# 这里只保留跑动统计量(min/max/和/平方和/计数)与一个固定大小的# 分位数蓄水池,内存与集数无关。ch_sum = np.zeros(channels, dtype=np.float64)ch_sq = np.zeros(channels, dtype=np.float64)ch_min = np.full(channels, np.inf, dtype=np.float64)ch_max = np.full(channels, -np.inf, dtype=np.float64)pixel_count = 0# 蓄水池上限与每帧贡献:分位数只需近似,但样本必须**跨帧、跨集**# 均匀铺开 —— 只取前几帧会让分位数偏向最早的那一集。每帧按固定# 步长抽约 1200 个像素,800 万像素上限可覆盖数千帧。reservoir_cap = 8_000_000per_frame_budget = 1200taken = 0reservoir: list = []for vpath in videos:cap = cv2.VideoCapture(str(vpath))if not cap.isOpened():8 unmodified linesif not ok:breakif read_idx % step == 0 and frame.ndim == 3:# 先按步长抽样再转 float:一帧 960×1280 有 120 万像素,# 对整帧做 astype(float32)/255 是这一步的主要开销,# 而统计只需要千级样本。抽样后再运算快约三个数量级。flat_u8 = frame[..., :channels].reshape(-1, channels)stride_u8 = max(1, flat_u8.shape[0] // per_frame_budget)flat = (flat_u8[::stride_u8].astype(np.float32) / 255.0)ch_sum += flat.sum(axis=0, dtype=np.float64)ch_sq += np.square(flat, dtype=np.float64).sum(axis=0)ch_min = np.minimum(ch_min, flat.min(axis=0))ch_max = np.maximum(ch_max, flat.max(axis=0))pixel_count += flat.shape[0]if taken < reservoir_cap:# flat 已是抽样结果,直接入池take = min(reservoir_cap - taken, flat.shape[0])reservoir.append(flat[:take].copy())taken += takeread_idx += 1cap.release()if not pixel_count:continuedef _nested(vals):return [[[float(v)] for v in vals]]mean = ch_sum / pixel_countvar = np.maximum(ch_sq / pixel_count - mean * mean, 0.0)pooled = np.concatenate(reservoir, axis=0) if reservoir else Noneif pooled is not None and pooled.shape[0]:q = np.percentile(pooled, [1, 10, 50, 90, 99], axis=0)else:q = np.stack([mean] * 5)stats[vkey] = {"min": _nested(ch_min),"max": _nested(ch_max),"mean": _nested(mean),"std": _nested(np.sqrt(var)),"q01": _nested(q[0]), "q10": _nested(q[1]),"q50": _nested(q[2]), "q90": _nested(q[3]),"q99": _nested(q[4]),"count": [int(pixel_count)],}except Exception:pass378 unmodified linesdef _read_sensor_rows(session_dir: Path,episode_id: str | None = None,skip_columns: set[str] | None = None) -> dict[int, dict]:"""Merge independently stored glove/action parquet rows by frame_index.``skip_columns``: 调用方已排除的列。这些列在读取阶段就被跳过 ——触觉力矩阵每帧 0.8MB,整集 14MB,在 SSHFS 上读完要十几秒;既然最终不会写进数据集,就不该读。仅按列名裁剪,不改变任何保留列的值。"""rows: dict[int, dict] = {}try:import pyarrow.parquet as pq11 unmodified linesand path.name != f"episode_{episode_index:06d}.parquet"):continuetry:if skip_columns:# 先读 schema(只读 footer,便宜),再只取需要的列。available = [str(n) for n in pq.read_schema(path).names]wanted = [n for n in available if n not in skip_columns]table = pq.read_table(path, columns=wanted)else:table = pq.read_table(path)names = table.schema.namesif "frame_index" not in names:continue347 unmodified linesreturn "float32"def _write_video_dense_keyframes(source: Path, destination: Path) -> None:"""把视频写入数据集,必要时重编码以加密关键帧。采集端用 ffmpeg 默认设置编码(GOP=250),10 秒的集只有 2 个关键帧(0s 和 8.3s)。lerobot 按时间戳取帧时先 seek 到关键帧再向前解码,当查询点紧邻下一个关键帧时 seek 会落到**目标之后**,该帧永远取不到,训练直接抛 FrameTimestampError(实测 7 个采样点里坏 2 个)。GOP=30(每秒一个关键帧)可让 seek 稳定落在目标之前,实测 7/7 全通过;代价是文件约大 2 倍(2.7MB -> 5.7MB/集)。编码失败(缺 ffmpeg、编码器不可用)时退回原样复制:宁可保留稀疏关键帧也不要让整个导出失败 —— 取不到的帧会让那条样本报错,而不是产出错数据。"""import subprocesstry:result = subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", str(source),"-c:v", "libx264", "-g", "30", "-pix_fmt", "yuv420p","-crf", "20", "-preset", "veryfast", str(destination)],capture_output=True, timeout=300)if result.returncode == 0 and destination.is_file() and destination.stat().st_size:returnexcept (OSError, subprocess.SubprocessError):passshutil.copy2(source, destination)def _ensure_observation_state(rows: list[dict]) -> str | None:"""确保每帧有 ``observation.state``;缺失时由 UMI 列派生。ACT 的 VAE 编码器无条件读取 ``batch[observation.state]``(modeling_act.py 里那句 ``device=batch[OBS_STATE].device`` 没做robot_state_feature 判空),缺这列直接 KeyError。即便抛开这个上游问题,单帧观测的 ACT 也需要 proprioception 才知道夹爪在哪。派生口径 ``[Δx, Δy, Δz, gripper]``:位置是本帧相对**本集第一帧**的偏移。SLAM 的世界原点是每次采集初始化时任意确定的,直接喂绝对坐标等于把无关的世界位置当特征。夹爪取开合度 0–1。已有 observation.state 时不动(尊重上游的显式声明)。返回派生列名或None。"""import numpy as npif any("observation.state" in row for row in rows):return Noneif not any("observation.slam_pose" in row for row in rows):return None# 按 episode_index 分组:相对偏移必须在**各自集内**计算,跨集求差# 会把两集世界原点的差异当成运动。by_episode: dict[int, list[dict]] = {}for row in rows:try:episode = int(row.get("episode_index", 0))except (TypeError, ValueError):episode = 0by_episode.setdefault(episode, []).append(row)derived = 0for episode_rows in by_episode.values():origin = Nonefor row in episode_rows:pose = row.get("observation.slam_pose")try:pose_values = np.asarray(pose, dtype=float).reshape(-1)except (TypeError, ValueError):continueif pose_values.size < 3 or not np.isfinite(pose_values[:3]).all():continueif origin is None:origin = pose_values[:3].copy()gripper = 0.0raw = row.get("observation.gripper_state")try:gripper_values = np.asarray(raw, dtype=float).reshape(-1)if gripper_values.size:gripper = float(np.clip(gripper_values[0] / 100.0, 0.0, 1.0))except (TypeError, ValueError):passrow["observation.state"] = [float(value) for value in np.concatenate([pose_values[:3] - origin, [gripper]])]derived += 1if not derived:return Noneprint(f"[lerobot_export] derived observation.state for {derived} frames")return "observation.state"def _ensure_slam_pose(rows: list[dict]) -> str | None:"""确保每帧有 ``observation.slam_pose``;缺失时由 ``slam_trajectory`` 重建。采集端从 52 集起不再写 ``observation.slam_pose``,只写高频样本缓冲``observation.slam_trajectory``(旧批两列都有)。ACT 的输入特征里声明了slam_pose,整列缺失会让官方加载器与策略直接 KeyError —— 这批数据因此完全无法训练或评估。重建口径见 ``app.umi_slam_action.poses_from_trajectory``(与派生 action用的是同一个函数)。拿旧集(有 slam_pose)做过对照:位置相关系数0.998~0.9999、逐帧位置差 std 仅 1~4mm(亚帧采样差),数值范围完全一致,四元数 |dot| 中位 1.0000 —— **同一个物理量、同一个世界系**,不是近似。重建版反而补上了采集端留的 28.5% 零填充行,质量更好。起点偏移的口径与 ``_ensure_observation_state`` 一致,故两者可以串联:本函数先跑,缺 state 的集还能继续从重建出的 slam_pose 派生 state。已有该列时不动(旧批重导行为完全不变)。返回写入的列名或 None。"""import numpy as npif any("observation.slam_pose" in row for row in rows):return Noneif not any("observation.slam_trajectory" in row for row in rows):return Nonefrom app.umi_slam_action import poses_from_trajectory# 按 episode_index 分组:时间基映射是每集单独拟合的(各集 SLAM 会话# 独立),跨集混在一起会把不同集的时间基搅乱,重建出的位姿全错。by_episode: dict[int, list[dict]] = {}for row in rows:try:episode = int(row.get("episode_index", 0))except (TypeError, ValueError):episode = 0by_episode.setdefault(episode, []).append(row)written = 0for episode_rows in by_episode.values():count = len(episode_rows)trajectories = [row.get("observation.slam_trajectory")for row in episode_rows]# 时间戳必须是稠密 float 数组:缺帧补 NaN(poses_from_trajectory 会# 把它们标为缺失再插值),混进 None 会让 np.asarray 推断出 object。stamps = np.full(count, np.nan, dtype=float)for index, row in enumerate(episode_rows):try:stamps[index] = float(row.get("timestamp"))except (TypeError, ValueError):continueposes = poses_from_trajectory(trajectories, stamps, count)if poses is None:continuefor row, pose in zip(episode_rows, poses):row["observation.slam_pose"] = [float(value) for value in pose]written += 1if not written:return Noneprint(f"[lerobot_export] derived observation.slam_pose for {written} frames")return "observation.slam_pose"def _pad_sparse_matrix_columns(rows: list[dict], nan_fill: float) -> dict[str, int]:"""定长矩阵/trajectory 列的空帧补齐到声明长度。采集端在尚无数据的帧上写空数组(如触觉矩阵首帧、SLAM 丢帧时的trajectory),同一列因此长短不一。官方加载器按声明的 shape 转成定长Sequence,遇到空值直接 cast 失败:TypeError: Couldn't cast array of type list<element: int64>to List(Value('int64'), length=187500)只补空值,不动有值帧 —— 缺失语义由列本身的值域表达。返回 ``{列名: 补齐后的长度}``:features 声明必须用这个长度,而不是首帧样本的长度 —— 首帧常常正是空的那一帧,拿它声明会得到 shape [0],与实际写入的长度不符,加载器照样 cast 失败。"""import numpy as nptargets: dict[str, int] = {}for key in {k for row in rows for k in row}:if not (key.endswith("_matrix") or key.endswith("_trajectory")):continuetarget = 0sample_value = Nonefor row in rows:value = row.get(key)if isinstance(value, (list, tuple)) and len(value) > target:target = len(value)sample_value = valueif not target or not sample_value:continuetargets[key] = target# 补齐值的类型必须与该列已有元素**逐位一致**:触觉矩阵是 int16# (声明 int64),补浮点会让 pyarrow 把整列推断成 double,与声明的# dtype 冲突 → 加载器 cast 失败。int 列补 0,浮点列补 nan_fill。existing = next((v for v in sample_value if v is not None), None)if isinstance(existing, (int, np.integer)) and not isinstance(existing, bool):fill = 0else:fill = nan_fillfor row in rows:value = row.get(key)if not isinstance(value, (list, tuple)) or len(value) == target:continuerow[key] = list(value) + [fill] * (target - len(value))return targetsdef _pad_variable_columns(rows: list[dict],nan_fill: float = float("nan")) -> tuple[int, dict[str, int]]:"""变长/稀疏列固定长度化。返回 ``(imu_cap, {列名: 补齐长度})``。- observation.imu:每样本 6 维 → 展平为 cap*6(nan_fill 补尾)- observation.imu_ts_ns:补 0 到 cap- 矩阵/trajectory 类的空帧:补齐到该列最大长度(见 _pad_sparse_matrix_columns)第二个返回值供 features 声明使用 —— 声明必须等于**实际写入的长度**,否则官方加载器 cast 失败。"""import numpy as npmatrix_targets = _pad_sparse_matrix_columns(rows, nan_fill)imu_cap = 3for row in rows:for key in ("observation.imu", "observation.imu_ts_ns"):1 unmodified lineif isinstance(value, (list, tuple)):imu_cap = max(imu_cap, len(value))if not any("observation.imu" in row for row in rows):return imu_cap, matrix_targetsfor row in rows:imu = row.get("observation.imu")if isinstance(imu, (list, tuple)):17 unmodified linesif isinstance(ts, (list, tuple)):row["observation.imu_ts_ns"] = ([int(v) for v in ts] + [0] * (imu_cap - len(ts)))[:imu_cap]return imu_cap, matrix_targetsdef _propagated_hand_sets(source_row: dict) -> tuple[set[str], set[str], dict[str, set[str]]]:555 unmodified lineshand_3d_right_paths: list[str] | None = None,version: str = "v3.0",hand_3d_unit: str | None = None,exclude_columns: list[str] | None = None,progress_callback=None) -> Path:"""Build a LeRobot dataset (``version`` = "v2.1" | "v3.0").``exclude_columns``: 可选,精确列名列表,从数据集中整体剔除。用于丢掉训练用不到但体积/计算代价极高的列(如 250×250×3 的触觉力矩阵:每帧 0.8MB,且逐元素分位数统计是导出耗时的主要来源)。被剔除的列不会出现在 parquet、features 声明和 stats 里。Depth sources are exported as their preview video (``is_depth_map``)plus the per-frame ``observation.depth.<source>.valid`` marker; theoriginal 16-bit PNG sequence stays in the session directory and is not78 unmodified lines# 本集实际导出的每路视频(帧数, fps) → episodes parquet 的# videos/<key>/from_timestamp 映射(官方 v3 加载器按时间戳定位帧)episode_video_meta: dict[str, tuple[int, float]] = {}sensor_rows = _read_sensor_rows(session_dir, episode_id,skip_columns=set(str(name) for name in exclude_columns or []))annotation_map, annotation_defs, _skipped_candidates = _annotation_maps(episode_id)description = str(episode.get("project") or "").strip()35 unmodified lines/ f"observation.images.{source_key}")output_video = destination / f"file-{out_episode_index:03d}.mp4"destination.mkdir(parents=True, exist_ok=True)_write_video_dense_keyframes(source, output_video)total_videos += 1probed_count, probed_fps, width, height = _probe_video(source)episode_video_meta[f"observation.images.{source_key}"] = (227 unmodified linesexcept Exception:pass # 进度回调失败不影响导出本身# 调用方指定剔除的列(如触觉力矩阵):在补齐/统计/写盘之前删掉,# 这样 parquet、features 声明与 stats 三处天然一致,不需要各自过滤。if exclude_columns:dropped = set(str(name) for name in exclude_columns)if dropped:for row in rows:for key in dropped:row.pop(key, None)print(f"[lerobot_export] excluded columns: {sorted(dropped)}")# SLAM 位姿列:采集端 52 集起只写 slam_trajectory,不再写 slam_pose。# 必须赶在 _pad_variable_columns 之前做 —— 补齐会把冲空帧填成 0,而# 0 在 slam_trajectory 里是一个"合法样本"(t=0 的位姿),重建时会被# 当成真实帧混进去。此处补出的 slam_pose 又是下面 observation.state# 的派生依据,故顺序不能颠倒。_ensure_slam_pose(rows)# ACT 的观测需要 proprioception:单帧图像不足以让模型知道夹爪当前# 在哪。数据集若已有 observation.state 则原样保留;否则在 UMI 会话上# 由 SLAM 位姿 + 夹爪开合派生 [Δx, Δy, Δz, gripper](位置为相对本集# 起点的偏移 —— SLAM 世界原点是每集任意初始化的,绝对坐标是噪声)。_ensure_observation_state(rows)# 变长异步传感器列固定长度化:官方加载器不支持变长列(实测# list<int64> 对声明 int64[1] 直接 cast 失败)。取全数据集最大# 样本数补齐,声明 shape 同步为固定长度,变长语义保留在 note。imu_cap, padded_lengths = _pad_variable_columns(rows, nan_fill=0.0 if is_v2 else float("nan"))# 收敛:删恒定哨兵垃圾列(全程 NaN/-1/0/空串 → 数据从未写入)。266 unmodified linesimport numpy as nparr = np.asarray(value)shape = list(arr.shape) if arr.ndim else [1]# 补齐过的列必须以实际写入的长度声明。首帧样本往往正是空的那# 一帧(触觉矩阵首帧、SLAM 丢帧),照它声明会得到 shape [0] 或# 偏小的长度,与实际写入的数据不符 → 官方加载器 cast 失败。if key in padded_lengths:shape = [padded_lengths[key]]if key in ("observation.tactile.left", "observation.tactile.right"):features[key] = {"dtype": "float32", "shape": [256],34 unmodified lines"shape": shape}if junk_cols:features = {k: v for k, v in features.items() if k not in junk_cols}# 调用方剔除的列同样从声明里去掉。features 由 sensor_rows 样本推导,# 而剔除只作用于 rows,不过滤这里会留下"声明了但数据里没有"的列,# 官方加载器读不出来会报错。if exclude_columns:excluded = set(str(name) for name in exclude_columns)features = {k: v for k, v in features.items() if k not in excluded}# 导出的行里有 observation.state 就必须声明,否则官方加载器读不完整。# 声明放在剔除之后:调用方显式排除的列不该被这里复活。# 补出来的 slam_pose 同样必须声明:features 是从**源 parquet** 采样的# (sensor_rows),而这列由 _ensure_slam_pose 在内存里写进 rows,采样# 看不到它 —— 不补声明就是"数据里有列、声明里没有",官方加载器读不完整。if rows and "observation.slam_pose" in rows[0] and "observation.slam_pose" not in features:features["observation.slam_pose"] = {"dtype": "float32", "shape": [7],"names": ["x", "y", "z", "qx", "qy", "qz", "qw"],"note": ("世界系绝对位姿(米 + 四元数 xyzw)。采集端 52 集起不再""写入该列,导出时由 observation.slam_trajectory 的 50Hz""样本重建(与采集端原始列实测位置相关 0.998+,同一世界系)。"),}if rows and "observation.state" in rows[0] and "observation.state" not in features:features["observation.state"] = {"dtype": "float32", "shape": [4],"names": ["delta_x", "delta_y", "delta_z", "gripper"],"note": ("proprioception:本帧位置相对**本集第一帧**的偏移(米)""+ 夹爪开合(0–1)。SLAM 世界原点是每集任意初始化的,""故用相对量而非绝对坐标。"),}# 深度有效帧标记列(行循环写入,不声明会导致官方加载器读不完整)for depth_key in sorted(depth_source_keys):key = f"observation.depth.{depth_key}.valid"
36 unmodified lines3738394041425 unmodified lines48495051525375 unmodified lines1291301311321331346 unmodified lines14114214314414514614714861 unmodified lines2102112122132142152162172182192202 unmodified lines223224225226227228229453 unmodified lines683684685686687688501 unmodified lines119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612273 unmodified lines12311232123312341235123612374 unmodified lines12421243124412451246124712481249125014 unmodified lines12651266126712681269127012718 unmodified lines1280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130236 unmodified lines# 全量遍历远程挂载很慢:只允许单一线程执行(_scan_lock),遍历本身不持有# _lock —— 缓存过期触发的重扫不再把状态读写请求拖在锁后面排队。_scan_lock = threading.Lock()_scan_generation = 0 # invalidate_session_cache 递增;并发扫描据此丢弃过期结果_state_write_generation = 0 # write_episode_state 递增;扫描期间的状态写入触发重扫_video_probe_cache: dict[str, tuple[int, float]] = {}5 unmodified lines_workflows_cache_at = 0.0_runs_cache: list[dict] | None = None_runs_cache_at = 0.0# Runs are written by the API process and read by separate worker processes.# A ten-minute process-local cache can hide a newly queued upload/reprocess# from workers. Keep the cache short while still coalescing rapid UI scans.75 unmodified lines_sessions_cache = None_sessions_cache_at = 0.0_video_probe_cache.clear()def scan_sessions() -> list[dict]:6 unmodified lines_lock:缓存过期触发的重扫不再把状态读写等无关请求拖在锁后面排队。遍历期间发生结构变化(invalidate)/状态写入时,按代际计数丢弃过期结果重扫一次。"""global _sessions_cache, _sessions_cache_at, _task_sessions_cachewhile True:with _lock:now = time.monotonic()61 unmodified linesdef _scan_project_dir(project_dir: Path, project: str) -> list[dict]:"""Scan a project-level LeRobot tree and expose one row per episode."""from app.lerobot_v21 import is_depth_sourcefrom app.project_dataset import episode_files, project_episode_rowsinfo = _read_json(project_dir / "meta" / "info.json", {})if not isinstance(info, dict):info = {}rows: list[dict] = []for row in project_episode_rows(project_dir):try:2 unmodified linescontinueepisode_id = str(row.get("episode_id") or row.get("source_batch")or f"{project}_{episode_index:06d}")files = episode_files(project_dir, episode_index)state = read_episode_state(episode_id)# Project-level info is an aggregate. Do not let it make a new# one-camera episode display devices that belong to another episode.453 unmodified lines_remove_json(EPISODE_STATES_DIR / f"{name}.json")_remove_json(ANNOTATIONS_DIR / f"{name}.json")_episode_state_cache.pop(name, None)global _deleted_episodes_cache, _deleted_episodes_cache_at_deleted_episodes_cache = None_deleted_episodes_cache_at = 0.0501 unmodified lines# ── 工作流运行队列 ───────────────────────────────────RUNS_DIR = STATE_ROOT / "runs"def list_runs() -> list[dict]:global _runs_cache, _runs_cache_atnow = time.monotonic()if (_runs_cache is not Noneand now - _runs_cache_at < _STATE_LIST_CACHE_TTL):return copy.deepcopy(_runs_cache)if not RUNS_DIR.is_dir():_runs_cache = []_runs_cache_at = nowreturn []runs = []for f in sorted(RUNS_DIR.glob("*.json")):run = _read_json(f, None)if isinstance(run, dict):runs.append(run)_runs_cache = runs_runs_cache_at = time.monotonic()return copy.deepcopy(runs)def get_run(run_id: str) -> dict | None:return _read_json(RUNS_DIR / f"{run_id}.json", None)def save_run(run: dict) -> None:global _runs_cache, _runs_cache_atwith _lock:_write_json(RUNS_DIR / f"{run.get('id')}.json", run)_runs_cache = None_runs_cache_at = 0.0def update_run_if_owned(3 unmodified linesmutator: Callable[[dict], None],) -> dict | None:"""Atomically mutate a running job only for its current lease owner."""global _runs_cache, _runs_cache_atwith _lock:path = RUNS_DIR / f"{run_id}.json"run = _read_json(path, None)4 unmodified linesor run.get("lease_token") != lease_token):return Nonemutator(run)_write_json(path, run)_runs_cache = None_runs_cache_at = 0.0return run14 unmodified lines``workflow_revision`` 时,queued/running 仍视为占用,completed 则允许第一次迁移到带版本的幂等记录。"""global _runs_cache, _runs_cache_atwith _lock:revision = run.get("workflow_revision")for existing in list_runs():8 unmodified linesexisting["status"] = "superseded"existing["finished_at"] = utcnow_iso()existing["error_log"] = "Superseded by a newer upload or reprocess request"_write_json(RUNS_DIR / f"{existing.get('id')}.json", existing)_runs_cache = None_runs_cache_at = 0.0continueif same_revision or legacy_active:if existing.get("status") in ("queued", "running"):return existing, Falseif existing.get("status") == "completed" and not allow_completed_rerun:return existing, False_write_json(RUNS_DIR / f"{run.get('id')}.json", run)_runs_cache = None_runs_cache_at = 0.0return run, Truedef delete_run(run_id: str) -> None:global _runs_cache, _runs_cache_at_remove_json(RUNS_DIR / f"{run_id}.json")_runs_cache = None_runs_cache_at = 0.036 unmodified lines373839404142435 unmodified lines495051525354555657585960616275 unmodified lines1381391401411421431441451461471481491501516 unmodified lines15815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921061 unmodified lines2722732742752762772782792802812822832842852862872882892902 unmodified lines293294295296297298299453 unmodified lines753754755756757758759760761762763764765501 unmodified lines1267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314643 unmodified lines1468146914701471147214734 unmodified lines147814791480148114821483148414851486148714 unmodified lines1502150315041505150615078 unmodified lines15161517151815191520152115221523152415251526152715281529153015311532153315341535153636 unmodified lines# 全量遍历远程挂载很慢:只允许单一线程执行(_scan_lock),遍历本身不持有# _lock —— 缓存过期触发的重扫不再把状态读写请求拖在锁后面排队。_scan_lock = threading.Lock()_sessions_refresh_running = False # 后台 stale-while-revalidate 单飞标志_scan_generation = 0 # invalidate_session_cache 递增;并发扫描据此丢弃过期结果_state_write_generation = 0 # write_episode_state 递增;扫描期间的状态写入触发重扫_video_probe_cache: dict[str, tuple[int, float]] = {}5 unmodified lines_workflows_cache_at = 0.0_runs_cache: list[dict] | None = None_runs_cache_at = 0.0_runs_cache_revision: tuple = ()# list_runs(include_archived=False) keeps its own slot; the two variants are# cached independently so neither call pattern can serve the other's result._runs_live_cache: list[dict] | None = None_runs_live_cache_at = 0.0_runs_live_cache_revision: tuple = ()# 指纹变化时才重建快照;单飞,避免并发请求各读一遍 539 个 JSON。_runs_scan_lock = threading.Lock()# Runs are written by the API process and read by separate worker processes.# A ten-minute process-local cache can hide a newly queued upload/reprocess# from workers. Keep the cache short while still coalescing rapid UI scans.75 unmodified lines_sessions_cache = None_sessions_cache_at = 0.0_video_probe_cache.clear()# 项目索引缓存(project_dataset)按指纹自校验,但上传/删除/改名必须# 立刻可见,不能等 TTL。懒导入避免模块级循环依赖。try:from app.project_dataset import invalidate_project_cacheinvalidate_project_cache()except Exception as exc:print(f"[Cache] Project index invalidation skipped: {exc}")def scan_sessions() -> list[dict]:6 unmodified lines_lock:缓存过期触发的重扫不再把状态读写等无关请求拖在锁后面排队。遍历期间发生结构变化(invalidate)/状态写入时,按代际计数丢弃过期结果重扫一次。TTL 过期但已有快照时走 stale-while-revalidate:立刻返回旧快照,后台单飞重建。全量遍历要 5s+,让审核页的请求撞上它正是"打开一条数据等十几秒"的一个来源;旧快照里缺的只是刚上传的那一集,而上传会走invalidate_session_cache() 清空缓存,所以这里不会藏住新数据。"""global _sessions_cache, _sessions_cache_at, _task_sessions_cachewith _lock:snapshot = (copy.deepcopy(_sessions_cache)if _sessions_cache is not None else None)fresh = (snapshot is not Noneand time.monotonic() - _sessions_cache_at < _SESSIONS_CACHE_TTL)if fresh:return snapshotif snapshot is not None:_refresh_sessions_in_background()return snapshot# 冷启动或刚被 invalidate:必须同步扫出第一份快照。return _scan_sessions_blocking()def _refresh_sessions_in_background() -> None:"""Single-flight background rebuild of the expired session snapshot."""global _sessions_refresh_runningwith _lock:if _sessions_refresh_running:return_sessions_refresh_running = Truethreading.Thread(target=_run_session_refresh, name="session-refresh", daemon=True).start()def _run_session_refresh() -> None:global _sessions_refresh_runningtry:_scan_sessions_blocking()except Exception as exc:print(f"[Cache] Background session refresh failed: {exc}")finally:with _lock:_sessions_refresh_running = Falsedef _scan_sessions_blocking() -> list[dict]:"""Full remote tree walk; callers block for the duration."""global _sessions_cache, _sessions_cache_at, _task_sessions_cachewhile True:with _lock:now = time.monotonic()61 unmodified linesdef _scan_project_dir(project_dir: Path, project: str) -> list[dict]:"""Scan a project-level LeRobot tree and expose one row per episode."""from app.lerobot_v21 import is_depth_sourcefrom app.project_dataset import (episode_files_from_index,project_episode_file_index,project_episode_rows,)info = _read_json(project_dir / "meta" / "info.json", {})if not isinstance(info, dict):info = {}# One index for the whole project: asking ``episode_files`` per episode# would re-walk data/, videos/ and every episode index file each time,# costing (1 + episodes) x parquet reads on the storage mount.file_index = project_episode_file_index(project_dir)rows: list[dict] = []for row in project_episode_rows(project_dir):try:2 unmodified linescontinueepisode_id = str(row.get("episode_id") or row.get("source_batch")or f"{project}_{episode_index:06d}")files = episode_files_from_index(project_dir, episode_index, file_index)state = read_episode_state(episode_id)# Project-level info is an aggregate. Do not let it make a new# one-camera episode display devices that belong to another episode.453 unmodified lines_remove_json(EPISODE_STATES_DIR / f"{name}.json")_remove_json(ANNOTATIONS_DIR / f"{name}.json")_episode_state_cache.pop(name, None)# 内容指纹指向已删除的批次:清掉,否则同一条录制重新上传时会被# 误判成"重复"而试图覆盖一个已经不存在的 episode。try:from app.batch_fingerprint import forget_fingerprintforget_fingerprint(name)except Exception:passglobal _deleted_episodes_cache, _deleted_episodes_cache_at_deleted_episodes_cache = None_deleted_episodes_cache_at = 0.0501 unmodified lines# ── 工作流运行队列 ───────────────────────────────────RUNS_DIR = STATE_ROOT / "runs"# Finished runs keep their full record for the UI, but they are moved out of# the live queue directory: the worker polls /jobs/claim every few seconds and# used to re-read every historical run (hundreds of 26 KB JSON files on the# NAS mount) on each poll. Only unfinished work stays in RUNS_DIR.RUNS_ARCHIVE_DIR = RUNS_DIR / "archive"_TERMINAL_RUN_STATUSES = frozenset({"completed", "failed", "superseded"})# claim_job only needs these to pick the next job; the full run payload is# loaded afterwards for the winner alone._RUN_SUMMARY_FIELDS = ("id", "status", "created_at", "lease_until","worker_id", "lease_token", "attempt")def list_runs(include_archived: bool = True) -> list[dict]:"""All runs, newest-finished records included by default.``include_archived=False`` restricts the scan to the live queue and isonly for callers that just need claimable work. Everything else keepsthe historical view it had before archiving existed.The two variants are cached separately — a single shared cache wouldserve whichever variant ran first to both callers.TTL 过期后先比一次廉价指纹(目录 listing + stat,539 个 run 实测 4ms),内容没变就只刷新时间戳。历史快照要读 539 个 JSON,冷读 6s —— 那正是``/export/episode-format`` 每次点开数据都要付的代价;而 worker 领取走的是 :func:`list_run_summaries`,不经过这里,所以缓存不会耽误派活。"""global _runs_cache, _runs_cache_at, _runs_cache_revisionglobal _runs_live_cache, _runs_live_cache_at, _runs_live_cache_revisionnow = time.monotonic()cache, cache_at = ((_runs_cache, _runs_cache_at) if include_archivedelse (_runs_live_cache, _runs_live_cache_at))if cache is not None and now - cache_at < _STATE_LIST_CACHE_TTL:return copy.deepcopy(cache)revision = _run_dirs_revision(include_archived)cached_revision = (_runs_cache_revision if include_archivedelse _runs_live_cache_revision)if cache is not None and cached_revision == revision:if include_archived:_runs_cache_at = nowelse:_runs_live_cache_at = nowreturn copy.deepcopy(cache)# 指纹变化时才真读;单飞避免并发请求各读一遍 539 个文件。with _runs_scan_lock:now = time.monotonic()cache, cache_at = ((_runs_cache, _runs_cache_at) if include_archivedelse (_runs_live_cache, _runs_live_cache_at))cached_revision = (_runs_cache_revision if include_archivedelse _runs_live_cache_revision)if cache is not None and (cached_revision == revisionor now - cache_at < _STATE_LIST_CACHE_TTL):return copy.deepcopy(cache)runs: list[dict] = []for directory in _run_dirs(include_archived):if not directory.is_dir():continuefor f in sorted(directory.glob("*.json")):run = _read_json(f, None)if isinstance(run, dict):runs.append(run)revision = _run_dirs_revision(include_archived)if include_archived:_runs_cache = runs_runs_cache_at = time.monotonic()_runs_cache_revision = revisionelse:_runs_live_cache = runs_runs_live_cache_at = time.monotonic()_runs_live_cache_revision = revisionreturn copy.deepcopy(runs)def _run_dirs_revision(include_archived: bool) -> tuple:"""Cheap fingerprint of the run files (name, size, mtime)."""parts: list[tuple] = []try:for directory in _run_dirs(include_archived):if not directory.is_dir():continuefor f in sorted(directory.glob("*.json")):stat = f.stat()parts.append((f.name, stat.st_size, stat.st_mtime_ns))except OSError:return ()return tuple(parts)def _run_dirs(include_archived: bool = False) -> list[Path]:"""Live queue directory first; the archive only when explicitly asked."""dirs = [RUNS_DIR]if include_archived:dirs.append(RUNS_ARCHIVE_DIR)return dirsdef _invalidate_runs_cache() -> None:"""Drop both run-list caches. Callers must hold ``_lock``."""global _runs_cache, _runs_cache_at, _runs_live_cache, _runs_live_cache_at_runs_cache = None_runs_cache_at = 0.0_runs_live_cache = None_runs_live_cache_at = 0.0def list_run_summaries() -> list[dict]:"""Live runs with only the fields the claim scan needs.Parsing 26 KB of JSON per historical run is what made an idle worker burnthe backend's CPU; the claim path only compares ``status`` /``created_at`` / ``lease_until``. Archived (terminal) runs are skippedentirely — nothing in the live queue can be claimed from them."""summaries: list[dict] = []if not RUNS_DIR.is_dir():return summariesfor f in sorted(RUNS_DIR.glob("*.json")):run = _read_json(f, None)if not isinstance(run, dict):continuesummaries.append({key: run.get(key) for key in _RUN_SUMMARY_FIELDS})return summariesdef archive_run_file(run_id: str) -> bool:"""Move a finished run out of the live queue directory.Keeps the record (the UI can still load it by id) while taking it out ofthe per-poll directory listing. Safe to call repeatedly."""source = RUNS_DIR / f"{run_id}.json"if not source.is_file():return Falsetry:RUNS_ARCHIVE_DIR.mkdir(parents=True, exist_ok=True)destination = RUNS_ARCHIVE_DIR / source.nameif destination.exists():destination.unlink()source.replace(destination)except OSError:return Falsewith _lock:_invalidate_runs_cache()return Truedef get_run(run_id: str) -> dict | None:"""Load one run by id from the live queue, falling back to the archive."""run = _read_json(RUNS_DIR / f"{run_id}.json", None)if isinstance(run, dict):return runreturn _read_json(RUNS_ARCHIVE_DIR / f"{run_id}.json", None)def _write_run_record(run: dict) -> None:"""Persist a run, keeping finished ones out of the live queue directory.Callers must hold ``_lock``. Terminal runs are archived so everycompletion path (worker complete/fail, dispatch, API status writes, thesupersede branch) stops contributing to the claim scan without each sitehaving to remember. A run that leaves a terminal state is pulled backinto the live queue."""run_id = str(run.get("id") or "")_write_json(RUNS_DIR / f"{run_id}.json", run)if not run_id:returnif run.get("status") in _TERMINAL_RUN_STATUSES:try:RUNS_ARCHIVE_DIR.mkdir(parents=True, exist_ok=True)live = RUNS_DIR / f"{run_id}.json"if live.is_file():live.replace(RUNS_ARCHIVE_DIR / f"{run_id}.json")except OSError:passelse:# Re-queued after a re-run: drop the stale archived copy so the run# is not listed twice.stale = RUNS_ARCHIVE_DIR / f"{run_id}.json"try:if stale.is_file():stale.unlink()except OSError:passdef save_run(run: dict) -> None:"""Write a run, keeping finished runs out of the live queue directory."""with _lock:_write_run_record(run)_invalidate_runs_cache()def update_run_if_owned(3 unmodified linesmutator: Callable[[dict], None],) -> dict | None:"""Atomically mutate a running job only for its current lease owner."""with _lock:path = RUNS_DIR / f"{run_id}.json"run = _read_json(path, None)4 unmodified linesor run.get("lease_token") != lease_token):return Nonemutator(run)# The mutator may mark the run completed/failed; archiving happens in# the shared writer so this path stays in sync with save_run._write_run_record(run)_invalidate_runs_cache()return run14 unmodified lines``workflow_revision`` 时,queued/running 仍视为占用,completed 则允许第一次迁移到带版本的幂等记录。"""with _lock:revision = run.get("workflow_revision")for existing in list_runs():8 unmodified linesexisting["status"] = "superseded"existing["finished_at"] = utcnow_iso()existing["error_log"] = "Superseded by a newer upload or reprocess request"_write_run_record(existing)_invalidate_runs_cache()continueif same_revision or legacy_active:if existing.get("status") in ("queued", "running"):return existing, Falseif existing.get("status") == "completed" and not allow_completed_rerun:return existing, False_write_run_record(run)_invalidate_runs_cache()return run, Truedef delete_run(run_id: str) -> None:"""Remove a run from the live queue and from the archive."""_remove_json(RUNS_DIR / f"{run_id}.json")_remove_json(RUNS_ARCHIVE_DIR / f"{run_id}.json")_invalidate_runs_cache()
20 unmodified lines21222324252627282950 unmodified lines8081828384851 unmodified line8788899091929320 unmodified linescolor = EXPORT_COLORinputs = ({"key": "data", "label": "Exportable Data"},)outputs = ({"key": "dataset", "label": "Dataset"},)default_config = {"version": "v3.0", "split_ratio": 0.9, "shard_size": 100000}config_schema = (field("version", "select", "Version", "v3.0", options=["v2.1", "v3.0"]),)execution_target = "worker"capabilities = ("dataset_export", "lerobot")50 unmodified linesNone)# 数据集先输出到 worker 临时目录,API 完成阶段会把导出产品放到# state/exports,不在项目根目录新增 processed/。dataset_dir = build_lerobot_dataset(episode_id, [episode_id],ctx.output_root, split_ratio,include_video_keys=include_video_keys,1 unmodified linehand_3d_paths=hand_3d_paths,hand_3d_right_paths=hand_3d_right_paths,version=version,hand_3d_unit=hand_3d_unit)info = dataset_dir / "meta" / "info.json"if not info.exists():ctx.skip("Dataset build produced no meta/info.json")20 unmodified lines212223242526272829303132333435363738394050 unmodified lines9192939495969798991001011021 unmodified line10410510610710810911011120 unmodified linescolor = EXPORT_COLORinputs = ({"key": "data", "label": "Exportable Data"},)outputs = ({"key": "dataset", "label": "Dataset"},)# 默认排除 UMI 触觉力矩阵:每帧 250×250×3(187500 个整数),实测占# canonical parquet 体积的九成以上,且 99.99% 是零 —— 训练用不到,# 却让单集导出从 2.5 秒涨到 57 秒(写盘 + 逐元素统计 + 结果包上传),# 结果 zip 也从几 MB 涨到几十 MB。要保留就把它从配置里删掉。_DEFAULT_EXCLUDE = ",".join(("observation.gripper_left_force_matrix","observation.gripper_right_force_matrix",))default_config = {"version": "v3.0", "split_ratio": 0.9,"shard_size": 100000, "exclude_columns": _DEFAULT_EXCLUDE}config_schema = (field("version", "select", "Version", "v3.0", options=["v2.1", "v3.0"]),field("exclude_columns", "string", "Exclude columns (comma separated)",_DEFAULT_EXCLUDE),)execution_target = "worker"capabilities = ("dataset_export", "lerobot")50 unmodified linesNone)# 数据集先输出到 worker 临时目录,API 完成阶段会把导出产品放到# state/exports,不在项目根目录新增 processed/。# 排除列:配置里逗号分隔。留空 = 全量导出(旧行为)。exclude_columns = [name.strip() for namein str(ctx.config.get("exclude_columns", "") or "").split(",")if name.strip()]dataset_dir = build_lerobot_dataset(episode_id, [episode_id],ctx.output_root, split_ratio,include_video_keys=include_video_keys,1 unmodified linehand_3d_paths=hand_3d_paths,hand_3d_right_paths=hand_3d_right_paths,version=version,hand_3d_unit=hand_3d_unit,exclude_columns=exclude_columns)info = dataset_dir / "meta" / "info.json"if not info.exists():ctx.skip("Dataset build produced no meta/info.json")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192"""UMI Slam Action — 从 SLAM 位姿派生 imitation learning 的 action 列。
UMI 采集端不录 action(写的是占位全零,导出时被恒定列过滤器剔除),导致数据集无法训练。本模块读取 UMI 夹爪的 SLAM 位姿与夹爪开合,按 UMI 官方口径反推出 7 维 action 并合并回 canonical:
Δp = R_tᵀ · (p_{t+1} − p_t) # 平移增量, 米 Δr = rotvec(R_tᵀ · R_{t+1}) # 旋转增量, 弧度 g = gripper_state[t+1, 0] / 100 # 夹爪开合, 0–1
纯计算在 app/umi_slam_action.py(不依赖框架,便于单测与跨格式复用)。"""
from pathlib import Path
from app.processing import ProcessingModule, JobContext, ArtifactReffrom app.processing.registry import registerfrom app.processing.theme import HAND3D_COLOR
# 本模块产出的 artifact kind。合并白名单在 project_dataset 里单独维护,# 新增 kind 必须同步加进那张表,否则列不会被并入 canonical。ACTION_KIND = "umi_slam_action"
# 位姿只读 slam_trajectory:它是采集端的高频样本缓冲,丢帧时相邻格子里# 仍有真实样本;而 slam_pose 在同样位置直接写零,只能插值硬补。_TRAJECTORY_COLUMN = "observation.slam_trajectory"_TIMESTAMP_COLUMN = "timestamp"_GRIPPER_COLUMN = "observation.gripper_state"
@registerclass UmiSlamActionModule(ProcessingModule): slug = ACTION_KIND version = "1.0" category = "process" label = "UMI Slam Action" # 语义是"位姿 → 增量"的坐标变换,与同组做几何变换的手部模块一致; # sync 也贴合"由轨迹反推动作"。必须取自 iconify-preload.js 的白名单 # (图标离线预载,不在表内的名字渲染为空白)。 icon = "ant-design:sync-outlined" color = HAND3D_COLOR # 端口 key 必须与上游 UMI Gripper 的输出 key 逐字一致 —— 前端对 # 类型化端口按 ``out.key === inp.key`` 校验,改名会导致连线被拒。 inputs = ( {"key": "slam_trajectory", "label": "SLAM Trajectory"}, {"key": "gripper_state", "label": "ESP Gripper State"}, ) outputs = ({"key": "action", "label": "Action"},) default_config = {} config_schema = () execution_target = "worker" capabilities = ("umi_gripper", "action_derivation")
def run(self, ctx: JobContext) -> dict[str, ArtifactRef] | None: parquet = self._find_source_parquet(ctx) if parquet is None: ctx.skip("No parquet with SLAM pose found in batch")
from app.umi_slam_action import derive_action import time import numpy as np import pandas as pd
# 读取重试:采集端可能还在往同一项目目录写新集(每上传一集都会重写 # 项目数据树),worker 恰好读到写了一半的文件就会抛异常。实测 # ep52/ep71 都因此被误判为"列不可读"而跳过 —— 几秒后同一文件完全 # 正常。瞬时故障不该等同于永久失败,故重试若干次。 columns = [_TRAJECTORY_COLUMN, _TIMESTAMP_COLUMN, _GRIPPER_COLUMN] frame = None last_error: Exception | None = None for attempt in range(5): try: frame = pd.read_parquet(parquet, columns=columns) break except Exception as exc: last_error = exc time.sleep(1.0 + attempt) if frame is None: # 带上路径与大小:同样的 ArrowInvalid 可能来自「文件被截断」或 # 「根本不是 parquet」,只看异常分不出来,必须知道读的是哪个文件。 try: size = parquet.stat().st_size head = parquet.open("rb").read(4) detail = f"size={size}B head={head!r}" except OSError as exc: detail = f"stat failed: {exc}" ctx.skip(f"SLAM columns unreadable after retries: " f"{type(last_error).__name__}: {last_error} | " f"file={parquet} ({detail})")
if _TRAJECTORY_COLUMN not in frame.columns: # 非 UMI 批次(如 D435 手套、S80C)没有 SLAM 缓冲 —— 跳过, # 不写入任何列,保证其他设备的导出行为完全不变。 ctx.skip("No SLAM trajectory column — not a UMI gripper batch")
total = len(frame) stamps = (frame[_TIMESTAMP_COLUMN].to_numpy(dtype=float) if _TIMESTAMP_COLUMN in frame.columns else np.arange(total) / 30.0) derived = derive_action( frame[_TRAJECTORY_COLUMN].tolist(), stamps, frame[_GRIPPER_COLUMN].tolist() if _GRIPPER_COLUMN in frame.columns else [], total, ) if not derived: ctx.skip("No usable SLAM samples (all frames dropped)")
# 输出按原 frame_index 对齐并保持升序:_merge_processing_frame 按 # frame_index 匹配,乱序会让列���位。 frames = sorted(derived) ctx.progress(0.5) output = ctx.output_dir / "umi_slam_action.parquet" # 必须写 np.float32:pyarrow 对 Python float 推断 double,而 LeRobot # 的 action 声明是 float32 —— 声明与实际 schema 不一致会让官方加载器 # 读出不匹配的类型。与导出端 _cast_float32 的做法保持一致。 pd.DataFrame({ "frame_index": [int(f) for f in frames], "action": [[np.float32(value) for value in derived[f]["action"]] for f in frames], # ACT 的观测需要 proprioception:只有图像时模型不知道夹爪当前 # 在哪。这里的 observation.state 是相对本集起点的位置 + 夹爪开合。 "observation.state": [ [np.float32(value) for value in derived[f]["observation.state"]] for f in frames], }).to_parquet(output, index=False) ctx.progress(1.0)
covered = len(frames) return { "action": ctx.ref(ACTION_KIND, output, metadata={ "column": "action", "shape": [7], "names": ["delta_x", "delta_y", "delta_z", "rot_x", "rot_y", "rot_z", "gripper"], "frames_covered": covered, "frames_total": int(total), "note": ("UMI 口径 action:当前夹爪局部系增量位姿 + 夹爪开合。" "由 SLAM 位姿派生,零位姿丢帧已插值修复。"), }), }
@staticmethod def _find_source_parquet(ctx: JobContext) -> Path | None: """定位含 SLAM 位姿的 canonical parquet。
优先用上游 ``slam_trajectory`` 端口连过来的产物(工作流连接驱动); 未连或产物不可用时回退到 ``ctx.find_parquet()`` 扫描批次, 保证"只连一根线也能跑"。
上游 ref **必须验证是 parquet**:worker 组装 incoming 时,若边的 sourceHandle 对不上上游任何输出端口,会把该节点的**全部输出平铺** 进来(runner `_incoming_artifacts` 规则 3),视频 ref 也会挂到 ``slam_trajectory`` 这个键上。实测因此把 mp4 当 parquet 读,报 ``magic bytes not found in footer`` —— 只看键名不验证就会中招。
回退扫描**必须按 episode_id 过滤**:批次目录里往往躺着几十集的 canonical parquet,直接取第一个会静默用错集的数据(实测表现为 每集算出的 action 完全相同)。worker 打包输入时通常只含一集, 但本地重跑/整目录传入时就不是了。 """ import pyarrow.parquet as pq
def _is_slam_parquet(candidate: Path) -> bool: if candidate.suffix.lower() != ".parquet" or not candidate.is_file(): return False try: return _TRAJECTORY_COLUMN in set(pq.read_schema(candidate).names) except Exception: return False
for key, ref in (ctx.incoming or {}).items(): if not str(key).startswith("slam_trajectory"): continue resolved = ctx.resolve(ref) if resolved and _is_slam_parquet(resolved): return resolved
episode_id = str((ctx.job or {}).get("episode_id") or "") suffix = "" if "_" in episode_id: tail = episode_id.rsplit("_", 1)[-1] if tail.isdigit(): suffix = f"episode_{int(tail):06d}.parquet" candidates = ctx.find_parquet() # 先只看文件名匹配本集的那一个 ordered = ([c for c in candidates if c.name == suffix] if suffix else []) ordered += [c for c in candidates if c.name != suffix] for candidate in ordered: if _is_slam_parquet(candidate): return candidate return None11 unmodified lines12131415161718192021420 unmodified lines4424434444454464474486 unmodified lines45545645745845946058 unmodified lines519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549156 unmodified lines7067077087097107117124 unmodified lines7177187197207217227237247257267 unmodified lines73473573673773873920 unmodified lines76076176276376476576611 unmodified linesfrom __future__ import annotationsimport jsonimport osimport reimport shutilfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Iterable420 unmodified linesreturn int(match.group(1)) if match else Nonedef project_episode_rows(project_root: Path) -> list[dict[str, Any]]:rows: list[dict[str, Any]] = []for path in _episode_parquet_files(project_root):try:6 unmodified linesreturn rowsdef _match_episode_row(rows: list[dict[str, Any]],episode_id: str) -> dict[str, Any] | None:"""Match an episode row by canonical id first, then trailing index.58 unmodified linesreturn 0def episode_files(project_root: Path, episode_index: int) -> dict[str, Any]:"""Return only one episode's source files from a project dataset."""root = Path(project_root)data_files = [path for path in (root / "data").rglob("*.parquet")if path.is_file() and _episode_number_from_path(path) == episode_index] if (root / "data").is_dir() else []videos: list[tuple[str, Path]] = []for source, path in iter_video_streams(root / "videos"):if _episode_number_from_path(path) == episode_index:videos.append((source, path))row = next((item for item in project_episode_rows(root)if _episode_index(item.get("episode_index")) == episode_index), {})episode_id = _episode_id_for_row(row, root.name)relative_meta: list[Path] = [Path("meta/info.json"), Path("meta/tasks.json")]return {"episode_index": episode_index,"episode_id": episode_id,"row": row,"data": data_files,"videos": videos,"meta": [path for path in relative_meta if (root / path).is_file()],}def _processing_token(value: Any, fallback: str = "result") -> str:text = re.sub(r"[^A-Za-z0-9_.-]+", "_", str(value or "")).strip("._-")return text or fallback156 unmodified linesrecords = _processing_artifacts(outputs)tabular_records = [item for item in recordsif str(item[2].get("kind") or "") in{"hand_keypoints", "hand_3d", "glove_sensor"}]# A reprocess is authoritative for its hand-3D sources. Remove any# source-qualified hand-3D columns left by an earlier partial publish# (including legacy ``*_1`` collision columns) before merging the fresh4 unmodified linesif str(name).startswith("processing.hand_3d.")]if stale_hand3d:data_frame = data_frame.drop(columns=stale_hand3d, errors="ignore")assigned_columns: set[str] = set(data_frame.columns)merged_columns: list[str] = []published = {"artifacts": {}}merged_hand3d_sources: set[str] = set()for node_id, handle, ref in records:source_path = _processing_ref_path(Path(extracted_root), ref)7 unmodified linespublished_ref = dict(ref)source = _processing_token(ref.get("source_key") or metadata.get("source_key")or handle, kind)# Review/export nodes pass the node-36 hand-3D refs through again.# They are the same source data, not a second measurement. Merge each# source once and keep the passthrough artifact only as an audit link.20 unmodified lines"storage": "browser_overlay"}published["artifacts"].setdefault(node_id, {})[handle] = published_refcontinueif kind in {"hand_keypoints", "hand_3d", "glove_sensor"}:result_frame = pd.read_parquet(source_path)raw_columns = [str(name) for name in result_frame.columnsif name not in {"frame_index", "episode_index"}]11 unmodified lines12131415161718192021222324420 unmodified lines4454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854866 unmodified lines49349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455558 unmodified lines614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699156 unmodified lines8568578588598608618628634 unmodified lines8688698708718728738748758768778788798808818828838848858868878888898908918928937 unmodified lines90190290390490590690790890991091191291391491591691791891992092192292392420 unmodified lines94594694794894995095111 unmodified linesfrom __future__ import annotationsimport copyimport jsonimport osimport reimport shutilimport threadingimport timefrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Iterable420 unmodified linesreturn int(match.group(1)) if match else None# ── Project index cache ───────────────────────────────# Every _canonical_episode_data_files() call reads the complete episode# metadata parquet set (52 episodes = 52 remote reads) plus two project-wide# directory walks — measured at 1.4s warm, and the review page issues ~11# video requests per episode open, so the same index was rebuilt a dozen# times per click. Cache the parsed rows and the file index against a cheap# fingerprint of the episode index files._PROJECT_CACHE_LOCK = threading.RLock()_PROJECT_CACHE: dict[str, dict[str, Any]] = {}# Computing the fingerprint still stats every episode index file, so a short# TTL skips even that inside one page load. Structural changes are announced# explicitly through invalidate_project_cache()._PROJECT_CACHE_TTL = 60.0_PROJECT_SCAN_LOCK = threading.Lock()def _project_source_revision(project_root: Path) -> tuple:"""Fingerprint the episode index files (name, size, mtime).The index files are written by whoever writes the data (upload, workflowmerge), so a change there means the project changed. ``data/`` and``videos/`` are deliberately not walked: any addition or removal there isaccompanied by an index write."""parts: list[tuple] = []try:for path in _episode_parquet_files(project_root):stat = path.stat()parts.append((path.name, stat.st_size, stat.st_mtime_ns))except OSError:return ()return tuple(parts)def _read_project_rows(project_root: Path) -> list[dict[str, Any]]:"""Uncached: one parquet read per episode, sorted by episode index."""rows: list[dict[str, Any]] = []for path in _episode_parquet_files(project_root):try:6 unmodified linesreturn rowsdef _project_cache_entry(project_root: Path) -> dict[str, Any]:"""Return the cached ``{rows, index}`` for a project, rebuilding if stale."""root = Path(project_root)key = str(root)now = time.monotonic()with _PROJECT_CACHE_LOCK:entry = _PROJECT_CACHE.get(key)if entry is not None and now - entry["checked_at"] < _PROJECT_CACHE_TTL:return entry# The fingerprint touches the remote mount, so keep it outside the lock.revision = _project_source_revision(root)with _PROJECT_CACHE_LOCK:entry = _PROJECT_CACHE.get(key)if entry is not None and entry["revision"] == revision:entry["checked_at"] = nowreturn entry# Single-flight: a page load fires its requests in parallel, and they all# miss at once. One rebuild serves the whole burst.with _PROJECT_SCAN_LOCK:now = time.monotonic()with _PROJECT_CACHE_LOCK:entry = _PROJECT_CACHE.get(key)if entry is not None and (entry["revision"] == revisionor now - entry["checked_at"] < _PROJECT_CACHE_TTL):return entryrows = _read_project_rows(root)index = _build_project_file_index(root, rows)entry = {"revision": revision,"checked_at": time.monotonic(),"rows": rows,"index": index,}with _PROJECT_CACHE_LOCK:_PROJECT_CACHE[key] = entryreturn entrydef invalidate_project_cache(project_root: Path | None = None) -> None:"""Drop cached project indexes after a structural change.Called from ``localstore.invalidate_session_cache`` so an upload, delete orrename becomes visible on the next read instead of after the TTL."""with _PROJECT_CACHE_LOCK:if project_root is None:_PROJECT_CACHE.clear()else:_PROJECT_CACHE.pop(str(Path(project_root)), None)def project_episode_rows(project_root: Path) -> list[dict[str, Any]]:# Callers may assume they own the rows, so never hand out the cache itself.return copy.deepcopy(_project_cache_entry(project_root)["rows"])def _match_episode_row(rows: list[dict[str, Any]],episode_id: str) -> dict[str, Any] | None:"""Match an episode row by canonical id first, then trailing index.58 unmodified linesreturn 0def _build_project_file_index(project_root: Path, rows: list[dict[str, Any]] | None = None) -> dict[int, dict[str, Any]]:"""Uncached: one pass over ``data/``, ``videos/`` and the episode rows."""root = Path(project_root)index: dict[int, dict[str, Any]] = {}data_root = root / "data"if data_root.is_dir():for path in data_root.rglob("*.parquet"):if not path.is_file():continuenumber = _episode_number_from_path(path)if number is None:continueindex.setdefault(number, {"data": []})["data"].append(path)for source, path in iter_video_streams(root / "videos"):number = _episode_number_from_path(path)if number is None:continueindex.setdefault(number, {"data": []}).setdefault("videos", []).append((source, path))if rows is None:rows = _read_project_rows(root)for row in rows:number = _episode_index(row.get("episode_index"))if number is None:continue# ``episode_files`` resolves a duplicate episode number to the first# row in index order; ``setdefault`` keeps that same winner.index.setdefault(number, {"data": []}).setdefault("row", row)return indexdef project_episode_file_index(project_root: Path) -> dict[int, dict[str, Any]]:"""Index every episode's source files with a single pass over the project.:func:`episode_files` re-walks ``data/``, ``videos/`` and the whole episodeindex for each episode it is asked about, so scanning a project costs``(1 + episodes) x index files`` parquet reads on the (possibly remote)storage mount. This entry point keeps that contract while serving repeatcallers from the revision-checked project cache.Keys are episode numbers; values carry the same ``data`` / ``videos`` /``row`` payload :func:`episode_files` reports, and are ordered exactly asa per-episode walk would have produced them."""return copy.deepcopy(_project_cache_entry(Path(project_root))["index"])def episode_files_from_index(project_root: Path, episode_index: int,index: dict[int, dict[str, Any]]) -> dict[str, Any]:"""Look one episode up in a prebuilt :func:`project_episode_file_index`.Returns the same shape as :func:`episode_files`; the caller owns the indexlifetime and is responsible for rebuilding it when the project changes."""root = Path(project_root)entry = index.get(episode_index) or {}row = entry.get("row") or {}relative_meta: list[Path] = [Path("meta/info.json"), Path("meta/tasks.json")]return {"episode_index": episode_index,"episode_id": _episode_id_for_row(row, root.name),"row": row,"data": list(entry.get("data") or []),"videos": list(entry.get("videos") or []),"meta": [path for path in relative_meta if (root / path).is_file()],}def episode_files(project_root: Path, episode_index: int) -> dict[str, Any]:"""Return only one episode's source files from a project dataset.Single-episode callers keep this entry point; it builds a one-shot index,so it now walks the project once instead of three times."""return episode_files_from_index(project_root, episode_index, project_episode_file_index(project_root))def _processing_token(value: Any, fallback: str = "result") -> str:text = re.sub(r"[^A-Za-z0-9_.-]+", "_", str(value or "")).strip("._-")return text or fallback156 unmodified linesrecords = _processing_artifacts(outputs)tabular_records = [item for item in recordsif str(item[2].get("kind") or "") in{"hand_keypoints", "hand_3d", "glove_sensor","umi_slam_action"}]# A reprocess is authoritative for its hand-3D sources. Remove any# source-qualified hand-3D columns left by an earlier partial publish# (including legacy ``*_1`` collision columns) before merging the fresh4 unmodified linesif str(name).startswith("processing.hand_3d.")]if stale_hand3d:data_frame = data_frame.drop(columns=stale_hand3d, errors="ignore")# Derived action replaces the collector's placeholder column instead of# being renamed to ``processing.<kind>.*.action``. The UMI collector# writes an all-zero ``action`` that the LeRobot exporter correctly drops# as a constant/zero-information column, so without this drop the fresh# action would land under a name no exporter reads. Only drop it when a# umi_slam_action result is actually being published for this episode.if any(str(ref.get("kind") or "") == "umi_slam_action"for _node, _handle, ref in records):# 本模块产出的列全部按原名覆盖(重跑幂等):action 之外还有# observation.state,它同样不该因为二次合并被改名成 processing.*。stale_action = [str(name) for name in data_frame.columnsif str(name) in {"action", "observation.state"}or str(name).startswith("processing.umi_slam_action.")]if stale_action:data_frame = data_frame.drop(columns=stale_action, errors="ignore")assigned_columns: set[str] = set(data_frame.columns)merged_columns: list[str] = []published = {"artifacts": {}}merged_hand3d_sources: set[str] = set()merged_action_files: set[str] = set()for node_id, handle, ref in records:source_path = _processing_ref_path(Path(extracted_root), ref)7 unmodified linespublished_ref = dict(ref)source = _processing_token(ref.get("source_key") or metadata.get("source_key")or handle, kind)# A review/review-export node forwards its upstream action ref, so the# same derived action arrives twice (once from the producing node,# once forwarded). Merging both would add a duplicate# ``processing.<kind>.*.action`` column holding identical values.# Deduplicate on the artifact file, not the node id: two genuinely# separate umi_slam_action nodes produce different files and must both# merge.if kind == "umi_slam_action":action_file = str(source_path.resolve())if action_file in merged_action_files:published_ref["path"] = str(data_path.relative_to(root)).replace("\\", "/")published_ref["metadata"] = {**metadata, "merged_into": published_ref["path"],"deduplicated": True, "merged_columns": [],}published["artifacts"].setdefault(node_id, {})[handle] = published_refcontinuemerged_action_files.add(action_file)# Review/export nodes pass the node-36 hand-3D refs through again.# They are the same source data, not a second measurement. Merge each# source once and keep the passthrough artifact only as an audit link.20 unmodified lines"storage": "browser_overlay"}published["artifacts"].setdefault(node_id, {})[handle] = published_refcontinueif kind in {"hand_keypoints", "hand_3d", "glove_sensor", "umi_slam_action"}:result_frame = pd.read_parquet(source_path)raw_columns = [str(name) for name in result_frame.columnsif name not in {"frame_index", "episode_index"}]
123456710 unmodified lines181920212223213 unmodified lines2372382392402412422432442452462472482492502512522532546 unmodified lines261262263264265266"""Device heartbeat & polling API — 本地 JSON 存储(无数据库)。设备存 data/state/devices.json;采集端轮询 /device/tasks 获取active 项目列表(任务概念已移除,项目即采集任务)。"""from __future__ import annotations10 unmodified lineslist_projects,scan_sessions,)from app.security import verify_api_keyfrom app.device_naming import decorate_device_sources, display_names_for_sources213 unmodified linesdevice_name: str = Query(..., min_length=1),_: str = Depends(verify_api_key),):"""采集端轮询此接口获取 active 项目(DAQ client 格式)。"""project_rows = await asyncio.to_thread(list_projects)projects = [p for p in project_rows if p.get("status", "active") == "active"]# Prefer the last complete snapshot. A cache miss only happens during a# cold start, and even that first remote scan is kept off the event loop.episodes = cached_sessions_for_tasks()if episodes is None:episodes = await asyncio.to_thread(scan_sessions)tasks = []for p in projects:cur = sum(1 for e in episodes if e.get("project") == p.get("name"))params = p.get("params") or {}if not isinstance(params, dict):params = {}6 unmodified lines"current_count": cur,"assigned_at": p.get("created_at"),"params": params,})return {"tasks": tasks, "updated_at": utcnow().isoformat()}1234567810 unmodified lines1920212223242526213 unmodified lines2402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692706 unmodified lines277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313"""Device heartbeat & polling API — 本地 JSON 存储(无数据库)。设备存 data/state/devices.json;采集端轮询 /device/tasks 获取active 项目列表(任务概念已移除,项目即采集任务);采集端「录制完成」的增量上报存 data/state/device_task_progress.json(见 app/device_progress.py)。"""from __future__ import annotations10 unmodified lineslist_projects,scan_sessions,)from app import device_progressfrom app.device_progress import reported_totalsfrom app.security import verify_api_keyfrom app.device_naming import decorate_device_sources, display_names_for_sources213 unmodified linesdevice_name: str = Query(..., min_length=1),_: str = Depends(verify_api_key),):"""采集端轮询此接口获取 active 项目(DAQ client 格式)。current_count 口径:各设备上报的录制完成数之和(见 app/device_progress.py);只有从未收到过上报的项目才回退到「项目目录下的 session 数」,让升级前就存在的历史项目不归零。session 是**上传**的产物,早先直接拿它当进度会让同一条数据被算两次(录制一次、上传一次)。"""project_rows = await asyncio.to_thread(list_projects)projects = [p for p in project_rows if p.get("status", "active") == "active"]reported = await asyncio.to_thread(reported_totals)# 只有需要 session 兜底时才扫目录(用了上报口径的项目不再触发远程遍历)needs_sessions = device_progress.needs_session_fallback(projects, reported)episodes: list = []if needs_sessions:# Prefer the last complete snapshot. A cache miss only happens during a# cold start, and even that first remote scan is kept off the event loop.episodes = cached_sessions_for_tasks()if episodes is None:episodes = await asyncio.to_thread(scan_sessions)tasks = []for p in projects:sessions = (sum(1 for e in episodes if e.get("project") == p.get("name"))if needs_sessions else None)cur, source = device_progress.resolve_count(p, reported, sessions or 0)params = p.get("params") or {}if not isinstance(params, dict):params = {}6 unmodified lines"current_count": cur,"assigned_at": p.get("created_at"),"params": params,# 供 Web UI/排查用:进度口径与该项目实际已上传的 session 数"progress_source": source,"session_count": sessions,})return {"tasks": tasks, "updated_at": utcnow().isoformat()}@router.post("/device/tasks/progress")async def device_task_progress(body: dict | None = None,_: str = Depends(verify_api_key)):"""采集端「录制完成」增量上报(幂等)。body::{"task_id": "<项目 id>", "device_name": "EGO_001","session_id": "EGO_001:<task_id>:<本地水位>", "increment": 1}返回 ``{"completed_count": <该项目最新进度>}`` —— 采集端把这个数当后端权威数落进自己的分账(backend_count)。同一 (device_name, session_id)重放不重复计数:采集端崩溃/断网后重发同一个水位是安全的。错误:参数缺失/非法、任务不存在 → 400。**刻意不用 404** —— 采集端把 404当成「后端还没实现该端点」并永久降级(整机不再上报任何进度)。"""from fastapi import HTTPExceptionprojects = await asyncio.to_thread(list_projects)known = {str(p.get("id") or "") for p in projects}try:return await asyncio.to_thread(device_progress.apply_report, body or {}, known)except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc))
361 unmodified lines362363364365366367368369361 unmodified lines@router.get("/episode-format/{episode_id}")async def episode_export_format(episode_id: str):"""前端按钮徽标:该批次下载时实际返回的格式。"""if get_episode(episode_id) is None:raise HTTPException(status_code=404, detail="Episode not found")target = _episode_export_target(episode_id)361 unmodified lines362363364365366367368369370371372373374375376361 unmodified lines@router.get("/episode-format/{episode_id}")def episode_export_format(episode_id: str):"""前端按钮徽标:该批次下载时实际返回的格式。同步端点(FastAPI 丢线程池执行)。以前写成 ``async def`` 却调:func:`_episode_export_target` —— 那里读历史 run 快照 + 逐个 ``is_file()``全是远程阻塞 I/O,在事件循环上跑会把同一次开页的其它请求一起冻住:实测该接口冷调用 4.4s,期间 hand-3d / slam / tactile 全部排队,这正是"打开一条数据时而 2 秒时而 7 秒"的来源。"""if get_episode(episode_id) is None:raise HTTPException(status_code=404, detail="Episode not found")target = _episode_export_target(episode_id)
488 unmodified lines48949049149249349478 unmodified lines573574575576577578488 unmodified linesis_depth_source, iter_video_streams, normalize_extracted_dataset,)normalize_extracted_dataset(staging_dir, batch_name)info = _read_json(staging_dir / "meta" / "info.json")if not isinstance(info, dict):info = {}78 unmodified lines)write_episode_state(batch_name, new_state)save_annotations(batch_name, [])# A new upload or a same-name re-upload changes files/cameras, not# just review state. Force the next session scan to discover the new# structure before a workflow or review request can use stale streams.488 unmodified lines48949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452578 unmodified lines604605606607608609610611612613614615616488 unmodified linesis_depth_source, iter_video_streams, normalize_extracted_dataset,)normalize_extracted_dataset(staging_dir, batch_name)# ── 内容级重复检测(与包名无关)──# 采集端可能把已上传过的录制换个包名再推一次(本地去重标记丢失 /# 包名规则变化),此时上面的 incoming_name 判断不出来,同一份数据# 会被追加成新批次。用规范化后的内容指纹兜底:命中已有批次就按# 同名重传处理,覆盖原批次而不是新增一条重复数据。# 算不出指纹时返回 None,一律按新批次正常入库。try:from app.batch_fingerprint import (compute_fingerprint, lookup_duplicate,)content_fingerprint = compute_fingerprint(staging_dir)duplicate_of = lookup_duplicate(project_folder, content_fingerprint, existing_ids)except Exception as fingerprint_err:content_fingerprint = Noneduplicate_of = Noneprint(f"[Upload] Fingerprint skipped: {fingerprint_err}")if duplicate_of and duplicate_of != batch_name:print(f"[Upload] Duplicate content of {duplicate_of} "f"(incoming name {incoming_name!r}) → replacing that episode")batch_name = duplicate_ofis_reupload = Truebatch_preexisted = True# staging 目录名只是本地上传中转名,append_project_episode 以# batch_name 参数为准,无需跟着改名。old_state = read_episode_state(batch_name)old_annotations = list_annotations(batch_name)info = _read_json(staging_dir / "meta" / "info.json")if not isinstance(info, dict):info = {}78 unmodified lines)write_episode_state(batch_name, new_state)save_annotations(batch_name, [])# 指纹只在批次真正提交后记录:失败的上传不该占住一个内容身份,# 否则重试时会被判成"重复"而覆盖掉自己。try:from app.batch_fingerprint import record_fingerprintrecord_fingerprint(project_folder, content_fingerprint, batch_name)except Exception as fingerprint_err:print(f"[Upload] Fingerprint record skipped: {fingerprint_err}")# A new upload or a same-name re-upload changes files/cameras, not# just review state. Force the next session scan to discover the new# structure before a workflow or review request can use stale streams.
56 unmodified lines575859606162213 unmodified lines2762772782792802812827 unmodified lines2902912922932942952962972982993003013023033043053063073083093103113123 unmodified lines31631731831932032132232332432532610 unmodified lines33733833934034134234380 unmodified lines4244254264274284292 unmodified lines43243343443543643743843926 unmodified lines46646746846947047132 unmodified lines5045055065075085095105 unmodified lines51651751851952052152252321 unmodified lines54554654754854955055155255355455555610 unmodified lines56756856957057157257357457557657738 unmodified lines61661761861962062162262362462562662762862963063163263363463556 unmodified lines"left": "observation.gripper_left_force","right": "observation.gripper_right_force",}# Sequential decode is cheap, but decoding through more than this many# frames to reach a scrub target is not; jump via a seek reader instead._DEPTH_WINDOW_SEEK_GAP = 6213 unmodified linesdef _read_slam_rows(path: Path) -> tuple[str, list[dict]]:"""Read canonical ``observation.slam_pose`` rows once per parquet revision."""import numpy as npimport pandas as pd7 unmodified linescached = _SLAM_DATA_CACHE.get(cache_key)if cached is not None and cached[0] == revision:return cachedcolumns = ["frame_index", "timestamp", "observation.slam_pose"]has_gripper_state = Falsetry:import pyarrow.parquet as pqavailable_columns = set(pq.ParquetFile(path).schema_arrow.names)has_gripper_state = "observation.gripper_state" in available_columnsexcept Exception:passif has_gripper_state:columns.append("observation.gripper_state")try:df = pd.read_parquet(path, columns=columns, engine="pyarrow")except Exception:return revision, []rows: list[dict] = []for _, row in df.iterrows():try:frame = int(row.get("frame_index", len(rows)))except (TypeError, ValueError):3 unmodified linestimestamp = float(timestamp) if np.isfinite(float(timestamp)) else Noneexcept (TypeError, ValueError):timestamp = Nonepose = row.get("observation.slam_pose")try:values = np.asarray(pose, dtype=np.float64).reshape(-1)except (TypeError, ValueError):values = np.empty(0, dtype=np.float64)# A missing native SLAM sample is represented by an all-zero pose in# some recordings. It is not the same thing as a valid pose at the10 unmodified lines"p": [float(value) for value in values[:7]],"t": timestamp,"g": _read_gripper_state(row.get("observation.gripper_state"))if has_gripper_state else None,})rows.sort(key=lambda item: item["f"])80 unmodified linesreturn Nonedef _decode_tactile_matrix(value):"""Decode one canonical 250x250x3 row-diff force matrix to mN.2 unmodified linesprefix sum must run over the full 750-value row before reshaping back toHWC. Splitting H/W/C first and accumulating each channel independentlyproduces a different matrix and was the cause of the incorrect preview.The int16 cast is intentional: the recorder's contract is modulo-2^16 andthe final values are integer mN."""import numpy as np26 unmodified linesreturn decodeddef _read_tactile_frame(path: Path, frame_index: int, side: str):"""Read only the requested parquet row and side.32 unmodified lines# making the UI show a broken image.if decoded is None:return np.zeros((3, *_TACTILE_SHAPE), dtype=np.float32)return decodedexcept Exception:return Nonereturn None5 unmodified lines"""Return one smoothed fz pressure field as float32 bytes.The payload is numeric data, not a rendered image. The frontend appliesthe color map in WebGL2. ``lo``/``hi`` preserve the acquisition-sideper-frame contrast normalization without sending a rendered image."""import cv2import numpy as np21 unmodified lines# pressure visualization.pressure = np.maximum(matrix[2], 0.0)pressure = cv2.GaussianBlur(pressure, (3, 3), 0.8)valid = pressure[pressure > 0.01]lo = 0.0hi = 1.0if valid.size > 50:lo = float(np.percentile(valid, 10))hi = max(float(np.percentile(valid, 98)) * 1.3, lo + 0.5)field = np.ascontiguousarray(pressure, dtype="<f4")result = (field.tobytes(), lo, hi)with _TACTILE_PREVIEW_LOCK:10 unmodified linesdef _tactile_range_payload(path: Path, first: int, last: int,side: str) -> bytes | None:"""Encode a run of consecutive fz fields as R8 plus per-frame min/max.Body layout: ``frames * 250 * 250`` bytes of R8 (one byte per cell, rowmajor) followed by ``frames * 2`` little-endian float32 values holdingeach frame's ``lo``/``hi`` normalisation pair. One request per windowreplaces one 250 KB request per frame, which is what saturated thebrowser's socket buffers (net::ERR_NO_BUFFER_SPACE) during playback."""38 unmodified linespixels = _TACTILE_SHAPE[0] * _TACTILE_SHAPE[1]blocks: list[bytes] = []pairs: list[float] = []for frame in range(int(first), int(last)):matrix = _decode_tactile_matrix(rows.get(frame))if matrix is None:blocks.append(bytes(pixels))pairs.extend((0.0, 1.0))continuepressure = np.maximum(matrix[2], 0.0)pressure = cv2.GaussianBlur(pressure, (3, 3), 0.8)valid = pressure[pressure > 0.01]lo = 0.0hi = 1.0if valid.size > 50:lo = float(np.percentile(valid, 10))hi = max(float(np.percentile(valid, 98)) * 1.3, lo + 0.5)scaled = np.clip((pressure - lo) / (hi - lo + 1e-6), 0.0, 1.0)blocks.append(np.rint(scaled * 255.0).astype(np.uint8).tobytes())pairs.extend((lo, hi))56 unmodified lines575859606162636465666768697071727374757677213 unmodified lines2912922932942952962972982993003013023033043053063077 unmodified lines3153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593 unmodified lines36336436536636736836937037137237337437537637737810 unmodified lines38939039139239339439580 unmodified lines4764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275282 unmodified lines53153253353453553653753853926 unmodified lines56656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763832 unmodified lines6716726736746756766775 unmodified lines68368468568668768868969021 unmodified lines71271371471571671771810 unmodified lines72973073173273373473573673773873974038 unmodified lines77978078178278378478578678778878979079179279379479579679756 unmodified lines"left": "observation.gripper_left_force","right": "observation.gripper_right_force",}# Colour-scale anchors for the force heatmaps. The range is measured over the# whole episode, never per frame: a frame with no contact holds nothing above# the noise threshold but noise, so a per-frame range collapses onto that noise# and stretches every blip to the top of the colour ramp - the tile lights up# with red dots that read as real pressure. ``lo`` is the episode's median# valid pressure (its noise floor; anything at or below renders as background)# and ``hi`` its peak plus headroom._TACTILE_NOISE_FLOOR_MN = 0.01_TACTILE_RANGE_BASELINE_PERCENTILE = 50.0_TACTILE_RANGE_PEAK_PERCENTILE = 99.9_TACTILE_RANGE_HEADROOM = 1.3_TACTILE_RANGE_MIN_SPAN_MN = 0.5_TACTILE_RANGE_SAMPLE_FRAMES = 256_TACTILE_SCALE_CACHE: OrderedDict[tuple, tuple[float, float]] = OrderedDict()_TACTILE_SCALE_CACHE_MAX = 8# Sequential decode is cheap, but decoding through more than this many# frames to reach a scrub target is not; jump via a seek reader instead._DEPTH_WINDOW_SEEK_GAP = 6213 unmodified linesdef _read_slam_rows(path: Path) -> tuple[str, list[dict]]:"""Read canonical SLAM rows once per parquet revision.位姿有两个来源,取决于采集端版本:- 旧版写 ``observation.slam_pose``(每帧一个 7 维位姿);- 新版只写 ``observation.slam_trajectory``(高频样本缓冲),没有``slam_pose``。此时前端曾经整块空白 —— 因为这里硬编码读后者。两条路径统一成每帧一个位姿:trajectory 交给 ``poses_from_trajectory``重建(它已按时间戳取最近样本,丢帧时也能从相邻格子找回)。"""import numpy as npimport pandas as pd7 unmodified linescached = _SLAM_DATA_CACHE.get(cache_key)if cached is not None and cached[0] == revision:return cachedtry:import pyarrow.parquet as pqavailable_columns = set(pq.ParquetFile(path).schema_arrow.names)except Exception:return revision, []has_pose = "observation.slam_pose" in available_columnshas_trajectory = "observation.slam_trajectory" in available_columnsif not has_pose and not has_trajectory:return revision, []columns = ["frame_index", "timestamp"]if has_pose:columns.append("observation.slam_pose")if has_trajectory:columns.append("observation.slam_trajectory")if "observation.gripper_state" in available_columns:columns.append("observation.gripper_state")try:df = pd.read_parquet(path, columns=columns, engine="pyarrow")except Exception:return revision, []# 新版只有 trajectory:重建出逐帧位姿,让下游按同一套逻辑消费。rebuilt = Noneif not has_pose:from app.umi_slam_action import poses_from_trajectorystamps = (df["timestamp"].to_numpy(dtype=float)if "timestamp" in df.columns else None)if stamps is None:stamps = np.arange(len(df), dtype=float) / 30.0rebuilt = poses_from_trajectory(df["observation.slam_trajectory"].tolist(), stamps, len(df))if rebuilt is None:return revision, []rows: list[dict] = []for position, (_, row) in enumerate(df.iterrows()):try:frame = int(row.get("frame_index", len(rows)))except (TypeError, ValueError):3 unmodified linestimestamp = float(timestamp) if np.isfinite(float(timestamp)) else Noneexcept (TypeError, ValueError):timestamp = Noneif has_pose:pose = row.get("observation.slam_pose")try:values = np.asarray(pose, dtype=np.float64).reshape(-1)except (TypeError, ValueError):values = np.empty(0, dtype=np.float64)else:# 已从 trajectory 重建,按位置对齐取本帧位姿values = (rebuilt[position] if position < len(rebuilt)else np.empty(0, dtype=np.float64))# A missing native SLAM sample is represented by an all-zero pose in# some recordings. It is not the same thing as a valid pose at the10 unmodified lines"p": [float(value) for value in values[:7]],"t": timestamp,"g": _read_gripper_state(row.get("observation.gripper_state"))if "observation.gripper_state" in available_columns else None,})rows.sort(key=lambda item: item["f"])80 unmodified linesreturn Nonedef _tactile_scale_factor(path: Path) -> float:"""Read ``features.*.scale`` for the force matrix from dataset metadata.Newer recorders store the matrix as quantised integers scaled by 100(``"scale": 100`` alongside ``units: mN``), so the raw values must bedivided by that factor to recover mN. Older recordings omit the field andalready store plain mN, so the default is 1.The factor is read from metadata rather than hard-coded because therecordings genuinely differ; assuming 100 would divide old data by 100."""try:import json# parquet 位于 <root>/data/chunk-000/,info.json 位于 <root>/meta/。# 逐级上溯找 meta/info.json,避免依赖固定的目录深度。root = Path(path).parentfor candidate in (root, *root.parents):meta = candidate / "meta" / "info.json"if meta.is_file():info = json.loads(meta.read_text(encoding="utf-8"))breakelse:return 1.0except (OSError, ValueError, TypeError):return 1.0features = info.get("features") or {}for key in _TACTILE_COLUMNS.values():entry = features.get(key)if not isinstance(entry, dict):continuetry:factor = float(entry.get("scale"))except (TypeError, ValueError):continue# 0/负数会让整块力值失真,视为未声明。if factor > 0:return factorreturn 1.0def _apply_tactile_scale(matrix, factor: float):"""把量化整数还原成物理单位(mN);factor<=1 时不做任何改动。"""if matrix is None or not factor or factor <= 1:return matrixreturn matrix / factordef _decode_tactile_matrix(value):"""Decode one canonical 250x250x3 row-diff force matrix to mN.2 unmodified linesprefix sum must run over the full 750-value row before reshaping back toHWC. Splitting H/W/C first and accumulating each channel independentlyproduces a different matrix and was the cause of the incorrect preview.The int16 cast is intentional: the recorder's contract is modulo-2^16.Values are quantised integers in ``units: mN``; the physical scale isapplied by callers via ``_tactile_scale_factor``."""import numpy as np26 unmodified linesreturn decodeddef _compute_tactile_display_range(path: Path, column: str) -> tuple[float, float]:"""Sample a whole episode and return its ``(lo, hi)`` colour range in mN.Every stored frame shares one row group, so reading the column costs thesame as reading any slice of it; the sampling stride bounds the decode andthe pooled sample, not the I/O."""import cv2import numpy as npimport pyarrow as paimport pyarrow.parquet as pqtry:table = pq.read_table(path, columns=[column])except Exception:return 0.0, 1.0column_data = table.column(column)if isinstance(column_data, pa.ChunkedArray):column_data = column_data.combine_chunks()offsets = np.asarray(column_data.offsets, dtype=np.int64)values = np.asarray(column_data.values, dtype=np.int16)frames = len(offsets) - 1if frames <= 0:return 0.0, 1.0stride = max(1, frames // _TACTILE_RANGE_SAMPLE_FRAMES)scale_factor = _tactile_scale_factor(path)samples: list[np.ndarray] = []for index in range(0, frames, stride):matrix = _apply_tactile_scale(_decode_tactile_matrix(values[offsets[index]:offsets[index + 1]]),scale_factor)if matrix is None:continuepressure = cv2.GaussianBlur(np.maximum(matrix[2], 0.0), (3, 3), 0.8)valid = pressure[pressure > _TACTILE_NOISE_FLOOR_MN]if valid.size:samples.append(valid)if not samples:return 0.0, 1.0pooled = np.concatenate(samples)lo = float(np.percentile(pooled, _TACTILE_RANGE_BASELINE_PERCENTILE))hi = max(float(np.percentile(pooled, _TACTILE_RANGE_PEAK_PERCENTILE))* _TACTILE_RANGE_HEADROOM, lo + _TACTILE_RANGE_MIN_SPAN_MN)return lo, hidef _tactile_display_range(path: Path, revision: str,side: str) -> tuple[float, float]:"""Return the cached episode-wide colour range ``(lo, hi)`` for one side."""column = _TACTILE_COLUMNS.get(side)if column is None:return 0.0, 1.0key = (str(path.resolve()), revision, side)with _TACTILE_PREVIEW_LOCK:cached = _TACTILE_SCALE_CACHE.get(key)if cached is not None:_TACTILE_SCALE_CACHE.move_to_end(key)return cachedresult = _compute_tactile_display_range(path, column)with _TACTILE_PREVIEW_LOCK:_TACTILE_SCALE_CACHE[key] = result_TACTILE_SCALE_CACHE.move_to_end(key)while len(_TACTILE_SCALE_CACHE) > _TACTILE_SCALE_CACHE_MAX:_TACTILE_SCALE_CACHE.popitem(last=False)return resultdef _read_tactile_frame(path: Path, frame_index: int, side: str):"""Read only the requested parquet row and side.32 unmodified lines# making the UI show a broken image.if decoded is None:return np.zeros((3, *_TACTILE_SHAPE), dtype=np.float32)return _apply_tactile_scale(decoded, _tactile_scale_factor(path))except Exception:return Nonereturn None5 unmodified lines"""Return one smoothed fz pressure field as float32 bytes.The payload is numeric data, not a rendered image. The frontend appliesthe color map in WebGL2. ``lo``/``hi`` are the episode-wide contrastrange, so the same mN value maps to the same colour in every frame."""import cv2import numpy as np21 unmodified lines# pressure visualization.pressure = np.maximum(matrix[2], 0.0)pressure = cv2.GaussianBlur(pressure, (3, 3), 0.8)lo, hi = _tactile_display_range(path, f"{revision[0]:x}-{revision[1]:x}", side)field = np.ascontiguousarray(pressure, dtype="<f4")result = (field.tobytes(), lo, hi)with _TACTILE_PREVIEW_LOCK:10 unmodified linesdef _tactile_range_payload(path: Path, first: int, last: int,side: str) -> bytes | None:"""Encode a run of consecutive fz fields as R8 plus the episode's min/max.Body layout: ``frames * 250 * 250`` bytes of R8 (one byte per cell, rowmajor) followed by ``frames * 2`` little-endian float32 values holdingeach frame's ``lo``/``hi`` normalisation pair - the episode-wide range,repeated once per frame so the header count stays fixed. One request per windowreplaces one 250 KB request per frame, which is what saturated thebrowser's socket buffers (net::ERR_NO_BUFFER_SPACE) during playback."""38 unmodified linespixels = _TACTILE_SHAPE[0] * _TACTILE_SHAPE[1]blocks: list[bytes] = []pairs: list[float] = []# 量化整数先还原成 mN;色阶取整集区间,不逐帧重算,否则没有接触的帧会# 拿自身噪声当满量程,把噪点画成接触点。scale_factor = _tactile_scale_factor(path)lo, hi = _tactile_display_range(path, revision, side)for frame in range(int(first), int(last)):matrix = _apply_tactile_scale(_decode_tactile_matrix(rows.get(frame)),scale_factor)if matrix is None:blocks.append(bytes(pixels))pairs.extend((lo, hi))continuepressure = np.maximum(matrix[2], 0.0)pressure = cv2.GaussianBlur(pressure, (3, 3), 0.8)scaled = np.clip((pressure - lo) / (hi - lo + 1e-6), 0.0, 1.0)blocks.append(np.rint(scaled * 255.0).astype(np.uint8).tobytes())pairs.extend((lo, hi))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269"""UMI Gripper 动作派生 —— 从 SLAM 位姿反推 imitation learning 的 action。
UMI 硬件不录 action:采集端写入的 ``action`` 列是占位全零,导出时会被``lerobot_export._junk_columns`` 当零信息列剔除,导致数据集无法训练。官方 UMI 的做法同样是从 SLAM 位姿反推 —— 本模块实现这套口径。
action(7 维,当前夹爪局部坐标系):
Δp = R_tᵀ · (p_{t+1} − p_t) # 平移增量, 米 Δr = rotvec(R_tᵀ · R_{t+1}) # 旋转增量, 弧度 g = gripper_state[t+1, 0] / 100 # 夹爪开合, 0–1
本模块是纯函数(不依赖 Web 框架与数据库),便于单测与跨格式复用。"""
from __future__ import annotations
import numpy as np
# 动作维度:Δp(3) + Δr(3) + 夹爪(1)ACTION_DIM = 7
def quat_to_matrix(q) -> np.ndarray | None: """四元数 ``(x, y, z, w)`` → 3×3 旋转矩阵。
范数过小(零四元数)说明该帧没有有效姿态,返回 ``None`` 而不是抛异常 —— 调用方据此跳过该帧。 """ x, y, z, w = (float(v) for v in np.asarray(q, dtype=float).ravel()[:4]) norm = (x * x + y * y + z * z + w * w) ** 0.5 if norm < 1e-12: return None x, y, z, w = x / norm, y / norm, z / norm, w / norm return np.array([ [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], ])
def matrix_to_rotvec(rotation: np.ndarray) -> np.ndarray: """3×3 旋转矩阵 → 旋转向量(轴×角,弧度)。
近 180° 时 ``sin(角) → 0``,标准轴公式会除零并产生 NaN。手部大幅翻转 是真实存在的姿态,一旦产生 NaN 会污染整列 action,因此单独走 ``(R + I)/2`` 的对角元求轴。 """ trace = (float(rotation[0, 0]) + float(rotation[1, 1]) + float(rotation[2, 2]) - 1.0) / 2.0 angle = float(np.arccos(max(-1.0, min(1.0, trace))))
if angle < 1e-9: return np.zeros(3)
if np.pi - angle < 1e-6: # 近 π:用 (R+I)/2 的列向量恢复转轴,再按对角元归一化。 symmetric = (rotation + np.eye(3)) / 2.0 diagonal = np.clip(np.diag(symmetric), 0.0, None) index = int(np.argmax(diagonal)) if diagonal[index] < 1e-9: return np.zeros(3) axis = symmetric[:, index] / (diagonal[index] ** 0.5) norm = float(np.linalg.norm(axis)) return axis / norm * angle if norm > 1e-9 else np.zeros(3)
axis = np.array([ float(rotation[2, 1]) - float(rotation[1, 2]), float(rotation[0, 2]) - float(rotation[2, 0]), float(rotation[1, 0]) - float(rotation[0, 1]), ]) / (2.0 * np.sin(angle)) return axis * angle
def poses_from_trajectory(trajectories, timestamps, frame_count: int) -> np.ndarray | None: """从 ``observation.slam_trajectory`` 的样本缓冲重建逐帧位姿 ``(N, 7)``。
slam_trajectory 是采集端的高频(50Hz)样本缓冲,每格存 ``[t, x, y, z, qx, qy, qz, qw]`` 的整数倍。数据帧是 30fps,所以两个 数据帧之间到达的样本会落在其中一格的格子里 —— 某一帧自己的格子为空, 不代表那个时刻没有位姿,**相邻格子里往往就有**。
因此正确做法是把所有格子的样本汇总,按时间戳逐帧取最近的: 实测 30% 的「丢帧」里有 97% 能被真实样本覆盖,且单帧位移上限从 113.9mm 降到 24.8mm(插值方案会横跨 SLAM 重定位跳变)。
时间基映射:slam 时间戳与数据时间戳之间是**线性关系**(实测斜率 1.02,采集端时钟略快)。用「每个非空格子的最后一组对应本帧时刻」 的锚点做最小二乘拟合,不依赖外部时钟。
返回 ``(frame_count, 7)``;样本不足返回 ``None``。 """ import numpy as np
if frame_count <= 0: return None stamp = np.asarray(timestamps, dtype=float).reshape(-1)[:frame_count] if stamp.size < frame_count: stamp = np.concatenate([stamp, np.full(frame_count - stamp.size, np.nan)])
# 1) 汇总样本,并收集时间基锚点(非空格子的最后一组 ≈ 本帧时刻) samples: list[tuple[float, list[float]]] = [] anchor_slam: list[float] = [] anchor_data: list[float] = [] has_anchor = ~np.isnan(stamp) for index in range(min(frame_count, len(trajectories))): values = np.asarray(trajectories[index], dtype=float).reshape(-1) groups = values.size // 8 if groups <= 0: continue for g in range(groups): chunk = values[g * 8:g * 8 + 8] if not np.isfinite(chunk).all(): continue samples.append((float(chunk[0]), [float(v) for v in chunk[1:8]])) if has_anchor[index]: anchor_slam.append(float(values[(groups - 1) * 8])) anchor_data.append(float(stamp[index])) if len(samples) < 2 or len(anchor_slam) < 2: return None
# 2) 线性映射 slam 时间 → 数据时间:data = slope*slam + intercept slam_t = np.array(anchor_slam, dtype=float) data_t = np.array(anchor_data, dtype=float) slope, intercept = np.polyfit(slam_t, data_t, 1) if not np.isfinite(slope) or slope <= 0: return None
samples.sort(key=lambda item: item[0]) sample_t = (np.array([item[0] for item in samples], dtype=float) * slope + intercept) sample_p = np.array([item[1] for item in samples], dtype=float)
# 3) 逐帧取时间上最近的样本。超过约一帧半间隔就认为真的没有数据, # 标为缺失留给插值,避免把远处的样本硬贴到当前帧。 poses = np.zeros((frame_count, 7), dtype=float) missing = np.zeros(frame_count, dtype=bool) dt = np.nanmedian(np.diff(stamp)) if frame_count > 1 else 1.0 / 30.0 if not np.isfinite(dt) or dt <= 0: dt = 1.0 / 30.0 tolerance = dt * 1.5 for index in range(frame_count): if np.isnan(stamp[index]): missing[index] = True continue j = int(np.abs(sample_t - stamp[index]).argmin()) if abs(sample_t[j] - stamp[index]) > tolerance: missing[index] = True continue poses[index] = sample_p[j]
# 4) 真实样本覆盖不到的少数帧(实测约 3%)才插值兜底 valid = np.where(~missing)[0] if len(valid) < 2: return None for index in np.where(missing)[0]: lo = valid[valid < index] hi = valid[valid > index] if len(lo) and len(hi): a, b = int(lo[-1]), int(hi[0]) w = (index - a) / (b - a) poses[index] = (1 - w) * poses[a] + w * poses[b] else: poses[index] = poses[int(lo[-1])] if len(lo) else poses[int(hi[0])]
norms = np.linalg.norm(poses[:, 3:7], axis=1, keepdims=True) poses[:, 3:7] = poses[:, 3:7] / np.maximum(norms, 1e-12) return poses
def _gripper_fraction(states, frame_count: int) -> np.ndarray: """取夹爪开合度 → 0–1。契约 ``[percent, gripped, raw]``,只用首维。
``gripped`` 恒为 0、``raw`` 是带噪编码器计数,都不参与 action。 """ fraction = np.zeros(frame_count) total = len(states) if states is not None else 0 for frame in range(frame_count): raw = states[frame] if frame < total else None if raw is None: continue values = np.asarray(raw, dtype=float).ravel() if values.size: fraction[frame] = float(values[0]) / 100.0 # 采集端开合度是 0–100;越界值(标定异常)夹到合法区间的边界, # 避免动作维度出现 >1 的离群值把归一化统计带偏。 return np.clip(fraction, 0.0, 1.0)
def derive_action(trajectories, timestamps, gripper_states, frame_count: int) -> dict[int, dict] | None: """派生 UMI 口径的 action 与 proprioception。
位姿**只从** ``observation.slam_trajectory`` 重建 —— 它是采集端的高频 样本缓冲,丢帧时相邻格子里仍有真实样本(实测可覆盖 97% 的丢帧); 而 ``observation.slam_pose`` 在同样位置直接写零,只能靠插值硬补, 还会横跨 SLAM 重定位跳变(实测产生过 113.9mm 的假位移)。
返回 ``{frame_index: {"action": [7], "observation.state": [4]}}``:
- ``action``(7 维):当前夹爪局部系的增量位姿 + 夹爪开合,见上文; - ``observation.state``(4 维):``[Δx, Δy, Δz, gripper]``,位置为 **相对本集起点**的偏移。ACT 用单帧观测,没有 state 时模型无从得知 夹爪当前在哪(只能看图像猜);而 SLAM 的世界原点是每集任意初始化的, 给绝对坐标会把无关的世界位置当特征,故取相对量。
输入按 ``frame_index`` 顺序排列。无可用样本(非 UMI 数据、或全程丢帧) 返回 ``None``,调用方应跳过该集而非写入垃圾。
末帧没有 ``t+1``,沿用倒数第二帧的增量 —— 与 LeRobot 的 ``next.done`` 语义一致(末帧只是终止标记,不承载新动作)。 """ if frame_count <= 0: return None cleaned = poses_from_trajectory(trajectories, timestamps, frame_count) if cleaned is None: return None if len(cleaned) != frame_count: # 位姿列与帧数不一致时以较短者为准,避免错位写入。 frame_count = min(frame_count, len(cleaned))
fraction = _gripper_fraction(gripper_states, frame_count) # observation.state 的位置分量取**相对本集起点**的偏移。SLAM 的世界 # 原点是每次采集初始化时任意确定的,直接给绝对坐标会让模型把无关的 # 世界坐标当特征;相对起点才是可迁移的"相对自己出发点多远"。 origin = cleaned[0, :3].copy() result: dict[int, dict] = {}
for frame in range(frame_count): if frame < frame_count - 1: current = quat_to_matrix(cleaned[frame, 3:7]) following = quat_to_matrix(cleaned[frame + 1, 3:7]) index = frame + 1 else: # 末帧沿用倒数第二帧的位姿对,只取夹爪当前值。 if frame_count < 2: continue current = quat_to_matrix(cleaned[frame - 1, 3:7]) following = quat_to_matrix(cleaned[frame, 3:7]) index = frame if current is None or following is None: continue
if frame < frame_count - 1: delta_position = current.T @ (cleaned[frame + 1, :3] - cleaned[frame, :3]) else: delta_position = current.T @ (cleaned[frame, :3] - cleaned[frame - 1, :3]) delta_rotation = matrix_to_rotvec(current.T @ following)
action = np.concatenate([ delta_position, delta_rotation, [fraction[min(index, frame_count - 1)]], ]) # 非有限值宁缺勿脏:该帧不写,由下游按缺失处理。 if not np.all(np.isfinite(action)): continue result[frame] = { "action": [float(value) for value in action], "observation.state": [ float(value) for value in np.concatenate([ cleaned[frame, :3] - origin, [fraction[frame]], ]) ], } return result or None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""内容指纹:识别"换个包名重传同一份数据"。
实测背景:采集端把已上传的录制重新推一遍时包名会变(本地去重标记丢失或包名规则变化),``session.py`` 的 incoming_name 判断不出来,同一份数据被追加成新 episode(UMIGripper_AI 出现 4 组字节级相同的批次)。这里的指纹必须与包名无关,且对"同一次录制的两份拷贝"稳定命中。"""
import jsonimport tempfileimport unittestfrom pathlib import Pathfrom unittest import mock
import numpy as npimport pyarrow as paimport pyarrow.parquet as pq
from app import batch_fingerprint
def _write_episode(root: Path, episode_index: int, video_bytes: bytes, frames: int = 4) -> None: """写一个最小 canonical 布局:一个视频 + 一个 data parquet。""" videos = root / "videos" / "observation.images.gripper_rgb" / "chunk-000" videos.mkdir(parents=True, exist_ok=True) (videos / f"episode_{episode_index:06d}.mp4").write_bytes(video_bytes)
data = root / "data" / "chunk-000" data.mkdir(parents=True, exist_ok=True) table = pa.table({ "episode_index": pa.array([episode_index] * frames, pa.int64()), "frame_index": pa.array(list(range(frames)), pa.int64()), "observation.value": pa.array( [[float(i), float(i) + 1.0] for i in range(frames)], pa.list_(pa.float32()), ), }) pq.write_table(table, data / f"episode_{episode_index:06d}.parquet")
class FingerprintTests(unittest.TestCase): def setUp(self): self._tmp = tempfile.TemporaryDirectory() self.root = Path(self._tmp.name) # 索引落到临时目录,别碰真实 state/ self._index_patch = mock.patch.object( batch_fingerprint, "INDEX_PATH", self.root / "fingerprints.json") self._index_patch.start()
def tearDown(self): self._index_patch.stop() self._tmp.cleanup()
def test_same_recording_different_episode_index_matches(self): """同一次录制的两份拷贝,只有 episode_index 不同 → 指纹相同。""" a = self.root / "a" b = self.root / "b" _write_episode(a, 3, b"IDENTICAL-VIDEO-BYTES") _write_episode(b, 4, b"IDENTICAL-VIDEO-BYTES")
self.assertIsNotNone(batch_fingerprint.compute_fingerprint(a)) self.assertEqual( batch_fingerprint.compute_fingerprint(a), batch_fingerprint.compute_fingerprint(b), )
def test_different_video_differs(self): a = self.root / "a" b = self.root / "b" _write_episode(a, 0, b"VIDEO-ONE") _write_episode(b, 0, b"VIDEO-TWO") self.assertNotEqual( batch_fingerprint.compute_fingerprint(a), batch_fingerprint.compute_fingerprint(b), )
def test_different_frame_data_differs(self): """视频相同但帧数据不同 → 不同指纹(不能只比视频)。""" a = self.root / "a" b = self.root / "b" _write_episode(a, 0, b"SAME-VIDEO") _write_episode(b, 0, b"SAME-VIDEO") # 只改 b 的一帧数据 path = b / "data" / "chunk-000" / "episode_000000.parquet" table = pq.read_table(path).to_pydict() table["observation.value"] = [[9.0, 9.0] for _ in table["frame_index"]] pq.write_table(pa.table(table), path) self.assertNotEqual( batch_fingerprint.compute_fingerprint(a), batch_fingerprint.compute_fingerprint(b), )
def test_missing_data_returns_none(self): """没有 parquet 就算不出指纹 → None(调用方按新批次放行)。""" empty = self.root / "empty" empty.mkdir() self.assertIsNone(batch_fingerprint.compute_fingerprint(empty))
def test_record_and_lookup_roundtrip(self): fingerprint = "v:test=abc;d:def" batch_fingerprint.record_fingerprint("UMIGripper_AI", fingerprint, "ep_000003") self.assertEqual( batch_fingerprint.lookup_duplicate( "UMIGripper_AI", fingerprint, {"ep_000003"}), "ep_000003", )
def test_lookup_ignores_deleted_episode(self): """索引指向的 episode 已删除 → 不判重(允许重新上传)。""" fingerprint = "v:test=abc;d:def" batch_fingerprint.record_fingerprint("UMIGripper_AI", fingerprint, "ep_000003") self.assertIsNone( batch_fingerprint.lookup_duplicate( "UMIGripper_AI", fingerprint, {"ep_000004"}), )
def test_lookup_none_fingerprint_is_safe(self): self.assertIsNone( batch_fingerprint.lookup_duplicate("p", None, {"a"}))
def test_record_drops_stale_entry_for_same_episode(self): """同名重传换了内容:旧指纹不该继续指向这个 episode。""" batch_fingerprint.record_fingerprint("p", "old-content", "ep_1") batch_fingerprint.record_fingerprint("p", "new-content", "ep_1") self.assertIsNone( batch_fingerprint.lookup_duplicate("p", "old-content", {"ep_1"})) self.assertEqual( batch_fingerprint.lookup_duplicate("p", "new-content", {"ep_1"}), "ep_1", )
def test_forget_fingerprint(self): batch_fingerprint.record_fingerprint("p", "abc", "ep_1") batch_fingerprint.forget_fingerprint("ep_1") self.assertIsNone( batch_fingerprint.lookup_duplicate("p", "abc", {"ep_1"}))
def test_corrupt_index_is_tolerated(self): batch_fingerprint.INDEX_PATH.write_text("{not json", encoding="utf-8") self.assertIsNone( batch_fingerprint.lookup_duplicate("p", "abc", {"ep_1"})) batch_fingerprint.record_fingerprint("p", "abc", "ep_1") self.assertEqual( batch_fingerprint.lookup_duplicate("p", "abc", {"ep_1"}), "ep_1")
def test_index_is_valid_json_with_episode_map(self): batch_fingerprint.record_fingerprint("proj", "fp1", "ep_1") data = json.loads(batch_fingerprint.INDEX_PATH.read_text(encoding="utf-8")) self.assertEqual(data["proj"]["fp1"], "ep_1")
class ParquetHashTests(unittest.TestCase): def test_episode_index_column_is_excluded(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) table = pa.table({ "episode_index": pa.array([7], pa.int64()), "frame_index": pa.array([0], pa.int64()), "v": pa.array([[1.0, 2.0]], pa.list_(pa.float32())), }) one = root / "one.parquet" pq.write_table(table, one) other = root / "other.parquet" pq.write_table( table.set_column(0, "episode_index", pa.array([99], pa.int64())), other) self.assertEqual( batch_fingerprint._parquet_content_hash(one), batch_fingerprint._parquet_content_hash(other), )
def test_unreadable_parquet_returns_none(self): with tempfile.TemporaryDirectory() as tmp: bad = Path(tmp) / "bad.parquet" bad.write_bytes(b"not a parquet file") self.assertIsNone(batch_fingerprint._parquet_content_hash(bad))
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181"""采集端任务进度账本单测(app/device_progress.py)。
覆盖:幂等重放、多设备聚合、增量水位、参数校验、未知任务拒绝(400 而非404 —— 采集端把 404 当"后端未实现"永久降级)、持久化与坏文件容错。
pytest tests/test_device_task_progress.py python3 tests/test_device_task_progress.py # 无 pytest 也能跑"""import jsonimport sysfrom pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app import device_progress as dp # noqa: E402
TASK = "task-aaa"OTHER = "task-bbb"KNOWN = {TASK, OTHER}
def _report(tmp, increment, session_id, task=TASK, device="EGO_001"): return dp.apply_report( {"task_id": task, "device_name": device, "session_id": session_id, "increment": increment}, KNOWN, path=tmp)
def test_first_report_sets_total(tmp_path): f = tmp_path / "p.json" out = _report(f, 1, "EGO_001:t:0") assert out["applied"] is True assert out["completed_count"] == 1 assert dp.reported_total(TASK, path=f) == 1
def test_replayed_watermark_is_idempotent(tmp_path): """采集端崩溃重启后会重发同一水位 —— 不能重复计数。""" f = tmp_path / "p.json" first = _report(f, 12, "EGO_001:t:0") again = _report(f, 12, "EGO_001:t:0") assert first["completed_count"] == 12 assert again["applied"] is False assert again["completed_count"] == 12 # 重放仍要回当前聚合数(采集端拿它当后端权威数) assert isinstance(again["completed_count"], int) assert not isinstance(again["completed_count"], bool)
def test_incremental_watermarks_accumulate(tmp_path): f = tmp_path / "p.json" _report(f, 12, "EGO_001:t:0") out = _report(f, 1, "EGO_001:t:12") assert out["completed_count"] == 13
def test_multiple_devices_aggregate(tmp_path): f = tmp_path / "p.json" _report(f, 3, "EGO_001:t:0", device="EGO_001") _report(f, 2, "EGO_002:t:0", device="EGO_002") out = _report(f, 1, "EGO_003:t:0", device="EGO_003") assert out["completed_count"] == 6 # 同一水位键跨设备不冲突 assert dp.reported_total(TASK, path=f) == 6
def test_zero_increment_is_recorded_without_growth(tmp_path): f = tmp_path / "p.json" _report(f, 5, "EGO_001:t:0") out = _report(f, 0, "EGO_001:t:5") assert out["applied"] is True and out["completed_count"] == 5
def test_totals_only_contain_reported_tasks(tmp_path): """没上报过的项目不能出现在这里 —— 调用方据此回退 session 计数。""" f = tmp_path / "p.json" _report(f, 1, "EGO_001:t:0") totals = dp.reported_totals(path=f) assert totals == {TASK: 1} assert dp.reported_total(OTHER, path=f) is None
def test_validation_errors(tmp_path): f = tmp_path / "p.json" bad = [ ({}, "task_id"), # 空 body ({"task_id": TASK, "session_id": "s"}, "device_name"), ({"task_id": TASK, "device_name": "d"}, "session_id"), ({"task_id": TASK, "device_name": "d", "session_id": "s", "increment": -1}, "increment"), ({"task_id": TASK, "device_name": "d", "session_id": "s", "increment": "x"}, "increment"), ({"task_id": TASK, "device_name": "d", "session_id": "s", "increment": True}, "increment"), ({"task_id": TASK, "device_name": "d", "session_id": "s", "increment": dp.MAX_INCREMENT + 1}, "increment"), ] for body, needle in bad: try: dp.apply_report(body, KNOWN, path=f) except ValueError as exc: assert needle in str(exc), (body, str(exc)) else: raise AssertionError(f"应当拒绝: {body}") assert dp.reported_totals(path=f) == {} # 拒绝的请求不落账
def test_unknown_task_rejected_not_silently_accepted(tmp_path): """未知任务要报错(路由转 400)。绝不能 404:采集端会永久降级上报。""" f = tmp_path / "p.json" try: _report(f, 1, "EGO_001:t:0", task="no-such-task") except ValueError as exc: assert "unknown task_id" in str(exc) else: raise AssertionError("未知任务应当被拒绝") # known_task_ids=None(不校验)时照常落账 —— 路由必须传已知集合 out = dp.apply_report({"task_id": "no-such-task", "device_name": "d", "session_id": "s", "increment": 1}, None, path=f) assert out["completed_count"] == 1
def test_count_prefers_report_over_sessions(tmp_path): """核心口径:有上报就用录制数 —— 之后再上传多少条都不动它。""" f = tmp_path / "p.json" proj = {"id": TASK, "name": "UMIGripper_AI"} _report(f, 12, "EGO_001:t:0") reported = dp.reported_totals(path=f) assert dp.resolve_count(proj, reported, sessions=16) == (12, "reported") # 又上传了 3 条(项目下 session 变 19)→ 进度不变 assert dp.resolve_count(proj, reported, sessions=19) == (12, "reported") # 录了一条 → 上报后 +1 _report(f, 1, "EGO_001:t:12") assert dp.resolve_count(proj, dp.reported_totals(path=f), sessions=19) == (13, "reported")
def test_count_falls_back_to_sessions_before_any_report(tmp_path): """升级前就有数据的历史项目不归零:没有上报时仍按 session 数。""" proj = {"id": TASK, "name": "UMIGripper_AI"} assert dp.resolve_count(proj, {}, sessions=16) == (16, "sessions") assert dp.needs_session_fallback([proj], {}) is True assert dp.needs_session_fallback([proj], {TASK: 12}) is False
def test_persisted_across_reload(tmp_path): f = tmp_path / "p.json" _report(f, 2, "EGO_001:t:0") raw = json.loads(f.read_text(encoding="utf-8")) assert raw["tasks"][TASK]["devices"]["EGO_001"]["count"] == 2 # 重新读文件(模拟进程重启)后水位仍生效 again = _report(f, 2, "EGO_001:t:0") assert again["applied"] is False and again["completed_count"] == 2
def test_corrupt_file_degrades_to_empty(tmp_path): f = tmp_path / "p.json" f.write_text("{ not json", encoding="utf-8") assert dp.reported_totals(path=f) == {} out = _report(f, 1, "EGO_001:t:0") assert out["completed_count"] == 1
if __name__ == "__main__": import tempfile import traceback
failed = 0 for name, fn in sorted(globals().items()): if not name.startswith("test_") or not callable(fn): continue with tempfile.TemporaryDirectory() as d: try: fn(Path(d)) print(f" PASS: {name}") except Exception: failed += 1 print(f" FAIL: {name}") traceback.print_exc() print("FAIL" if failed else "PASS: device_task_progress 全部通过") sys.exit(1 if failed else 0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105import unittest
import numpy as np
from app.lerobot_export import _ensure_slam_pose, _ensure_observation_statefrom app.umi_slam_action import poses_from_trajectory
def _sample(t: float, x: float, z: float) -> list[float]: """一组 slam_trajectory 样本:[t, x, y, z, qx, qy, qz, qw]。""" return [float(t), float(x), 0.0, float(z), 0.0, 0.0, 0.0, 1.0]
def _rows(episode: int, count: int, *, t0: float, slam_offset: float = 0.0) -> list[dict]: """造一集 rows:每帧两个 slam 样本,位姿随帧号线性推进。""" rows = [] for index in range(count): stamp = t0 + index / 30.0 rows.append({ "episode_index": episode, "timestamp": stamp, "observation.slam_trajectory": [ _sample(stamp - slam_offset, index * 0.01, index * 0.002), _sample(stamp - slam_offset + 0.01, index * 0.01 + 0.001, index * 0.002), ], }) return rows
class EnsureSlamPoseTests(unittest.TestCase): def test_derives_column_and_matches_direct_reconstruction(self): """整列缺失时补出 slam_pose,且值与单独调用重建函数逐值一致。""" rows = _rows(0, 40, t0=100.0) self.assertEqual(_ensure_slam_pose(rows), "observation.slam_pose")
self.assertTrue(all(len(row["observation.slam_pose"]) == 7 for row in rows)) expected = poses_from_trajectory( [row["observation.slam_trajectory"] for row in rows], np.array([row["timestamp"] for row in rows]), len(rows)) actual = np.array([row["observation.slam_pose"] for row in rows]) self.assertTrue(np.allclose(actual, expected, atol=1e-12))
def test_episodes_are_fitted_independently(self): """时间基映射必须每集单独拟合,否则跨集求差会把原点差异当运动。
两集的 slam 时钟相差一个很大的偏移量;若混在一起拟合,时间轴被拉 成两段,重建值会偏离该集单独重建的结果。 """ first = _rows(0, 30, t0=100.0, slam_offset=0.0) second = _rows(1, 30, t0=500.0, slam_offset=400.0) rows = first + second self.assertEqual(_ensure_slam_pose(rows), "observation.slam_pose")
for group, offset in ((first, 0.0), (second, 400.0)): expected = poses_from_trajectory( [row["observation.slam_trajectory"] for row in group], np.array([row["timestamp"] for row in group]), len(group), ) actual = np.array([row["observation.slam_pose"] for row in group]) self.assertTrue(np.allclose(actual, expected, atol=1e-12))
def test_existing_column_is_left_untouched(self): """旧批两列都有 —— 重导时不得覆盖采集端原始 slam_pose。""" rows = _rows(0, 10, t0=100.0) original = [9.0] * 7 for row in rows: row["observation.slam_pose"] = list(original) self.assertIsNone(_ensure_slam_pose(rows)) self.assertTrue(all(row["observation.slam_pose"] == original for row in rows))
def test_skips_batches_without_trajectory(self): """手套 / D435 批次没有 slam_trajectory —— 不得凭空写入该列。""" rows = [{"episode_index": 0, "timestamp": 0.0, "observation.tactile.left": [0.0] * 256}] self.assertIsNone(_ensure_slam_pose(rows)) self.assertNotIn("observation.slam_pose", rows[0])
def test_missing_timestamp_does_not_break_reconstruction(self): """时间戳缺帧(None)不能把 np.asarray 推断成 object 而抛异常。""" rows = _rows(0, 20, t0=200.0) rows[5]["timestamp"] = None self.assertEqual(_ensure_slam_pose(rows), "observation.slam_pose") self.assertTrue(all(np.all(np.isfinite(row["observation.slam_pose"])) for row in rows))
def test_derived_pose_feeds_observation_state(self): """串联顺序:补出的 slam_pose 要能继续供 state 派生使用。
新批里 ep72/ep73 两列都缺,只补 slam_pose 而不让 state 跟上,导出 产物仍然缺 observation.state,ACT 依旧 KeyError。 """ rows = _rows(0, 25, t0=300.0) _ensure_slam_pose(rows) self.assertEqual(_ensure_observation_state(rows), "observation.state") self.assertTrue(all(len(row["observation.state"]) == 4 for row in rows)) # 位置分量是本帧相对本集第一帧的偏移 —— 首帧必须为原点 self.assertTrue(np.allclose(rows[0]["observation.state"][:3], 0.0))
if __name__ == "__main__": unittest.main()1234567814 unmodified lines2324252627import unittestimport numpy as npfrom app.routes.video import _decode_tactile_matrixclass TactileDecodeTests(unittest.TestCase):14 unmodified linesnp.testing.assert_array_equal(decoded.transpose(1, 2, 0), matrix)if __name__ == "__main__":unittest.main()1234567891011121314151614 unmodified lines313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172import jsonimport tempfileimport unittestfrom pathlib import Pathimport numpy as npfrom app.routes.video import (_apply_tactile_scale,_compute_tactile_display_range,_decode_tactile_matrix,_tactile_scale_factor,)class TactileDecodeTests(unittest.TestCase):14 unmodified linesnp.testing.assert_array_equal(decoded.transpose(1, 2, 0), matrix)class TactileScaleTests(unittest.TestCase):"""量化整数 → mN 的比例因子必须取自元数据,不能硬编码。新采集端按 ``scale: 100`` 存储(units 仍是 mN);旧数据无该字段且本身就是 mN。硬编码 100 会把旧数据错误缩小 100 倍。"""def _dataset(self, root: Path, scale) -> Path:(root / "meta").mkdir(parents=True)(root / "data" / "chunk-000").mkdir(parents=True)feature = {"dtype": "int16", "shape": [250, 250, 3],"units": ["mN", "mN", "mN"]}if scale is not None:feature["scale"] = scale(root / "meta" / "info.json").write_text(json.dumps({"features": {"observation.gripper_left_force_matrix": feature},}), encoding="utf-8")return root / "data" / "chunk-000" / "episode_000000.parquet"def test_reads_declared_scale(self):with tempfile.TemporaryDirectory() as temp:path = self._dataset(Path(temp), 100)self.assertEqual(_tactile_scale_factor(path), 100.0)def test_defaults_to_one_when_declared_or_missing(self):with tempfile.TemporaryDirectory() as temp:path = self._dataset(Path(temp), None)self.assertEqual(_tactile_scale_factor(path), 1.0)with tempfile.TemporaryDirectory() as temp:path = self._dataset(Path(temp), 0)self.assertEqual(_tactile_scale_factor(path), 1.0)def test_missing_metadata_is_not_an_error(self):with tempfile.TemporaryDirectory() as temp:path = Path(temp) / "data" / "chunk-000" / "episode_000000.parquet"path.parent.mkdir(parents=True)self.assertEqual(_tactile_scale_factor(path), 1.0)def test_old_data_is_left_untouched(self):"""scale=1 时不得改变数值 —— 旧数据必须保持原样。"""matrix = np.full((3, 250, 250), 5.0, dtype=np.float32)scaled = _apply_tactile_scale(matrix, 1.0)np.testing.assert_array_equal(scaled, matrix)def test_new_data_is_divided(self):matrix = np.full((3, 250, 250), 250.0, dtype=np.float32)scaled = _apply_tactile_scale(matrix, 100.0)np.testing.assert_allclose(scaled, 2.5, atol=1e-6)def test_none_matrix_is_passed_through(self):self.assertIsNone(_apply_tactile_scale(None, 100.0))def _write_episode(path: Path, matrices) -> Path:"""Write an episode whose row-diff column decodes back to ``matrices``."""import pyarrow as paimport pyarrow.parquet as pqflattened = []for matrix in matrices:rows = np.asarray(matrix, dtype=np.int16).reshape(250, 750)diff = np.empty_like(rows)diff[:, 0] = rows[:, 0]diff[:, 1:] = rows[:, 1:] - rows[:, :-1]flattened.append(diff.reshape(-1))table = pa.table({"frame_index": pa.array(range(len(matrices)), type=pa.int64()),"observation.gripper_left_force_matrix":pa.array(flattened, type=pa.list_(pa.int16())),})path.parent.mkdir(parents=True, exist_ok=True)pq.write_table(table, str(path))return pathdef _episode_frames(quiet=9, contact=80):"""A quiet episode (noise only) with one frame carrying real contact."""rng = np.random.default_rng(20260911)matrices = []for _ in range(quiet):frame = np.zeros((250, 250, 3), dtype=np.int16)frame[:, :, 2] = rng.integers(0, 3, (250, 250))matrices.append(frame)loaded = np.zeros((250, 250, 3), dtype=np.int16)loaded[100:130, 100:130, 2] = contactmatrices.append(loaded)return matricesclass TactileDisplayRangeTests(unittest.TestCase):"""色阶必须取自整集,不能逐帧自比。没有接触的帧里唯一超过噪声门限的就是噪声本身;逐帧归一化会把这份噪声当成满量程,每个噪点都被拉成"接触点"。整集取色阶后安静帧保持背景色。"""def _episode(self, temp: str):path = _write_episode(Path(temp) / "data" / "chunk-000" / "episode_000000.parquet",_episode_frames())return pathdef test_range_is_driven_by_the_contact_not_the_noise(self):with tempfile.TemporaryDirectory() as temp:path = self._episode(temp)lo, hi = _compute_tactile_display_range(path, "observation.gripper_left_force_matrix")self.assertGreaterEqual(hi, 80.0)self.assertLess(lo, hi)def test_quiet_frame_stays_background(self):"""整集色阶下,无接触的帧几乎全黑;旧逐帧逻辑在该帧给出 174 级亮度。"""from app.routes.video import _tactile_range_payloadwith tempfile.TemporaryDirectory() as temp:path = self._episode(temp)payload = _tactile_range_payload(path, 0, 10, "left")self.assertIsNotNone(payload)pixels = 250 * 250blocks = np.frombuffer(payload[:10 * pixels], dtype=np.uint8)quiet = blocks[:9 * pixels].reshape(9, pixels)loud = blocks[9 * pixels:].reshape(pixels)self.assertLess(float((quiet >= 128).mean()), 0.01)self.assertGreater(int(loud.max()), 150)def test_flat_episode_is_drawable(self):with tempfile.TemporaryDirectory() as temp:blank = np.zeros((250, 250, 3), dtype=np.int16)path = _write_episode(Path(temp) / "data" / "chunk-000" / "episode_000000.parquet",[blank, blank])lo, hi = _compute_tactile_display_range(path, "observation.gripper_left_force_matrix")self.assertLess(lo, hi)if __name__ == "__main__":unittest.main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369import mathimport tempfileimport unittestfrom pathlib import Path
import numpy as npimport pyarrow as paimport pyarrow.parquet as pq
from app.processing import JobContext, ModuleSkipfrom app.processing.modules.umi_slam_action import UmiSlamActionModulefrom app.umi_slam_action import ( derive_action, matrix_to_rotvec, quat_to_matrix,)
def _yaw_quat(angle: float) -> list[float]: """绕 Z 轴 angle 弧度的四元数 (x, y, z, w)。""" return [0.0, 0.0, math.sin(angle / 2.0), math.cos(angle / 2.0)]
def _pose(x, y, z, quat=None) -> list[float]: return [float(x), float(y), float(z)] + (quat or [0.0, 0.0, 0.0, 1.0])
class RotationMathTests(unittest.TestCase): def test_identity_and_quarter_turn(self): # 单位四元数 → 单位阵 → 零旋转向量 self.assertTrue(np.allclose(matrix_to_rotvec(quat_to_matrix([0, 0, 0, 1])), np.zeros(3), atol=1e-9))
# 绕 X 轴 90° q = [math.sin(math.pi / 4), 0.0, 0.0, math.cos(math.pi / 4)] self.assertTrue(np.allclose(matrix_to_rotvec(quat_to_matrix(q)), [math.pi / 2, 0.0, 0.0], atol=1e-6))
def test_near_180_degrees_is_finite(self): """近 180° 时 sin(角)→0,标准轴公式会除零 —— 必须走退化分支。""" for angle in (math.pi, math.pi - 1e-7, math.pi - 1e-4): q = [0.0, 0.0, math.sin(angle / 2.0), math.cos(angle / 2.0)] rotvec = matrix_to_rotvec(quat_to_matrix(q)) self.assertTrue(np.all(np.isfinite(rotvec)), f"angle={angle} produced non-finite {rotvec}") self.assertAlmostEqual(float(np.linalg.norm(rotvec)), angle, places=5)
def test_zero_quaternion_returns_none(self): self.assertIsNone(quat_to_matrix([0.0, 0.0, 0.0, 0.0]))
def _traj(poses, dt=1/30, offset=1000.0): """把逐帧位姿包成 slam_trajectory 的格子。
每格是 ``[slam_t, x, y, z, qx, qy, qz, qw]`` 的整数倍;slam 时间戳与 数据时间戳差一个常数偏移(采集端时钟独立)。 """ return [[ (i * dt + offset) ] + list(pose) for i, pose in enumerate(poses)]
def _stamps(n, dt=1/30): return [i * dt for i in range(n)]
class DeriveActionTests(unittest.TestCase): def test_pure_translation_matches_analytic_delta(self): """沿 +X 每帧 10mm、姿态恒为身份 → Δp 应为 [0.01, 0, 0]。""" poses = [_pose(0.01 * i, 0, 0) for i in range(6)] out = derive_action(_traj(poses), _stamps(6), [[0.0, 0, 0]] * 6, 6) self.assertIsNotNone(out) for frame in range(5): self.assertTrue(np.allclose(out[frame]["action"][:3], [0.01, 0, 0], atol=1e-9)) self.assertTrue(np.allclose(out[frame]["action"][3:6], [0, 0, 0], atol=1e-9))
def test_local_frame_delta_follows_current_orientation(self): """世界系位移须换算到**当前**夹爪局部系,而不是原样透传。""" step = 0.02 quat = [0.0, 0.0, math.sin(-math.pi / 4), math.cos(-math.pi / 4)] poses = [_pose(0.0, -step * frame, 0.0, quat) for frame in range(5)] out = derive_action(_traj(poses), _stamps(5), None, 5) self.assertTrue(np.allclose(out[0]["action"][:3], [step, 0, 0], atol=1e-6))
def test_world_delta_is_not_passed_through_verbatim(self): step = 0.02 quat = [0.0, 0.0, math.sin(-math.pi / 4), math.cos(-math.pi / 4)] poses = [_pose(0.0, -step * frame, 0.0, quat) for frame in range(3)] out = derive_action(_traj(poses), _stamps(3), None, 3) self.assertFalse(np.allclose(out[0]["action"][:3], [0, -step, 0], atol=1e-6))
def test_pure_rotation_matches_analytic_delta(self): angle = 0.1 poses = [_pose(0, 0, 0, _yaw_quat(angle * i)) for i in range(5)] out = derive_action(_traj(poses), _stamps(5), None, 5) self.assertTrue(np.allclose(out[0]["action"][3:6], [0, 0, angle], atol=1e-6))
def test_gripper_dimension_tracks_open_fraction(self): poses = [_pose(0.01 * i, 0, 0) for i in range(4)] gripper = [[0.0, 0, 0], [50.0, 0, 0], [100.0, 0, 0], [100.0, 0, 0]] out = derive_action(_traj(poses), _stamps(4), gripper, 4) self.assertAlmostEqual(out[0]["action"][6], 0.5, places=6) self.assertAlmostEqual(out[1]["action"][6], 1.0, places=6)
def test_gripper_is_clipped_to_unit_range(self): poses = [_pose(0.01 * i, 0, 0) for i in range(3)] out = derive_action(_traj(poses), _stamps(3), [[500.0, 0, 0]] * 3, 3) self.assertLessEqual(out[0]["action"][6], 1.0) self.assertGreaterEqual(out[0]["action"][6], 0.0)
def test_last_frame_reuses_previous_delta(self): poses = [_pose(0.01 * i, 0, 0) for i in range(5)] out = derive_action(_traj(poses), _stamps(5), None, 5) self.assertIn(4, out) self.assertTrue(np.allclose(out[4]["action"][:3], out[3]["action"][:3], atol=1e-9))
def test_action_dimension_is_seven(self): poses = [_pose(0.01 * i, 0, 0) for i in range(5)] out = derive_action(_traj(poses), _stamps(5), None, 5) self.assertEqual(len(out[0]["action"]), 7)
def test_all_finite_on_mixed_input(self): poses = [_pose(0.01 * i, 0, 0) for i in range(6)] traj = _traj(poses) traj[3] = [] # 该格没有样本 out = derive_action(traj, _stamps(6), None, 6) values = np.array([out[i]["action"] for i in sorted(out)]) self.assertTrue(np.all(np.isfinite(values)))
def test_empty_and_degenerate_inputs(self): self.assertIsNone(derive_action([], [], None, 0)) self.assertIsNone(derive_action([[]] * 3, _stamps(3), None, 3)) self.assertIsNone(derive_action(_traj([_pose(0, 0, 0)]), _stamps(1), None, 1))
def test_sample_from_neighbour_cell_recovers_empty_frame(self): """空帧若能从相邻格子的样本里找到位姿,就不该被当作丢帧。
这是换用 slam_trajectory 的核心收益:采集端 50Hz、数据帧 30fps, 两帧之间到达的样本落在其中一格,所以「本帧格子为空」不代表那一刻 没有位姿。 """ # 真实形态:绝大多数帧的格子只装属于自己的那一个样本,个别格子会 # 多装一个「属于下一帧窗口」的样本。帧 5 自己的格子为空,但帧 4 的 # 格子里存着它 —— 这正是采集端 50Hz 快于数据 30fps 的结果。 dt = 1 / 30 n = 10 traj = [] for i in range(n): if i == 5: traj.append([]) # 本帧格子空 continue cell = [1000.0 + i * dt] + _pose(0.01 * i, 0, 0) if i == 4: # 帧 5 的样本溢到了上一个格子里(它比本帧时刻晚一点) cell += [1000.0 + 5 * dt] + _pose(0.05, 0, 0) traj.append(cell)
out = derive_action(traj, _stamps(n), None, n) self.assertIsNotNone(out) self.assertIn(5, out, "空帧应能从相邻格子的样本恢复") # 帧 5 用的应是那个真实样本(0.05),而不是帧 4/6 的插值中点 self.assertAlmostEqual(out[5]["observation.state"][0], 0.05, places=5)
def test_observation_state_is_relative_to_episode_start(self): poses = [_pose(1.0 + 0.01 * i, 2.0, 3.0) for i in range(5)] out = derive_action(_traj(poses), _stamps(5), [[50.0, 0, 0]] * 5, 5) # 位置分量是相对本集首帧的偏移 → 首帧为 0 self.assertTrue(np.allclose(out[0]["observation.state"][:3], [0.0, 0.0, 0.0], atol=1e-9)) self.assertAlmostEqual(out[3]["observation.state"][0], 0.03, places=6) self.assertAlmostEqual(out[3]["observation.state"][3], 0.5, places=6)
class UmiSlamActionModuleTests(unittest.TestCase): def _context(self, root: Path) -> JobContext: return JobContext( node_id="umi_slam_action", node_type="umi_slam_action", config={}, job={}, input_root=root, output_root=root / "outputs", incoming={}, progress=lambda _value: None, node_states={}, )
def _write_episode(self, root: Path, poses, gripper=None, extra_columns: dict | None = None) -> Path: """写入一份 canonical parquet。
位姿写成 ``observation.slam_trajectory`` 的格子格式(每格 8 的整数 倍)并配 ``timestamp`` 列 —— 模块只从这个缓冲重建位姿。 """ (root / "data" / "chunk-000").mkdir(parents=True, exist_ok=True) stamps = _stamps(len(poses)) columns = { "frame_index": list(range(len(poses))), "timestamp": stamps, "observation.slam_trajectory": _traj(poses), } if gripper is not None: columns["observation.gripper_state"] = gripper for name, values in (extra_columns or {}).items(): columns[name] = values path = root / "data" / "chunk-000" / "episode_000000.parquet" pq.write_table(pa.table(columns), path) return path
def test_derives_varying_action_and_reports_metadata(self): with tempfile.TemporaryDirectory() as temp: root = Path(temp) # 用非等距轨迹:等距平移的每帧增量恒等,会被导出端的恒定列 # 过滤剔除,验证不出"动作确实在变化"这一点。 poses = [_pose(0.01 * i + 0.004 * (i % 3), 0, 0) for i in range(20)] self._write_episode(root, poses, [[50.0, 0, 0]] * 20)
outputs = UmiSlamActionModule().run(self._context(root))
self.assertIn("action", outputs) ref = outputs["action"] self.assertEqual(ref.metadata["shape"], [7]) self.assertEqual(ref.metadata["frames_total"], 20) self.assertEqual(len(ref.metadata["names"]), 7)
import pandas as pd frame = pd.read_parquet(root / "outputs" / "umi_slam_action" / "umi_slam_action.parquet") values = np.array(frame["action"].tolist()) self.assertEqual(values.shape[1], 7) # 必须是真正变化的动作,否则导出的恒定列过滤会把它删掉 self.assertGreater(len(np.unique(values[:, 0])), 1)
def test_output_is_float32(self): """LeRobot 的 action 声明是 float32;写 double 会造成声明与 schema 不一致(官方加载器按声明 cast)。""" import pyarrow.parquet as pq with tempfile.TemporaryDirectory() as temp: root = Path(temp) poses = [_pose(0.01 * i, 0, 0) for i in range(10)] self._write_episode(root, poses, [[50.0, 0, 0]] * 10) UmiSlamActionModule().run(self._context(root))
path = root / "outputs" / "umi_slam_action" / "umi_slam_action.parquet" field_type = pq.read_schema(path).field("action").type self.assertIn("float", str(field_type)) self.assertNotIn("double", str(field_type))
def test_skips_batch_without_slam_pose(self): """非 UMI 批次(如 D435 手套)必须跳过,不能写坏数据。""" with tempfile.TemporaryDirectory() as temp: root = Path(temp) self._write_episode(root, [_pose(0, 0, 0)], None, extra_columns={"observation.glove": [[1.0, 2.0]]}) # 覆盖掉 slam 列,模拟没有 SLAM 的设备 (root / "data" / "chunk-000" / "episode_000000.parquet").unlink() pq.write_table(pa.table({ "frame_index": [0, 1], "observation.glove": [[1.0, 2.0], [3.0, 4.0]], }), root / "data" / "chunk-000" / "episode_000000.parquet")
with self.assertRaises(ModuleSkip): UmiSlamActionModule().run(self._context(root))
def test_retries_transient_read_failure(self): """上传/处理并发时 parquet 可能瞬时不可读,不能一次失败就放弃。
实测 ep52/ep71 都因此被误判成「列不可读」跳过,几秒后同一文件完全 正常。这里注入两次失败,验证第三次成功读到时模块照常产出。 """ from unittest.mock import patch
import pandas as pd
with tempfile.TemporaryDirectory() as temp: root = Path(temp) poses = [_pose(0.01 * i + 0.004 * (i % 3), 0, 0) for i in range(12)] self._write_episode(root, poses, [[50.0, 0, 0]] * 12)
original = pd.read_parquet state = {"calls": 0}
def flaky(*args, **kwargs): state["calls"] += 1 if state["calls"] <= 2: raise OSError("file is being written") return original(*args, **kwargs)
with patch.object(pd, "read_parquet", flaky), \ patch("time.sleep", lambda _s: None): outputs = UmiSlamActionModule().run(self._context(root))
self.assertGreaterEqual(state["calls"], 3, "应当重试到成功") self.assertIn("action", outputs)
def test_skip_message_carries_the_real_exception(self): """笼统提示无法区分竞态与设备类型不符,必须带上真实异常。""" from unittest.mock import patch
import pandas as pd
with tempfile.TemporaryDirectory() as temp: root = Path(temp) self._write_episode(root, [_pose(0.01 * i, 0, 0) for i in range(8)], [[50.0, 0, 0]] * 8)
def always_fail(*args, **kwargs): raise OSError("mount is stale")
with patch.object(pd, "read_parquet", always_fail), \ patch("time.sleep", lambda _s: None): with self.assertRaises(ModuleSkip) as caught: UmiSlamActionModule().run(self._context(root))
message = str(caught.exception) self.assertIn("OSError", message) self.assertIn("stale", message)
def test_skips_when_all_poses_are_zero(self): with tempfile.TemporaryDirectory() as temp: root = Path(temp) self._write_episode(root, [[0.0] * 7] * 10, [[0.0, 0, 0]] * 10) with self.assertRaises(ModuleSkip): UmiSlamActionModule().run(self._context(root))
def test_skips_when_no_parquet_present(self): with tempfile.TemporaryDirectory() as temp: root = Path(temp) (root / "data").mkdir(parents=True, exist_ok=True) with self.assertRaises(ModuleSkip): UmiSlamActionModule().run(self._context(root))
def test_ignores_non_parquet_upstream_ref(self): """上游 ``slam_trajectory`` 端口可能挂着一个非 parquet 产物。
worker 组装 incoming 时,若边的 sourceHandle 对不上上游任何输出, 会把该节点的**全部输出平铺**进来 —— 视频 ref 也会落到这个键上。 实测因此把 mp4 当 parquet 读,报 magic bytes not found。模块必须 验证产物类型,并回退到扫描批次里的真 parquet。 """ from app.processing import ArtifactRef
with tempfile.TemporaryDirectory() as temp: root = Path(temp) poses = [_pose(0.01 * i + 0.004 * (i % 3), 0, 0) for i in range(12)] self._write_episode(root, poses, [[50.0, 0, 0]] * 12)
# 上游把视频文件挂到了 slam_trajectory 这个端口上 video = root / "videos" / "observation.images.gripper_rgb" / "chunk-000" video.mkdir(parents=True, exist_ok=True) clip = video / "episode_000000.mp4" clip.write_bytes(b"\x00\x00\x00\x1cftypisom" + b"\x00" * 64)
ctx = self._context(root) ctx.incoming = {"slam_trajectory": ArtifactRef( kind="rgb_video", path=str(clip.relative_to(root)), source_key="gripper_rgb")}
outputs = UmiSlamActionModule().run(ctx)
self.assertIn("action", outputs, "应回退到真正的 parquet")
if __name__ == "__main__": unittest.main()123451213 unmodified lines1219122012211222122312241225555 unmodified lines178117821783178417851786178727 unmodified lines1815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189126 unmodified lines1918191919201921192219231924132 unmodified lines20572058205920602061206220632064560 unmodified lines262526262627262826292630693 unmodified lines332433253326332733283329885 unmodified lines4215421642174218421942204221422242234224133 unmodified lines435843594360436143624363436443654366436755 unmodified lines442344244425442644274428442944304431443216 unmodified lines4449445044514452445344544455445644574458445944604461446244634464446544667 unmodified lines447444754476447744784479448044814482448344844485448644874488448944904491449244934494/* Plyr video player management */console.log('[player.js] build 202609091912-tactile-chunk-prefetch');const players = {}; // {camera_name: Plyr instance}let currentEpisodeId = null;1213 unmodified linesif (typeof startHeatmapSync === 'function') startHeatmapSync(active);if (masterPlaying) {Object.values(players).forEach(player => {try { player.play(); } catch (e) {}});}}555 unmodified linescanvas.width = width;canvas.height = height;}gl.viewport(0, 0, width, height);gl.clearColor(0.0039, 0.0039, 0.502, 1.0);gl.clear(gl.COLOR_BUFFER_BIT);if (!this.field) return;27 unmodified lines};}// Wheel zoom / drag pan / double-click reset for one tactile matrix tile.// One texture texel is one sensor cell, so zooming in reveals the individual// contact cells that the whole-field view averages away (same interaction as// the acquisition-side demo viewer).function _tactileScreenUv(canvas, clientX, clientY) {const rect = canvas.getBoundingClientRect();return [(clientX - rect.left) / Math.max(1, rect.width),1 - (clientY - rect.top) / Math.max(1, rect.height),];}function _clampTactileView(renderer) {const limit = Math.max(0, (1 - 1 / renderer.zoom) / 2);renderer.pan[0] = Math.max(-limit, Math.min(limit, renderer.pan[0]));renderer.pan[1] = Math.max(-limit, Math.min(limit, renderer.pan[1]));}function initTactileView(entry) {const canvas = entry?.canvas;const renderer = entry?.renderer;if (!canvas || !renderer) return;const maxZoom = 12;canvas.addEventListener('wheel', event => {event.preventDefault();const [u, v] = _tactileScreenUv(canvas, event.clientX, event.clientY);const before = 1 / renderer.zoom;renderer.zoom = Math.max(1, Math.min(maxZoom,renderer.zoom * (event.deltaY < 0 ? 1.2 : 1 / 1.2)));const delta = before - 1 / renderer.zoom;renderer.pan[0] += (u - 0.5) * delta;renderer.pan[1] += (v - 0.5) * delta;_clampTactileView(renderer);canvas.style.cursor = renderer.zoom > 1 ? 'grab' : 'default';renderer.render();}, { passive: false });canvas.addEventListener('pointerdown', event => {if (event.button !== 0 || renderer.zoom <= 1) return;entry._panDrag = { x: event.clientX, y: event.clientY };canvas.style.cursor = 'grabbing';if (canvas.setPointerCapture) canvas.setPointerCapture(event.pointerId);event.preventDefault();});canvas.addEventListener('pointermove', event => {if (!entry._panDrag) return;const rect = canvas.getBoundingClientRect();renderer.pan[0] -= (event.clientX - entry._panDrag.x)/ Math.max(1, rect.width) / renderer.zoom;renderer.pan[1] += (event.clientY - entry._panDrag.y)/ Math.max(1, rect.height) / renderer.zoom;entry._panDrag = { x: event.clientX, y: event.clientY };_clampTactileView(renderer);renderer.render();});const endPan = event => {if (!entry._panDrag) return;entry._panDrag = null;canvas.style.cursor = renderer.zoom > 1 ? 'grab' : 'default';if (event && canvas.hasPointerCapture&& canvas.hasPointerCapture(event.pointerId)) {canvas.releasePointerCapture(event.pointerId);}};canvas.addEventListener('pointerup', endPan);canvas.addEventListener('pointercancel', endPan);canvas.addEventListener('dblclick', () => {renderer.zoom = 1;renderer.pan = [0, 0];canvas.style.cursor = 'default';renderer.render();});}// One chunk = 96 frames of 250x250 R8 = 6 MB per request. The old code issued26 unmodified linesconst signal = getMediaLoadSignal();const url = `/api/v1/video/${currentEpisodeId}/tactile-matrix-range`+ `?side=${entry.source.side}&start=${chunkStart}`+ `&limit=${TACTILE_CHUNK_FRAMES}&v=202609091912-tactile-chunk-prefetch`;const options = { credentials: 'same-origin', cache: 'force-cache' };if (signal) options.signal = signal;fetch(url, options).then(response => {132 unmodified linescurveCanvas, loadedFrame: -1, pendingFrame: null,chunks: new Map(), chunkInflight: new Set(),frameCount: Number(tactileMatrixData?.frame_count) || 0 };initTactileView(entry);canvas.title = '滚轮缩放 / 拖拽平移 / 双击复位';currentTactileTiles.push(entry);const frame = typeof currentFrameTarget === 'number' ? currentFrameTarget : 0;_updateTactileForceTile(entry, frame);560 unmodified lines_restorePlayersToCurrentFrame();const active = getActivePlayer();if (!active) { hideVideoLoading(); return; }_syncWorkspacePlayers();refreshPlayButton(false);try {693 unmodified linesfunction pauseAll() {Object.values(players).forEach(p => {try { p.pause(); } catch(e) {}});885 unmodified lines// world frame: +Z is up (measured on real data - a physical turn of the// gripper rotates about world +Z, and the gripper's own up axis sits within// ~12 deg of it for the whole episode). The browser camera uses a right-handed// frame with Y up, so display=[source X, source Z, -source Y] keeps the// stored values untouched and puts world up on screen up.function _slamDisplayPoint(sourcePoint) {return [Number(sourcePoint[0]), Number(sourcePoint[2]), -Number(sourcePoint[1])];}function _slamSourcePoint(row) {133 unmodified lines// Small axis marker at the fitted area: the recorded world axes, drawn in// the display frame that _slamDisplayPoint produces (world +Z is up).const axisOrigin = [fit.center[0], fit.gridY, fit.center[2]];const axisTips = [// World axes: X and Y horizontal, Z up.[[axisOrigin[0] + 0.2, axisOrigin[1], axisOrigin[2]], 'rgb(248,90,90)', 'X'],[[axisOrigin[0], axisOrigin[1], axisOrigin[2] - 0.2], 'rgb(80,220,130)', 'Y'],[[axisOrigin[0], axisOrigin[1] + 0.2, axisOrigin[2]], 'rgb(90,150,255)', 'Z'],];55 unmodified lines});// Simplified UMI gripper model. The recorded pose frame is the S80M// camera frame; measured on real data the device axes sit at// +X = camera right (~world +Y), +Y = gripper up (~world +Z, the// camera is mounted inverted) and +Z = gripper forward (~world +X,// the optical axis). So the body extends along local +Z, the two// plates separate along local X, and each plate is 0.20m long// (forward) by 0.05m tall (up) with a 0.12m maximum opening.const grip = _slamGripperState(currentRow);16 unmodified linesconst jawFill = grip.gripped? 'rgba(248,90,90,0.16)' : 'rgba(88,168,232,0.12)';const relativeCorners = [[0, -plateHeight / 2, -plateLength / 2],[0, -plateHeight / 2, plateLength / 2],[0, plateHeight / 2, plateLength / 2],[0, plateHeight / 2, -plateLength / 2],];for (const sign of [1, -1]) {const centerX = sign * halfGap;const corners = relativeCorners.map(corner => project(toDisplay([centerX + corner[0],corner[1],baseOffset + corner[2],])));if (corners.every(item => Number.isFinite(item[0]) && Number.isFinite(item[1]))) {ctx.fillStyle = jawFill;7 unmodified linesctx.stroke();}line(toDisplay([centerX, 0, baseOffset - plateLength / 2]),toDisplay([centerX, 0, baseOffset + plateLength / 2]),jawColor, 1);}// Rear crossbar plus the two supports that tie each plate back to// the body, so the opening stays readable when it is small.line(toDisplay([-maxHalfGap, 0, baseOffset]),toDisplay([maxHalfGap, 0, baseOffset]),'rgba(148,163,184,0.8)', 1.5);for (const sign of [1, -1]) {for (const cornerZ of [-plateLength / 2, plateLength / 2]) {line(toDisplay([sign * halfGap, 0, baseOffset + cornerZ]),toDisplay([0, 0, baseOffset + cornerZ]),'rgba(148,163,184,0.8)', 1);}}123451213 unmodified lines121912201221122212231224122512261227122812291230123112321233555 unmodified lines178917901791179217931794179517961797179817991800180127 unmodified lines182918301831183218331834183518361837183818391840184118421843184418451846184726 unmodified lines1874187518761877187818791880132 unmodified lines20132014201520162017201820192020560 unmodified lines258125822583258425852586258725882589259025912592693 unmodified lines3286328732883289329032913292329332943295885 unmodified lines4181418241834184418541864187418841894190419141924193133 unmodified lines43274328432943304331433243334334433543364337433855 unmodified lines439443954396439743984399440044014402440344044405440616 unmodified lines4423442444254426442744284429443044314432443344344435443644374438443944407 unmodified lines444844494450445144524453445444554456445744584459446044614462446344644465446644674468/* Plyr video player management */console.log('[player.js] build 20260911-tactile-episode-color-scale');const players = {}; // {camera_name: Plyr instance}let currentEpisodeId = null;1213 unmodified linesif (typeof startHeatmapSync === 'function') startHeatmapSync(active);if (masterPlaying) {Object.values(players).forEach(player => {// play() returns a promise: a try/catch cannot see its rejection,// and the load chain right after this call runs pauseAll(), which// aborts the pending play → uncaught AbortError in the console.try {const result = player.play();if (result && typeof result.catch === 'function') {result.catch(() => {});}} catch (e) {}});}}555 unmodified linescanvas.width = width;canvas.height = height;}// 传感器是 250x250 的方格阵列,必须等比显示 —— 铺满 canvas 会按// tile 的宽高比横向拉伸(实测宽窗约 2.9:1),格子就不再是正方形,// 接触位置的形状判断会失真。取短边做居中正方形 viewport,多出来的// 两侧留背景色(gl.clear 不受 viewport 限制,会整块清成底色)。const side = Math.min(width, height);gl.viewport(Math.round((width - side) / 2),Math.round((height - side) / 2), side, side);gl.clearColor(0.0039, 0.0039, 0.502, 1.0);gl.clear(gl.COLOR_BUFFER_BIT);if (!this.field) return;27 unmodified lines};}// The tactile force matrix tile is display-only. Zoom/pan were removed on// purpose: the review page is read-only evidence, and a stray wheel or drag// could leave the matrix zoomed into a few cells and look like a sensor// defect. The whole 250x250 field stays fixed, one texture texel per cell.// The renderer keeps supporting zoom/pan (uniforms u_zoom/u_pan) so the// acquisition-side demo viewer and any future opt-in can reuse it; here the// view is pinned to identity.function _resetTactileView(renderer) {if (!renderer) return;renderer.zoom = 1;renderer.pan = [0, 0];if (renderer.canvas) renderer.canvas.style.cursor = 'default';renderer.render();}// One chunk = 96 frames of 250x250 R8 = 6 MB per request. The old code issued26 unmodified linesconst signal = getMediaLoadSignal();const url = `/api/v1/video/${currentEpisodeId}/tactile-matrix-range`+ `?side=${entry.source.side}&start=${chunkStart}`+ `&limit=${TACTILE_CHUNK_FRAMES}&v=20260911-tactile-episode-color-scale`;const options = { credentials: 'same-origin', cache: 'force-cache' };if (signal) options.signal = signal;fetch(url, options).then(response => {132 unmodified linescurveCanvas, loadedFrame: -1, pendingFrame: null,chunks: new Map(), chunkInflight: new Set(),frameCount: Number(tactileMatrixData?.frame_count) || 0 };_resetTactileView(renderer);canvas.title = '接触力场(固定全幅,不可缩放)';currentTactileTiles.push(entry);const frame = typeof currentFrameTarget === 'number' ? currentFrameTarget : 0;_updateTactileForceTile(entry, frame);560 unmodified lines_restorePlayersToCurrentFrame();const active = getActivePlayer();if (!active) { hideVideoLoading(); return; }// A freshly mounted episode always starts paused. Clear the state and// sync before wiring the players: _syncWorkspacePlayers() re-issues// play() for a workspace still marked as playing, and the pauseAll()// further down then aborts it — a play/pause race that fires an// uncaught AbortError and leaves the transport button flapping.masterPlaying = false;_syncWorkspacePlayers();refreshPlayButton(false);try {693 unmodified linesfunction pauseAll() {// Keep the transport state consistent with reality: callers that pause// without flipping the flag left the button reading "Pause" while every// player was stopped, so the next click replayed instead of resuming.masterPlaying = false;Object.values(players).forEach(p => {try { p.pause(); } catch(e) {}});885 unmodified lines// world frame: +Z is up (measured on real data - a physical turn of the// gripper rotates about world +Z, and the gripper's own up axis sits within// ~12 deg of it for the whole episode). The browser camera uses a right-handed// frame with Y up, so the display mapping puts world up on screen up.//// 源 +X 指向设备的**左侧**(S80M R_corr 之后源系是"左、后、上"),// 直接透传会让整个空间视图相对真实动作左右镜像:设备往左绕圈,// 画面里往右走。取反 X 修正左右;Y/Z 不动,前后与上下仍与实测一致。function _slamDisplayPoint(sourcePoint) {return [-Number(sourcePoint[0]), Number(sourcePoint[2]), -Number(sourcePoint[1])];}function _slamSourcePoint(row) {133 unmodified lines// Small axis marker at the fitted area: the recorded world axes, drawn in// the display frame that _slamDisplayPoint produces (world +Z is up).// The X tip follows the same negation as _slamDisplayPoint: display +X is// source -X, so the recorded +X axis points toward display -X.const axisOrigin = [fit.center[0], fit.gridY, fit.center[2]];const axisTips = [// World axes: X and Y horizontal, Z up.[[axisOrigin[0] - 0.2, axisOrigin[1], axisOrigin[2]], 'rgb(248,90,90)', 'X'],[[axisOrigin[0], axisOrigin[1], axisOrigin[2] - 0.2], 'rgb(80,220,130)', 'Y'],[[axisOrigin[0], axisOrigin[1] + 0.2, axisOrigin[2]], 'rgb(90,150,255)', 'Z'],];55 unmodified lines});// Simplified UMI gripper model. The recorded pose frame is the S80M// camera frame; measured on the uploaded UMIGripper_AI episodes (every// frame of every batch) the device axes sit at// +X = gripper right (jaw separation, horizontal),// +Y = gripper forward (the optical axis, horizontal) and// +Z = gripper up (vertical, within ~12 deg of world +Z — the world// frame is gravity-aligned, so this is a fixed sensor-frame fact, not// a per-episode pose). So the body extends along local +Y, the two// plates separate along local X, and each plate is 0.20m long// (forward) by 0.05m tall (up) with a 0.12m maximum opening.const grip = _slamGripperState(currentRow);16 unmodified linesconst jawFill = grip.gripped? 'rgba(248,90,90,0.16)' : 'rgba(88,168,232,0.12)';const relativeCorners = [[0, -plateLength / 2, -plateHeight / 2],[0, plateLength / 2, -plateHeight / 2],[0, plateLength / 2, plateHeight / 2],[0, -plateLength / 2, plateHeight / 2],];for (const sign of [1, -1]) {const centerX = sign * halfGap;const corners = relativeCorners.map(corner => project(toDisplay([centerX + corner[0],baseOffset + corner[1],corner[2],])));if (corners.every(item => Number.isFinite(item[0]) && Number.isFinite(item[1]))) {ctx.fillStyle = jawFill;7 unmodified linesctx.stroke();}line(toDisplay([centerX, baseOffset - plateLength / 2, 0]),toDisplay([centerX, baseOffset + plateLength / 2, 0]),jawColor, 1);}// Rear crossbar plus the two supports that tie each plate back to// the body, so the opening stays readable when it is small.line(toDisplay([-maxHalfGap, baseOffset, 0]),toDisplay([maxHalfGap, baseOffset, 0]),'rgba(148,163,184,0.8)', 1.5);for (const sign of [1, -1]) {for (const cornerY of [-plateLength / 2, plateLength / 2]) {line(toDisplay([sign * halfGap, baseOffset + cornerY, 0]),toDisplay([0, baseOffset + cornerY, 0]),'rgba(148,163,184,0.8)', 1);}}
563 unmodified lines564565566567568569570563 unmodified lines<script src="/static/js/media-cache.js?v=202609081530"></script><script src="/static/js/depth-renderer.js?v=202609081530"></script><script src="/static/js/player.js?v=202609091912-tactile-chunk-prefetch"></script><script src="/static/js/hand-overlay.js?v=202609081630"></script><script src="/static/js/heatmap.js?v=202609081530"></script><script src="/static/js/annotations.js?v=202609081530"></script>563 unmodified lines564565566567568569570563 unmodified lines<script src="/static/js/media-cache.js?v=202609081530"></script><script src="/static/js/depth-renderer.js?v=202609081530"></script><script src="/static/js/player.js?v=20260911-tactile-square-1to1"></script><script src="/static/js/hand-overlay.js?v=202609081630"></script><script src="/static/js/heatmap.js?v=202609081530"></script><script src="/static/js/annotations.js?v=202609081530"></script>
processor/README.md+49-47
processor/app/api/worker.py+84-26
processor/app/batch_fingerprint.pyAdded+194
processor/app/device_progress.pyAdded+218
processor/app/lerobot_export.py+341-25
processor/app/localstore.py+269-35
processor/app/processing/modules/lerobot_export.py+20-2
processor/app/processing/modules/umi_slam_action.pyAdded+192
processor/app/project_dataset.py+203-18
processor/app/routes/devices.py+55-8
processor/app/routes/export.py+9-2
processor/app/routes/session.py+38
processor/app/routes/video.py+196-34
processor/app/umi_slam_action.pyAdded+269
processor/tests/test_batch_fingerprint.pyAdded+181
processor/tests/test_device_task_progress.pyAdded+181
processor/tests/test_lerobot_export.pyAdded+105
processor/tests/test_tactile_decode.py+146-1
processor/tests/test_umi_slam_action.pyAdded+369
processor/web/static/js/player.js+72-98
processor/web/templates/index.html+1-1