# -*- coding: utf-8 -*-
# 動画「命令どおりに外れる」（SO-101 のお手本50本の4割が外れた・LOG599＋LOG601）の場面。2026-11-29 1版。「次の1秒を3Dに」の scenes.py の部品を写した
PATTERN = 2   # 大文字型・動きあり（12/2〜12/9 の SO-101 の4本と同じ型・LOG603）
MOVE = True
# 背景はお手本（var_v1・redo347）の机のカメラと手首のカメラの録画・LOG599 の画像（bg_*.mp4・mk_bg.sh で作る）
# Physical Intelligence の映像は引用（6-1 の B）：紙の上の窓。前の4本と別の映像（ナイトスタンドに片付ける）
import os as _os, sys as _sys, json as _json, base64 as _b64
_here = _os.path.dirname(_os.path.abspath(__file__))
for _c in (_os.environ.get("P2M_BASE", ""), _os.path.join(_here, "..", "base"), _os.path.join(_here, "..", "_制作ベース")):
    if _c and _os.path.exists(_os.path.join(_c, "scene_kit.py")):
        _sys.path.insert(0, _c); break
from scene_kit import *
from scene_kit import _p2page
from motion_kit import use_motion

# --- 場面ごとの、文の始まりの秒（声の長さから）---
_idx = _json.load(open(_os.path.join(_here, 'tts/index.json'))) if _os.path.exists(_os.path.join(_here, 'tts/index.json')) else []
_LINES = {}
for _o in _idx:
    _d = _LINES.setdefault(_o['scene'], [])
    _t0 = (_d[-1][0] + _d[-1][1] + _d[-1][2]) if _d else 0.0
    _d.append((_t0, _o['dur'], _o['pause']))


def at(scene, k=0, f=0.0):
    """その場面の k 番目の文の、読み上げの f 割の所（秒）"""
    L = _LINES.get(scene)
    if not L:
        return 0.3
    k = min(k, len(L) - 1)
    return round(L[k][0] + L[k][1] * f, 2)


def scene_len(scene):
    L = _LINES.get(scene)
    return (L[-1][0] + L[-1][1] + L[-1][2]) if L else 4.0


# --- 出どころの札（左上）---
FUDA_CSS = """
.fuda{position:absolute;left:140px;top:96px;display:flex;align-items:center;gap:14px;font-size:30px;font-weight:700;color:#0D0D0D}
.fuda .k{padding:6px 18px;border-radius:999px;font-size:28px;font-weight:900}
.fuda .k.hap{background:#0D0D0D;color:#fff}
.fuda .k.news{background:#406ED8;color:#fff}
.fuda .k.ken{border:3px solid #888888;color:#555}
.fuda .k.ei{background:#C8322B;color:#fff}
.fuda .k.clip{background:#0D0D0D;color:#fff}
.fuda .k.chosa{background:#5A5A5A;color:#fff}
"""
FUDA_NAME = {"hap": "会社の発表", "news": "ニュース", "ken": "論文や本", "ei": "エイイチの記録と見立て", "clip": "公開されている実物の動画", "chosa": "調査会社の推計"}


def fuda(kind, who):
    return f'<style>{FUDA_CSS}</style><div class="fuda"><span class="k {kind}">{FUDA_NAME[kind]}</span><span>{who}</span></div>'


# --- エイイチ（ドット絵）---
def _uri(p):
    return 'data:image/png;base64,' + _b64.b64encode(open(_os.path.join(_here, p), 'rb').read()).decode()


import ei_talk as _talk
EI = {k: (_talk.base_uri(k), _talk.base_uri(k, True)) for k in ('udegumi', 'unazuku', 'yubisasu', 'hirameku')}
# エイイチが話す文（narration.py の EI_LINES）→ (場面, 場面の中で何番目の文か, 文番号)
import importlib.util as _ilu
_sp = _ilu.spec_from_file_location('_narr_here', _os.path.join(_here, 'narration.py'))
_nm = _ilu.module_from_spec(_sp); _sp.loader.exec_module(_nm)
_EIL = getattr(_nm, 'EI_LINES', [])
_EI_SPEAK = {}
_cnt = {}
for _o in _idx:
    _k = _cnt.get(_o['scene'], 0); _cnt[_o['scene']] = _k + 1
    if _o['i'] in _EIL:
        _EI_SPEAK.setdefault(_o['scene'], []).append((_k, _o['i']))

EI_CSS = """
.eiw{position:absolute;right:10px;bottom:0px;width:420px;height:420px;overflow:hidden}
.eiw img{position:absolute;left:0;top:8px;width:420px;height:420px;image-rendering:pixelated}
.ein{position:absolute;right:40px;bottom:346px;width:300px;text-align:center;font-size:30px;font-weight:900;color:#0D0D0D}
.ein span{display:inline-block;background:#F5F5F0;border:3px solid #D6D6D1;border-radius:999px;padding:4px 20px}
"""


def _blinks(start, end):
    t, out = start, []
    while t < end - 0.4:
        out.append(round(t, 2)); t += 3.3
    return out


def ei_wipe(pose, scene, pop=None, name=None, poses=None):
    """右下の小窓。pop=秒 で、ぽんと出る。poses=[(秒, 絵)] で途中で絵を替える（指さしは大事な所だけ。2026-10-28 エイイチの指示）。
    話している間は口と目を声に合わせて動かし、話していない間はまばたきだけする。
    絵ごとにまとまり（div）を作り、替える時刻に前のまとまりを消して（out）、次を出す（fade）。絵の透明な所から前の絵が見えないように"""
    seq_p = sorted(poses or [(0, pose)])
    if seq_p[0][0] > 0:
        seq_p = [(0, pose)] + seq_p
    L = scene_len(scene) + 1
    segs = [(t, seq_p[k + 1][0] if k + 1 < len(seq_p) else L, p) for k, (t, p) in enumerate(seq_p)]
    spans, mouth, blinks = [], [], []
    for k, i in _EI_SPEAK.get(scene, []):
        t0 = at(scene, k, 0.0)
        sq, end = _talk.mouth_seq(i, t0)
        spans.append((t0, end)); mouth += sq
        blinks += [(b, 0.13) for b in _talk.blink_times(t0, end)]
    mouth.sort()
    blinks += [(b, 0.15) for b in _blinks((pop or 0) + 1.3, scene_len(scene)) if not any(a0 - 0.2 <= b <= a1 + 0.2 for a0, a1 in spans)]
    out = ''
    for s0, s1, p in segs:
        ev = []
        lv = ([l for (t, l) in mouth if t <= s0] or [1])[-1]
        if lv != 1 and p in _talk.MOUTH:
            ev.append((s0, f'<img src="{_talk.mouth_patches(p)[lv]}">'))
        for t, l in mouth:
            if s0 < t < s1 and p in _talk.MOUTH:
                ev.append((t, f'<img src="{_talk.mouth_patches(p)[l]}" data-a="fade" data-t="{t}" data-d="0.01">'))
        e = _talk.eye_patches(p) if p != 'unazuku' else None
        for b, d in blinks:
            if e and s0 <= b and b + d < s1:
                ev.append((b, f'<img src="{e[1]}" data-a="fade" data-t="{b}" data-d="0.01">'))
                ev.append((round(b + d, 2), f'<img src="{e[0]}" data-a="fade" data-t="{round(b + d, 2)}" data-d="0.01">'))
        ev.sort(key=lambda x: x[0])
        inner = f'<img src="{EI[p][0]}">' + ''.join(h for _, h in ev)
        if s0 > 0:
            inner = f'<div style="position:absolute;inset:0" data-a="fade" data-t="{s0}" data-d="0.01">{inner}</div>'
        if s1 < L:
            inner = f'<div style="position:absolute;inset:0" data-a="out" data-t="{s1}" data-d="0.01">{inner}</div>'
        out += inner
    a = f' data-a="pop" data-t="{pop}" data-d="0.35"' if pop is not None else ''
    nm = f'<div class="ein"{a}><span>{name}</span></div>' if name else ''
    return f'<style>{EI_CSS}</style>{nm}<div class="eiw"{a}>{out}</div>'


