{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cell-01",
   "metadata": {},
   "source": [
    "# 09 · Tune visual document retrieval\n",
    "\n",
    "An accounts-payable analyst remembers a supplier and displayed balance, or the\n",
    "date and a service line. Retrieve the one matching page from a fixed candidate\n",
    "pool. Compare OCR BM25, a frozen image retriever and a learned query projection.\n",
    "The projection changes scores against an index built once.\n",
    "\n",
    "## 1. Choose a bounded profile\n",
    "\n",
    "Start with the default T4 profile. The full profile raises the page and step\n",
    "counts. Both profiles preserve the source fixtures, model revision and comparison."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-02",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import shutil\n",
    "import subprocess\n",
    "import sys\n",
    "\n",
    "import torch\n",
    "\n",
    "if not torch.cuda.is_available() or \"T4\" not in torch.cuda.get_device_name():\n",
    "    raise RuntimeError(\"Select a Colab T4 for this notebook.\")\n",
    "if not shutil.which(\"tesseract\"):\n",
    "    subprocess.run([\"apt-get\", \"update\", \"-qq\"], check=True)\n",
    "    subprocess.run([\"apt-get\", \"install\", \"-y\", \"-qq\", \"tesseract-ocr\"], check=True)\n",
    "subprocess.run(\n",
    "    [sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"transformers==4.57.1\",\n",
    "     \"rank-bm25==0.2.2\", \"pytesseract==0.3.13\"],\n",
    "    check=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-03",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Versioned synthetic invoices and independent record scoring for the course.\"\"\"\n",
    "\n",
    "from __future__ import annotations\n",
    "\n",
    "import json\n",
    "import random\n",
    "import re\n",
    "from collections import Counter\n",
    "from dataclasses import dataclass\n",
    "from datetime import date, timedelta\n",
    "from typing import Any\n",
    "\n",
    "CATALOG_VERSION = \"course-invoice-v1\"\n",
    "SPLIT_SIZES = {\"train\": 576, \"dev\": 72, \"familiar\": 96, \"novel\": 96, \"independent\": 48, \"release\": 120}\n",
    "VISIBLE_CONTRACT = (\n",
    "    \"Extract exactly one JSON object with invoice_id, issued_on (YYYY-MM-DD), supplier, \"\n",
    "    \"currency (ISO code), line_items (description, quantity, unit_minor), subtotal_minor, \"\n",
    "    \"tax_minor, and total_minor. Preserve line order and convert currency amounts to integer cents. \"\n",
    "    \"Use null only for a missing or ambiguous field. Do not rewrite printed amounts, invent fields, or add explanations.\"\n",
    ")\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class Line:\n",
    "    description: str\n",
    "    quantity: int\n",
    "    unit_minor: int\n",
    "\n",
    "\n",
    "@dataclass(frozen=True)\n",
    "class Invoice:\n",
    "    key: str\n",
    "    family: str\n",
    "    supplier: str\n",
    "    issued_on: str\n",
    "    currency: str\n",
    "    items: tuple[Line, ...]\n",
    "    tax_minor: int | None\n",
    "    locale: str\n",
    "    split: str\n",
    "    layout: str = \"register\"\n",
    "    printed_total_minor: int | None = None\n",
    "\n",
    "\n",
    "def invoice_record(invoice: Invoice) -> dict[str, Any]:\n",
    "    subtotal = sum(line.quantity * line.unit_minor for line in invoice.items)\n",
    "    total = subtotal + invoice.tax_minor if invoice.tax_minor is not None else None\n",
    "    if invoice.printed_total_minor is not None:\n",
    "        total = invoice.printed_total_minor\n",
    "    return {\n",
    "        \"invoice_id\": invoice.key,\n",
    "        \"issued_on\": invoice.issued_on,\n",
    "        \"supplier\": invoice.supplier,\n",
    "        \"currency\": invoice.currency,\n",
    "        \"line_items\": [\n",
    "            {\"description\": item.description, \"quantity\": item.quantity, \"unit_minor\": item.unit_minor}\n",
    "            for item in invoice.items\n",
    "        ],\n",
    "        \"subtotal_minor\": subtotal,\n",
    "        \"tax_minor\": invoice.tax_minor,\n",
    "        \"total_minor\": total,\n",
    "    }\n",
    "\n",
    "\n",
    "def make_catalog() -> list[Invoice]:\n",
    "    rng = random.Random(20261126)\n",
    "    sources = {\n",
    "        \"train\": (24, (\"register\", \"memo\", \"checkout\", \"ledger\")),\n",
    "        \"dev\": (6, (\"register\", \"memo\", \"checkout\", \"ledger\")),\n",
    "        \"familiar\": (8, (\"register\", \"memo\", \"checkout\", \"ledger\")),\n",
    "        \"novel\": (8, (\"packing\", \"remittance\", \"service\", \"notice\")),\n",
    "        \"independent\": (4, (\"separate\",)),\n",
    "        \"release\": (10, (\"packing\", \"remittance\", \"service\", \"notice\", \"separate\")),\n",
    "    }\n",
    "    locales = ((\"en-US\", \"USD\"), (\"en-GB\", \"GBP\"), (\"de-DE\", \"EUR\"), (\"fr-FR\", \"EUR\"), (\"en-US\", \"CAD\"))\n",
    "    services = (\"Cooling filter\", \"Cable sleeve\", \"Bench calibration\", \"Door seal\", \"Grounding clip\",\n",
    "                \"Rack inspection\", \"Meter label\", \"Packing insert\", \"Carrier adjustment\", \"Mounting plate\")\n",
    "    catalog = []\n",
    "    seen_keys = set()\n",
    "    supplier_codes = rng.sample(range(1000, 9999), sum(n for n, _ in sources.values()))\n",
    "    supplier_index = 0\n",
    "    for split, (family_count, layouts) in sources.items():\n",
    "        for family_number in range(family_count):\n",
    "            supplier_code = supplier_codes[supplier_index]\n",
    "            supplier_index += 1\n",
    "            layout = layouts[family_number % len(layouts)]\n",
    "            family = f\"{split}-{family_number:02d}\"\n",
    "            locale, currency = locales[family_number % len(locales)]\n",
    "            for row in range(SPLIT_SIZES[split] // family_count):\n",
    "                code = f\"SF-{rng.randrange(100000, 1000000)}\"\n",
    "                while code in seen_keys:\n",
    "                    code = f\"SF-{rng.randrange(100000, 1000000)}\"\n",
    "                seen_keys.add(code)\n",
    "                items = tuple(\n",
    "                    Line(kind, rng.randint(1, 9), rng.randrange(200, 24800))\n",
    "                    for kind in rng.sample(services, rng.randrange(1, 4))\n",
    "                )\n",
    "                subtotal = sum(x.quantity * x.unit_minor for x in items)\n",
    "                tax = (subtotal * (7 if currency == \"USD\" else 13) + 50) // 100\n",
    "                if split in {\"novel\", \"independent\", \"release\"} and row % 12 == 4:\n",
    "                    tax = None\n",
    "                displayed = subtotal + tax + 101 if tax is not None and row % 12 == 7 else None\n",
    "                issued_on = (date(2025, 1, 1) + timedelta(days=rng.randint(0, 590))).isoformat()\n",
    "                catalog.append(Invoice(code, family, f\"Sample Supplier {supplier_code}\", issued_on,\n",
    "                                       currency, items, tax, locale, split, layout, displayed))\n",
    "    return catalog\n",
    "\n",
    "\n",
    "def formatted_money(minor: int | None, locale: str) -> str:\n",
    "    if minor is None:\n",
    "        return \"-\"\n",
    "    dollars, cents = divmod(minor, 100)\n",
    "    number = f\"{dollars:,}.{cents:02d}\"\n",
    "    if locale == \"de-DE\":\n",
    "        return number.replace(\",\", \"_\").replace(\".\", \",\").replace(\"_\", \".\")\n",
    "    if locale == \"fr-FR\":\n",
    "        return number.replace(\",\", \" \").replace(\".\", \",\")\n",
    "    return number\n",
    "\n",
    "\n",
    "def invoice_text(invoice: Invoice) -> str:\n",
    "    gold = invoice_record(invoice)\n",
    "    money = lambda value: formatted_money(value, invoice.locale)\n",
    "    identifier = f\"{invoice.key}\"\n",
    "    supplier = invoice.supplier\n",
    "    issued = invoice.issued_on\n",
    "    currency = invoice.currency\n",
    "    subtotal = money(gold[\"subtotal_minor\"])\n",
    "    tax = money(gold[\"tax_minor\"])\n",
    "    total = money(gold[\"total_minor\"])\n",
    "    register = [f\"{row.description} | {row.quantity} | {money(row.unit_minor)}\" for row in invoice.items]\n",
    "    inline = [f\"{row.quantity} x {row.description} @ {money(row.unit_minor)} per unit\" for row in invoice.items]\n",
    "    service = [f\"{row.description}: {money(row.unit_minor)} each for {row.quantity} units\" for row in invoice.items]\n",
    "    if invoice.layout == \"register\":\n",
    "        return \"\\n\".join([f\"Supplier: {supplier}\", f\"Invoice: {identifier}\", f\"Issued: {issued}\", f\"Currency: {currency}\",\n",
    "                          \"Description | Quantity | Unit price\", *register,\n",
    "                          f\"Subtotal: {subtotal}\", f\"Tax: {tax}\", f\"Amount due: {total}\"])\n",
    "    if invoice.layout == \"memo\":\n",
    "        return \"\\n\".join([f\"{supplier} billing memo / {issued}\", f\"Account invoice {identifier} [{currency}]\",\n",
    "                          *inline, f\"Total due {total} including tax {tax}; net amount {subtotal}.\"])\n",
    "    if invoice.layout == \"checkout\":\n",
    "        return \"\\n\".join([f\"{identifier} / supplier {supplier}\", f\"Date of issue {issued} / All amounts {currency}\",\n",
    "                          *service, f\"Net {subtotal}\", f\"Sales tax {tax}\", f\"Payable {total}\"])\n",
    "    if invoice.layout == \"ledger\":\n",
    "        return \"\\n\".join([f\"{supplier} | issued {issued} | invoice {identifier}\", f\"Ledger in {currency}\",\n",
    "                          \"Service | Count | Per unit\", *register, f\"Before tax {subtotal}\",\n",
    "                          f\"Tax charged {tax}\", f\"Balance {total}\"])\n",
    "    if invoice.layout == \"packing\":\n",
    "        return \"\\n\".join([f\"Billing details / {identifier}\", f\"Sold by {supplier}\", f\"Document date {issued}\",\n",
    "                          f\"Invoice currency {currency}\", f\"Balance payable {total}\", *service,\n",
    "                          f\"Merchandise {subtotal}\", f\"Tax {tax}\"])\n",
    "    if invoice.layout == \"remittance\":\n",
    "        return \"\\n\".join([f\"Remittance advice for {identifier} ({currency})\", f\"{supplier} / Document issued {issued}\",\n",
    "                          f\"Pay this amount {total}\", *inline, f\"Net charges {subtotal} / Tax {tax}\"])\n",
    "    if invoice.layout == \"service\":\n",
    "        return \"\\n\".join([f\"Ref {identifier} / {currency}\", f\"Service fee notice, {issued}\", supplier,\n",
    "                          *[f\"Unit {money(row.unit_minor)} / {row.quantity} times / {row.description}\" for row in invoice.items],\n",
    "                          f\"Fee subtotal {subtotal}\", f\"Plus tax {tax}\", f\"Amount requested {total}\"])\n",
    "    if invoice.layout == \"notice\":\n",
    "        return \"\\n\".join([f\"{supplier} / statement {identifier}\", f\"Issued on {issued}\",\n",
    "                          f\"Invoice denomination {currency}\", \"One-off charges\", *service,\n",
    "                          f\"Pre-tax {subtotal} / Tax assessment {tax} / Final bill {total}\"])\n",
    "    return \"\\n\".join([f\"Document {identifier}\", f\"Biller {supplier} / As of {issued} / {currency}\", *inline,\n",
    "                      f\"Gross {total}\", f\"Breakdown: net {subtotal} and taxes {tax}.\"])\n",
    "\n",
    "\n",
    "def _strict_dict(pairs: list[tuple[str, Any]]) -> dict[str, Any]:\n",
    "    result: dict[str, Any] = {}\n",
    "    for key, value in pairs:\n",
    "        if key in result:\n",
    "            raise ValueError(f\"Duplicate JSON key {key!r}\")\n",
    "        result[key] = value\n",
    "    return result\n",
    "\n",
    "\n",
    "def parse_record(completion: str | dict[str, Any]) -> dict[str, Any] | None:\n",
    "    if isinstance(completion, str):\n",
    "        try:\n",
    "            data = json.loads(completion, object_pairs_hook=_strict_dict)\n",
    "        except (ValueError, TypeError, RecursionError):\n",
    "            return None\n",
    "    else:\n",
    "        data = completion\n",
    "    keys = {\"invoice_id\", \"issued_on\", \"supplier\", \"currency\", \"line_items\", \"subtotal_minor\", \"tax_minor\", \"total_minor\"}\n",
    "    if not isinstance(data, dict) or set(data) != keys:\n",
    "        return None\n",
    "    for name in (\"invoice_id\", \"supplier\", \"issued_on\", \"currency\"):\n",
    "        value = data[name]\n",
    "        if value is not None and (not isinstance(value, str) or not value.strip()):\n",
    "            return None\n",
    "    try:\n",
    "        if data[\"issued_on\"] is not None and date.fromisoformat(data[\"issued_on\"]).isoformat() != data[\"issued_on\"]:\n",
    "            return None\n",
    "    except ValueError:\n",
    "        return None\n",
    "    if data[\"currency\"] is not None and re.fullmatch(\"[A-Z]{3}\", data[\"currency\"]) is None:\n",
    "        return None\n",
    "    for name in (\"subtotal_minor\", \"tax_minor\", \"total_minor\"):\n",
    "        if data[name] is not None and type(data[name]) is not int:\n",
    "            return None\n",
    "    if not isinstance(data[\"line_items\"], list):\n",
    "        return None\n",
    "    for row in data[\"line_items\"]:\n",
    "        if not isinstance(row, dict) or set(row) != {\"description\", \"quantity\", \"unit_minor\"}:\n",
    "            return None\n",
    "        if type(row[\"description\"]) is not str or type(row[\"quantity\"]) is not int or type(row[\"unit_minor\"]) is not int:\n",
    "            return None\n",
    "        if not row[\"description\"].strip() or row[\"quantity\"] <= 0:\n",
    "            return None\n",
    "    return data\n",
    "\n",
    "\n",
    "def score_record(completion: str | dict[str, Any], invoice: Invoice) -> dict[str, Any]:\n",
    "    truth = invoice_record(invoice)\n",
    "    observed = parse_record(completion)\n",
    "    field_correct = {key: observed is not None and observed.get(key) == value\n",
    "                     for key, value in truth.items() if key != \"line_items\"}\n",
    "    keys = (\"description\", \"quantity\", \"unit_minor\")\n",
    "    expected = Counter(tuple(r[k] for k in keys) for r in truth[\"line_items\"])\n",
    "    predicted = Counter(tuple(r[k] for k in keys) for r in observed[\"line_items\"]) if observed is not None else Counter()\n",
    "    matches = (expected & predicted).total()\n",
    "    row_count = expected.total() + predicted.total()\n",
    "    return {\"valid\": observed is not None, \"exact\": observed == truth,\n",
    "            \"fields\": sum(field_correct.values()) / len(field_correct), \"field_correct\": field_correct,\n",
    "            \"row_f1\": 2 * matches / row_count if row_count else 1.0}\n",
    "\n",
    "\n",
    "def rules_extract(text: str) -> dict[str, Any] | None:\n",
    "    lines = text.splitlines()\n",
    "    if len(lines) < 9 or lines[4] != \"Description | Quantity | Unit price\":\n",
    "        return None\n",
    "    property_names = (\"supplier\", \"invoice_id\", \"issued_on\", \"currency\")\n",
    "    headers = (\"Supplier: \", \"Invoice: \", \"Issued: \", \"Currency: \")\n",
    "    if any(not line.startswith(header) for line, header in zip(lines, headers)):\n",
    "        return None\n",
    "    data = {name: line.removeprefix(header) for name, line, header in zip(property_names, lines, headers)}\n",
    "\n",
    "    def minor(text_amount: str) -> int | None:\n",
    "        if text_amount == \"-\":\n",
    "            return None\n",
    "        if re.fullmatch(r\"(?:\\d+|\\d{1,3}(?:[., ]\\d{3})+)[.,]\\d{2}\", text_amount) is None:\n",
    "            raise ValueError(\"Unsupported amount format\")\n",
    "        units, frac = text_amount[:-3], text_amount[-2:]\n",
    "        return int(re.sub(r\"\\D\", \"\", units)) * 100 + int(frac)\n",
    "\n",
    "    try:\n",
    "        rows = [line.split(\" | \") for line in lines[5:-3]]\n",
    "        data[\"line_items\"] = [{\"description\": desc, \"quantity\": int(qty), \"unit_minor\": minor(unit)}\n",
    "                              for desc, qty, unit in rows]\n",
    "        data[\"subtotal_minor\"] = minor(lines[-3].removeprefix(\"Subtotal: \"))\n",
    "        data[\"tax_minor\"] = minor(lines[-2].removeprefix(\"Tax: \"))\n",
    "        data[\"total_minor\"] = minor(lines[-1].removeprefix(\"Amount due: \"))\n",
    "    except ValueError:\n",
    "        return None\n",
    "    return parse_record(data)\n",
    "\n",
    "\n",
    "def examples_for(split: str, limit: int | None = None) -> list[Invoice]:\n",
    "    found = [invoice for invoice in make_catalog() if invoice.split == split]\n",
    "    if not found:\n",
    "        raise ValueError(f\"Unknown invoice split {split!r}\")\n",
    "    if limit is None or limit >= len(found):\n",
    "        return found\n",
    "    if limit <= 0:\n",
    "        raise ValueError(\"Limit must be positive\")\n",
    "    groups: dict[str, list[Invoice]] = {}\n",
    "    for invoice in found:\n",
    "        groups.setdefault(invoice.family, []).append(invoice)\n",
    "    balanced = [invoice for group_rows in zip(*groups.values(), strict=True) for invoice in group_rows]\n",
    "    return balanced[:limit]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-04",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"Original invoice page and chart rendering for the document notebooks.\"\"\"\n",
    "\n",
    "from PIL import Image, ImageDraw, ImageFont\n",
    "\n",
    "# The notebooks inline this file after the fixture contract. The fallback import\n",
    "# keeps the same functions usable in ordinary Python.\n",
    "if \"invoice_text\" not in globals():\n",
    "    from invoice_fixtures import Invoice, invoice_record, invoice_text\n",
    "\n",
    "\n",
    "def _font(size: int, bold: bool = False):\n",
    "    name = \"DejaVuSans-Bold.ttf\" if bold else \"DejaVuSans.ttf\"\n",
    "    try:\n",
    "        return ImageFont.truetype(name, size)\n",
    "    except OSError:\n",
    "        return ImageFont.load_default(size=size)\n",
    "\n",
    "\n",
    "def invoice_image(invoice: Invoice) -> Image.Image:\n",
    "    image = Image.new(\"RGB\", (896, 624), \"#faf9f5\")\n",
    "    draw = ImageDraw.Draw(image)\n",
    "    fields = invoice_text(invoice).splitlines()\n",
    "    accents = {\n",
    "        \"register\": \"#245067\", \"memo\": \"#732f41\", \"checkout\": \"#30614e\", \"ledger\": \"#2a3e72\",\n",
    "        \"packing\": \"#31535c\", \"remittance\": \"#694323\", \"service\": \"#4b3f65\", \"notice\": \"#73422d\",\n",
    "    }\n",
    "    accent = accents.get(invoice.layout, \"#4a5744\")\n",
    "    draw.rounded_rectangle((32, 29, 864, 595), 11, fill=\"white\", outline=\"#d9dad8\", width=2)\n",
    "    draw.rectangle((33, 34, 863, 42), fill=accent)\n",
    "    draw.text((64, 63), \"Supplier billing\", font=_font(28, bold=True), fill=accent)\n",
    "    draw.text((64, 102), \"Original synthetic course fixture\", font=_font(15), fill=\"#5b6462\")\n",
    "    draw.line((61, 134, 835, 134), fill=\"#d5dad8\", width=2)\n",
    "    for i, line in enumerate(fields):\n",
    "        y = 153 + 35 * i\n",
    "        if i % 2:\n",
    "            draw.rectangle((58, y - 3, 837, y + 28), fill=\"#f5f7f6\")\n",
    "        is_heading = line.startswith((\"Description |\", \"Service |\", \"One-off charges\"))\n",
    "        draw.text((65, y), line, fill=\"#233034\", font=_font(20, bold=is_heading))\n",
    "        if draw.textbbox((65, y), line, font=_font(20, bold=is_heading))[2] >= 837:\n",
    "            raise ValueError(f\"Invoice field did not fit the page: {line!r}\")\n",
    "    return image\n",
    "\n",
    "\n",
    "def spend_chart(invoice: Invoice, *, varied: bool = False):\n",
    "    \"\"\"Render line-item spending as labelled bars with separately known cents.\"\"\"\n",
    "    gold = invoice_record(invoice)\n",
    "    values = [row[\"quantity\"] * row[\"unit_minor\"] for row in gold[\"line_items\"]]\n",
    "    image = Image.new(\"RGB\", (896, 512), \"#ffffff\")\n",
    "    draw = ImageDraw.Draw(image)\n",
    "    accent = \"#266978\" if varied else \"#27598b\"\n",
    "    order = list(reversed(range(len(values)))) if varied else list(range(len(values)))\n",
    "    draw.text((48, 39), f\"Line item spending · {invoice.currency}\", fill=accent, font=_font(28, bold=True))\n",
    "    draw.text((48, 80), \"Total before tax per line item\", fill=\"#53575b\", font=_font(17))\n",
    "    largest = max(values)\n",
    "    rows = []\n",
    "    for position, index in enumerate(order):\n",
    "        row = gold[\"line_items\"][index]\n",
    "        value = values[index]\n",
    "        y = 141 + 86 * position\n",
    "        draw.text((51, y), row[\"description\"], font=_font(19), fill=\"#222222\")\n",
    "        money = f\"{value / 100:,.2f}\"\n",
    "        draw.text((734, y), money, font=_font(19, bold=True), fill=\"#222222\")\n",
    "        draw.rounded_rectangle((51, y + 34, 51 + int(value / largest * 650), y + 55), 4, fill=accent)\n",
    "        rows.append({\"description\": row[\"description\"], \"line_total_minor\": value})\n",
    "    return image, {\"currency\": invoice.currency, \"rows\": rows}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-05",
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import defaultdict\n",
    "from hashlib import sha256\n",
    "from pathlib import Path\n",
    "from time import perf_counter\n",
    "import importlib.metadata\n",
    "import json\n",
    "import math\n",
    "import random\n",
    "import re\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib_inline.backend_inline import set_matplotlib_formats\n",
    "import numpy as np\n",
    "import pytesseract\n",
    "from IPython.display import display\n",
    "from rank_bm25 import BM25Okapi\n",
    "from torch import nn\n",
    "from torch.nn import functional as F\n",
    "from torch.nn.utils.rnn import pad_sequence\n",
    "from transformers import ColQwen2ForRetrieval, ColQwen2Processor\n",
    "\n",
    "MODEL_ID = \"vidore/colqwen2-v1.0-hf\"\n",
    "REVISION = \"ddc07d2317c80f75fc742b7362ee9ad1912908f9\"\n",
    "PROFILE = os.environ.get(\"COURSE_PROFILE\", \"profile\")\n",
    "LIMITS = {\n",
    "    \"profile\": {\"train\": 48, \"familiar\": 16, \"novel\": 16, \"independent\": 8, \"steps\": 32},\n",
    "    \"full\": {\"train\": 144, \"familiar\": 48, \"novel\": 48, \"independent\": 24, \"steps\": 144},\n",
    "}[PROFILE]\n",
    "SEED = 409\n",
    "TEMPERATURE = 1.0\n",
    "PAGE_BATCH_SIZE = 1\n",
    "QUERY_BATCH_SIZE = 4\n",
    "OUT = Path(\"outputs\")\n",
    "OUT.mkdir(exist_ok=True)\n",
    "device = torch.device(\"cuda\")\n",
    "torch.manual_seed(SEED)\n",
    "set_matplotlib_formats(\"svg\")\n",
    "plt.rcParams[\"svg.fonttype\"] = \"none\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-06",
   "metadata": {},
   "source": [
    "## 2. Define answerable queries\n",
    "\n",
    "Build the split before rendering. Construct queries from supplier and the\n",
    "displayed amount or from date, currency and a service line. Retain queries\n",
    "whose complete clue combination identifies exactly one candidate. Keep\n",
    "ambiguous pages as distractors. The evaluation pool mixes familiar, unseen\n",
    "and independently authored layouts. No training supplier crosses that\n",
    "boundary, and the adjudicated clues are used only to create fixtures."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-07",
   "metadata": {},
   "outputs": [],
   "source": [
    "# SMOKE LIBRARY START\n",
    "def tokenize(text):\n",
    "    return re.findall(r\"[a-z0-9]+\", text.lower())\n",
    "\n",
    "\n",
    "def clues(page, kind):\n",
    "    if kind == \"supplier-and-balance\":\n",
    "        total = formatted_money(invoice_record(page)[\"total_minor\"], page.locale)\n",
    "        return [(page.supplier, total)] if total != \"-\" else []\n",
    "    return [(page.issued_on, page.currency, item.description) for item in page.items]\n",
    "\n",
    "\n",
    "def build_queries(documents):\n",
    "    by_clue = defaultdict(list)\n",
    "    for page in documents:\n",
    "        for kind in (\"supplier-and-balance\", \"date-and-service\"):\n",
    "            for clue in clues(page, kind):\n",
    "                by_clue[(kind, clue)].append(page.key)\n",
    "    rows = []\n",
    "    for page in documents:\n",
    "        kind_options = (\"supplier-and-balance\", \"date-and-service\")\n",
    "        for kind in kind_options:\n",
    "            unique = next((c for c in clues(page, kind) if by_clue[(kind, c)] == [page.key]), None)\n",
    "            if unique is None:\n",
    "                continue\n",
    "            if kind == \"supplier-and-balance\":\n",
    "                supplier, total = unique\n",
    "                text = f\"Find the invoice from {supplier} showing {total} due.\"\n",
    "            else:\n",
    "                date, currency, service = unique\n",
    "                text = f\"Find the {currency} bill issued on {date} that charges for {service}.\"\n",
    "            rows.append({\n",
    "                \"id\": f\"{page.key}/{kind}\", \"gold\": page.key, \"text\": text, \"kind\": kind,\n",
    "                \"split\": page.split, \"family\": page.family, \"layout\": page.layout,\n",
    "            })\n",
    "    return rows\n",
    "\n",
    "\n",
    "def pack_documents(vectors):\n",
    "    padded = pad_sequence(vectors, batch_first=True).float()\n",
    "    lengths = torch.tensor([len(v) for v in vectors], device=padded.device)\n",
    "    mask = torch.arange(padded.shape[1], device=padded.device)[None, :] < lengths[:, None]\n",
    "    return padded, mask\n",
    "\n",
    "\n",
    "def maxsim(query, documents, mask):\n",
    "    similarities = torch.einsum(\"qd,nkd->nqk\", query.float(), documents)\n",
    "    return similarities.masked_fill(~mask[:, None, :], -torch.inf).amax(dim=-1).sum(dim=-1)\n",
    "\n",
    "\n",
    "class QueryProjection(nn.Module):\n",
    "    def __init__(self, dimension):\n",
    "        super().__init__()\n",
    "        self.delta = nn.Linear(dimension, dimension, bias=False)\n",
    "        nn.init.zeros_(self.delta.weight)\n",
    "\n",
    "    def forward(self, tokens):\n",
    "        return F.normalize(tokens + self.delta(tokens), dim=-1)\n",
    "\n",
    "\n",
    "def rank_of(scores, keys, gold):\n",
    "    ranks = sorted(zip(keys, scores, strict=True), key=lambda item: (-item[1], item[0]))\n",
    "    return next(i for i, (key, _) in enumerate(ranks, 1) if key == gold), ranks[0][0]\n",
    "# SMOKE LIBRARY END\n",
    "\n",
    "\n",
    "train_pages = examples_for(\"train\", LIMITS[\"train\"])\n",
    "test_pages = sum((examples_for(split, LIMITS[split]) for split in (\"familiar\", \"novel\", \"independent\")), [])\n",
    "assert {p.family for p in train_pages}.isdisjoint(p.family for p in test_pages)\n",
    "assert {p.supplier for p in train_pages}.isdisjoint(p.supplier for p in test_pages)\n",
    "train_queries, test_queries = build_queries(train_pages), build_queries(test_pages)\n",
    "assert train_queries and test_queries and len({q[\"id\"] for q in test_queries}) == len(test_queries)\n",
    "train_by_key = {page.key: page for page in train_pages}\n",
    "test_by_key = {page.key: page for page in test_pages}\n",
    "print(f\"{len(train_queries)} fit queries and {len(test_queries)} held-out queries.\")\n",
    "display(invoice_image(test_pages[0]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-08",
   "metadata": {},
   "source": [
    "## 3. Build both indexes\n",
    "\n",
    "Tesseract extracts plain text from the same page image used by ColQwen2.\n",
    "OCR index storage is the UTF-8 text and IDs needed to reconstruct this\n",
    "in-memory BM25 index. Visual index storage is the persisted token vectors\n",
    "in float16 and IDs. This comparison measures serialized payloads. A\n",
    "production search service can use a different index representation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-09",
   "metadata": {},
   "outputs": [],
   "source": [
    "ocr_start = perf_counter()\n",
    "ocr_text = {\n",
    "    page.key: pytesseract.image_to_string(invoice_image(page), lang=\"eng\", config=\"--psm 11\")\n",
    "    for page in test_pages\n",
    "}\n",
    "assert any(tokenize(text) for text in ocr_text.values()), \"OCR produced no indexable text\"\n",
    "test_keys = sorted(test_by_key)\n",
    "bm25 = BM25Okapi([tokenize(ocr_text[key]) for key in test_keys])\n",
    "ocr_index_time = perf_counter() - ocr_start\n",
    "(OUT / \"ocr-index.json\").write_text(json.dumps(ocr_text, ensure_ascii=False), encoding=\"utf-8\")\n",
    "\n",
    "processor = ColQwen2Processor.from_pretrained(MODEL_ID, revision=REVISION)\n",
    "model = ColQwen2ForRetrieval.from_pretrained(\n",
    "    MODEL_ID, revision=REVISION, dtype=torch.float16, attn_implementation=\"sdpa\",\n",
    ").eval().requires_grad_(False).to(device)\n",
    "torch.cuda.reset_peak_memory_stats()\n",
    "\n",
    "\n",
    "@torch.no_grad()\n",
    "def embed(items, encode, batch_size):\n",
    "    vectors = []\n",
    "    for offset in range(0, len(items), batch_size):\n",
    "        features = encode(items[offset:offset + batch_size], return_tensors=\"pt\").to(device)\n",
    "        if \"pixel_values\" in features:\n",
    "            features[\"pixel_values\"] = features[\"pixel_values\"].to(dtype=torch.float16)\n",
    "        output = model(**features, use_cache=False).embeddings\n",
    "        for tokens, mask in zip(output, features.attention_mask, strict=True):\n",
    "            vectors.append(tokens[mask.bool()].float().cpu())\n",
    "    return vectors\n",
    "\n",
    "\n",
    "def encode_pages(pages):\n",
    "    return embed(pages, lambda rows, **kw: processor.process_images(\n",
    "        images=[invoice_image(row) for row in rows], **kw), PAGE_BATCH_SIZE)\n",
    "\n",
    "\n",
    "def encode_queries(texts, batch_size=QUERY_BATCH_SIZE):\n",
    "    return embed(texts, lambda rows, **kw: processor.process_queries(text=rows, **kw), batch_size)\n",
    "\n",
    "\n",
    "# Profile one document encode and the real projection objective before building indexes.\n",
    "torch.cuda.synchronize()\n",
    "preflight_started = perf_counter()\n",
    "probe_page = encode_pages(train_pages[:1])[0].to(device)\n",
    "probe_query = encode_queries([max(train_queries, key=lambda row: len(row[\"text\"]))[\"text\"]], batch_size=1)[0].to(device)\n",
    "probe_adapter = QueryProjection(probe_query.shape[-1]).to(device)\n",
    "probe_pages, probe_mask = pack_documents([probe_page] * 7)\n",
    "probe_logits = maxsim(probe_adapter(probe_query), probe_pages, probe_mask)[None, :]\n",
    "probe_loss = F.cross_entropy(probe_logits, torch.zeros(1, device=device, dtype=torch.long))\n",
    "probe_loss.backward()\n",
    "assert torch.isfinite(probe_loss) and torch.isfinite(probe_adapter.delta.weight.grad).all()\n",
    "torch.cuda.synchronize()\n",
    "profile_evidence = {\n",
    "    \"seconds\": perf_counter() - preflight_started,\n",
    "    \"peak_allocated_bytes\": torch.cuda.max_memory_allocated(),\n",
    "    \"peak_reserved_bytes\": torch.cuda.max_memory_reserved(),\n",
    "}\n",
    "print(\"T4 preflight:\", profile_evidence)\n",
    "(OUT / \"t4-profile.json\").write_text(json.dumps(profile_evidence, indent=2), encoding=\"utf-8\")\n",
    "if profile_evidence[\"seconds\"] > 90 or profile_evidence[\"peak_reserved_bytes\"] > 13 * 1024**3:\n",
    "    raise RuntimeError(\"ColQwen2 profile exceeds the T4 budget.\")\n",
    "del probe_page, probe_query, probe_adapter, probe_pages, probe_mask, probe_logits, probe_loss\n",
    "torch.cuda.empty_cache()\n",
    "\n",
    "index_start = perf_counter()\n",
    "test_index = {\n",
    "    page.key: tokens.half()\n",
    "    for page, tokens in zip(test_pages, encode_pages(test_pages), strict=True)\n",
    "}\n",
    "torch.cuda.synchronize()\n",
    "torch.save(test_index, OUT / \"colqwen-index.pt\")\n",
    "vision_index_time = perf_counter() - index_start\n",
    "page_vectors = {\n",
    "    page.key: tokens.half()\n",
    "    for page, tokens in zip(train_pages, encode_pages(train_pages), strict=True)\n",
    "}\n",
    "fit_queries = dict(zip((q[\"id\"] for q in train_queries),\n",
    "                       encode_queries([q[\"text\"] for q in train_queries]), strict=True))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-10",
   "metadata": {},
   "source": [
    "## 4. Train the query-only projection\n",
    "\n",
    "For every query token, find the most similar token on each candidate page.\n",
    "Sum those maxima into one page score. Padding is masked before the maximum.\n",
    "An identity-initialized residual projection updates only query embeddings.\n",
    "Train it against one positive and six negatives drawn from training pages.\n",
    "Score lexical overlap between visible texts only to select training negatives.\n",
    "Same-supplier pages take priority. The original page embeddings remain fixed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-11",
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = random.Random(SEED)\n",
    "adapter = QueryProjection(next(iter(fit_queries.values())).shape[-1]).to(device)\n",
    "optimizer = torch.optim.AdamW(adapter.parameters(), lr=1e-3)\n",
    "history = []\n",
    "schedule = list(train_queries)\n",
    "rng.shuffle(schedule)\n",
    "train_start = perf_counter()\n",
    "for step in range(LIMITS[\"steps\"]):\n",
    "    q = schedule[step % len(schedule)]\n",
    "    gold = train_by_key[q[\"gold\"]]\n",
    "    terms = set(tokenize(q[\"text\"]))\n",
    "    candidates = [p for p in train_pages if p.key != gold.key]\n",
    "    candidates.sort(key=lambda page: (\n",
    "        page.supplier != gold.supplier,\n",
    "        -len(terms.intersection(tokenize(invoice_text(page)))),\n",
    "        page.key,\n",
    "    ))\n",
    "    hard = candidates[:3]\n",
    "    negatives = hard + rng.sample(candidates[len(hard):], 3)\n",
    "    vectors, mask = pack_documents([page_vectors[p.key].to(device) for p in [gold, *negatives]])\n",
    "    query = fit_queries[q[\"id\"]].to(device)\n",
    "    logits = maxsim(adapter(query), vectors, mask)[None, :] / TEMPERATURE\n",
    "    loss = F.cross_entropy(logits, torch.zeros(1, device=device, dtype=torch.long))\n",
    "    if not torch.isfinite(loss):\n",
    "        raise RuntimeError(f\"Nonfinite contrastive loss at step {step + 1}\")\n",
    "    optimizer.zero_grad(set_to_none=True)\n",
    "    loss.backward()\n",
    "    optimizer.step()\n",
    "    history.append({\"step\": step + 1, \"query\": q[\"id\"], \"loss\": loss.item(),\n",
    "                    \"positive\": gold.key, \"negatives\": [p.key for p in negatives]})\n",
    "torch.cuda.synchronize()\n",
    "training_seconds = perf_counter() - train_start\n",
    "assert torch.count_nonzero(adapter.delta.weight).item()\n",
    "torch.save(adapter.state_dict(), OUT / \"query-projection.pt\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-12",
   "metadata": {},
   "source": [
    "## 5. Retrieve from the same candidate pool\n",
    "\n",
    "Query preparation and ranking both contribute to latency. For the paired\n",
    "visual arms, measure query encoding once and charge that cost to both arms.\n",
    "Report the OCR and visual index build costs separately. The training pages\n",
    "stay outside all three held-out rankings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cell-13",
   "metadata": {},
   "outputs": [],
   "source": [
    "pages, page_mask = pack_documents([test_index[key].to(device) for key in test_keys])\n",
    "results = []\n",
    "\n",
    "\n",
    "def add_result(query, arm, scores, started, encoding_seconds=0.0):\n",
    "    rank, first = rank_of(scores, test_keys, query[\"gold\"])\n",
    "    seconds = encoding_seconds + perf_counter() - started\n",
    "    results.append({**query, \"arm\": arm, \"rank\": rank, \"top1\": first, \"seconds\": seconds})\n",
    "\n",
    "\n",
    "# Warm up each ranking path once with a train query outside the held-out results.\n",
    "q0 = train_queries[0][\"text\"]\n",
    "with torch.no_grad():\n",
    "    v0 = encode_queries([q0], batch_size=1)[0].to(device)\n",
    "    maxsim(F.normalize(v0, dim=-1), pages, page_mask).tolist()\n",
    "    maxsim(adapter(v0), pages, page_mask).tolist()\n",
    "bm25.get_scores(tokenize(q0))\n",
    "torch.cuda.synchronize()\n",
    "\n",
    "with torch.no_grad():\n",
    "    for q in test_queries:\n",
    "        start = perf_counter()\n",
    "        lexical = bm25.get_scores(tokenize(q[\"text\"])).tolist()\n",
    "        add_result(q, \"ocr-bm25\", lexical, start)\n",
    "\n",
    "        start = perf_counter()\n",
    "        embedding = encode_queries([q[\"text\"]], batch_size=1)[0].to(device)\n",
    "        torch.cuda.synchronize()\n",
    "        encode_seconds = perf_counter() - start\n",
    "\n",
    "        start = perf_counter()\n",
    "        baseline = maxsim(F.normalize(embedding, dim=-1), pages, page_mask).tolist()\n",
    "        add_result(q, \"frozen-colqwen2\", baseline, start, encode_seconds)\n",
    "\n",
    "        start = perf_counter()\n",
    "        adapted = maxsim(adapter(embedding), pages, page_mask).tolist()\n",
    "        add_result(q, \"query-adapted-colqwen2\", adapted, start, encode_seconds)\n",
    "\n",
    "\n",
    "def summarize(rows):\n",
    "    count = len(rows)\n",
    "    return {\n",
    "        \"queries\": count,\n",
    "        \"recall_at_1\": sum(r[\"rank\"] <= 1 for r in rows) / count,\n",
    "        \"recall_at_5\": sum(r[\"rank\"] <= 5 for r in rows) / count,\n",
    "        \"ndcg_at_10\": sum(1 / math.log2(r[\"rank\"] + 1) for r in rows if r[\"rank\"] <= 10) / count,\n",
    "        \"median_query_ms\": 1_000 * float(np.median([r[\"seconds\"] for r in rows])),\n",
    "        \"p95_query_ms\": 1_000 * float(np.percentile([r[\"seconds\"] for r in rows], 95)),\n",
    "    }\n",
    "\n",
    "\n",
    "arms = (\"ocr-bm25\", \"frozen-colqwen2\", \"query-adapted-colqwen2\")\n",
    "scores = {}\n",
    "for arm in arms:\n",
    "    arm_rows = [r for r in results if r[\"arm\"] == arm]\n",
    "    assert {r[\"id\"] for r in arm_rows} == {q[\"id\"] for q in test_queries}\n",
    "    scores[arm] = {\"all\": summarize(arm_rows)}\n",
    "    for name in (\"split\", \"layout\", \"kind\"):\n",
    "        values = sorted({r[name] for r in arm_rows})\n",
    "        scores[arm][name] = {v: summarize([r for r in arm_rows if r[name] == v]) for v in values}\n",
    "\n",
    "def paired_ndcg_delta(treatment, control):\n",
    "    treated = {r[\"id\"]: r for r in results if r[\"arm\"] == treatment}\n",
    "    controls = {r[\"id\"]: r for r in results if r[\"arm\"] == control}\n",
    "    family_rows = defaultdict(list)\n",
    "\n",
    "    def gain(rank):\n",
    "        return 1 / math.log2(rank + 1) if rank <= 10 else 0.0\n",
    "\n",
    "    for key, row in treated.items():\n",
    "        family_rows[row[\"family\"]].append(gain(row[\"rank\"]) - gain(controls[key][\"rank\"]))\n",
    "    grouped = [family_rows[f] for f in sorted(family_rows)]\n",
    "    rng = np.random.default_rng(SEED)\n",
    "    sums = np.asarray([sum(group) for group in grouped])\n",
    "    counts = np.asarray([len(group) for group in grouped])\n",
    "    picks = rng.integers(0, len(grouped), size=(2000, len(grouped)))\n",
    "    boot = sums[picks].sum(axis=1) / counts[picks].sum(axis=1)\n",
    "    return {\"delta\": float(sums.sum() / counts.sum()),\n",
    "            \"p025\": float(np.percentile(boot, 2.5)), \"p975\": float(np.percentile(boot, 97.5)),\n",
    "            \"families\": len(grouped)}\n",
    "\n",
    "\n",
    "paired = {f\"{a}_minus_{b}\": paired_ndcg_delta(a, b) for a, b in (\n",
    "    (\"frozen-colqwen2\", \"ocr-bm25\"), (\"query-adapted-colqwen2\", \"frozen-colqwen2\"),\n",
    ")}\n",
    "\n",
    "fixture_digest = sha256(\"\".join(invoice_text(p) for p in train_pages + test_pages).encode()).hexdigest()\n",
    "report = {\n",
    "    \"gpu\": torch.cuda.get_device_name(), \"cuda\": torch.version.cuda, \"profile\": PROFILE, \"limits\": LIMITS,\n",
    "    \"model\": MODEL_ID, \"revision\": REVISION, \"seed\": SEED, \"fixture_text_sha256\": fixture_digest,\n",
    "    \"training_pages\": sorted(train_by_key), \"evaluation_candidates\": test_keys,\n",
    "    \"peak_allocated_bytes\": torch.cuda.max_memory_allocated(), \"training_seconds\": training_seconds,\n",
    "    \"ocr_index_seconds\": ocr_index_time, \"visual_index_seconds\": vision_index_time,\n",
    "    \"ocr_index_bytes\": (OUT / \"ocr-index.json\").stat().st_size,\n",
    "    \"visual_index_bytes\": (OUT / \"colqwen-index.pt\").stat().st_size,\n",
    "    \"tesseract\": str(pytesseract.get_tesseract_version()),\n",
    "    \"packages\": {p: importlib.metadata.version(p) for p in (\"torch\", \"transformers\", \"rank-bm25\", \"pytesseract\")},\n",
    "    \"scores\": scores, \"paired_ndcg_at_10\": paired, \"preflight\": profile_evidence,\n",
    "}\n",
    "(OUT / \"report.json\").write_text(json.dumps(report, indent=2), encoding=\"utf-8\")\n",
    "(OUT / \"ranks.jsonl\").write_text(\"\".join(json.dumps(r) + \"\\n\" for r in results), encoding=\"utf-8\")\n",
    "(OUT / \"train.jsonl\").write_text(\"\".join(json.dumps(r) + \"\\n\" for r in history), encoding=\"utf-8\")\n",
    "print(json.dumps({\"all\": {a: s[\"all\"] for a, s in scores.items()}, \"paired_ndcg_at_10\": paired}, indent=2))\n",
    "\n",
    "\n",
    "fig, ax = plt.subplots(figsize=(9, 3.8), layout=\"constrained\")\n",
    "x = np.arange(len(arms))\n",
    "ax.bar(x - 0.17, [scores[a][\"all\"][\"recall_at_1\"] for a in arms], 0.34, color=\"#257560\", label=\"Recall@1\")\n",
    "ax.bar(x + 0.17, [scores[a][\"all\"][\"ndcg_at_10\"] for a in arms], 0.34, color=\"#bb7754\", label=\"nDCG@10\")\n",
    "ax.set_xticks(x, [\"OCR BM25\", \"Frozen ColQwen2\", \"Query-adapted ColQwen2\"])\n",
    "ax.set_ylim(0, 1)\n",
    "ax.legend(frameon=False)\n",
    "fig.savefig(OUT / \"retrieval-quality.svg\")\n",
    "plt.show()\n",
    "\n",
    "frozen = {r[\"id\"]: r for r in results if r[\"arm\"] == \"frozen-colqwen2\"}\n",
    "adapted = {r[\"id\"]: r for r in results if r[\"arm\"] == \"query-adapted-colqwen2\"}\n",
    "case = max(adapted, key=lambda key: adapted[key][\"rank\"] - frozen[key][\"rank\"])\n",
    "print(json.dumps({\"frozen\": frozen[case], \"adapted\": adapted[case]}, indent=2))\n",
    "for name, key in ((\"correct\", adapted[case][\"gold\"]), (\"adapter-top\", adapted[case][\"top1\"])):\n",
    "    invoice_image(test_by_key[key]).save(OUT / f\"case-{name}.png\")\n",
    "    print(name, key)\n",
    "    print(invoice_text(test_by_key[key]))\n",
    "    print(\"OCR:\", ocr_text[key])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cell-14",
   "metadata": {},
   "source": [
    "## Read the result\n",
    "\n",
    "Resample held-out supplier families, retaining all their paired queries, to\n",
    "summarize uncertainty in each overall nDCG difference. Check whether any\n",
    "aggregate gain survives on the unseen layouts. Add the\n",
    "cost of storing visual token vectors and editing the retrieval query path to\n",
    "the decision. The fixture is a small, generated corpus with a single positive\n",
    "page per query. The page renderer, OCR language, layouts and candidate\n",
    "density determine how far this result transfers.\n",
    "\n",
    "[ColPali and ViDoRe](https://arxiv.org/abs/2407.01449) ·\n",
    "[ColQwen2 checkpoint](https://huggingface.co/vidore/colqwen2-v1.0-hf) ·\n",
    "[Tesseract OCR](https://github.com/tesseract-ocr/tesseract) ·\n",
    "[Course lesson](https://docs.recohut.com/courses/advanced-llm-fine-tuning/3-adapt-models/09-tune-visual-retrieval)"
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "gpuType": "T4",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
