{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# 피지컬 AI 입문 · 로봇 없이 3시간 실습 노트북\n\n데이터팝콘 웹교안: https://physical-ai.datapopcorn.ai\n\n**먼저** 메뉴 `런타임 → 런타임 유형 변경`에서 **T4 GPU**를 고르고 저장하세요. 2026-10-28 Colab 무료 런타임(Python 3.13, PyTorch 2.11, T4) + LeRobot 0.6.1로 확인했습니다."
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 02. LeRobot 설치\n`lerobot 0.6.1`, `mujoco 3.3.7`이 찍히면 성공입니다."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "!pip install -q \"lerobot[dataset,metaworld,smolvla]==0.6.1\" \"mujoco==3.3.7\" \"imageio[ffmpeg]\"\n!pip show lerobot mujoco | grep -E \"^(Name|Version)\""
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 03. 실제 로봇 데이터 열어 보기\n사람이 SO-100 로봇팔로 \"큐브를 집어 상자에 넣기\"를 50번 시연한 녹화본입니다."
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "from lerobot.datasets.lerobot_dataset import LeRobotDataset\n\nds = LeRobotDataset(\"lerobot/svla_so100_pickplace\")\nprint(\"에피소드:\", ds.num_episodes, \"프레임:\", ds.num_frames, \"fps:\", ds.fps)\nfor k, v in ds.features.items():\n    print(k, v[\"dtype\"], v[\"shape\"])\n\nsample = ds[0]\nprint(\"지시문:\", sample[\"task\"])\nprint(\"첫 동작:\", [round(x, 1) for x in sample[\"action\"].tolist()])"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 04. 가상 SO-101 로봇팔 띄우기"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import os\nos.environ[\"MUJOCO_GL\"] = \"egl\"   # 화면 없는 서버(Colab)에서 그림을 그리기 위한 설정\nimport numpy as np, imageio\nfrom lerobot.envs.factory import make_env\n\nenvs = make_env(\"lerobot/so101-tabletop-mujoco\", n_envs=1, trust_remote_code=True)\nenv = envs[\"so101_tabletop\"][0]\nobs, info = env.reset(seed=0)\n\nfront = obs[\"pixels\"][\"front\"][0]\nwrist = obs[\"pixels\"][\"wrist\"][0]\nimageio.imwrite(\"so101.png\", np.concatenate([front, wrist], axis=1))\nprint(\"관절 각도:\", obs[\"agent_pos\"][0].round(1))\n\nfrom IPython.display import Image\nImage(\"so101.png\")"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 05. 사람 동작을 그대로 틀어 보기\n**실행 전에 예상해 보세요.** 큐브가 상자에 들어갈까요? (약 5분 걸립니다)"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "ep = LeRobotDataset(\"lerobot/svla_so100_pickplace\", episodes=[0])\nactions = np.stack([ep[i][\"action\"].numpy() for i in range(len(ep))])\n\nobs, info = env.reset(seed=0)\nframes = [np.concatenate([obs[\"pixels\"][\"front\"][0], obs[\"pixels\"][\"wrist\"][0]], axis=1)]\nfor a in actions[::3]:   # 3프레임마다 하나씩 재생\n    obs, reward, terminated, truncated, info = env.step(a[None].astype(np.float32))\n    frames.append(np.concatenate([obs[\"pixels\"][\"front\"][0], obs[\"pixels\"][\"wrist\"][0]], axis=1))\n\nimageio.mimsave(\"replay.mp4\", frames, fps=10)\nprint(\"상자 안 큐브 수:\", info[\"cubes_in_box\"])\n\nfrom IPython.display import Video\nVideo(\"replay.mp4\", embed=True)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 06. VLA가 보고 움직이게 하기\n### 서랍 열기 (약 3분)"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "!MUJOCO_GL=egl lerobot-eval \\\n  --policy.path=lerobot/smolvla_metaworld \\\n  --env.type=metaworld \\\n  --env.task=drawer-open-v3 \\\n  --eval.batch_size=1 \\\n  --eval.n_episodes=3 \\\n  --eval.use_async_envs=false \\\n  --policy.device=cuda \\\n  --rename_map='{\"observation.image\": \"observation.images.camera1\"}' \\\n  --output_dir=outputs/eval_drawer"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### 결과 영상 보기"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "import glob\nfrom IPython.display import Video\nmp4 = sorted(glob.glob(\"outputs/eval_drawer/videos/**/*.mp4\", recursive=True))\nprint(mp4)\nVideo(mp4[0], embed=True)"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### 지시만 바꿔서 버튼 누르기"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": "!MUJOCO_GL=egl lerobot-eval \\\n  --policy.path=lerobot/smolvla_metaworld \\\n  --env.type=metaworld \\\n  --env.task=button-press-v3 \\\n  --eval.batch_size=1 \\\n  --eval.n_episodes=3 \\\n  --eval.use_async_envs=false \\\n  --policy.device=cuda \\\n  --rename_map='{\"observation.image\": \"observation.images.camera1\"}' \\\n  --output_dir=outputs/eval_button"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## 정리\n- 녹화한 동작을 그대로 틀면 장면이 조금만 달라져도 실패합니다.\n- VLA는 매번 화면과 지시를 보고 다음 동작을 계획합니다.\n- 발표를 볼 때: 데이터 양 / 시뮬레이션인지 실물인지 / 조건이 바뀌어도 되는지"
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "provenance": [],
   "gpuType": "T4"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}