def add(page_html, *parts):
    return page_html.replace('</body>', ''.join(parts) + '</body>', 1)


S = {}
MOTION = {}
O = {}
VIDEO = {}




# --- 背景の映像の上にカード（4-4e）---
HL, WARN = "#FFE14D", "#FFE14D"
CARD_CSS = f"""
.cw{{position:absolute;left:0;right:0;top:215px;bottom:300px;display:flex;align-items:center;justify-content:center}}
.cd{{background:rgba(8,8,8,.86);border-radius:30px;padding:46px 84px 52px;text-align:center;color:#fff;max-width:1400px;box-shadow:0 10px 40px rgba(0,0,0,.35)}}
.cd .k{{font-size:42px;font-weight:700;color:#BDBDBD;margin-bottom:22px}}
.cd .b{{font-weight:900;line-height:1.16}}
.cd .s{{font-size:44px;font-weight:700;color:#D0D0D0;margin-top:26px;line-height:1.35}}
.cd .hl{{color:{HL}}} .cd .wn{{color:{WARN}}}
.cap{{position:absolute;left:140px;right:auto;top:110px;background:rgba(8,8,8,.72);color:#fff;font-size:30px;font-weight:700;padding:10px 22px;border-radius:10px}}
.ff{{position:absolute;right:120px;top:170px;background:#C8322B;color:#fff;font-size:64px;font-weight:900;padding:10px 34px;border-radius:16px;letter-spacing:.04em}}
"""


def card(inner, cap="", pop=0.05):
    c = f'<div class="cap">{cap}</div>' if cap else ""
    return f'<style>{CARD_CSS}</style>{c}<div class="cw"><div class="cd" data-a="pop" data-t="{pop:.2f}" data-d="0.4">{inner}</div></div>'


def C_word(lines, kicker="", sub="", size=130):
    k = f'<div class="k">{kicker}</div>' if kicker else ""
    s = f'<div class="s">{sub}</div>' if sub else ""
    return f'{k}<div class="b" style="font-size:{size}px">{"<br>".join(lines)}</div>{s}'


def bg_card(name, file, ss, inner=None, cap="", ei_pose=None, dim=0.5, slow=1.0, ff=False, poses=None, img_first=None):
    """背景に映像を流し、上にカード（inner が None なら映像だけ・左上に何の映像か）。
    img_first=割合：画像を見せたい場面。はじめはカードを出さず、背景を暗くしないで絵を見せ、場面のその割合の所でカードを出す
    （2026-11-13 エイイチの指示「画像の内容を見せたい時はカードを一時的に非表示に。センターから右にずらさない」）"""
    if inner:
        pop = 0.05
        if img_first is not None:
            pop = round(scene_len(name) * img_first, 2)
            dim = 1.0
        parts = card(inner, cap=cap, pop=pop)
    else:
        parts = f'<style>{CARD_CSS}</style>' + (f'<div class="cap">{cap}</div>' if cap else '')
    if ff:
        parts += '<div class="ff" data-a="pop" data-t="0.1" data-d="0.3">▶▶ 早送り</div>'
    if ei_pose:
        parts += ei_wipe(ei_pose, name, poses=poses)
    html = overlay(parts)
    MOTION[name] = dict(type="html", bg=dict(file=file, ss=ss, dim=dim, slow=slow), html=html)
    S[name] = html


def ei(name, page_html, pose='udegumi', pop=None, poses=None):
    S[name] = add(page_html, ei_wipe(pose, name, pop=pop, poses=poses))
    MOTION[name] = dict(type='html', html=S[name])


def img(name, file, title, w=1100, top=230, tag=None, credit=""):
    """画像を出し、上に題（ゴシックの太字。明朝・手書き風は使わない 2026-11-13 エイイチの指示）。画像は y 830 より上・x 400 より右に収める"""
    src = 'file://' + _os.path.join(_here, file)
    left = (1920 - w) // 2
    body = (f'<div style="position:absolute;left:0;right:0;top:110px;text-align:center">'
            f'<span data-a="pop" data-t="0.1" data-d="0.35" style="display:inline-block;font-weight:900;font-size:96px;color:#0D0D0D">{title}</span></div>'
            f'<img data-a="pop" data-t="0.35" data-d="0.5" src="{src}" style="position:absolute;left:{left}px;top:{top}px;width:{w}px">')
    S[name] = page(body, tag=tag)
    MOTION[name] = dict(type='html', html=S[name])





def C_list(items, kicker="", size=56):
    rows = "".join(f'<div style="font-size:{size}px;font-weight:900;line-height:1.38;text-align:left"><span class="hl" style="margin-right:26px">{n}</span>{t}</div>' for n, t in items)
    k = f'<div class="k">{kicker}</div>' if kicker else ""
    return f'{k}<div style="display:inline-block">{rows}</div>'


def chap(name, no, word, sub, file, ss=0, size=150):
    """章の扉。番号も大きく出す（2026-11-25 エイイチの指摘「数字が小さい」）"""
    num = f'<div style="font-size:150px;font-weight:900;color:#fff;line-height:1;margin-bottom:10px">{no}</div>'
    bg_card(name, file, ss, num + C_word([f'<span class="hl">{word}</span>'], "", sub, size), dim=0.45)


