{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ce5742cd",
   "metadata": {},
   "source": [
    "# Indox — Image convert\n",
    "\n",
    "Simple OpenAPI-style flow: **convert → poll → save**.\n",
    "\n",
    "| | |\n",
    "|---|---|\n",
    "| **What** | `INPUT` → `TARGET` |\n",
    "| **How** | one POST convert, poll status, GET download |\n",
    "| **Where** | `output/` next to this notebook |\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "98ac1509",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-29T21:18:00.839532Z",
     "iopub.status.busy": "2026-10-29T21:18:00.839397Z",
     "iopub.status.idle": "2026-10-29T21:18:02.178397Z",
     "shell.execute_reply": "2026-10-29T21:18:02.177645Z"
    }
   },
   "outputs": [],
   "source": [
    "# Config\n",
    "%pip install -q requests\n",
    "\n",
    "import os\n",
    "from getpass import getpass\n",
    "from pathlib import Path\n",
    "\n",
    "def load_dotenv(path: Path) -> dict:\n",
    "    out = {}\n",
    "    if not path.is_file():\n",
    "        return out\n",
    "    for raw in path.read_text(encoding=\"utf-8\").splitlines():\n",
    "        line = raw.strip()\n",
    "        if not line or line.startswith(\"#\") or \"=\" not in line:\n",
    "            continue\n",
    "        k, _, v = line.partition(\"=\")\n",
    "        out[k.strip()] = v.strip().strip('\"').strip(\"'\")\n",
    "    return out\n",
    "\n",
    "for p in (Path.cwd().parents[1] / \".env\", Path.cwd().parent / \".env\", Path(\"/content/indox-sdk/.env\")):\n",
    "    env = load_dotenv(p)\n",
    "    if env:\n",
    "        break\n",
    "else:\n",
    "    env = {}\n",
    "\n",
    "BASE_URL = (\n",
    "    os.getenv(\"INDOX_BASE_URL\")\n",
    "    or env.get(\"INDOX_PUBLIC_BASE_URL\")\n",
    "    or env.get(\"INDOX_BASE_URL\")\n",
    "    or \"https://indox.org\"\n",
    ").rstrip(\"/\")\n",
    "API_KEY = (os.getenv(\"INDOX_API_KEY\") or env.get(\"INDOX_API_KEY\") or \"\").strip()\n",
    "if not API_KEY:\n",
    "    API_KEY = getpass(\"INDOX_API_KEY: \").strip()\n",
    "\n",
    "INPUT = Path('samples/sample.png')   # what\n",
    "TARGET = 'jpg'       # convert to\n",
    "OUT_DIR = Path(\"output\")         # where\n",
    "OUT_DIR.mkdir(exist_ok=True)\n",
    "\n",
    "assert INPUT.is_file(), f\"missing {INPUT.resolve()}\"\n",
    "print(\"BASE_URL\", BASE_URL)\n",
    "print(\"INPUT   \", INPUT.resolve())\n",
    "print(\"TARGET  \", TARGET)\n",
    "print(\"OUT_DIR \", OUT_DIR.resolve())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77227f15",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-29T21:18:02.180051Z",
     "iopub.status.busy": "2026-10-29T21:18:02.179889Z",
     "iopub.status.idle": "2026-10-29T21:18:08.028299Z",
     "shell.execute_reply": "2026-10-29T21:18:08.027718Z"
    }
   },
   "outputs": [],
   "source": [
    "# Convert → poll → save (OpenAPI-style)\n",
    "import time\n",
    "import requests\n",
    "\n",
    "headers = {\"Authorization\": f\"Bearer {API_KEY}\"}\n",
    "\n",
    "# 1) convert\n",
    "with INPUT.open(\"rb\") as f:\n",
    "    job = requests.post(\n",
    "        f\"{BASE_URL}/api/v1/convert/image/convert/\",\n",
    "        headers=headers,\n",
    "        data={\"target_formats\": TARGET},\n",
    "        files={\"file\": (INPUT.name, f)},\n",
    "        timeout=60,\n",
    "    )\n",
    "job.raise_for_status()\n",
    "cid = job.json().get(\"id\") or job.json().get(\"conversion_id\")\n",
    "print(\"job\", cid)\n",
    "\n",
    "# 2) poll\n",
    "status_url = f\"{BASE_URL}/api/v1/convert/image/conversion/{cid}/\"\n",
    "while True:\n",
    "    s = requests.get(status_url, headers=headers, timeout=60)\n",
    "    s.raise_for_status()\n",
    "    body = s.json()\n",
    "    state = str(body.get(\"status\") or \"\").lower()\n",
    "    print(\"status\", state)\n",
    "    if state in {\"completed\", \"success\", \"failed\", \"error\"}:\n",
    "        break\n",
    "    time.sleep(1)\n",
    "\n",
    "if state not in {\"completed\", \"success\"}:\n",
    "    raise SystemExit(body)\n",
    "\n",
    "# 4) download + save (URL from status payload)\n",
    "dl_path = body.get(\"download_url\") or (body.get(\"output\") or {}).get(TARGET)\n",
    "if not dl_path:\n",
    "    raise SystemExit(f\"no download_url in status: {body}\")\n",
    "dl_url = dl_path if str(dl_path).startswith(\"http\") else f\"{BASE_URL}{dl_path}\"\n",
    "dl = requests.get(dl_url, headers=headers, timeout=120)\n",
    "dl.raise_for_status()\n",
    "out = OUT_DIR / f\"{INPUT.stem}.{TARGET}\"\n",
    "out.write_bytes(dl.content)\n",
    "print(\"saved\", out.resolve(), f\"({out.stat().st_size} bytes)\")\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "every-format-md",
   "metadata": {},
   "source": [
    "## Every output format\n",
    "Converts `INPUT` to each format the API accepts for it (with the engine it names) and prints PASS or FAIL per format. Each conversion spends credits."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "every-format",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Convert INPUT to every output format this service accepts for it\n",
    "import sys\n",
    "sys.path.insert(0, str(Path.cwd().parents[1]))\n",
    "from tests.convert_coverage import SERVICES, Api, convert_one, fetch_inventory, targets_for\n",
    "\n",
    "SERVICE = \"image\"\n",
    "api = Api(BASE_URL, API_KEY)\n",
    "source = SERVICES[SERVICE][\"ext_to_fmt\"][INPUT.suffix.lower()]\n",
    "targets = targets_for(api, fetch_inventory(api, SERVICE), SERVICE, source)\n",
    "print(f\"{INPUT.name} ({source}) → {len(targets)} output formats\\n\")\n",
    "\n",
    "results = []\n",
    "for target, engine in targets:\n",
    "    r = convert_one(api, SERVICE, INPUT, source, target, poll_timeout=300, poll_interval=1, engine=engine)\n",
    "    results.append(r)\n",
    "    print(f\"{'PASS' if r.ok else 'FAIL'}  {target:10} {r.seconds:6.1f}s  {'' if r.ok else r.detail[:150]}\")\n",
    "\n",
    "failed = [r.output_format for r in results if not r.ok]\n",
    "print(f\"\\n{len(results) - len(failed)} / {len(results)} passed\" + (f\" — FAILED: {', '.join(failed)}\" if failed else \"\"))"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
