"""
=============================================================================
CMU 11-777 · 第 1 讲共享模块：scene_world.py —— 一个"知道真相"的三模态场景世界
=============================================================================

【这个模块是干什么的】
    多模态机器学习研究的是"同一件事物，通过不同的通道表达出来"的数据：一张照片和描述它的一句话，
    一段视频和它的声音，一个人说话时的语言、语调和表情……真实的多模态数据集（MS COCO、VQA、
    MOSEI……）有两个问题：
        1. 动辄几十 GB，要下载、要 GPU；
        2. 更要命的是：我们**不知道真相**——这句话里的 "dog" 指的是图里的哪一块像素？
           这张图里哪些信息根本没被说出来？两个模态之间到底共享了多少信息？

    所以这里造一个**场景世界（Scene World）**：先由一个已知的随机过程生成一个"场景"
    （3×3 的格子里放 1–3 个物体，每个物体有形状、颜色、大小），然后让这个场景通过
    **三个不同的通道**表达出来：

        图像 image   ：一个"相机"把场景画成 33×33 的彩色图片（有光照变化、位置抖动、像素噪声）
        文字 caption ：一个"说话人"用一句英文描述场景（会漏说颜色、大小，会用同义词，还会表达自己的喜好）
        声音 audio   ：一个"发声器"按从左到右、从上到下的顺序，让每个物体发出一声短促的音调
                       （形状决定音高，大小决定响度；**颜色不发声**）

    因为每一步都是我们自己写的，所有"真相"都是已知的：
        - 每个模态里**有哪些信息、缺哪些信息**（例如声音里没有颜色，文字里没有准确的位置）；
        - 文字里的每一个词指的是**哪一个物体**（真实的对应关系 / grounding）；
        - 声音里每个音调**从第几毫秒开始**（真实的时间对齐）；
        - 说话人的喜好（只存在于文字里的信息）。
    第 1 讲用它说明"异质性、连接、交互"三个基本概念和六大技术挑战；后面的讲次会反复使用它：
    融合（第 5 讲）、协调表示与对比学习（第 6 讲）、离散 / 连续对齐（第 7–8 讲）、迁移（第 9 讲）、
    小型视觉-语言模型（第 10–11 讲）、组合推理（第 13–14 讲）、生成（第 15–16 讲）、量化（第 18 讲）。

【场景的生成过程（先验 prior，全部已知）】
    第 1 步  物体个数 n ∈ {1, 2, 3}，概率 0.2 / 0.4 / 0.4
    第 2 步  在 9 个格子里不放回地均匀选 n 个格子（一个格子最多一个物体）
    第 3 步  每个物体独立地均匀选：形状（圆 / 方块 / 三角 / 十字）、颜色（红 / 绿 / 蓝 / 黄）、大小（小 / 大）
    于是一共有 Σ_n C(9, n) · 32^n = 2,789,664 种场景，每种场景的概率都能精确写出来（scene_log2prob）。

【主要接口 API】
    常数：SHAPES, COLORS, SIZES（英文名）、SHAPE_ZH, COLOR_ZH, SIZE_ZH（中文名）、GRID, CELL, IMG, SR
    Obj, Scene                      物体与场景（Scene 就是按格子编号排好序的 Obj 元组）
    sample_scene(rng, n)            按先验采样一个场景
    scene_log2prob(scene)           log₂ p(scene)，精确值
    scene_entropy_bits(), N_SCENES  场景先验的精确熵、场景总数
    render_image(scene, rng, ...)   相机：场景 → 33×33×3 的图片
    describe(scene, rng, speaker)   说话人：场景 → Caption（词序列 + 每个词指向哪个物体 + 说话人喜好……）
    sonify(scene, rng, ...)         发声器：场景 → Audio（波形 + 每个音调的真实起止时间）
    parse_image / parse_caption / parse_audio
                                    三个"理想解析器"：从一个模态里把能读出来的场景信息读出来
                                    （用来回答"这个模态里到底有什么信息"，不是机器学习模型）
    read_objects(sample, modality)  评估工具：把某个模态解析出的结果和真实物体一一对上
    corrupt_caption(tokens, p, rng) 文字噪声：每个词以概率 p 被换成随机的词
    make_dataset(n, seed, ...)      一次生成 n 个 Sample（scene, image, caption, audio）
    image_features / color_mass / bow_features / audio_features
                                    几个简单的特征提取器（给第 1 讲的线性模型用）
    ascii_image(s) / ascii_side_by_side / describe_scene_zh / audio_envelope_line
                                    在终端里"看"图片、场景和声音

【运行方式】
    python3 scene_world.py          # 自检：先验之和、解析器在干净数据上的准确率、可复现性（不到 1 秒）

【numpy 小知识（第一次接触 numpy 的读者先看这里）】
    - np.ndarray：多维数组。一张图片是形状 (33, 33, 3) 的数组：33 行、33 列、每个像素 3 个颜色通道（R, G, B）。
    - img[r0:r1, c0:c1]：切片，取出第 r0..r1−1 行、第 c0..c1−1 列（包含起点、不包含终点）。
    - mask = (a > 0.3)：逐元素比较，得到同样形状的布尔数组（True / False），可以用来"挑出"元素：a[mask]。
    - np.random.default_rng(seed)：一个"私人"的随机数生成器。固定种子，结果就能逐位复现。
      本模块让场景、图像、文字、声音各用一个**独立的**生成器（SeedSequence.spawn），
      这样调高图像噪声时，场景和文字一个字都不会变——做对照实验时非常重要。
"""

import math
import zlib
from dataclasses import dataclass, field

import numpy as np

from console import display_width, pad

# ---------------------------------------------------------------------------
# 世界的常数
# ---------------------------------------------------------------------------
SHAPES = ("circle", "square", "triangle", "cross")       # 形状编号 0..3
COLORS = ("red", "green", "blue", "yellow")              # 颜色编号 0..3
SIZES = ("small", "large")                               # 大小编号 0..1
SHAPE_ZH = ("圆", "方块", "三角", "十字")
COLOR_ZH = ("红", "绿", "蓝", "黄")
SIZE_ZH = ("小", "大")
ROW_ZH = ("上", "中", "下")
COL_ZH = ("左", "中", "右")