def W(lines, k="", s="", size=150):
    return C_word(lines, k, s, size)


def hl(t): return f'<span class="hl">{t}</span>'
def wn(t): return f'<span class="wn">{t}</span>'
def cnt(n, a=0.3, b=1.3): return f'<span data-c="{a},{b},{n}">{n:,}</span>'


def ei_poses(name, k, pose, dur=3.0):
    t = at(name, k, 0.1)
    return [(t, pose), (round(t + dur, 2), 'udegumi')]


EI_BIG_CSS = """<style>
.eiw{right:auto;left:700px;top:150px;bottom:auto;width:520px;height:520px;border-radius:40px;background:#F5F5F0;border:6px solid #D6D6D1}
.eiw img{width:520px;height:520px;top:10px}
.ein{right:auto;left:460px;width:1000px;top:690px;bottom:auto;font-size:64px}
.ein span{background:none;border:none;padding:0}
.ein small{display:block;font-size:38px;font-weight:700;color:#BDBDBD;margin-top:4px}
</style>"""





# ===== ここから「命令どおりに外れる」の場面 =====
GRAY, BL, OR = "#B9B9B4", "#406ED8", "#C8322B"
RD = OR

GCSS = f"""
.gc{{background:rgba(245,245,240,.9);border-radius:34px;padding:30px 50px 34px;box-shadow:0 12px 44px rgba(0,0,0,.35);display:flex;flex-direction:column;align-items:center;max-width:1640px}}
.gb{{position:absolute;left:120px;right:120px;top:96px;bottom:296px;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center}}
.gt{{font-size:70px;font-weight:900;margin-bottom:40px;line-height:1.22;text-align:center}}
.gt small{{display:block;font-size:40px;font-weight:700;color:{SUB};margin-top:12px}}
.hb{{display:flex;align-items:center;margin:18px 0;width:1240px}}
.hb .l{{width:380px;font-size:48px;font-weight:700;text-align:right;padding-right:30px;line-height:1.15}}
.hb .l small{{display:block;font-size:32px;color:{SUB}}}
.hb .tr{{flex:1;position:relative;height:110px}}
.hb .bar{{position:absolute;left:0;top:0;bottom:0;border-radius:10px}}
.hb .v{{position:absolute;top:50%;font-size:68px;font-weight:900;white-space:nowrap}}
.box2{{background:#fff;border-radius:24px;padding:34px 18px;text-align:center;font-size:54px;font-weight:900;line-height:1.25;border:6px solid transparent;white-space:nowrap}}
.box2 small{{display:block;font-size:32px;font-weight:700;color:{SUB};margin-top:10px;white-space:normal}}
.arr{{font-size:60px;font-weight:900;color:{SUB};padding:0 6px;white-space:nowrap}}
.chip{{display:inline-block;background:#fff;border-radius:16px;padding:20px 26px;font-size:46px;font-weight:900;margin:10px}}
.hl2{{color:{OR}}} .bl2{{color:{BL}}}
"""


# 図の場面の背景の映像（2026-11-26 エイイチの指示「図解を載せる時も背景の動画が見えた方がいい」）。場面の名前の頭で決める
B = lambda n: f"src/bg_{n}.mp4"
D04, D02, W04, FAILS, FAILSW, REDO, GRID, RGRID = B("desk04"), B("desk02"), B("wrist04"), B("fails"), B("fails_w"), B("redo"), B("grid"), B("redo_grid")
C_D = "机のカメラ（真上から）・お手本の録画"
C_W = "手首のカメラ・お手本の録画"
G_BG = [("hook", FAILS), ("search", D04), ("clue", W04), ("pre", D02), ("ans", D04), ("fix", REDO), ("rest", RGRID), ("end", FAILS),
        ("view", D02), ("next", REDO)]
_G_USE = {}


def G(name, inner, title="", sub="", tag=None, ei_pose=None, poses=None, bg=None, ss=None):
    """図・グラフの場面。背景に映像を流し、半透明の板の上に図を描く。中身は画面の中央（x 960）にそろえる
    （2026-11-26 エイイチの指示「テキストが右寄り → センター合わせ」）。板は y 786 までで、左下のハコブくんの区画に入らない"""
    if bg is None:
        bg = next(f for k, f in G_BG if name.startswith(k))
    if ss is None:
        ss = _G_USE.get(bg, 0); _G_USE[bg] = (ss + 4) % 20
    t = f'<div class="gt" data-a="up" data-t="0.05" data-d="0.4">{title}' + (f'<small>{sub}</small>' if sub else '') + '</div>' if title else ''
    html = overlay(f'<style>{GCSS}</style><div class="gb"><div class="gc">{t}{inner}</div></div>')
    if ei_pose:
        html = add(html, ei_wipe(ei_pose, name, poses=poses))
    S[name] = html
    MOTION[name] = dict(type='html', bg=dict(file=bg, ss=ss, dim=0.7, slow=1.0), html=html)


def hbars(rows, maxv, t0=0.4, step=0.6, scale=0.68):
    """横の棒グラフ。rows=[(ラベル, 値, 色, 値の文字, 出す秒 or None)]。棒は左から伸ばす（write）"""
    out = ''
    for k, (lab, v, col, vt, *tt) in enumerate(rows):
        t = tt[0] if tt and tt[0] is not None else round(t0 + k * step, 2)
        w = max(v / maxv * scale * 100, 0.6)
        out += (f'<div class="hb"><div class="l" data-a="fade" data-t="{t}" data-d="0.3">{lab}</div><div class="tr">'
                f'<div class="bar" style="width:{w:.1f}%;background:{col}" data-a="write" data-t="{t}" data-d="0.7"></div>'
                f'<div class="v" style="left:calc({w:.1f}% + 20px);color:{col if col != GRAY else SUB}" data-base="translateY(-50%)" data-a="pop" data-t="{round(t + 0.55, 2)}" data-d="0.35">{vt}</div>'
                '</div></div>')
    return out


