{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# S8 lab notebook — redact, predict the endpoint, then call\n",
    "\n",
    "The caption pipeline sends media and text to a managed inference service. Two\n",
    "facts organise this notebook. First, the provider sees what you send, so\n",
    "identifiers and metadata must be gone before the request leaves the laptop.\n",
    "Second, on OpenRouter **the model id is not the data policy**: one model id\n",
    "routes to many provider endpoints, and each endpoint has its own retention\n",
    "terms. The notebook predicts which endpoints satisfy the rule before it sends\n",
    "anything.\n",
    "\n",
    "The shared synthetic pack is `course/assets/synthetic-media/`: 20 EXIF-tagged\n",
    "photos and 100 transcripts with fabricated contact details. Nothing in it is a\n",
    "real person or place.\n",
    "\n",
    "**You submit:** `inference_results.json`, the redaction and EXIF evidence, the\n",
    "endpoint prediction table, the four calls A–D (including the refusal and the\n",
    "ZDR-only retry), the marked trust-boundary map, the six-part rule, the ten-row\n",
    "register with a 200-word residual-risk justification, a 150–250 word *what this\n",
    "proves* note and the teardown log.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "ไปป์ไลน์คำบรรยายภาพส่งสื่อและข้อความไปยังบริการอนุมานแบบจัดการ โน้ตบุ๊กนี้ยึดสองข้อ: ผู้ให้บริการเห็นสิ่งที่ส่งออกไป ดังนั้นต้องลบข้อมูลระบุตัวตนและเมตาดาตาก่อนออกจากแล็ปท็อป และบน OpenRouter ชื่อโมเดลไม่ใช่ข้อกำหนดข้อมูล เพราะโมเดลเดียวเส้นทางไปยังหลาย endpoint ซึ่งแต่ละแห่งมีเงื่อนไขการเก็บรักษาของตัวเอง โน้ตบุ๊กทำนายว่า endpoint ใดตรงกับกฎก่อนส่งคำขอใด ๆ แพ็กสังเคราะห์ใช้ร่วมกับสัปดาห์ที่ 7 ไม่มีบุคคลหรือสถานที่จริง\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "图像描述管道把媒体和文本发送到托管推理服务。本 notebook 坚持两点：提供商能看到发送出去的内容，因此标识符和元数据必须在离开笔记本电脑之前删除；在 OpenRouter 上，模型名称不是数据政策，因为同一个模型会路由到多个 endpoint，而每个 endpoint 都有自己的保留条款。本 notebook 在任何请求发出之前，先预测哪些 endpoint 符合规则。合成数据包与第 7 课共用，其中没有真实的人物或地点。\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import base64\n",
    "import json\n",
    "import os\n",
    "import random\n",
    "import re\n",
    "import sys\n",
    "import urllib.error\n",
    "import urllib.request\n",
    "from pathlib import Path\n",
    "\n",
    "SEED = 42\n",
    "random.seed(SEED)\n",
    "print(\"seed\", SEED)\n",
    "print(\"Python\", sys.version.split()[0])\n",
    "assert sys.version_info >= (3, 11)\n",
    "DEVICE = \"cpu\"\n",
    "print(\"device\", DEVICE, \"(S8 has no local accelerator path)\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "WEEK = next(path for path in [Path.cwd(), *Path.cwd().parents]\n",
    "             if (path / \"redact.py\").exists() and (path / \"data\").is_dir())\n",
    "OUT = Path(os.environ.get(\"S8_OUT\", \".\"))\n",
    "OUT.mkdir(parents=True, exist_ok=True)\n",
    "sys.path.insert(0, str(WEEK))\n",
    "\n",
    "from redact import contains_pii, exif_gps, exif_tags, load_people, redact_text, strip_exif\n",
    "\n",
    "\n",
    "def week_data():\n",
    "    candidates = [WEEK / \"data\", Path(\"/kaggle/input/sensitive-data-managed-ai\")]\n",
    "    env = os.environ.get(\"COURSE_DATA\")\n",
    "    if env:\n",
    "        candidates.append(Path(env))\n",
    "    required = [\"governance-rule.json\", \"canned-inference.json\", \"register.json\",\n",
    "                \"endpoints-deepseek.json\", \"endpoints-gemini.json\", \"endpoints-zdr.json\"]\n",
    "    for path in candidates:\n",
    "        if path and all((path / name).exists() for name in required):\n",
    "            return path\n",
    "    raise FileNotFoundError(\"put the S8 data files in data/\")\n",
    "\n",
    "\n",
    "def pack_dir():\n",
    "    candidates = [WEEK / \"../../assets/synthetic-media\",\n",
    "                  Path(\"/kaggle/input/synthetic-media\")]\n",
    "    env = os.environ.get(\"COURSE_DATA\")\n",
    "    if env:\n",
    "        candidates.extend([Path(env) / \"synthetic-media\", Path(env)])\n",
    "    for path in candidates:\n",
    "        if path and (path / \"manifest.json\").exists() and (path / \"transcripts-100.jsonl\").exists():\n",
    "            return path.resolve()\n",
    "    raise FileNotFoundError(\"synthetic-media pack not found; mount it or set COURSE_DATA\")\n",
    "\n",
    "\n",
    "DATA = week_data()\n",
    "PACK = pack_dir()\n",
    "rule = json.loads((DATA / \"governance-rule.json\").read_text())\n",
    "canned = json.loads((DATA / \"canned-inference.json\").read_text())\n",
    "register = json.loads((DATA / \"register.json\").read_text())\n",
    "meta = json.loads((DATA / \"snapshot-meta.json\").read_text())\n",
    "people = load_people(PACK)\n",
    "manifest = json.loads((PACK / \"manifest.json\").read_text())\n",
    "\n",
    "\n",
    "SNAPSHOT_DIR = Path(os.environ.get(\"S8_SNAPSHOT_DIR\", DATA))\n",
    "\n",
    "\n",
    "def load_snapshot(name):\n",
    "    raw = json.loads((SNAPSHOT_DIR / name).read_text())\n",
    "    if \"payload\" in raw:\n",
    "        return raw[\"retrieved\"], raw[\"payload\"][\"data\"], \"shipped\"\n",
    "    retrieved = os.environ.get(\"S8_SNAPSHOT_DATE\")\n",
    "    if isinstance(raw, dict) and \"data\" in raw:\n",
    "        return retrieved, raw[\"data\"], \"refreshed\"\n",
    "    return retrieved, raw, \"refreshed\"\n",
    "\n",
    "\n",
    "zdr_date, zdr, snapshot_source = load_snapshot(\"endpoints-zdr.json\")\n",
    "ds_date, ds, _ = load_snapshot(\"endpoints-deepseek.json\")\n",
    "gem_date, gem, _ = load_snapshot(\"endpoints-gemini.json\")\n",
    "DS_ID = \"deepseek/deepseek-v4.1-flash-1017\"\n",
    "GEM_ID = \"google/gemini-4-hydrogen\"\n",
    "assert ds[\"id\"] == DS_ID and gem[\"id\"] == GEM_ID\n",
    "if snapshot_source == \"shipped\":\n",
    "    assert zdr_date == ds_date == gem_date == meta[\"retrieved\"]\n",
    "snapshot_date = zdr_date or meta[\"retrieved\"]\n",
    "\n",
    "print(\"data\", DATA)\n",
    "print(\"pack\", PACK, manifest[\"pack\"], len(manifest[\"files\"]), \"entries\")\n",
    "print(\"snapshot\", snapshot_date, \"(\" + snapshot_source + \")\", \"ZDR catalogue\", meta[\"zdr_catalogue_endpoints\"], \"endpoints;\", len(zdr), \"rows for the two models\")\n",
    "assert manifest[\"pack\"] == \"synthetic-media-s7-s8\"\n",
    "assert len(people) == 10\n",
    "assert len(register[\"rows\"]) == 10"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 1 — predict which endpoints satisfy the rule\n",
    "\n",
    "`GET /api/v1/models/{id}/endpoints` lists every provider endpoint for a model.\n",
    "`GET /api/v1/endpoints/zdr` lists the endpoints that meet zero-data-retention\n",
    "terms, and each row carries `safety_retention`. Join the two on the endpoint\n",
    "`tag`: the join is the prediction. Do it before any call, so the rule chooses\n",
    "the endpoint rather than the dashboard choosing it for you.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "`GET /api/v1/models/{id}/endpoints` แสดง endpoint ของผู้ให้บริการทั้งหมดของโมเดล ส่วน `GET /api/v1/endpoints/zdr` แสดง endpoint ที่เข้าเงื่อนไขไม่เก็บข้อมูล และมีฟิลด์ `safety_retention` การเชื่อมสองรายการด้วย `tag` คือการทำนาย ต้องทำก่อนเรียกใด ๆ เพื่อให้กฎเลือก endpoint ไม่ใช่แดชบอร์ดเลือกให้\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "`GET /api/v1/models/{id}/endpoints` 列出某个模型的所有提供商 endpoint，而 `GET /api/v1/endpoints/zdr` 列出符合零数据保留条件的 endpoint，并带有 `safety_retention` 字段。用 `tag` 把这两份列表连接起来就是预测。必须在任何调用之前完成，这样是规则选择 endpoint，而不是由仪表板替你选择。\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def endpoint_table(model):\n",
    "    rows = model[\"endpoints\"]\n",
    "    zrows = [row for row in zdr if row[\"model_id\"] == model[\"id\"]]\n",
    "    by_tag = {row[\"tag\"]: row for row in zrows}\n",
    "    table = []\n",
    "    for row in sorted(rows, key=lambda item: float(item[\"pricing\"][\"prompt\"])):\n",
    "        eligible = by_tag.get(row[\"tag\"])\n",
    "        table.append({\n",
    "            \"provider\": row[\"provider_name\"],\n",
    "            \"tag\": row[\"tag\"],\n",
    "            \"prompt_per_m\": round(float(row[\"pricing\"][\"prompt\"]) * 1_000_000, 4),\n",
    "            \"completion_per_m\": round(float(row[\"pricing\"][\"completion\"]) * 1_000_000, 4),\n",
    "            \"status\": row[\"status\"],\n",
    "            \"zdr\": eligible is not None,\n",
    "            \"safety_retention\": None if eligible is None else eligible.get(\"safety_retention\"),\n",
    "        })\n",
    "    return zrows, table\n",
    "\n",
    "\n",
    "ds_zdr, ds_table = endpoint_table(ds)\n",
    "gem_zdr, gem_table = endpoint_table(gem)\n",
    "\n",
    "for label, table in ((\"DeepSeek\", ds_table), (\"Gemini\", gem_table)):\n",
    "    print(f\"\\n{label}: {len(table)} endpoints, {sum(row['zdr'] for row in table)} ZDR\")\n",
    "    for row in table:\n",
    "        print(f\"  {row['provider']:18} {row['tag']:28} ${row['prompt_per_m']:6.2f}/M \"\n",
    "              f\"zdr={row['zdr']!s:5} safety={row['safety_retention']}\")\n",
    "\n",
    "ds_excluded = [row for row in ds_table if not row[\"zdr\"]]\n",
    "gem_excluded = [row for row in gem_table if not row[\"zdr\"]]\n",
    "assert len(ds_table) == 48 and len(ds_zdr) == 42 and len(ds_excluded) == 6\n",
    "assert len(gem_table) == 7 and len(gem_zdr) == 4 and len(gem_excluded) == 3\n",
    "assert all(row[\"safety_retention\"] is False for row in ds_zdr)\n",
    "assert all(row[\"safety_retention\"] is True for row in gem_zdr)\n",
    "assert all(row[\"tag\"].startswith(\"google-vertex\") for row in gem_zdr)\n",
    "assert \"deepseek\" not in {row[\"tag\"] for row in ds_zdr}\n",
    "assert {row[\"provider\"] for row in gem_excluded} == {\"Google AI Studio\"}\n",
    "\n",
    "cheapest = next(row for row in ds_table if row[\"zdr\"] and row[\"status\"] == 0)\n",
    "predictions = {\n",
    "    \"retrieved\": snapshot_date,\n",
    "    \"zdr_catalogue_endpoints\": meta[\"zdr_catalogue_endpoints\"],\n",
    "    \"models\": {\n",
    "        \"deepseek\": {\"model\": DS_ID, \"all\": len(ds_table), \"zdr\": len(ds_zdr),\n",
    "                     \"excluded\": [row[\"provider\"] for row in ds_excluded],\n",
    "                     \"safety_retention_on_zdr\": sorted({row[\"safety_retention\"] for row in ds_zdr}),\n",
    "                     \"cheapest_zdr\": cheapest},\n",
    "        \"gemini\": {\"model\": GEM_ID, \"all\": len(gem_table), \"zdr\": len(gem_zdr),\n",
    "                   \"excluded\": [row[\"provider\"] for row in gem_excluded],\n",
    "                   \"safety_retention_on_zdr\": sorted({row[\"safety_retention\"] for row in gem_zdr})},\n",
    "    },\n",
    "}\n",
    "print(\"\\nprediction: DeepSeek first-party excluded;\", len(ds_zdr), \"ZDR endpoints remain\")\n",
    "print(\"prediction: every Gemini ZDR endpoint is Safety Retention; ZDR-only removes the model\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 2 — redact the 100 transcripts\n",
    "\n",
    "The pack's rows contain fabricated names, emails, phone numbers and student\n",
    "IDs. Redaction removes direct identifiers before the prompt is built. It is a\n",
    "control, not anonymisation: context can still identify someone, which is why\n",
    "the rule also limits what may be sent and where.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "แถวในแพ็กมีชื่อ อีเมล เบอร์โทร และรหัสนักศึกษาที่สร้างขึ้น การปิดข้อมูลลบตัวระบุโดยตรงก่อนสร้างพรอมต์ เป็นมาตรการควบคุม ไม่ใช่การทำให้ไม่ระบุตัวตน เพราะบริบทยังระบุตัวตนได้ กฎจึงจำกัดสิ่งที่ส่งได้และสถานที่ปลายทางด้วย\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "数据包中的行包含虚构的姓名、电子邮件、电话号码和学号。脱敏在构建 prompt（提示词）之前删除直接标识符。它是一种控制措施，而不是匿名化，因为上下文仍然可以识别出个人，所以规则也限制可以发送的内容和目的地。\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "transcripts = [json.loads(line) for line in\n",
    "               (PACK / \"transcripts-100.jsonl\").read_text().splitlines() if line.strip()]\n",
    "assert len(transcripts) == 100\n",
    "\n",
    "pii_before = sum(contains_pii(row[\"text\"], people) for row in transcripts)\n",
    "redacted = [{**row, \"text\": redact_text(row[\"text\"], people)} for row in transcripts]\n",
    "pii_after = sum(contains_pii(row[\"text\"], people) for row in redacted)\n",
    "\n",
    "(OUT / \"redacted-transcripts.jsonl\").write_text(\n",
    "    \"\\n\".join(json.dumps(row, ensure_ascii=False) for row in redacted) + \"\\n\")\n",
    "print(\"before:\", transcripts[0][\"text\"])\n",
    "print(\"after: \", redacted[0][\"text\"])\n",
    "print(\"rows with PII before\", pii_before, \"after\", pii_after)\n",
    "assert pii_before == 100\n",
    "assert pii_after == 0\n",
    "assert all(\"[\" in row[\"text\"] for row in redacted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 3 — strip EXIF from all 20 photos\n",
    "\n",
    "Each photo carries fabricated GPS, device and timestamp fields. The metadata is\n",
    "not part of the pixels, but it travels with the file unless the pipeline removes\n",
    "it. Strip every image you might send, not only the one you test with.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "ภาพทุกภาพมีพิกัด GPS อุปกรณ์ และเวลาที่สร้างขึ้น ข้อมูลเมตาไม่ใช่ส่วนของพิกเซล แต่เดินทางไปกับไฟล์หากไปป์ไลน์ไม่ลบ ต้องลบทุกภาพที่อาจส่ง ไม่ใช่เพียงภาพทดสอบ\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "每一张照片都有 GPS 坐标、设备和创建时间。元数据不是像素的一部分，但如果管道不删除，它就会随文件一起传播。必须删除每一张可能发送的照片，而不只是测试用的那一张。\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "photos = sorted(PACK.glob(\"photo-*.jpg\"))\n",
    "assert len(photos) == 20\n",
    "photos_out = OUT / \"photos\"\n",
    "photos_out.mkdir(parents=True, exist_ok=True)\n",
    "gps_before = gps_after = tags_before = tags_after = 0\n",
    "for photo in photos:\n",
    "    gps_before += bool(exif_gps(photo))\n",
    "    tags_before += exif_tags(photo)\n",
    "    clean = strip_exif(photo, photos_out / photo.name.replace(\".jpg\", \".stripped.jpg\"))\n",
    "    gps_after += bool(exif_gps(clean))\n",
    "    tags_after += exif_tags(clean)\n",
    "\n",
    "print(\"GPS present before\", gps_before, \"after\", gps_after)\n",
    "print(\"EXIF tags before\", tags_before, \"after\", tags_after)\n",
    "assert gps_before == 20 and gps_after == 0\n",
    "assert tags_before > 0 and tags_after == 0\n",
    "(OUT / \"exif-report.json\").write_text(json.dumps({\n",
    "    \"photos\": len(photos), \"gps_before\": gps_before, \"gps_after\": gps_after,\n",
    "    \"exif_tags_before\": tags_before, \"exif_tags_after\": tags_after}, indent=2) + \"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 4 — make the rule executable\n",
    "\n",
    "The rule has six parts. Parts 1 and 2 decide what may be sent and what must be\n",
    "removed; part 3 decides **which endpoint** may serve the call; parts 4–6 decide\n",
    "where it may go, how long it may stay and who reviews. A request is allowed only\n",
    "when every part holds. The cases below include the two that matter most: the\n",
    "maker's own endpoint is not in the ZDR list, and ZDR-only fails closed when every\n",
    "eligible endpoint has a safety-retention carve-out.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "กฎมีหกส่วน ส่วนที่ 1 และ 2 กำหนดสิ่งที่ส่งได้และสิ่งที่ต้องลบ ส่วนที่ 3 กำหนดว่า endpoint ใดให้บริการได้ ส่วนที่ 4–6 กำหนดสถานที่ ระยะเวลาเก็บ และผู้ตรวจสอบ คำขอจะผ่านได้เมื่อทุกส่วนเป็นจริง กรณีสำคัญคือ endpoint ของผู้ผลิตเองไม่อยู่ในรายการ ZDR และโหมด ZDR-only จะปิดเมื่อทุก endpoint ที่เหลือมีข้อยกเว้น safety retention\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "规则有六个部分。第 1 和第 2 部分规定可以发送什么、必须删除什么；第 3 部分规定哪个 endpoint 可以提供服务；第 4–6 部分规定目的地、保留时长和审核人。只有当每个部分都成立时，请求才能通过。最重要的案例是：制造商自己的 endpoint 不在 ZDR 列表中，而当所有剩余 endpoint 都有 safety retention 例外时，ZDR-only 模式会关闭。\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def decide(data_class, synthetic, redacted_ok, stripped_ok, endpoint,\n",
    "           request_zdr=True, account_zdr_only=False):\n",
    "    if data_class in {\"personal\", \"sensitive\"} and not synthetic:\n",
    "        return \"block\", \"real personal or sensitive data is never sent\"\n",
    "    if data_class not in {\"public\", \"internal\", \"personal\", \"sensitive\"}:\n",
    "        return \"block\", \"unknown data class\"\n",
    "    if data_class in {\"personal\", \"sensitive\"} and not (redacted_ok and stripped_ok):\n",
    "        return \"block\", \"identifiers or metadata still present\"\n",
    "    if endpoint[\"status\"] != 0:\n",
    "        return \"block\", \"endpoint is not healthy\"\n",
    "    if request_zdr and not endpoint[\"zdr\"]:\n",
    "        return \"block\", \"endpoint is not in the ZDR list\"\n",
    "    if account_zdr_only and endpoint[\"safety_retention\"]:\n",
    "        return \"block\", \"ZDR-only excludes safety retention\"\n",
    "    if data_class in {\"personal\", \"sensitive\"} and not synthetic and endpoint[\"safety_retention\"]:\n",
    "        return \"block\", \"safety retention is not allowed for real personal or sensitive data\"\n",
    "    return \"allow\", \"all six parts satisfied\"\n",
    "\n",
    "\n",
    "ds_first_party = next(row for row in ds_table if row[\"tag\"] == \"deepseek\")\n",
    "ds_clean = next(row for row in ds_table if row[\"tag\"] == \"digitalocean\")\n",
    "gem_vertex = next(row for row in gem_table if row[\"tag\"] == \"google-vertex/global\")\n",
    "cases = [\n",
    "    (\"sensitive\", False, False, False, ds_clean, True, False, \"block\"),\n",
    "    (\"sensitive\", True, False, False, ds_clean, True, False, \"block\"),\n",
    "    (\"sensitive\", True, True, True, ds_first_party, True, False, \"block\"),\n",
    "    (\"sensitive\", True, True, True, ds_clean, True, False, \"allow\"),\n",
    "    (\"sensitive\", True, True, True, gem_vertex, True, False, \"allow\"),\n",
    "    (\"sensitive\", True, True, True, gem_vertex, True, True, \"block\"),\n",
    "    (\"internal\", False, False, False, ds_clean, True, False, \"allow\"),\n",
    "    (\"sensitive\", True, True, True, ds_clean, True, True, \"allow\"),\n",
    "]\n",
    "decisions = []\n",
    "for data_class, synthetic, red, strip, endpoint, request_zdr, zdronly, expected in cases:\n",
    "    result, reason = decide(data_class, synthetic, red, strip, endpoint, request_zdr, zdronly)\n",
    "    decisions.append({\"class\": data_class, \"synthetic\": synthetic, \"redacted\": red,\n",
    "                      \"stripped\": strip, \"endpoint\": endpoint[\"tag\"],\n",
    "                      \"account_zdr_only\": zdronly, \"decision\": result, \"reason\": reason})\n",
    "    print(data_class, \"synthetic\" if synthetic else \"real\", \"redacted\" if red else \"-\",\n",
    "          \"stripped\" if strip else \"-\", endpoint[\"tag\"], \"zdr_only\" if zdronly else \"default\",\n",
    "          \"->\", result, \"-\", reason)\n",
    "    assert result == expected\n",
    "\n",
    "asset_decisions = [decide(\"sensitive\", True, True, True, ds_clean, True, False)[0] for _ in redacted]\n",
    "assert all(result == \"allow\" for result in asset_decisions)\n",
    "print(\"redacted synthetic transcripts allowed\", len(asset_decisions))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 5 — the four calls\n",
    "\n",
    "The calls are the experiment, not the conclusion. **A** sends an unredacted\n",
    "synthetic line to DeepSeek's first-party endpoint and records that the provider\n",
    "saw it. **B** sends the same request with the policy enforced: the endpoint is\n",
    "excluded from ZDR, so the request is refused before it leaves. **C** sends the\n",
    "redacted prompt and the stripped image with no provider pinned; the serving\n",
    "endpoint must be one of the ZDR rows. **D** repeats C on Gemini and lands on\n",
    "Vertex, whose ZDR has `safety_retention: true`; under ZDR-only that route\n",
    "disappears and the call fails closed.\n",
    "\n",
    "The notebook runs offline against `canned-inference.json` by default. A live run\n",
    "needs `OPENROUTER_LIVE=1` and `OPENROUTER_API_KEY`. The ZDR-only retry needs the\n",
    "account toggle; when it is not applied in this run, the canned pair is used and\n",
    "the artifact says so.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "การเรียกทั้งสี่คือการทดลอง A ส่งข้อความสังเคราะห์ที่ยังไม่ปิดข้อมูลไปยัง endpoint ของ DeepSeek โดยตรง และบันทึกว่าผู้ให้บริการเห็น B ส่งคำขอเดิมโดยบังคับนโยบาย และถูกปฏิเสธก่อนออกจากเครื่อง C ส่งพรอมต์ที่ปิดข้อมูลและภาพที่ลบ EXIF โดยไม่ระบุผู้ให้บริการ และ endpoint ที่ให้บริการต้องอยู่ในรายการ ZDR D ทำซ้ำบน Gemini และไปยัง Vertex ซึ่ง ZDR มี safety_retention=true ภายใต้โหมด ZDR-only เส้นทางนี้หายไปและคำขอถูกปิด โน้ตบุ๊กทำงานออฟไลน์ด้วย canned-inference.json เป็นค่าเริ่มต้น การเรียกจริงต้องตั้ง OPENROUTER_LIVE=1 และ OPENROUTER_API_KEY\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "四次调用就是实验。A 把尚未脱敏的合成文本直接发送到 DeepSeek 的 endpoint，并记录提供商看到了它。B 强制实施策略发送同样的请求，请求在离开机器之前被拒绝。C 发送经过脱敏的提示词和已删除 EXIF 的照片，不指定提供商，提供服务的 endpoint 必须位于 ZDR 列表中。D 在 Gemini 上重复该请求并到达 Vertex，其 ZDR 带有 safety_retention=true；在 ZDR-only 模式下，这条路径消失，请求被关闭。本 notebook 默认使用 canned-inference.json 离线运行。真实调用需要设置 OPENROUTER_LIVE=1 和 OPENROUTER_API_KEY。\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "LIVE = os.environ.get(\"OPENROUTER_LIVE\") == \"1\" and bool(os.environ.get(\"OPENROUTER_API_KEY\"))\n",
    "ZDR_ONLY_LIVE = os.environ.get(\"OPENROUTER_ZDR_ONLY\") == \"1\"\n",
    "API = \"https://openrouter.ai/api/v1/chat/completions\"\n",
    "print(\"live mode\", LIVE, \"| ZDR-only live\", ZDR_ONLY_LIVE)\n",
    "\n",
    "raw_prompt = transcripts[0][\"text\"]\n",
    "assert contains_pii(raw_prompt, people)\n",
    "clean_prompt = (\"Describe this redacted caption request in one sentence. \"\n",
    "                \"Do not include names, places or identifiers.\")\n",
    "image_path = photos_out / \"photo-01.stripped.jpg\"\n",
    "image_b64 = base64.b64encode(image_path.read_bytes()).decode()\n",
    "\n",
    "\n",
    "def post(payload):\n",
    "    request = urllib.request.Request(\n",
    "        API, data=json.dumps(payload).encode(),\n",
    "        headers={\"Authorization\": f\"Bearer {os.environ['OPENROUTER_API_KEY']}\",\n",
    "                 \"Content-Type\": \"application/json\"})\n",
    "    try:\n",
    "        with urllib.request.urlopen(request, timeout=90) as response:\n",
    "            return response.status, json.loads(response.read() or b\"{}\")\n",
    "    except urllib.error.HTTPError as error:\n",
    "        return error.code, json.loads(error.read() or b\"{}\")\n",
    "\n",
    "\n",
    "def provider_key(name):\n",
    "    return re.sub(r\"[^a-z0-9]\", \"\", (name or \"\").lower())\n",
    "\n",
    "\n",
    "def serving_meta(model_id, body):\n",
    "    provider = body.get(\"provider\")\n",
    "    zrows = [row for row in zdr if row[\"model_id\"] == model_id]\n",
    "    matches = [row for row in zrows if provider_key(row[\"provider_name\"]) == provider_key(provider)]\n",
    "    if not matches:\n",
    "        source = ds if model_id == DS_ID else gem\n",
    "        matches = [row for row in source[\"endpoints\"]\n",
    "                   if provider_key(row[\"provider_name\"]) == provider_key(provider)]\n",
    "    tags = sorted({row[\"tag\"] for row in matches})\n",
    "    safety = {bool(row[\"safety_retention\"]) for row in matches if \"safety_retention\" in row}\n",
    "    return (provider, tags[0] if len(tags) == 1 else None,\n",
    "            next(iter(safety)) if len(safety) == 1 else None,\n",
    "            matches[0] if matches else None, tags)\n",
    "\n",
    "\n",
    "def price_row(model_id, tag, provider):\n",
    "    source = ds if model_id == DS_ID else gem\n",
    "    row = next((item for item in source[\"endpoints\"] if tag and item[\"tag\"] == tag), None)\n",
    "    if row is None:\n",
    "        row = next((item for item in source[\"endpoints\"]\n",
    "                    if item[\"provider_name\"] == provider), None)\n",
    "    return row\n",
    "\n",
    "\n",
    "def cost_of(usage, row):\n",
    "    if row is None:\n",
    "        return 0.0\n",
    "    return round(usage.get(\"prompt_tokens\", 0) * float(row[\"pricing\"][\"prompt\"])\n",
    "                 + usage.get(\"completion_tokens\", 0) * float(row[\"pricing\"][\"completion\"]), 8)\n",
    "\n",
    "\n",
    "def live_call(label, model_id, messages, controls):\n",
    "    payload = {\"model\": model_id, \"messages\": messages, \"max_tokens\": 1200,\n",
    "               \"temperature\": 0.2, \"provider\": controls}\n",
    "    status, body = post(payload)\n",
    "    provider, tag, safety, row, tags = serving_meta(model_id, body)\n",
    "    finish_reason = (body.get(\"choices\") or [{}])[0].get(\"finish_reason\")\n",
    "    usage = body.get(\"usage\") or {}\n",
    "    output = None\n",
    "    if status == 200:\n",
    "        output = (body.get(\"choices\") or [{}])[0].get(\"message\", {}).get(\"content\")\n",
    "    error = None\n",
    "    if status != 200:\n",
    "        error = (body.get(\"error\") or {}).get(\"message\") or json.dumps(body)[:300]\n",
    "    return {\"label\": label, \"model\": model_id, \"request_controls\": controls,\n",
    "            \"status\": status, \"serving_provider\": provider, \"serving_tag\": tag,\n",
    "            \"candidate_tags\": tags, \"safety_retention\": safety,\n",
    "            \"output\": output, \"error\": error, \"finish_reason\": finish_reason,\n",
    "            \"echoed_identifier\": bool(output and any(p[\"name\"] in output for p in people)),\n",
    "            \"usage\": {\"prompt_tokens\": usage.get(\"prompt_tokens\", 0),\n",
    "                      \"completion_tokens\": usage.get(\"completion_tokens\", 0),\n",
    "                      \"total_tokens\": usage.get(\"total_tokens\", 0)},\n",
    "            \"cost_usd\": cost_of(usage, row),\n",
    "            \"reported_cost_usd\": usage.get(\"cost\"), \"source\": \"live\"}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "controls_a = {\"only\": [\"deepseek\"], \"allow_fallbacks\": False}\n",
    "controls_b = {\"only\": [\"deepseek\"], \"zdr\": True, \"data_collection\": \"deny\",\n",
    "              \"allow_fallbacks\": False}\n",
    "controls_c = {\"zdr\": True, \"data_collection\": \"deny\", \"allow_fallbacks\": False}\n",
    "messages_a = [{\"role\": \"user\", \"content\": raw_prompt}]\n",
    "messages_c = [{\"role\": \"user\", \"content\": [\n",
    "    {\"type\": \"text\", \"text\": clean_prompt},\n",
    "    {\"type\": \"image_url\", \"image_url\": {\"url\": f\"data:image/jpeg;base64,{image_b64}\"}},\n",
    "]}]\n",
    "\n",
    "canned_calls = canned[\"calls\"]\n",
    "if LIVE and ZDR_ONLY_LIVE:\n",
    "    prior_path = OUT / \"inference_results.json\"\n",
    "    assert prior_path.exists(), \"run the default live pass before the ZDR-only retry\"\n",
    "    prior = json.loads(prior_path.read_text())\n",
    "    assert prior[\"mode\"] == \"live\", \"the ZDR-only retry needs a live default pass\"\n",
    "    assert prior[\"calls\"][\"D\"][\"status\"] == 200, \"the default Gemini call did not succeed\"\n",
    "    calls = {name: prior[\"calls\"][name] for name in (\"A\", \"B\", \"C\", \"D\")}\n",
    "    calls[\"C_zdr_only\"] = live_call(\"C under ZDR-only\", DS_ID, messages_c, controls_c)\n",
    "    calls[\"C_zdr_only\"][\"request_controls\"] = {**controls_c, \"account_zdr_only\": True}\n",
    "    calls[\"D_zdr_only\"] = live_call(\"D under ZDR-only\", GEM_ID, messages_c, controls_c)\n",
    "    calls[\"D_zdr_only\"][\"request_controls\"] = {**controls_c, \"account_zdr_only\": True}\n",
    "    zdr_only_source = \"live\"\n",
    "elif LIVE:\n",
    "    calls = {\n",
    "        \"A\": live_call(\"A\", DS_ID, messages_a, controls_a),\n",
    "        \"B\": live_call(\"B\", DS_ID, messages_a, controls_b),\n",
    "        \"C\": live_call(\"C\", DS_ID, messages_c, controls_c),\n",
    "        \"D\": live_call(\"D\", GEM_ID, messages_c, controls_c),\n",
    "    }\n",
    "    calls[\"C_zdr_only\"] = {**canned_calls[\"C_zdr_only\"], \"source\": \"canned\",\n",
    "                           \"reported_cost_usd\": canned_calls[\"C_zdr_only\"][\"cost_usd\"]}\n",
    "    calls[\"D_zdr_only\"] = {**canned_calls[\"D_zdr_only\"], \"source\": \"canned\",\n",
    "                           \"reported_cost_usd\": canned_calls[\"D_zdr_only\"][\"cost_usd\"]}\n",
    "    zdr_only_source = \"canned (toggle not applied in this run)\"\n",
    "else:\n",
    "    calls = {name: {**canned_calls[name], \"source\": \"canned\",\n",
    "                    \"reported_cost_usd\": canned_calls[name][\"cost_usd\"]}\n",
    "             for name in (\"A\", \"B\", \"C\", \"D\", \"C_zdr_only\", \"D_zdr_only\")}\n",
    "    zdr_only_source = \"canned\"\n",
    "\n",
    "for name, call in calls.items():\n",
    "    print(f\"{name:12} status={call['status']} provider={call['serving_provider']} \"\n",
    "          f\"tag={call['serving_tag']} safety={call['safety_retention']} \"\n",
    "          f\"echoed={call['echoed_identifier']} cost=${call['cost_usd']:.8f}\")\n",
    "    if call[\"error\"]:\n",
    "        print(\" \" * 13, \"error:\", call[\"error\"])\n",
    "\n",
    "ds_zdr_providers = {provider_key(row[\"provider_name\"]) for row in ds_zdr}\n",
    "assert calls[\"A\"][\"status\"] == 200\n",
    "assert 400 <= calls[\"B\"][\"status\"] < 500\n",
    "assert calls[\"C\"][\"status\"] == 200\n",
    "assert provider_key(calls[\"C\"][\"serving_provider\"]) in ds_zdr_providers\n",
    "assert calls[\"D\"][\"status\"] == 200\n",
    "assert \"google\" in provider_key(calls[\"D\"][\"serving_provider\"])\n",
    "assert calls[\"D\"][\"safety_retention\"] is True\n",
    "assert calls[\"C_zdr_only\"][\"status\"] == 200\n",
    "assert provider_key(calls[\"C_zdr_only\"][\"serving_provider\"]) in ds_zdr_providers\n",
    "assert 400 <= calls[\"D_zdr_only\"][\"status\"] < 500"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 6 — price the calls\n",
    "\n",
    "The response `usage` multiplied by the serving endpoint's price is the actual\n",
    "cost. The four calls plus the ZDR-only retry must stay under the $0.10 lab\n",
    "ceiling. The separate $10 top-up and its 5.5% purchase fee are the account\n",
    "cost, not lab spend.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "ค่าใช้จ่ายจริงคือ `usage` ในคำตอบคูณราคาของ endpoint ที่ให้บริการ การเรียกสี่ครั้งบวกการลองใหม่ในโหมด ZDR-only ต้องต่ำกว่าเพดานห้องแล็บ $0.10 ส่วนการเติมเงิน $10 และค่าธรรมเนียม 5.5% เป็นต้นทุนบัญชี ไม่ใช่ค่าใช้จ่ายของแล็บ\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "实际成本是响应中的 `usage` 乘以提供服务的 endpoint 的价格。四次调用加上 ZDR-only 模式下的重试必须低于 $0.10 的实验上限。另计的 $10 充值和 5.5% 的手续费是账号成本，而不是实验支出。\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "CEILING_USD = 0.10\n",
    "estimated_cost = round(sum(call[\"cost_usd\"] for call in calls.values()), 8)\n",
    "reported_cost = round(sum(call[\"reported_cost_usd\"] if call.get(\"reported_cost_usd\") is not None\n",
    "                         else call[\"cost_usd\"] for call in calls.values()), 8)\n",
    "total_cost = reported_cost\n",
    "print(\"total call cost $\", total_cost, \"(estimated $\", estimated_cost, \") ceiling $\", CEILING_USD)\n",
    "assert total_cost <= CEILING_USD\n",
    "assert estimated_cost <= CEILING_USD\n",
    "assert calls[\"B\"][\"cost_usd\"] == 0 and calls[\"D_zdr_only\"][\"cost_usd\"] == 0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 7 — score the ten-row register\n",
    "\n",
    "R01–R05 come from S7 and name the R2 vault, the DigitalOcean tokens, SSH\n",
    "custody, the presigned URL and the Worker signing key. R06–R10 are the\n",
    "inference and compliance rows added here. The notebook checks the vocabulary,\n",
    "confirms each residual score is no higher than its inherent score, and ranks the\n",
    "rows so the two highest residual risks are the ones you justify in writing.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "R01–R05 มาจากสัปดาห์ที่ 7 และกล่าวถึง R2 vault, โทเค็น DigitalOcean, การดูแลกุญแจ SSH, presigned URL และกุญแจลงนามของ Worker ส่วน R06–R10 เป็นแถวการอนุมานและการปฏิบัติตามกฎที่เพิ่มที่นี่ โน้ตบุ๊กตรวจคำศัพท์ ยืนยันว่าคะแนนคงเหลือไม่สูงกว่าคะแนนเริ่มต้น และจัดอันดับเพื่อให้ความเสี่ยงคงเหลือสองอันดับแรกเป็นอันที่ต้องเขียนชี้แจง\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "R01–R05 来自第 7 课，涉及 R2 vault、DigitalOcean token、SSH 密钥保管、presigned URL 和 Worker 的签名密钥。R06–R10 是这里新增的推理与合规行。本 notebook 检查词汇表，确认每个剩余分数不高于初始分数，并进行排名，使剩余风险最高的两行就是需要书面说明的那些。\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ALLOWED_CLASSES = {\"public\", \"internal\", \"personal\", \"sensitive\"}\n",
    "ALLOWED_TREATMENTS = {\"avoid\", \"mitigate\", \"transfer\", \"accept\"}\n",
    "ALLOWED_OWNERS = {\"provider\", \"customer\", \"shared\"}\n",
    "\n",
    "rows = register[\"rows\"]\n",
    "assert len(rows) == 10\n",
    "assert [row[\"id\"] for row in rows] == [f\"R{index:02d}\" for index in range(1, 11)]\n",
    "scored = []\n",
    "for row in rows:\n",
    "    assert row[\"data_class\"] in ALLOWED_CLASSES\n",
    "    assert row[\"treatment\"] in ALLOWED_TREATMENTS\n",
    "    assert row[\"owner\"] in ALLOWED_OWNERS\n",
    "    assert 1 <= row[\"likelihood\"] <= 5 and 1 <= row[\"impact\"] <= 5\n",
    "    assert 1 <= row[\"residual_likelihood\"] <= 5 and 1 <= row[\"residual_impact\"] <= 5\n",
    "    inherent = row[\"likelihood\"] * row[\"impact\"]\n",
    "    residual = row[\"residual_likelihood\"] * row[\"residual_impact\"]\n",
    "    assert residual <= inherent\n",
    "    scored.append({\"id\": row[\"id\"], \"inherent\": inherent, \"residual\": residual,\n",
    "                   \"owner\": row[\"owner\"], \"treatment\": row[\"treatment\"]})\n",
    "\n",
    "top2 = sorted(rows, key=lambda row: row[\"residual_likelihood\"] * row[\"residual_impact\"],\n",
    "              reverse=True)[:2]\n",
    "for row in scored:\n",
    "    print(row[\"id\"], \"inherent\", row[\"inherent\"], \"residual\", row[\"residual\"])\n",
    "print(\"top residual risks\", [row[\"id\"] for row in top2])\n",
    "assert len(top2) == 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 8 — write the evidence\n",
    "\n",
    "`inference_results.json` is the machine-readable artifact. It records the\n",
    "snapshot date, the prediction, the redaction and EXIF counts, the six-part rule\n",
    "cases, every call with its serving endpoint and cost, and the register ranking.\n",
    "Keep the raw snapshots and the refusal bodies with it.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "`inference_results.json` เป็นหลักฐานที่เครื่องอ่านได้ บันทึกวันที่ของ snapshot การทำนาย จำนวนการปิดข้อมูลและ EXIF กรณีของกฎหกส่วน ทุกการเรียกพร้อม endpoint ที่ให้บริการและค่าใช้จ่าย และการจัดอันดับทะเบียน เก็บ snapshot ดิบและเนื้อหาการปฏิเสธไว้ด้วย\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "`inference_results.json` 是机器可读的证据。它记录 snapshot 的日期、预测、脱敏和 EXIF 的数量、六部分规则的案例、每一次调用及其提供服务的 endpoint 和成本，以及登记表的排名。请把原始 snapshot 和拒绝内容一并保存。\n",
    "\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "results = {\n",
    "    \"seed\": SEED,\n",
    "    \"device\": DEVICE,\n",
    "    \"mode\": \"live\" if LIVE else \"canned\",\n",
    "    \"zdr_only_source\": zdr_only_source,\n",
    "    \"snapshot\": {\"retrieved\": snapshot_date, \"source\": snapshot_source,\n",
    "                 \"zdr_catalogue_endpoints\": len(zdr)},\n",
    "    \"predictions\": predictions,\n",
    "    \"redaction\": {\"transcripts\": len(transcripts), \"pii_rows_before\": pii_before,\n",
    "                  \"pii_rows_after\": pii_after},\n",
    "    \"exif\": {\"photos\": len(photos), \"gps_before\": gps_before, \"gps_after\": gps_after,\n",
    "             \"exif_tags_before\": tags_before, \"exif_tags_after\": tags_after},\n",
    "    \"governance_cases\": decisions,\n",
    "    \"allowed_transcripts\": len(asset_decisions),\n",
    "    \"calls\": calls,\n",
    "    \"call_sources\": {name: call.get(\"source\") for name, call in calls.items()},\n",
    "    \"cost_usd\": total_cost,\n",
    "    \"estimated_cost_usd\": estimated_cost,\n",
    "    \"reported_cost_usd\": reported_cost,\n",
    "    \"cost_ceiling_usd\": CEILING_USD,\n",
    "    \"key_balance_note\": \"record GET /api/v1/key before and after; never store the key\",\n",
    "    \"register\": scored,\n",
    "    \"top_residual_risks\": [row[\"id\"] for row in top2],\n",
    "}\n",
    "target = OUT / \"inference_results.json\"\n",
    "target.write_text(json.dumps(results, indent=2) + \"\\n\")\n",
    "print(\"wrote\", target)\n",
    "print(json.dumps({key: results[key] for key in\n",
    "                  (\"mode\", \"zdr_only_source\", \"cost_usd\", \"estimated_cost_usd\",\n",
    "                   \"top_residual_risks\")}, indent=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What this proves\n",
    "\n",
    "Write 150–250 words: what the prediction said about the maker's own endpoint and\n",
    "about Gemini's ZDR carve-out, what redaction and EXIF stripping removed, which\n",
    "part of the rule refused call B, which endpoint served call C, why call D failed\n",
    "under ZDR-only, and which two residual risks you would defend to the unit.\n",
    "Attach the JSON, the dated snapshots, the refusal bodies, the marked\n",
    "trust-boundary map, the rule and the ten-row register.\n",
    "\n",
    "## Verification\n",
    "\n",
    "**Mac verified (M1 Max, Python 3.14, Pillow 11.3.0, 2026-11-13):** the notebook\n",
    "runs end to end offline against the dated snapshots and `canned-inference.json`,\n",
    "and writes `inference_results.json`. **Live verified (2026-11-13):** the four\n",
    "calls and the ZDR-only retry were run against the live API. A returned 200 at\n",
    "DeepSeek, B was refused with 404, C served from a ZDR endpoint, and D served\n",
    "from Google Vertex with `safety_retention: true`; under ZDR-only, C still\n",
    "returned 200 and D was refused with 404. The reported cost was $0.00728 against\n",
    "the $0.10 ceiling. A live cell never runs at build or import time.\n",
    "\n",
    "<details class=\"th\" lang=\"th\">\n",
    "<summary>สรุปภาษาไทย</summary>\n",
    "\n",
    "เขียนสรุป 150–250 คำว่าการทำนายบอกอะไรเกี่ยวกับ endpoint ของผู้ผลิตเองและข้อยกเว้นของ Gemini การปิดข้อมูลและ EXIF ลบอะไร ส่วนใดของกฎปฏิเสธการเรียก B endpoint ใดให้บริการ C ทำไม D ล้มเหลวภายใต้ ZDR-only และความเสี่ยงคงเหลือสองข้อใดจะปกป้องต่อหน่วย แนบไฟล์ JSON snapshot ที่มีวันที่ เนื้อหาการปฏิเสธ แผนขอบเขตที่ทำเครื่องหมาย กฎ และทะเบียนสิบแถว\n",
    "</details>\n",
    "\n",
    "<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n",
    "\n",
    "写一篇 150–250 词的总结：预测对制造商自己的 endpoint 和 Gemini 的例外说明了什么，脱敏和 EXIF 删除了什么，规则的哪个部分拒绝了调用 B，哪个 endpoint 为 C 提供服务，为什么 D 在 ZDR-only 下失败，以及你会向单位捍卫哪两个剩余风险。附上 JSON 文件、带日期的 snapshot、拒绝内容、标记好的信任边界图、规则和十行登记表。\n",
    "\n",
    "</details>"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