GRID = 3                          # 3×3 个格子
N_CELLS = GRID * GRID             # 9 个格子，编号 0..8，按"从左到右、从上到下"（阅读顺序）
CELL = 11                         # 每个格子 11×11 像素（奇数：格子正中心恰好是一个像素，细线才画得出来）
IMG = GRID * CELL                 # 图片边长 33 像素
N_OBJ_PROBS = (0.2, 0.4, 0.4)     # p(n = 1), p(n = 2), p(n = 3)
N_ATTR = len(SHAPES) * len(COLORS) * len(SIZES)   # 每个物体 32 种外观

BG = 0.10                         # 背景灰度（三个通道都是 0.10）
RGB = np.array([                  # 每种颜色的 (R, G, B)，取值 0..1
    [0.90, 0.15, 0.15],           # 红
    [0.15, 0.75, 0.20],           # 绿
    [0.15, 0.30, 0.90],           # 蓝
    [0.90, 0.80, 0.10],           # 黄
])
COLOR_LETTER = ("R", "G", "B", "Y")   # 字符画里用的字母

SR = 4000                         # 声音的采样率：每秒 4000 个采样点（真实音频常用 16000 或 44100）
PITCH = (300.0, 420.0, 560.0, 750.0)  # 每种形状的音高（Hz）：圆最低，十字最高
LOUD = (0.35, 0.80)               # 小物体轻、大物体响（音调的振幅）
TONE_DUR = 0.12                   # 每个音调的基本时长（秒）
GAP_DUR = 0.06                    # 音调之间的停顿（秒）


def bits_of(n_choices):
    """
    从 n 个等可能的选项里选一个需要多少 bit：log₂ n。

    【参数】n_choices：正整数
    【返回】float
    【多模态联系】本讲反复用"bit"来比较不同模态里的信息量：1 bit = 一次公平的二选一。
    """
    return math.log2(n_choices)


# ---------------------------------------------------------------------------
# 场景：物体与先验
# ---------------------------------------------------------------------------

@dataclass(frozen=True)
class Obj:
    """
    场景里的一个物体。

    【字段】shape / color / size：编号（见 SHAPES / COLORS / SIZES）；cell：格子编号 0..8
    【Python 小知识】@dataclass 自动生成 __init__、__repr__、__eq__ 等方法，省得手写；
        frozen=True 表示创建之后不能修改（像元组一样"不可变"），于是可以放进集合、当字典的键。
    """
    shape: int
    color: int
    size: int
    cell: int

    @property
    def row(self):
        """所在的行（0 上 / 1 中 / 2 下）。@property 让它像字段一样用：obj.row，不用写 obj.row()。"""
        return self.cell // GRID

    @property
    def col(self):
        """所在的列（0 左 / 1 中 / 2 右）。"""
        return self.cell % GRID

    def zh(self):
        """中文描述，例如 "小红圆@上左"。"""
        return f"{SIZE_ZH[self.size]}{COLOR_ZH[self.color]}{SHAPE_ZH[self.shape]}@{ROW_ZH[self.row]}{COL_ZH[self.col]}"


def sample_scene(rng, n=None):
    """
    按先验采样一个场景。

    【思路】先定物体个数，再不放回地选格子，最后给每个物体独立地选形状、颜色、大小。
    【参数】rng：np.random.Generator；n：指定物体个数（1..3），None 表示按 N_OBJ_PROBS 随机
    【返回】Scene = 按格子编号从小到大排好序的 Obj 元组（这就是"阅读顺序"：先上后下、先左后右）
    【边界】n 超出 1..3 时抛出 ValueError。
    【Python 小知识】tuple(...) 把列表变成元组；sorted(..., key=...) 按 key 给出的值排序。
    """
    if n is None:
        n = int(rng.choice(3, p=N_OBJ_PROBS)) + 1
    if not 1 <= n <= 3:
        raise ValueError(f"物体个数必须是 1..3，收到 {n}")
    cells = rng.choice(N_CELLS, size=n, replace=False)
    objs = [Obj(int(rng.integers(4)), int(rng.integers(4)), int(rng.integers(2)), int(c)) for c in cells]
    return tuple(sorted(objs, key=lambda o: o.cell))


def scene_log2prob(scene):
    """
    log₂ p(scene)：这个场景在先验下的精确概率（以 2 为底的对数）。

    【思路】p(scene) = p(n) × 1 / C(9, n) × (1/32)^n
        —— 选中这 n 个格子的概率是 1 / C(9, n)（格子集合是无序的，排好序就唯一了），每个物体的外观 1/32。
    【参数】scene：Scene
    【返回】float（负数；越接近 0 越常见）
    """
    n = len(scene)
    return math.log2(N_OBJ_PROBS[n - 1]) - math.log2(math.comb(N_CELLS, n)) - n * math.log2(N_ATTR)


def scene_entropy_bits():
    """
    场景先验的精确熵 H(scene)：平均每个场景"包含"多少 bit 的信息。

    【思路】H = H(n) + Σ_n p(n) [log₂ C(9, n) + n · log₂ 32]
        —— 链式法则：先付"物体个数"的 bit，再付"格子位置"的 bit，再付每个物体外观的 5 bit。
    【返回】float（约 17.8 bit）
    【多模态联系】这是"场景"这个最抽象的描述的信息量。原始图片有上千个像素值，但关于场景的信息只有这么多；
        剩下的都是光照、抖动和噪声——"离传感器越近，信息越多，但大部分和任务无关"。
    """
    h = 0.0
    for n, pn in enumerate(N_OBJ_PROBS, start=1):
        h += -pn * math.log2(pn) + pn * (math.log2(math.comb(N_CELLS, n)) + n * math.log2(N_ATTR))
    return h


N_SCENES = sum(math.comb(N_CELLS, n) * N_ATTR ** n for n in (1, 2, 3))   # 2,789,664 种场景


def describe_scene_zh(scene):
    """场景的中文描述，例如 "小红圆@上左, 大蓝十字@中中"。"""
    return ", ".join(o.zh() for o in scene)


# ---------------------------------------------------------------------------
# 模态 1：图像（相机）
# ---------------------------------------------------------------------------

_YY, _XX = np.mgrid[0:CELL, 0:CELL] + 0.5     # 格子里每个像素中心的 (y, x) 坐标：0.5, 1.5, ..., 10.5