def vbars(groups, maxv, series, t0=0.4, step=0.35, h=400, line=None):
    """縦の棒グラフ（場所ごとに2回など）。groups=[(ラベル, [値...])]、series=[(名前, 色)]。line=(値, 文字) で目安の破線"""
    cols = ''
    for g, (lab, vals) in enumerate(groups):
        bars = ''
        for s, v in enumerate(vals):
            col = series[min(s, len(series) - 1)][1]
            if isinstance(v, tuple):
                v, col = v
            t = round(t0 + (g * len(vals) + s) * step, 2)
            hh = v / maxv * h
            bars += (f'<div style="display:flex;flex-direction:column;align-items:center;justify-content:flex-end;width:104px;height:{h + 70}px">'
                     f'<div data-a="pop" data-t="{round(t + 0.4, 2)}" data-d="0.3" style="font-size:42px;font-weight:900;color:{col if col != GRAY else SUB};margin-bottom:6px">{v}</div>'
                     f'<div data-a="up" data-t="{t}" data-d="0.5" style="width:94px;height:{hh:.0f}px;background:{col};border-radius:8px 8px 0 0"></div></div>')
        cols += (f'<div style="display:flex;flex-direction:column;align-items:center;margin:0 18px">'
                 f'<div style="display:flex;align-items:flex-end;gap:8px">{bars}</div>'
                 f'<div style="font-size:44px;font-weight:700;margin-top:12px">{lab}</div></div>')
    ln = ''
    if line:
        y = line[0] / maxv * h
        ln = (f'<div style="position:absolute;left:0;right:0;bottom:{y + 70:.0f}px;border-top:4px dashed {INK}" data-a="fade" data-t="{t0}" data-d="0.4">'
              f'<span style="position:absolute;right:0;top:-56px;font-size:40px;font-weight:900">{line[1]}</span></div>')
    leg = ''.join(f'<span style="display:inline-flex;align-items:center;margin-right:30px"><i style="display:inline-block;width:30px;height:30px;background:{c};border-radius:6px;margin-right:10px"></i>{n}</span>' for n, c in series)
    return (f'<div style="font-size:40px;font-weight:700;margin-bottom:16px">{leg}</div>'
            f'<div style="position:relative;display:flex;align-items:flex-end;border-bottom:4px solid {INK};align-self:flex-start">{ln}{cols}</div>')


def strip(cells, h=92, gap=7, t=0.4, dt=0.05, k=1.35):
    """時間の帯。cells=[(幅, 色, 文字)]。左から順に出す"""
    out = ''
    for i, (w, c, tx) in enumerate(cells):
        out += (f'<div data-a="fade" data-t="{round(t + i * dt, 2)}" data-d="0.2" style="width:{w * k:.0f}px;height:{h}px;background:{c};border-radius:6px;margin-right:{gap}px;'
                f'display:flex;align-items:center;justify-content:center;color:#fff;font-size:38px;font-weight:900;flex:none">{tx}</div>')
    return f'<div style="display:flex">{out}</div>'


def row_lab(lab, inner, w=300):
    return f'<div style="display:flex;align-items:center;margin:26px 0;align-self:stretch"><div style="width:{w}px;font-size:50px;font-weight:900;flex:none">{lab}</div>{inner}</div>'


def flow(boxes, arrows=None, t0=0.3, step=0.7, hi=None):
    """箱を矢印でつなぐ流れ図。boxes=[(文字, 小さい文字, 枠の色 or None, 出す秒 or None)]"""
    out = ''
    for k, (a, b, c, *tt) in enumerate(boxes):
        t = tt[0] if tt and tt[0] is not None else round(t0 + k * step, 2)
        bd = f'border-color:{c}' if c else ''
        sm = f'<small>{b}</small>' if b else ''
        if k:
            ar = (arrows[k - 1] if arrows else '→')
            out += f'<div class="arr" data-a="fade" data-t="{round(t - 0.15, 2)}" data-d="0.3">{ar}</div>'
        out += f'<div class="box2" style="flex:1;{bd}" data-a="pop" data-t="{t}" data-d="0.4">{a}{sm}</div>'
    return f'<div style="display:flex;align-items:center;width:1340px">{out}</div>'


def places(marks, t0=0.4, step=0.35, note=None):
    """5か所の結果（○ ✕）。marks=[(○ か ✕, 色, 出す秒 or None)]"""
    out = ''
    for k, (m, c, *tt) in enumerate(marks):
        t = tt[0] if tt and tt[0] is not None else round(t0 + k * step, 2)
        mk = f'<div style="width:120px;height:120px;border-radius:50%;border:22px solid {c}"></div>' if m == '○' else m
        out += (f'<div style="display:flex;flex-direction:column;align-items:center;margin:0 26px">'
                f'<div data-a="pop" data-t="{t}" data-d="0.4" style="width:210px;height:210px;border-radius:50%;background:#fff;display:flex;align-items:center;justify-content:center;font-size:150px;font-weight:900;color:{c}">{mk}</div>'
                f'<div style="font-size:48px;font-weight:900;margin-top:16px">場所{k + 1}</div></div>')
    nt = f'<div style="font-size:46px;font-weight:700;color:{SUB};margin-top:34px;text-align:center">{note}</div>' if note else ''
    return f'<div style="display:flex;justify-content:center">{out}</div>{nt}'




def big(lines, sub="", size=130):
    sb = f'<div style="font-size:50px;font-weight:700;color:{SUB};margin-top:26px">{sub}</div>' if sub else ''
    return f'<div style="text-align:center"><div style="font-size:{size}px;font-weight:900;line-height:1.2">{"<br>".join(lines)}</div>{sb}</div>'


def dots_c(cols, t0, dt=0.04, size=70, per=10):
    out = ''.join(f'<div data-a="pop" data-t="{round(t0 + k * dt, 2)}" data-d="0.25" style="width:{size}px;height:{size}px;border-radius:50%;background:{c};margin:7px"></div>' for k, c in enumerate(cols))
    return f'<div style="display:flex;flex-wrap:wrap;width:{(size + 14) * per}px;justify-content:center">{out}</div>'


def _src(p):
    return 'file://' + _os.path.join(_here, p)


# --- Physical Intelligence の映像（引用・紙の上の窓。6-1 の B。窓の動画 src/pi_win.mp4 は mk_bg.sh で作る）---
PI_CSS = """
.fuda{position:absolute;left:420px;top:96px;display:flex;align-items:center;gap:14px;font-size:30px;font-weight:700;color:#0D0D0D}
.fuda .k{padding:6px 18px;border-radius:999px;font-size:28px;font-weight:900;background:#0D0D0D;color:#fff}
.tcr{position:absolute;left:420px;top:790px;font-size:26px;font-weight:700;color:#555}
"""


def pi(name, ss=0):
    html = overlay(f'<style>{PI_CSS}</style><div class="fuda"><span class="k">映像の引用</span><span>Physical Intelligence の π0.5</span></div>'
                   '<div class="tcr">映像：Physical Intelligence「π0.5: a VLA with Open-World Generalization」（pi.website/blog/pi05）</div>')
    MOTION[name] = dict(type="html", bg=dict(file="src/pi_win.mp4", ss=ss, dim=1.0, slow=1.0), html=html)
    S[name] = html


def pics(items, w=560):
    """画像を横に並べる。items=[(ファイル, ラベル, 色, 出す秒)]"""
    out = ''
    for f, lab, c, t in items:
        out += (f'<div style="margin:0 26px;text-align:center" data-a="pop" data-t="{t}" data-d="0.4">'
                f'<img src="{_src(f)}" style="width:{w}px;border-radius:14px;border:10px solid {c};display:block">'
                f'<div style="font-size:52px;font-weight:900;color:{c};margin-top:14px">{lab}</div></div>')
    return f'<div style="display:flex;justify-content:center">{out}</div>'


# ---------- 冒頭：謎（最初の10秒で実機） ----------
bg_card("hook_miss", D04, 0, None, dim=1.0, cap="机のカメラ（真上から）。爪を閉じたが、ブロックは机に残った")
G("hook_num", dots_c([BL] * 29 + [OR] * 21, at("hook_num", 1, 0.0), 0.03), title="50回のうち、つかめたのは<span class='bl2'>29回</span>",
  sub="赤＝外れた21回（4割）")
bg_card("hook_odd", FAILS, 0, W(['送った角度どおり', hl('誤差1°前後')], "アームの動きは", "", 130), cap=C_D, img_first=0.25)
bg_card("hook_q", FAILS, 9, W(['命令どおりなのに', wn('なぜ外れた？')], "今日の謎", "", 140), cap=C_D)
G("hook_not", flow([("✕ アームの故障", "", GRAY, 0.3), ("✕ 腕の力不足", "", GRAY, at("hook_not", 0, 0.6))], arrows=["／"]), title="犯人は")
bg_card("hook_hint", GRID, 0, W(['答えは', hl('1コマの写真')], "", "", 150), dim=0.6, cap="手首のカメラの1コマ（50回）")

# ---------- 手がかり ----------
bg_card("search", FAILS, 18, None, dim=1.0, cap="外れた回を続けて再生（机のカメラ）")
bg_card("search2", D04, 0, W(['見た目は', hl('ちゃんと狙っている')], "", "", 130), cap=C_D, img_first=0.45)
bg_card("search_guess", D04, 3, W(['ブロックが', wn('風圧で逃げた？')], "ハコブくんの最初の推理", "10グラムと軽いから……", 130), cap=C_D)
bg_card("search_guess2", D04, 6, W(['もちろん', wn('ちがいます')], "", "", 150), cap=C_D)
bg_card("clue", W04, 0, None, dim=1.0, cap="手首のカメラ（外れた回）。爪の間からブロックを見下ろしている")
bg_card("clue2", GRID, 0, None, dim=1.0, cap="爪を閉じる直前の1コマ × 50回（緑の枠＝つかめた・赤の枠＝外れた）")
G("clue3", pics([("src/w_ok.png", "つかめた回", BL, 0.3), ("src/w_ng.png", "外れた回：小さい", OR, at("clue3", 0, 0.45))], w=470),
  title="爪を閉じる直前の1コマ")
cam = (f'<svg viewBox="0 0 1100 470" style="width:1100px;height:470px">'
       f'<rect x="0" y="420" width="1100" height="10" fill="{INK}"/>'
       f'<rect x="250" y="355" width="70" height="65" rx="6" fill="#D33"/><rect x="780" y="355" width="70" height="65" rx="6" fill="#D33"/>'
       f'<g><rect x="230" y="250" width="22" height="120" rx="8" fill="{BL}"/><rect x="318" y="250" width="22" height="120" rx="8" fill="{BL}"/>'
       f'<rect x="245" y="220" width="80" height="34" rx="8" fill="{BL}"/><text x="285" y="190" font-size="42" font-weight="900" text-anchor="middle" fill="{BL}">つかめた回</text></g>'
       f'<g data-a="fade" data-t="{at("clue4", 0, 0.4)}" data-d="0.4"><rect x="760" y="110" width="22" height="120" rx="8" fill="{OR}"/><rect x="848" y="110" width="22" height="120" rx="8" fill="{OR}"/>'
       f'<rect x="775" y="80" width="80" height="34" rx="8" fill="{OR}"/><text x="815" y="50" font-size="42" font-weight="900" text-anchor="middle" fill="{OR}">外れた回</text>'
       f'<line x1="900" y1="230" x2="900" y2="355" stroke="{OR}" stroke-width="6" stroke-dasharray="12 8"/><text x="920" y="305" font-size="40" font-weight="900" fill="{OR}">遠い</text></g></svg>')
G("clue4", cam, title="爪が<span class='hl2'>上のほうで</span>閉じていた（模式図）")