def shape_mask(shape, size, dy=0, dx=0):
    """
    在一个 8×8 的格子里画出一个形状，返回布尔掩码（True = 这个像素属于物体）。

    【思路】每种形状用一个简单的几何不等式描述，物体中心在格子中心 (5.5, 5.5) 再加上抖动 (dy, dx)：
        圆：到中心的距离 ≤ 半径
        方块：横、竖两个方向的距离都 ≤ 半边长（实心正方形）
        三角：尖朝上的实心等腰三角形——越往下越宽
        十字：一横一竖两根细条（小十字 1 像素宽，大十字 3 像素宽）
        尺寸是试出来的：在 11×11 的格子里，8 种（形状, 大小）在任何抖动下画出来的像素集合都互不相同，
        否则"理想解析器"就分不清它们了（作者第一版用 8×8 的格子，小圆和小十字画出来一模一样）。
    【参数】shape：0..3；size：0 小 / 1 大；dy, dx：中心的抖动（像素）
    【返回】形状 (11, 11) 的布尔数组
    【边界】大物体加上抖动后可能碰到格子边缘，超出的部分直接被裁掉（物体不会画进别的格子）。
    """
    cy, cx = CELL / 2 + dy, CELL / 2 + dx
    ady, adx = np.abs(_YY - cy), np.abs(_XX - cx)
    if shape == 0:                                       # 圆
        r = (2.3, 3.6)[size]
        return (_YY - cy) ** 2 + (_XX - cx) ** 2 <= r * r
    if shape == 1:                                       # 方块
        half = (2.0, 3.0)[size]
        return (ady <= half) & (adx <= half)
    if shape == 2:                                       # 三角（尖朝上）
        h = (5.0, 8.0)[size]
        top = cy - h / 2
        depth = _YY - top                                 # 从尖往下走了多远
        return (depth >= 0) & (depth <= h) & (adx <= 0.55 * depth)
    if shape == 3:                                       # 十字
        arm, thick = ((2.0, 0.5), (4.0, 1.0))[size]
        return ((adx <= thick) & (ady <= arm)) | ((ady <= thick) & (adx <= arm))
    raise ValueError(f"未知形状编号 {shape}")


def render_image(scene, rng, noise=0.05, jitter=True, lighting=True):
    """
    相机：把场景画成一张 33×33 的彩色图片。

    【思路】
        1. 整张图先涂成背景灰（0.10）；
        2. 每个物体画在自己的格子里：形状掩码 × 颜色 × 全局亮度（模拟光照，0.85–1.15 倍）；
           物体中心在格子里随机抖动 −1 / 0 / +1 像素（模拟"摆放得不那么整齐"）；
        3. 每个像素、每个通道加上独立的高斯噪声（模拟传感器噪声），最后截断到 [0, 1]。
    【参数】
        scene：Scene；rng：np.random.Generator
        noise：高斯噪声的标准差（默认 0.05；第 1 讲代码 02 会把它调大，看各模态怎样"抗噪"）
        jitter / lighting：是否加位置抖动 / 光照变化（关掉它们就得到"理想相机"）
    【返回】形状 (33, 33, 3) 的 float64 数组
    【边界】不管参数怎样设置，消耗的随机数个数都一样（关掉抖动也照样抽签，只是不用），
        这样同一个种子下，改一个设置不会让后面的随机数"错位"。
    【多模态联系】图像是"离传感器最近"的原始模态：连续取值、空间结构、元素（像素）多、信息密度低。
    """
    img = np.full((IMG, IMG, 3), BG)
    brightness = rng.uniform(0.85, 1.15)
    if not lighting:
        brightness = 1.0
    for o in scene:
        dy, dx = rng.integers(-1, 2, size=2)             # −1, 0, 1 三选一（integers 的上界不包含）
        if not jitter:
            dy, dx = 0, 0
        m = shape_mask(o.shape, o.size, dy, dx)
        r0, c0 = o.row * CELL, o.col * CELL
        patch = img[r0:r0 + CELL, c0:c0 + CELL]          # 切片得到的是"视图"：改 patch 就是改 img
        patch[m] = np.clip(RGB[o.color] * brightness, 0.0, 1.0)
    img = img + rng.normal(0.0, 1.0, size=img.shape) * noise
    return np.clip(img, 0.0, 1.0)


# 理想图像解析器用的模板：每种 (形状, 大小, dy, dx) 的掩码，一共 4 × 2 × 9 = 72 个
_TEMPLATES = [((s, z), shape_mask(s, z, dy, dx))
              for s in range(4) for z in range(2) for dy in (-1, 0, 1) for dx in (-1, 0, 1)]
_RGB_NORM = RGB / RGB.max(axis=1, keepdims=True)     # 颜色"色度"：每种颜色除以自己最亮的通道


def _classify_color(mean_rgb):
    """把一个平均颜色归到最近的颜色类别。先除以最亮通道，消掉"光照让整体变亮 / 变暗"的影响。"""
    v = mean_rgb / max(mean_rgb.max(), 1e-9)
    return int(np.argmin(((_RGB_NORM - v) ** 2).sum(axis=1)))