# ---------- 自己紹介 ----------
O.update({
 "title": overlay('<div class="lt"><img class="a" src="' + LOGO + '"><div class="b">フィジカルAI解説</div><div class="c">案内役：ハコブくん（AI音声）</div></div>'),
 "title_eiichi": overlay('<div class="lt"><img class="a" src="' + LOGO + '"><div class="b">エイイチ</div><div class="c">デザイナー／ロボティクスの研究・開発</div></div>'),
 "outro": overlay('<div class="lt"><img class="a" src="' + LOGO + '"><div class="b">相談は概要欄の連絡先から</div><div class="c">高評価・チャンネル登録／コメントはエイイチが全部読んでいます</div></div>'),
})
VIDEO.update({
 "title": ("src/so101_intro.mp4", 0.5, False),
 "title_eiichi": ("src/so101_intro.mp4", None, False),
 "outro": ("src/so101_intro.mp4", 27.5, False),
})
# ---------- 計画の全体像（2026-11-29 エイイチの提案で、自己紹介のすぐあとに足した）----------
# 計画の全体像：専門の人が見る形の構成図（2026-11-29 エイイチの指示「もっと専門的な人が見るような図解に」）。数字は so101_real_sim_plan.md と LOG594 から
def _tech_plan(name):
    T = lambda k, f=0.0: at(name, k, f)
    C1, C2, C3, LN, TX, SB = "#5B9BFF", "#FFB02E", "#FF5A4F", "#3A4556", "#E8ECF2", "#8C97A8"
    def node(x, y, w, h, title, lines, col, t, tag=""):
        tg = f'<text x="{x + w - 14}" y="{y + 30}" font-size="22" font-weight="700" text-anchor="end" fill="{col}" font-family="monospace">{tag}</text>' if tag else ''
        ls = ''.join(f'<text x="{x + 18}" y="{y + 82 + i * 34}" font-size="26" font-weight="700" fill="{SB}">{l}</text>' for i, l in enumerate(lines))
        return (f'<g data-a="fade" data-t="{t}" data-d="0.4"><rect x="{x}" y="{y}" width="{w}" height="{h}" rx="10" fill="#141A24" stroke="{col}" stroke-width="3"/>'
                f'<rect x="{x}" y="{y}" width="8" height="{h}" rx="3" fill="{col}"/>'
                f'<text x="{x + 18}" y="{y + 44}" font-size="34" font-weight="900" fill="{TX}">{title}</text>{tg}{ls}</g>')
    def arr(x1, y1, x2, y2, t, dash=False, lab=""):
        d = ' stroke-dasharray="10 8"' if dash else ''
        lb = f'<text x="{(x1 + x2) / 2}" y="{(y1 + y2) / 2 - 12}" font-size="22" font-weight="700" text-anchor="middle" fill="{SB}">{lab}</text>' if lab else ''
        return (f'<g data-a="fade" data-t="{t}" data-d="0.3"><line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="{TX}" stroke-width="3"{d} marker-end="url(#ah)"/>{lb}</g>')
    t0, t1, t2 = T(0, 0.05), T(0, 0.45), T(1, 0.2)
    svg = (f'<svg viewBox="0 0 1600 600" style="width:1560px;height:585px">'
           f'<defs><marker id="ah" markerWidth="12" markerHeight="12" refX="10" refY="6" orient="auto"><path d="M0,0 L12,6 L0,12 z" fill="{TX}"/></marker>'
           f'<pattern id="gr" width="40" height="40" patternUnits="userSpaceOnUse"><path d="M40 0H0V40" fill="none" stroke="#1E2633" stroke-width="1"/></pattern></defs>'
           f'<rect width="1600" height="600" rx="18" fill="#0E131B"/><rect width="1600" height="600" rx="18" fill="url(#gr)"/>'
           f'<text x="30" y="46" font-size="30" font-weight="900" fill="{TX}">シム × 実機の映像を混ぜて学ぶ計画</text>'
           f'<text x="1570" y="46" font-size="24" font-weight="700" text-anchor="end" fill="{SB}" font-family="monospace">SO-101 / π0.5</text>'
           + node(30, 90, 400, 170, "実機", ["机のカメラ・手首のカメラ", "固定した机で録り直す"], C1, t0, "実データ")
           + node(30, 330, 400, 200, "シム（MuJoCo）", ["カメラを実機に合わせた", "写真と重なる：1.5px", "絵を実機に近づける"], C2, T(0, 0.3), "合成")
           + arr(430, 175, 560, 270, t1) + arr(430, 430, 560, 330, t1)
           + node(560, 190, 450, 230, "混ぜたお手本", ["つかむ所 ＝ 実機 ＋ リアルな合成", "近づく・運ぶ ＝ シムで増やす"], C3, t1, "混ぜて学習")
           + arr(1000, 305, 1110, 305, T(0, 0.75))
           + node(1120, 90, 450, 160, "π0.5 で学習", ["クラウドの GPU（Runpod）"], C3, T(0, 0.75))
           + arr(1345, 250, 1345, 330, t2)
           + node(1120, 340, 450, 200, "実機で比べる", ["成功率", "学習にかかる時間", "（実機だけ ／ 実機＋シム）"], C1, t2, "評価")
           + f'<g data-a="fade" data-t="{T(1, 0.6)}" data-d="0.4">'
           + f'<text x="800" y="578" font-size="22" font-weight="700" text-anchor="middle" fill="{SB}">ねらい：学習の時間を短く・シムと実機で認識をずらさない</text></g>'
           + '</svg>')
    html = overlay(f'<div style="position:absolute;left:0;right:0;top:110px;display:flex;justify-content:center" data-a="up" data-t="0.05" data-d="0.4">{svg}</div>')
    S[name] = html
    MOTION[name] = dict(type='html', bg=dict(file=D02, ss=4, dim=0.45, slow=1.0), html=html)


_tech_plan("plan")
def _tech_steps(name):
    TX, SB, C3 = "#E8ECF2", "#8C97A8", "#FF5A4F"
    steps = [("段階1", "固定した机で", "お手本を録り直す"), ("段階2", "実機だけで学習", "基準を測る"), ("段階3", "シムで", "映像を増やす"),
             ("段階4", "シムの絵を", "実機に近づける"), ("段階5", "混ぜて学習し", "実機で比べる")]
    g = ''
    for k, (n, a1, a2) in enumerate(steps):
        x = 40 + k * 306; on = k == 0; col = C3 if on else "#3A4556"
        t = round(0.3 + k * 0.3, 2)
        g += (f'<g data-a="fade" data-t="{t}" data-d="0.35"><rect x="{x}" y="120" width="270" height="250" rx="12" fill="{"#2A1416" if on else "#141A24"}" stroke="{col}" stroke-width="{4 if on else 2}"/>'
              f'<text x="{x + 20}" y="168" font-size="28" font-weight="700" fill="{C3 if on else SB}" font-family="monospace">{n}</text>'
              f'<text x="{x + 20}" y="250" font-size="30" font-weight="900" fill="{TX}">{a1}</text><text x="{x + 20}" y="294" font-size="30" font-weight="900" fill="{TX}">{a2}</text></g>')
        if k < 4:
            g += f'<g data-a="fade" data-t="{t}" data-d="0.35"><line x1="{x + 272}" y1="245" x2="{x + 302}" y2="245" stroke="{SB}" stroke-width="3"/></g>'
    g += (f'<g data-a="pop" data-t="{at(name, 0, 0.75)}" data-d="0.4"><rect x="40" y="395" width="270" height="56" rx="28" fill="{C3}"/>'
          f'<text x="175" y="433" font-size="30" font-weight="900" text-anchor="middle" fill="#fff">今日の50回</text></g>')
    svg = (f'<svg viewBox="0 0 1600 500" style="width:1560px;height:488px"><rect width="1600" height="500" rx="18" fill="#0E131B"/>'
           f'<text x="40" y="70" font-size="30" font-weight="900" fill="{TX}">計画の進め方（5段階）</text>{g}</svg>')
    html = overlay(f'<div style="position:absolute;left:0;right:0;top:150px;display:flex;justify-content:center" data-a="up" data-t="0.05" data-d="0.4">{svg}</div>')
    S[name] = html
    MOTION[name] = dict(type='html', bg=dict(file=D02, ss=8, dim=0.45, slow=1.0), html=html)


_tech_steps("plan_now")
bg_card("title_next", FAILS, 25, C_list([("1", "なぜ高い所で爪を閉じたのか"), ("2", "直しても残った7回の正体"), ("3", "AI にどこまで任せるか")], "このあと", 60), cap=C_D)

# ---------- 前提 ----------
bg_card("pre_arm", D02, 0, W([hl('SO-101')], "机の上の小さなロボットアーム", "", 190), cap=C_D, img_first=0.35)
pi("pre_task", 0)
G("pre_demo", flow([("置き場所", "机の広い範囲に", BL, at("pre_demo", 0, 0.7)), ("ブロックの向き", "左右に40°まで", BL, at("pre_demo", 0, 0.85))], arrows=["＋"]),
  title="お手本を<span class='hl2'>散らした</span>", sub="AI は、お手本の動きをまねて覚える")
G("pre_make", flow([("人が手で動かす", "今回はしない", GRAY, 0.3), ("計算で作る", "理想の動き", BL, at("pre_make", 0, 0.5))], arrows=["→"]), title="お手本の動き")
pts = ''.join(f'<circle cx="{120 + (k % 6) * 170}" cy="{90 + (k // 6) * 130}" r="22" fill="{BL}" data-a="pop" data-t="{round(0.3 + k * 0.08, 2)}" data-d="0.25"/>' for k in range(18))
gap = (f'<g data-a="fade" data-t="{at("pre_teach", 1, 0.2)}" data-d="0.5">'
       + ''.join(f'<circle cx="{205 + (k % 5) * 170}" cy="{155 + (k // 5) * 130}" r="14" fill="none" stroke="{SUB}" stroke-width="5" stroke-dasharray="6 6"/>' for k in range(10))
       + '</g>')
G("pre_teach", f'<svg viewBox="0 0 1100 400" style="width:1100px;height:400px">{pts}{gap}</svg>'
  + f'<div style="font-size:42px;font-weight:700;margin-top:8px"><span class="bl2">●</span> 人が教えた18か所　<span style="color:{SUB}">◌</span> 間は角度から計算で補う</div>',
  title="18か所で教え、<span class='bl2'>間は計算</span>")
G("pre_teach_time", big(['約<span class="hl2">1時間半</span>'], "18か所の教え込み", 170))
G("pre_rec", big(['50回 ／ <span class="bl2">47分</span>'], "1回およそ1分　→　結果は29回", 150))

# ---------- 答え ----------
G("clue5", hbars([("つかめた回", 7.0, BL, "7 mm"), ("外れた回", 13.1, OR, "13 mm", at("clue5", 0, 0.7))], 14), title="アームに送った手先の高さ", sub="真ん中の値")
bg_card("ans", D04, 2, W(['間違っていたのは', wn('命令のほう')], "アームは命令どおりに動いていた", "", 140), cap=C_D)
miss = (f'<svg viewBox="0 0 1000 420" style="width:1000px;height:420px">'
        f'<circle cx="150" cy="210" r="26" fill="{BL}"/><circle cx="850" cy="210" r="26" fill="{BL}"/>'
        f'<text x="150" y="150" font-size="40" font-weight="900" text-anchor="middle" fill="{BL}">教えた点</text><text x="850" y="150" font-size="40" font-weight="900" text-anchor="middle" fill="{BL}">教えた点</text>'
        f'<line x1="180" y1="210" x2="820" y2="210" stroke="{SUB}" stroke-width="5" stroke-dasharray="14 10"/>'
        f'<rect x="460" y="250" width="80" height="80" rx="8" fill="#D33"/><text x="500" y="380" font-size="38" font-weight="900" text-anchor="middle">本当のブロック</text>'
        f'<g data-a="pop" data-t="{at("ans2", 0, 0.5)}" data-d="0.4"><text x="500" y="200" font-size="90" font-weight="900" text-anchor="middle" fill="{OR}">✕</text>'
        f'<text x="500" y="95" font-size="44" font-weight="900" text-anchor="middle" fill="{OR}">計算の狙い</text>'
        f'<text x="580" y="310" font-size="48" font-weight="900" fill="{OR}">← 1〜2cm ずれる</text></g></svg>')
G("ans2", miss, title="間を補う計算に<span class='hl2'>誤差</span>（模式図）")
bg_card("ans_joke", FAILS, 30, W(['間違った地図どおりに', hl('まっすぐ迷子')], "", "", 120), cap=C_D)

# ---------- 直す ----------
bg_card("fix", REDO, 0, W([hl('狙いの作り方')], "替えた", "", 160), cap=C_D)
G("fix2", flow([("机のカメラ", "ブロックの位置", None, 0.3), ("アームの設計データ", "URDF", BL, at("fix2", 0, 0.55)), ("関節の角度", "届く形", BL, at("fix2", 1, 0.3))]),
  title="カメラから<span class='bl2'>直接計算</span>")
G("fix3", hbars([("前", 15.6, GRAY, "15.6 mm"), ("後", 6.7, BL, "6.7 mm", at("fix3", 0, 0.65))], 17), title="狙いの誤差", sub="真ん中の値")
G("fix4", dots_c([BL] * 13 + [OR] * 7, at("fix4", 0, 0.5), 0.05, 90), title="録り直した20か所 → <span class='bl2'>13か所</span>でつかめた")

# ---------- 残った7回 ----------
bg_card("rest", RGRID, 0, W(['残り', wn('7回')], "全部、ブロックの向きが大きい回", "", 160), dim=0.6, cap="録り直した20回の1コマ")
bg_card("rest_ei", RGRID, 4, W(['爪が', hl('斜めにいってる')], "エイイチの感想", "滑ってつかめない", 130), dim=0.6, cap="録り直した20回の1コマ",
        ei_pose="udegumi", poses=ei_poses("rest_ei", 1, "yubisasu"))
jaw = lambda x, ang, col: (f'<g transform="rotate({ang} {x} 330)"><rect x="{x - 60}" y="150" width="22" height="180" rx="8" fill="{col}"/>'
                           f'<rect x="{x + 38}" y="150" width="22" height="180" rx="8" fill="{col}"/></g>')
tilt = (f'<svg viewBox="0 0 1100 440" style="width:1100px;height:440px"><rect x="0" y="400" width="1100" height="8" fill="{INK}"/>'
        f'<rect x="245" y="330" width="70" height="70" rx="6" fill="#D33"/>{jaw(280, 0, BL)}'
        f'<text x="280" y="120" font-size="44" font-weight="900" text-anchor="middle" fill="{BL}">まっすぐ</text>'
        f'<g data-a="fade" data-t="{at("rest_check", 0, 0.4)}" data-d="0.4"><rect x="785" y="330" width="70" height="70" rx="6" fill="#D33"/>{jaw(820, 18, OR)}'
        f'<text x="820" y="120" font-size="44" font-weight="900" text-anchor="middle" fill="{OR}">傾いている</text></g></svg>')