def parse_image(img, ink_threshold=0.30, min_pixels=4):
    """
    理想图像解析器（"目标检测器"）：从图片里读出每个格子里有没有物体、是什么物体。

    【思路】对每个格子：
        1. "墨水"掩码 = 某个通道比背景亮出 ink_threshold 以上的像素；少于 min_pixels 个就认为是空格子；
        2. 颜色 = 墨水像素的平均颜色，归到最近的颜色类别；
        3. 形状和大小 = 和 72 个模板比较，取交并比（IoU = 交集 / 并集）最大的那个。
        这不是学出来的模型，而是一个"知道相机怎样工作"的手写解析器：它回答的是
        "这张图里**原则上**能读出多少场景信息"。噪声大了它也会出错——那正是信息被噪声毁掉了。
    【参数】img：(33, 33, 3) 数组；ink_threshold：判定墨水的亮度差；min_pixels：最少墨水像素数
    【返回】按格子编号排序的 Obj 元组（和 Scene 同样的格式，可以直接和真实场景比较）
    【边界】噪声很大时可能把空格子误判成有物体（假阳性），也可能漏掉小物体。
    """
    found = []
    for cell in range(N_CELLS):
        r0, c0 = (cell // GRID) * CELL, (cell % GRID) * CELL
        crop = img[r0:r0 + CELL, c0:c0 + CELL]
        ink = (crop - BG).max(axis=2) > ink_threshold
        if ink.sum() < min_pixels:
            continue
        color = _classify_color(crop[ink].mean(axis=0))
        best, best_iou = None, -1.0
        for key, m in _TEMPLATES:
            iou = (m & ink).sum() / (m | ink).sum()
            if iou > best_iou:
                best, best_iou = key, iou
        found.append(Obj(best[0], color, best[1], cell))
    return tuple(found)


def ascii_image(img):
    """
    把图片画成字符画：背景 "·"，物体像素用颜色的首字母 R / G / B / Y。

    【参数】img：(33, 33, 3) 数组
    【返回】33 个字符串组成的列表（每行一个字符串，每个像素一个字符）
    """
    lines = []
    for r in range(IMG):
        row = []
        for c in range(IMG):
            p = img[r, c]
            if (p - BG).max() < 0.25:
                row.append("·")
            else:
                row.append(COLOR_LETTER[_classify_color(p)])
        lines.append("".join(row))
    return lines


def ascii_side_by_side(images, titles=None, gap="   "):
    """
    把几张图片的字符画并排打印出来。

    【参数】images：图片列表；titles：每张图上方的标题（可选）；gap：两张图之间的空白
    【返回】None（直接打印）
    【Python 小知识】zip(*blocks) 把"每张图的第 r 行"组合在一起，于是可以一行一行地并排打印。
        标题里有汉字，所以用 console.pad 按"显示宽度"补空格（见 console.py）。
    """
    blocks = [ascii_image(im) for im in images]
    if titles:
        cut = []
        for t in titles:                                   # 标题太长就截断（按显示宽度：一个汉字占 2 格）
            while display_width(t) > IMG:
                t = t[:-1]
            cut.append(pad(t, IMG))
        print(gap.join(cut))
    for rows in zip(*blocks):
        print(gap.join(rows))


# ---------------------------------------------------------------------------
# 模态 2：文字（说话人）
# ---------------------------------------------------------------------------

SHAPE_WORDS = (("circle", "ball"), ("square", "box"), ("triangle",), ("cross", "plus"))   # 同义词
SIZE_WORDS = (("small", "little"), ("large", "big"))
COLOR_WORDS = COLORS
OPINION_WORDS = (("ugly", "boring"), ("lovely", "nice"))     # 0 = 不喜欢，1 = 喜欢
RELATION_WORDS = {"left": ("left", "of"), "right": ("right", "of"), "above": ("above",), "below": ("below",)}
FUNCTION_WORDS = ("a", "the", "and", ",", ".", "is")

# 词表：所有可能出现的词，按固定顺序排好（词的编号 = 它在 VOCAB 里的位置）
VOCAB = tuple(sorted(set(
    FUNCTION_WORDS + COLOR_WORDS
    + tuple(w for ws in SHAPE_WORDS for w in ws)
    + tuple(w for ws in SIZE_WORDS for w in ws)
    + tuple(w for ws in OPINION_WORDS for w in ws)
    + tuple(w for ws in RELATION_WORDS.values() for w in ws)
)))
WORD_ID = {w: i for i, w in enumerate(VOCAB)}
_SHAPE_OF = {w: s for s, ws in enumerate(SHAPE_WORDS) for w in ws}
_SIZE_OF = {w: z for z, ws in enumerate(SIZE_WORDS) for w in ws}
_COLOR_OF = {w: c for c, w in enumerate(COLOR_WORDS)}
_OPINION_OF = {w: o for o, ws in enumerate(OPINION_WORDS) for w in ws}


@dataclass
class Speaker:
    """
    说话人的习惯（全部是概率）。

    【字段】
        p_color：提到颜色的概率（0.9）——人通常会说颜色，但不总说
        p_size：提到大小的概率（0.5）——大小经常被省略
        p_reading_order：按阅读顺序（先上后下、先左后右）描述物体的概率（0.8），否则随机顺序
        p_relation：物体 ≥ 2 个时，再加一句空间关系（"the red ball is left of the box"）的概率（0.5）
        p_opinion：句首说出自己喜好（"lovely" / "ugly"……）的概率（0.8）
        p_synonym：用同义词（ball、box、plus、little、big）的概率（0.3）
    【多模态联系】这些"漏说""换个说法""夹带私货"正是自然语言和图像之间不对等的来源：
        文字比图像**抽象**（没有像素级细节）、**有选择**（只说说话人觉得重要的）、
        还带着**图像里没有的信息**（说话人的态度）。
    """
    p_color: float = 0.9
    p_size: float = 0.5
    p_reading_order: float = 0.8
    p_relation: float = 0.5
    p_opinion: float = 0.8
    p_synonym: float = 0.3


@dataclass
class Caption:
    """
    说话人说出的一句话，以及它背后的全部"真相"。

    【字段】
        tokens：词的列表，例如 ["lovely", ",", "a", "red", "ball", "and", "a", "big", "blue", "cross", "."]
        refs：和 tokens 等长，第 k 个词指向场景里的哪一个物体（场景元组里的下标），不指向物体的词是 −1
              —— 这就是**真实的跨模态对应关系**（grounding），第 7 讲的对齐算法要把它"猜"出来
        order：物体被提到的顺序（场景下标的列表）
        said_color / said_size：每个物体（按场景下标）的颜色 / 大小有没有被说出来
        opinion：说话人的喜好（0 不喜欢 / 1 喜欢）——**只存在于说话人心里**，不管说没说出来
        said_opinion：喜好有没有说出来
        relation：(i, 关系, j) 表示说了"物体 i 在物体 j 的左边 / 右边 / 上面 / 下面"，没说是 None
    """
    tokens: list
    refs: list
    order: list
    said_color: list
    said_size: list
    opinion: int
    said_opinion: bool
    relation: tuple = None

    def text(self):
        """把词列表拼成一句话（标点前不加空格）。"""
        out = ""
        for w in self.tokens:
            out += w if (w in (",", ".") or not out) else " " + w
        return out


def _pick(words, rng, p_synonym):
    """从同义词元组里选一个：第一个是"常用说法"，以 p_synonym 的概率改用后面的同义词。"""
    if len(words) > 1 and rng.random() < p_synonym:
        return words[1 + int(rng.integers(len(words) - 1))]
    return words[0]


def true_relation(a, b, rng=None):
    """
    物体 a 相对于物体 b 的一个**成立的**空间关系："left" / "right" / "above" / "below"。

    【思路】同一行只能说左右，同一列只能说上下；既不同行也不同列时，左右和上下都成立，随机选一个。
    【参数】a, b：Obj（不能在同一个格子里）；rng：需要随机选择时用的生成器（None 时优先说左右）
    【返回】字符串
    """
    options = []
    if a.col < b.col:
        options.append("left")
    elif a.col > b.col:
        options.append("right")
    if a.row < b.row:
        options.append("above")
    elif a.row > b.row:
        options.append("below")
    if rng is None or len(options) == 1:
        return options[0]
    return options[int(rng.integers(len(options)))]


def relation_holds(a, b, rel):
    """检查 "a 在 b 的 rel" 在几何上是否成立（rel ∈ left / right / above / below）。"""
    return {"left": a.col < b.col, "right": a.col > b.col,
            "above": a.row < b.row, "below": a.row > b.row}[rel]


def describe(scene, rng, speaker=None, opinion=None):
    """
    说话人：用一句英文描述场景。

    【思路】
        1. 决定喜好（不指定就抛硬币）；以 p_opinion 的概率在句首说出来（"lovely, ..."）；
        2. 决定描述顺序：以 p_reading_order 的概率按阅读顺序，否则随机打乱；
        3. 每个物体说成一个名词短语 "a [大小] [颜色] 形状"：颜色以 p_color、大小以 p_size 的概率说出；
           形状一定说（不然听的人不知道在说什么），但可能用同义词；
        4. 物体 ≥ 2 个时，以 p_relation 的概率再加一句 "the [颜色] 形状 is 关系 the [颜色] 形状 ."，
           关系一定是**真的**（这个说话人不说谎；第 6 讲会人为造出"不匹配"的句子做对比学习）。
    【参数】scene：Scene；rng：生成器；speaker：Speaker（默认参数）；opinion：强制指定喜好 0 / 1
    【返回】Caption
    【边界】空场景不会出现（先验保证至少 1 个物体）。
    【Python 小知识】list.extend(xs) 把 xs 里的元素逐个加到列表末尾；append(x) 只加一个元素。
    """
    sp = speaker or Speaker()
    n = len(scene)
    if opinion is None:
        opinion = int(rng.random() < 0.5)
    said_opinion = bool(rng.random() < sp.p_opinion)
    order = list(range(n))
    if rng.random() >= sp.p_reading_order:
        order = [int(i) for i in rng.permutation(n)]
    said_color = [False] * n
    said_size = [False] * n
    shape_word = [None] * n
    tokens, refs = [], []
    if said_opinion:
        tokens.extend([_pick(OPINION_WORDS[opinion], rng, 0.5), ","])
        refs.extend([-1, -1])
    for k, i in enumerate(order):
        o = scene[i]
        if k > 0:
            sep = "and" if k == n - 1 else ","
            tokens.append(sep)
            refs.append(-1)
        tokens.append("a")
        refs.append(i)
        if rng.random() < sp.p_size:
            said_size[i] = True
            tokens.append(_pick(SIZE_WORDS[o.size], rng, sp.p_synonym))
            refs.append(i)
        if rng.random() < sp.p_color:
            said_color[i] = True
            tokens.append(COLOR_WORDS[o.color])
            refs.append(i)
        shape_word[i] = _pick(SHAPE_WORDS[o.shape], rng, sp.p_synonym)
        tokens.append(shape_word[i])
        refs.append(i)
    tokens.append(".")
    refs.append(-1)
    relation = None
    if n >= 2 and rng.random() < sp.p_relation:
        i, j = (int(x) for x in rng.choice(n, size=2, replace=False))
        rel = true_relation(scene[i], scene[j], rng)
        relation = (i, rel, j)
        for idx, mid in ((i, RELATION_WORDS[rel]), (j, None)):
            tokens.append("the")
            refs.append(idx)
            if said_color[idx]:
                tokens.append(COLOR_WORDS[scene[idx].color])
                refs.append(idx)
            tokens.append(shape_word[idx])
            refs.append(idx)
            if mid is not None:
                tokens.append("is")
                refs.append(-1)
                tokens.extend(mid)
                refs.extend([-1] * len(mid))
        tokens.append(".")
        refs.append(-1)
    return Caption(tokens, refs, order, said_color, said_size, opinion, said_opinion, relation)


@dataclass
class ParsedCaption:
    """
    理想文字解析器读出来的东西。

    【字段】
        objects：按**提到的顺序**排列的 (形状, 颜色或 None, 大小或 None) 三元组
        opinion：读出的喜好 0 / 1，没说就是 None
        relation：(第几个短语, 关系, 第几个短语) 或 None —— 用的是"提到顺序"里的位置，不是场景下标
    """
    objects: list
    opinion: int = None
    relation: tuple = None


def parse_caption(tokens):
    """
    理想文字解析器：按语法把一句描述读回成结构化的信息。

    【思路】第一个句号之前是物体列表：遇到大小词、颜色词先记下，遇到形状词就"结算"一个物体；
        句首的喜好词单独记下；第一个句号之后是关系句：用"颜色 + 形状"在前面的物体列表里找它指的是谁。
    【参数】tokens：词列表（可以含有被噪声替换掉的词——不认识或位置不对的词会被跳过）
    【返回】ParsedCaption
    【边界】关系句里的短语在物体列表里找不到或有歧义（两个物体颜色、形状都一样）时，relation 记为 None。
    """
    out = ParsedCaption(objects=[])
    size = color = None
    k = 0
    while k < len(tokens) and tokens[k] != ".":
        w = tokens[k]
        if w in _OPINION_OF and k == 0:
            out.opinion = _OPINION_OF[w]
        elif w in _SIZE_OF:
            size = _SIZE_OF[w]
        elif w in _COLOR_OF:
            color = _COLOR_OF[w]
        elif w in _SHAPE_OF:
            out.objects.append((_SHAPE_OF[w], color, size))
            size = color = None
        k += 1
    rest = tokens[k + 1:]
    if rest:
        phrases, rel, cur = [], None, [None, None]       # cur = [颜色, 形状]
        for w in rest:
            if w in _COLOR_OF:
                cur[0] = _COLOR_OF[w]
            elif w in _SHAPE_OF:
                cur[1] = _SHAPE_OF[w]
                phrases.append(tuple(cur))
                cur = [None, None]
            elif w in RELATION_WORDS and rel is None:
                rel = w
        if len(phrases) == 2 and rel is not None:
            idx = []
            for color, shape in phrases:
                hits = [m for m, (s, c, _) in enumerate(out.objects) if s == shape and (color is None or c == color)]
                idx.append(hits[0] if len(hits) == 1 else None)
            if None not in idx and idx[0] != idx[1]:
                out.relation = (idx[0], rel, idx[1])
    return out


def corrupt_caption(tokens, p, rng):
    """
    文字噪声：每个词独立地以概率 p 被换成词表里一个随机的词（可能恰好换成自己）。

    【参数】tokens：词列表；p：0..1；rng：生成器
    【返回】新的词列表（不修改原列表）
    【边界】无论 p 是多少都抽同样多的随机数，保证不同 p 下"哪些位置被换"是嵌套的、可比较的。
    【多模态联系】文字的噪声是**离散**的：一个词要么对、要么彻底错（"red" 变成 "box"），
        不像像素噪声那样"每个值都偏一点点"。第 1 讲代码 02 比较两者的不同后果。
    """
    u = rng.random(len(tokens))
    repl = rng.integers(len(VOCAB), size=len(tokens))
    return [VOCAB[r] if ui < p else w for w, ui, r in zip(tokens, u, repl)]


# ---------------------------------------------------------------------------
# 模态 3：声音（发声器）
# ---------------------------------------------------------------------------

@dataclass
class Audio:
    """
    发声器发出的一段声音，以及它背后的"真相"。

    【字段】
        signal：一维波形（float64，采样率 SR = 4000）
        onsets / offsets：每个音调的真实开始 / 结束时间（秒），按发声顺序
        order：发声顺序（场景下标）——永远是阅读顺序 0, 1, 2, ...
        tempo：这一次的"语速"（< 1 更快，> 1 更慢）
    """
    signal: np.ndarray
    onsets: list
    offsets: list
    order: list
    tempo: float

    @property
    def duration(self):
        """整段声音有多长（秒）。"""
        return len(self.signal) / SR


def sonify(scene, rng, noise=0.02, tempo_range=(0.85, 1.15)):
    """
    发声器：按阅读顺序，让每个物体发出一声音调。

    【思路】
        音高（频率）由形状决定：圆 300 Hz、方块 420、三角 560、十字 750，再随机跑调 ±2%；
        响度（振幅）由大小决定：小 0.35、大 0.80；
        **颜色不影响声音**——这是故意的：声音和图像之间的"颜色"连接强度是 0（第 1 讲 §4）；
        每个音调时长 0.12 秒 × 语速，音调之间停 0.06 秒 × 语速；开头随机静音 0.03–0.08 秒；
        包络是 sin²（平滑地变响再变轻，避免"咔哒"声）；最后加高斯底噪。
    【参数】scene：Scene；rng：生成器；noise：底噪的标准差；tempo_range：语速的随机范围
    【返回】Audio
    【边界】tempo_range=(1, 1) 时语速固定。和 render_image 一样，参数不同时消耗的随机数个数不变。
    【多模态联系】声音是**时间**结构的连续信号：元素（采样点）极多（每秒 4000 个），
        同一个场景每次"说"的快慢不同——两段声音的对齐需要动态时间规整（DTW，第 7 讲）。
    """
    tempo = rng.uniform(*tempo_range)
    lead = rng.uniform(0.03, 0.08)
    detune = rng.uniform(-0.02, 0.02, size=len(scene))
    dur, gap = TONE_DUR * tempo, GAP_DUR * tempo
    total = lead + len(scene) * dur + (len(scene) - 1) * gap + 0.05
    sig = np.zeros(int(round(total * SR)))
    onsets, offsets = [], []
    t0 = lead
    for k, o in enumerate(scene):
        n0, n1 = int(round(t0 * SR)), int(round((t0 + dur) * SR))
        t = np.arange(n1 - n0) / SR
        env = np.sin(np.pi * t / dur) ** 2
        f = PITCH[o.shape] * (1.0 + detune[k])
        sig[n0:n1] += LOUD[o.size] * env * np.sin(2 * np.pi * f * t)
        onsets.append(n0 / SR)
        offsets.append(n1 / SR)
        t0 += dur + gap
    sig = sig + rng.normal(0.0, 1.0, size=sig.shape) * noise
    return Audio(sig, onsets, offsets, list(range(len(scene))), float(tempo))


FRAME = 40     # 声音解析器的帧长：40 个采样点 = 10 毫秒


def frame_rms(signal, frame=FRAME):
    """
    把波形切成不重叠的短帧，算每一帧的均方根（RMS，"这一小段有多响"）。

    【参数】signal：一维数组；frame：帧长（采样点数）
    【返回】长度为 len(signal) // frame 的数组（末尾不足一帧的部分丢掉）
    【numpy 小知识】reshape(-1, frame) 把一维数组折成"每行 frame 个"的二维数组，−1 表示行数自动算。
    """
    n = len(signal) // frame
    x = signal[: n * frame].reshape(n, frame)
    return np.sqrt((x ** 2).mean(axis=1))


def parse_audio(signal, min_threshold=0.07, min_frames=3):
    """
    理想声音解析器：找出每个音调，读出它的音高（→ 形状）和响度（→ 大小）。

    【思路】
        1. 按 10 毫秒一帧算响度（RMS）。先估计"底噪有多响"：取所有帧响度的第 20 百分位数
           （一段声音里总有约 40% 的时间是停顿，最安静的那些帧基本只有底噪）；
        2. 阈值 = max(min_threshold, 1.4 × 底噪 + 0.03)：底噪越大，阈值越高（"自适应阈值"）。
           响度超过阈值的连续帧就是一个音调（中间允许断 1 帧）；
           作者第一版用固定阈值 0.07，底噪标准差一超过 0.07，整段声音就被当成一个长音调，读对率从 1 掉到 0.33；
        3. 音高：对这一段做傅里叶变换（补零到 4096 点让频率更细），取能量最大的频率，归到最近的形状；
        4. 响度：这一段里最响的一帧的 RMS，先减掉底噪的能量（√(RMS² − 底噪²)），
           超过"小"和"大"中间值的算大。
    【参数】signal：一维波形；min_threshold：阈值的下限；min_frames：最短音调帧数（3 帧 = 30 毫秒）
    【返回】(形状, 大小) 的列表，按时间顺序——声音里**没有颜色、也没有准确的格子位置**
    【边界】底噪很大时会把噪声误判成音调，或者把两个音调粘成一个；整段都是音调、没有停顿时，
        "第 20 百分位数"会高估底噪。
    【numpy 小知识】np.fft.rfft 计算实数信号的傅里叶变换，np.fft.rfftfreq 给出每个分量对应的频率（Hz）；
        np.percentile(x, 20) 是"有 20% 的数比它小"的那个数。
    """
    rms = frame_rms(signal)
    floor = float(np.percentile(rms, 20)) if len(rms) else 0.0
    active = rms > max(min_threshold, 1.4 * floor + 0.03)
    segments, start, silent = [], None, 0
    for k, a in enumerate(active):
        if a:
            if start is None:
                start = k
            silent = 0
        elif start is not None:
            silent += 1
            if silent > 1:
                segments.append((start, k - silent + 1))
                start, silent = None, 0
    if start is not None:
        segments.append((start, len(active) - silent))
    peak_mid = 0.5 * (LOUD[0] + LOUD[1]) / math.sqrt(2.0)   # 正弦波的 RMS = 振幅 / √2
    out = []
    for a, b in segments:
        if b - a < min_frames:
            continue
        seg = signal[a * FRAME: b * FRAME]
        spec = np.abs(np.fft.rfft(seg, n=4096))
        freqs = np.fft.rfftfreq(4096, d=1.0 / SR)
        f = freqs[int(np.argmax(spec))]
        shape = int(np.argmin([abs(f - p) for p in PITCH]))
        peak = math.sqrt(max(float(rms[a:b].max()) ** 2 - floor ** 2, 0.0))
        out.append((shape, int(peak > peak_mid)))
    return out


def audio_envelope_line(audio, width=60):
    """
    把声音的响度包络画成一行字符（终端里的"波形图"）：越响用越"满"的字符。

    【参数】audio：Audio；width：输出多少个字符（整段声音被均匀地分成 width 段）
    【返回】字符串，例如 "  ▂▅█▅▂   ▃▆▆▃  "
    """
    levels = " ▁▂▃▄▅▆▇█"
    rms = frame_rms(audio.signal)
    idx = np.linspace(0, len(rms), width + 1).astype(int)
    vals = [rms[idx[k]:max(idx[k + 1], idx[k] + 1)].max() for k in range(width)]
    return "".join(levels[min(int(v / 0.6 * (len(levels) - 1) + 0.5), len(levels) - 1)] for v in vals)


# ---------------------------------------------------------------------------
# 一个样本 = 一个场景的三种表达
# ---------------------------------------------------------------------------

@dataclass
class Sample:
    """一个样本：同一个场景的图像、文字、声音（以及场景本身——"真相"）。"""
    scene: tuple
    image: np.ndarray
    caption: Caption
    audio: Audio


def make_dataset(n, seed, image_noise=0.05, audio_noise=0.02, speaker=None, n_objects=None,
                 jitter=True, lighting=True, tempo_range=(0.85, 1.15)):
    """
    生成 n 个样本。

    【思路】用 SeedSequence(seed).spawn(4) 造出 4 个**互相独立**的随机数生成器，分别负责
        场景、图像、文字、声音。于是：同一个 seed 下，改图像噪声不会改变场景和文字；
        改说话人的习惯不会改变图像。做"只改一个因素"的对照实验时，这一点必不可少。
    【参数】
        n：样本个数；seed：整数种子
        image_noise / audio_noise：图像 / 声音的噪声标准差
        speaker：Speaker（默认习惯）；n_objects：固定每个场景的物体个数（None 表示按先验随机）
        jitter / lighting / tempo_range：传给相机和发声器
    【返回】Sample 的列表
    【边界】n = 0 时返回空列表。
    """
    s_scene, s_img, s_txt, s_aud = np.random.SeedSequence(seed).spawn(4)
    r_scene, r_img = np.random.default_rng(s_scene), np.random.default_rng(s_img)
    r_txt, r_aud = np.random.default_rng(s_txt), np.random.default_rng(s_aud)
    out = []
    for _ in range(n):
        scene = sample_scene(r_scene, n_objects)
        img = render_image(scene, r_img, noise=image_noise, jitter=jitter, lighting=lighting)
        cap = describe(scene, r_txt, speaker)
        aud = sonify(scene, r_aud, noise=audio_noise, tempo_range=tempo_range)
        out.append(Sample(scene, img, cap, aud))
    return out


# ---------------------------------------------------------------------------
# 评估用：把解析结果和真实物体一一对上
# ---------------------------------------------------------------------------

def read_objects(sample, modality, image=None, tokens=None, signal=None):
    """
    用理想解析器读一个模态，并借助"真相"把读出来的东西和场景里的真实物体一一对上。

    【思路】三个模态"对上号"的方式不同：
        图像：按格子——第 c 个格子里读出的物体，就是真实场景里在格子 c 的那个；
        文字：按提到的顺序——读出的第 k 个名词短语，就是说话人第 k 个提到的物体（caption.order[k]）；
        声音：按时间顺序——听出的第 k 个音调，就是阅读顺序里的第 k 个物体。
        这里用到了真实的对应关系（caption.order、发声顺序），所以它是**评估工具**，不是模型能用的东西：
        它回答的是"假如对应关系已知，这个模态里每个物体的哪些属性读得出来"。
    【参数】
        sample：Sample；modality："image" / "text" / "audio"
        image / tokens / signal：用来代替 sample 里原始数据的版本（例如加了噪声、打乱过的），None 表示用原始的
    【返回】和 sample.scene 等长的列表；第 i 个元素是 dict(shape=, color=, size=, cell=)，
        读不出来的属性是 None；整个物体都没读到时，四个值都是 None
    【边界】解析出的物体比真实的多（噪声造成的假物体）时，多出来的被忽略；少时，缺的记为全 None。
    """
    n = len(sample.scene)
    empty = {"shape": None, "color": None, "size": None, "cell": None}
    out = [dict(empty) for _ in range(n)]
    if modality == "image":
        found = {o.cell: o for o in parse_image(sample.image if image is None else image)}
        for i, o in enumerate(sample.scene):
            if o.cell in found:
                f = found[o.cell]
                out[i] = {"shape": f.shape, "color": f.color, "size": f.size, "cell": f.cell}
    elif modality == "text":
        pc = parse_caption(sample.caption.tokens if tokens is None else tokens)
        for k, i in enumerate(sample.caption.order):
            if k < len(pc.objects):
                s_, c_, z_ = pc.objects[k]
                out[i] = {"shape": s_, "color": c_, "size": z_, "cell": None}
    elif modality == "audio":
        heard = parse_audio(sample.audio.signal if signal is None else signal)
        for i in range(min(n, len(heard))):
            out[i] = {"shape": heard[i][0], "color": None, "size": heard[i][1], "cell": None}
    else:
        raise ValueError(f"未知模态 {modality}")
    return out


# ---------------------------------------------------------------------------
# 简单的特征提取器（给线性模型用；第 3–4 讲会讲真正的"单模态表示"）
# ---------------------------------------------------------------------------

def image_features(img):
    """
    图像的手工特征：每个格子 4 个数——R、G、B 三个通道比背景亮多少（平均），以及"墨水"像素的比例。

    【参数】img：(33, 33, 3) 数组
    【返回】36 维向量（9 个格子 × 4）
    【多模态联系】这是一个**很粗**的表示：它知道"哪个格子里有什么颜色、有多少墨水"，
        但几乎不知道形状——形状藏在像素的空间排列里，平均值把它抹掉了（第 4 讲讲 CNN 怎样保留空间结构）。
    """
    f = []
    for cell in range(N_CELLS):
        r0, c0 = (cell // GRID) * CELL, (cell % GRID) * CELL
        crop = img[r0:r0 + CELL, c0:c0 + CELL]
        d = crop - BG
        f.extend(d.mean(axis=(0, 1)))
        f.append((d.max(axis=2) > 0.30).mean())
    return np.array(f)


def color_mass(img, ink_threshold=0.30):
    """
    每种颜色的墨水像素各有多少个（逐像素归到最近的颜色）——一个"颜色直方图"。

    【参数】img：(33, 33, 3) 数组；ink_threshold：判定墨水的亮度差
    【返回】长度 4 的数组（红、绿、蓝、黄的像素数）
    【多模态联系】它只保留"有多少红色"，扔掉了"红色在哪里、是什么形状"——
        用来做"图里有没有红色物体""颜色词和像素是否一致"这类问题足够了，做别的就不够。
    【numpy 小知识】这里一次处理所有墨水像素（和逐个调用 _classify_color 的结果逐位相同，但快几十倍；
        噪声大时墨水像素很多，逐个循环会很慢）：P[:, None, :] − _RGB_NORM[None] 借助"广播"得到
        (像素数, 4, 3) 的差，平方求和后每行取 argmin 就是最近的颜色；np.bincount 数每种颜色出现几次。
    """
    ink = (img - BG).max(axis=2) > ink_threshold
    P = img[ink]
    if len(P) == 0:
        return np.zeros(4)
    v = P / np.maximum(P.max(axis=1), 1e-9)[:, None]
    nearest = ((v[:, None, :] - _RGB_NORM[None]) ** 2).sum(axis=2).argmin(axis=1)
    return np.bincount(nearest, minlength=4).astype(float)


def bow_features(tokens):
    """
    文字的词袋（bag of words）特征：每个词出现了几次。

    【参数】tokens：词列表（不认识的词忽略）
    【返回】len(VOCAB) 维的计数向量
    【多模态联系】词袋扔掉了词序——"red ball and blue box" 和 "blue ball and red box" 的词袋一模一样。
        哪个颜色属于哪个形状（"绑定"）的信息就丢了（第 1 讲代码 02、05 会看到后果）。
    """
    v = np.zeros(len(VOCAB))
    for w in tokens:
        if w in WORD_ID:
            v[WORD_ID[w]] += 1
    return v


def audio_features(signal):
    """
    声音的手工特征：4 个音高频带各自的能量（对数），加上整体响度和时长。

    【思路】做一次傅里叶变换，把 4 个形状音高附近 ±25 Hz 的能量分别加起来——
        "这段声音里有没有圆的音高、有没有十字的音高……"。时间顺序被丢掉了。
    【参数】signal：一维波形
    【返回】6 维向量
    """
    spec = np.abs(np.fft.rfft(signal, n=8192)) ** 2
    freqs = np.fft.rfftfreq(8192, d=1.0 / SR)
    bands = [np.log(spec[(freqs > p - 25) & (freqs < p + 25)].sum() + 1e-6) for p in PITCH]
    return np.array(bands + [np.log((signal ** 2).mean() + 1e-9), len(signal) / SR])


def compressed_bytes(arr, levels=256):
    """
    把一个 0..1 的数组量化成 8 位整数后用 zlib 压缩，返回压缩后的字节数——"这堆原始数据有多少比特"的粗略上界。

    【参数】arr：数组（取值 0..1）；levels：量化级数（256 = 8 位）
    【返回】int（字节数；乘 8 就是比特数）
    【边界】zlib 是通用压缩器，不懂图像，所以这只是一个上界；噪声几乎不可压缩，会占掉大部分字节。
    """
    q = np.clip(np.round(arr * (levels - 1)), 0, levels - 1).astype(np.uint8)
    return len(zlib.compress(q.tobytes(), 9))


# ---------------------------------------------------------------------------
# 自检
# ---------------------------------------------------------------------------

def _self_test():
    """运行 python3 scene_world.py 时执行：检查先验、解析器和可复现性。"""
    # 1. 先验：所有场景的概率之和 = 1（按物体个数分组求和，不用真的枚举 279 万个场景）
    total = sum(N_OBJ_PROBS[n - 1] for n in (1, 2, 3))
    s = 0.0
    for n in (1, 2, 3):
        s += math.comb(N_CELLS, n) * N_ATTR ** n * 2 ** scene_log2prob(tuple(Obj(0, 0, 0, c) for c in range(n)))
    print(f"先验概率之和 = {s:.12f}（应为 {total:.1f}）；场景总数 {N_SCENES:,}；H(scene) = {scene_entropy_bits():.4f} bit")

    # 2. 解析器在默认噪声下的准确率
    data = make_dataset(300, seed=0)
    img_ok = np.mean([parse_image(d.image) == d.scene for d in data])
    aud_ok = np.mean([parse_audio(d.audio.signal) == [(o.shape, o.size) for o in d.scene] for d in data])
    cap_ok = []
    for d in data:
        pc = parse_caption(d.caption.tokens)
        truth = [(d.scene[i].shape,
                  d.scene[i].color if d.caption.said_color[i] else None,
                  d.scene[i].size if d.caption.said_size[i] else None) for i in d.caption.order]
        cap_ok.append(pc.objects == truth)
    print(f"理想解析器（300 个样本）：图像整场景全对 {img_ok:.3f}，声音（形状 + 大小序列）全对 {aud_ok:.3f}，"
          f"文字（说出的内容）全对 {np.mean(cap_ok):.3f}")

    # 3. 可复现性 + "改一个因素不影响其他模态"
    a = make_dataset(5, seed=1)
    b = make_dataset(5, seed=1, image_noise=0.3)
    same_scene = all(x.scene == y.scene and x.caption.tokens == y.caption.tokens for x, y in zip(a, b))
    print(f"同一种子、只改图像噪声：场景和文字完全相同 = {same_scene}")
    print("词表大小", len(VOCAB), "：", " ".join(VOCAB))


if __name__ == "__main__":
    _self_test()