G("rest_check", tilt, title="爪の面の傾き（模式図）")
G("rest_num", hbars([("外れた7回", 23.9, OR, "約11〜24°"), ("つかめた13回", 10.4, BL, "10.4°以下", at("rest_num", 1, 0.2))], 26),
  title="爪の面の傾き", sub="つかめた13回は、1回を除く")
slip = (f'<svg viewBox="0 0 1000 440" style="width:1000px;height:440px"><rect x="0" y="400" width="1000" height="8" fill="{INK}"/>{jaw(500, 18, OR)}'
        f'<g data-a="out" data-t="{at("rest_slip", 0, 0.6)}" data-d="0.2"><rect x="465" y="330" width="70" height="70" rx="6" fill="#D33"/></g>'
        f'<g data-a="fade" data-t="{at("rest_slip", 0, 0.6)}" data-d="0.3"><rect x="465" y="330" width="70" height="70" rx="6" fill="#D33" opacity=".18" stroke="#D33" stroke-width="4" stroke-dasharray="10 7"/>'
        f'<rect x="378" y="330" width="70" height="70" rx="6" fill="#D33" opacity=".32"/><text x="500" y="440" font-size="34" font-weight="900" text-anchor="middle" fill="{SUB}">元の位置</text></g>'
        f'<g data-a="pop" data-t="{at("rest_slip", 0, 0.6)}" data-d="0.4"><rect x="290" y="330" width="70" height="70" rx="6" fill="#D33" opacity=".85"/>'
        f'<text x="250" y="300" font-size="60" font-weight="900" text-anchor="end" fill="{OR}">← つるっ</text></g></svg>')
G("rest_slip", slip, title="傾いたまま閉じると<span class='hl2'>押し出す</span>（模式図）")
bg_card("rest_joke", RGRID, 10, W(['石けんを', hl('斜めにつまむ')], "", "", 150), dim=0.6, cap="録り直した20回の1コマ")
G("rest_got", big(['使えるお手本 <span class="bl2">42回</span>'], "29回 ＋ 13回", 140))

# ---------- 答えと確かめる3つ ----------
bg_card("end_q", FAILS, 40, W(['命令どおりなのに', wn('なぜ外れた？')], "冒頭の謎", "", 140), cap=C_D)
G("end_a", flow([("命令の狙い", "1〜2cmずれ・多くは高すぎ", OR, 0.3), ("残りの7回", "爪の傾き", OR, at("end_a", 1, 0.1))], arrows=["＋"]), title="答え")
bg_card("check", FAILSW, 0, C_list([("1", "狙いの位置は、合っていたか"), ("2", "爪の面は、傾いていなかったか"), ("3", "最後の1コマに、何が写っていたか")], "外れる映像を見たら", 60), cap=C_W)

# ---------- 見立て（まだ測っていない） ----------
bg_card("view_q", REDO, 10, W(['AI に', hl('どこまで任せる？')], "エイイチの見立て（まだ実機で測っていない仮説）", "", 140), cap=C_D)
bg_card("view_set", D02, 0, W(['今日直したのは', hl('つかむ直前の1〜2cm')], "", "", 120), cap=C_D, img_first=0.3)
bg_card("view_ei", D02, 3, W(['HOMEからの道は', wn('長い')], "エイイチの見立て", "お手本の量の勝負では、大企業にかなわない", 120), cap=C_D,
        ei_pose="udegumi", poses=ei_poses("view_ei", 1, "yubisasu"))
G("view_mf", flow([("AI", "動かすコードを書く", None, 0.3), ("コード", "位置の決まった作業を動かす", BL, at("view_mf", 1, 0.3))]),
  title="ヒント：<span class='bl2'>MicroFactory</span>（アメリカ）", sub="Claude を使ったプログラムがコードを書く")
G("view_split", flow([("近づく", "コード", None, at("view_split", 0, 0.5)), ("つかむ", "π0.5", OR, at("view_split2", 0, 0.0) if False else at("view_split", 0, 0.9)),
                      ("運ぶ", "コード", None, at("view_split", 0, 0.6)), ("置く", "コード", None, at("view_split", 0, 0.7))]), title="分担する")
G("view_split2", big(['π0.5 は', '<span class="hl2">つかむ直前〜つかむまで</span>'], "ほんの短い区間だけ", 110))
bg_card("view_ei2", D02, 8, W(['AI が必要なのは', hl('すごく少ない')], "エイイチの見立て", "", 140), cap=C_D, ei_pose="udegumi", poses=ei_poses("view_ei2", 0, "yubisasu"))
cost = (row_lab("全体を覚えさせる", flow([("直すとき", "全体を学び直し", OR, 0.3)]), 520)
        + row_lab("担当を短くする", flow([("直すとき", "その区間だけ", BL, at("view_cost", 1, 0.2))]), 520))
G("view_cost", cost, title="直す範囲も<span class='bl2'>短くなる</span>（見立て）")
bg_card("view_ei3", D02, 12, W(['デザインの', hl('コンポーネント')], "エイイチの見立て", "", 150), cap=C_D, ei_pose="udegumi", poses=ei_poses("view_ei3", 0, "hirameku"))
parts = ''.join(f'<span class="chip" style="border:6px solid {c}" data-a="pop" data-t="{round(0.3 + k * 0.3, 2)}" data-d="0.3">{t}</span>' for k, (t, c) in enumerate([("近づく", GRAY), ("つかむ", OR), ("運ぶ", GRAY), ("置く", GRAY)]))
G("view_parts", f'<div style="text-align:center">{parts}</div><div style="font-size:46px;font-weight:700;margin-top:30px" data-a="fade" data-t="{at("view_parts", 0, 0.6)}" data-d="0.4">現場では、部品を<span class="bl2">差し替えるだけ</span>？</div>',
  title="動きを<span class='hl2'>部品</span>にする")

# ---------- 次・サイト ----------
G("next", flow([("ブロックの上まで", "コード", None, 0.3), ("つかむまで", "π0.5", OR, at("next", 1, 0.3))]), title="次に実機で確かめること")
bg_card("site", REDO, 6, W(['pixelstomotors.com'], "研究の記録は、毎日公開", "50回の1コマの画像は SO-101 の記事に", 104))

use_motion(MOTION, VIDEO, O, _here, MOVE)
