{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7fb27b941602401d91542211134fc71a",
   "metadata": {},
   "source": [
    "# Assisted business document suggestions (ES/PT/EN)\n",
    "\n",
    "Available on [AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-abuc7lbqsoab4). The exact image passed real-time and batch qualification; the complete SDK notebook passed a seller-account rehearsal. Independent buyer checkout is not measured.\n",
    "\n",
    "Give a reviewer two type suggestions for one already extracted, known-supported business document. A person must choose or reject them. No OCR, unknown/mixed detection, authenticity checks or automated routing. Validation uses generated examples; real customer-document accuracy is unmeasured.\n",
    "\n",
    "Default **Run All is offline**. To deploy, subscribe in AWS Marketplace, copy your subscribed **us-east-1** model-package ARN into `DOCUMENT_CLASSIFIER_MODEL_PACKAGE_ARN`, supply an existing `SAGEMAKER_EXECUTION_ROLE_ARN`, review IAM/costs/cleanup, then set `RUN_DEMO=True`. AWS infrastructure charges are separate from software/trial terms. This example creates one temporary CPU endpoint and deletes its own resources in `finally`. If the kernel is terminated, use the printed name to verify/remove that endpoint in your account; charges continue while it exists. No S3 bucket, IAM role or data capture is created.\n",
    "\n",
    "The optional Batch Transform section below also defaults off. It uses the included fictional three-language examples and an existing S3 bucket you authorize in us-east-1. It writes only a unique demo prefix, retains its small input/output objects for inspection, and cleans up the task model after the job stops. Your execution role needs read/write access to that prefix. Neither example creates a bucket or IAM role.\n",
    "\n",
    "Seller-account rehearsal: a certified seller-owned source has no buyer ProductId.\n",
    "The notebook verifies its actual source association with this Limited/Public\n",
    "product and Released offer through read-only Catalog calls. Ordinary subscribed\n",
    "packages follow their Marketplace identity path. Seller rehearsal does not prove\n",
    "an independent buyer's checkout or entitlement, and no subscription is purchased.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "acae54e37e7d407bbb7b55eff062a284",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import os\n",
    "import re\n",
    "import uuid\n",
    "\n",
    "import boto3\n",
    "\n",
    "# Preserve references if an earlier cleanup needs attention.\n",
    "if any(\n",
    "    globals().get(key, False)\n",
    "    for key in (\"model_created\", \"config_created\", \"endpoint_created\", \"batch_model_created\", \"batch_job_started\")\n",
    "):\n",
    "    raise RuntimeError(\"Clean up the previous demo before rerunning setup; its resource names are preserved.\")\n",
    "\n",
    "# Default Run All performs no AWS requests and creates no resources.\n",
    "RUN_DEMO = False\n",
    "REGION = \"us-east-1\"\n",
    "# Exact image verified by private real-time and certified batch execution.\n",
    "APPROVED_IMAGE_DIGEST = \"sha256:58d7c9ad8b9f56f1ccb2f313cc9380327a7e45d91a5af4dd972b7ea34d9da89b\"\n",
    "PACKAGE_ARN = os.environ.get(\"DOCUMENT_CLASSIFIER_MODEL_PACKAGE_ARN\", \"\").strip()\n",
    "ROLE_ARN = os.environ.get(\"SAGEMAKER_EXECUTION_ROLE_ARN\", \"\").strip()\n",
    "DEMO_RUN_NAME = (\n",
    "    os.environ.get(\"DOCUMENT_CLASSIFIER_DEMO_RUN_NAME\", \"\").strip() or \"ss-document-demo-\" + uuid.uuid4().hex[:12]\n",
    ")\n",
    "SAMPLE_REQUEST = {\n",
    "    \"instances\": [\n",
    "        {\n",
    "            \"filename\": \"document-025.txt\",\n",
    "            \"id\": \"final-en-bank_statement-01\",\n",
    "            \"text\": \"Business Account Activity, Period Ending 31 October\\n\"\n",
    "            \"Fictional Stonebridge Ledger Bank reports account 4408 for \"\n",
    "            \"Northglass Exhibit Works. Opening balance was $9,840.00. \"\n",
    "            \"Credits were $3,500.00; debits were $1,120.00 for equipment \"\n",
    "            \"rental and $340.00 in service fees. Closing balance is \"\n",
    "            \"$11,880.00. The cycle covers 1 through 31 October 2026. \"\n",
    "            \"Reconcile outstanding entries before the next monthly close.\",\n",
    "        }\n",
    "    ]\n",
    "}\n",
    "\n",
    "\n",
    "MARKETPLACE_PRODUCT_ID = \"prod-c7nqgnwq4v55q\"\n",
    "MARKETPLACE_OFFER_ID = \"offer-5xz2zondvkpts\"\n",
    "\n",
    "\n",
    "def validate_package(package, session, caller_account):\n",
    "    if package.get(\"ModelPackageStatus\") != \"Completed\":\n",
    "        raise ValueError(\"The subscribed package is not Completed.\")\n",
    "    containers = package.get(\"InferenceSpecification\", {}).get(\"Containers\", [])\n",
    "    if len(containers) != 1:\n",
    "        raise ValueError(\"Use a single-container Marketplace model-package ARN.\")\n",
    "    digest = containers[0].get(\"ImageDigest\") or containers[0].get(\"Image\", \"\").partition(\"@\")[2]\n",
    "    if digest != APPROVED_IMAGE_DIGEST:\n",
    "        raise ValueError(\"The subscribed image differs from this release.\")\n",
    "    if containers[0].get(\"ProductId\"):\n",
    "        return \"marketplace_package\"\n",
    "    # A seller-owned source package has no buyer ProductId. Verify its actual\n",
    "    # association instead of pretending a subscription was purchased.\n",
    "    arn = package.get(\"ModelPackageArn\", \"\")\n",
    "    if not (\n",
    "        package.get(\"CertifyForMarketplace\") is True\n",
    "        and arn.startswith(f\"arn:aws:sagemaker:{REGION}:{caller_account}:model-package/\")\n",
    "    ):\n",
    "        raise ValueError(\"Use your subscribed Marketplace model-package ARN.\")\n",
    "    catalog = session.client(\"marketplace-catalog\")\n",
    "    product = json.loads(catalog.describe_entity(Catalog=\"AWSMarketplace\", EntityId=MARKETPLACE_PRODUCT_ID)[\"Details\"])\n",
    "    offer = json.loads(catalog.describe_entity(Catalog=\"AWSMarketplace\", EntityId=MARKETPLACE_OFFER_ID)[\"Details\"])\n",
    "    sources = [\n",
    "        source\n",
    "        for version in product.get(\"Versions\", [])\n",
    "        if version.get(\"VersionTitle\") == \"1.0.0\"\n",
    "        for source in version.get(\"Sources\", [])\n",
    "    ]\n",
    "    if not (\n",
    "        product.get(\"Description\", {}).get(\"Visibility\") in {\"Limited\", \"Public\"}\n",
    "        and len(sources) == 1\n",
    "        and sources[0].get(\"ModelPackageArn\") == arn\n",
    "        and offer.get(\"ProductId\") == MARKETPLACE_PRODUCT_ID\n",
    "        and offer.get(\"State\") == \"Released\"\n",
    "    ):\n",
    "        raise ValueError(\"Seller package is not associated with the released Marketplace offer.\")\n",
    "    print(\"Verified seller-account Marketplace source; this is not a buyer subscription test.\")\n",
    "    return \"seller_owned_marketplace_source\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9a63283cbaf04dbcab1f6479b197f3a8",
   "metadata": {},
   "outputs": [],
   "source": [
    "if not RUN_DEMO:\n",
    "    print(\"Offline preview only. Review costs and set RUN_DEMO=True to create a temporary endpoint.\")\n",
    "else:\n",
    "    if any(globals().get(key, False) for key in (\"model_created\", \"config_created\", \"endpoint_created\")):\n",
    "        raise RuntimeError(\"Clean up the previous demo before creating another endpoint.\")\n",
    "    if REGION != \"us-east-1\" or not re.fullmatch(r\"ss-document-demo-[0-9a-f]{12}\", DEMO_RUN_NAME):\n",
    "        raise ValueError(\"Use the qualified us-east-1 region and a unique demo run name.\")\n",
    "    if not re.fullmatch(r\"sha256:[0-9a-f]{64}\", APPROVED_IMAGE_DIGEST):\n",
    "        raise ValueError(\"Unreleased candidate: no qualified image digest is configured.\")\n",
    "    if not re.fullmatch(r\"arn:aws:sagemaker:us-east-1:\\d{12}:model-package/[A-Za-z0-9-]+\", PACKAGE_ARN):\n",
    "        raise ValueError(\"Set DOCUMENT_CLASSIFIER_MODEL_PACKAGE_ARN to your subscribed us-east-1 ARN.\")\n",
    "    session = boto3.Session(region_name=REGION)\n",
    "    account_id = session.client(\"sts\").get_caller_identity()[\"Account\"]\n",
    "    if not ROLE_ARN.startswith(f\"arn:aws:iam::{account_id}:role/\"):\n",
    "        raise ValueError(\"Provide an existing SageMaker execution role from your account.\")\n",
    "    sm = session.client(\"sagemaker\")\n",
    "    validate_package(sm.describe_model_package(ModelPackageName=PACKAGE_ARN), session, account_id)\n",
    "    name = DEMO_RUN_NAME\n",
    "    tags = [{\"Key\": \"SoftwareSushiDemoRun\", \"Value\": name}]\n",
    "    model_created = config_created = endpoint_created = False\n",
    "    print(\"Creating\", name, \"on one ml.c5.xlarge. Cleanup runs in finally; retain this name.\")\n",
    "    try:\n",
    "        sm.create_model(\n",
    "            ModelName=name,\n",
    "            ExecutionRoleArn=ROLE_ARN,\n",
    "            PrimaryContainer={\"ModelPackageName\": PACKAGE_ARN},\n",
    "            EnableNetworkIsolation=True,\n",
    "            Tags=tags,\n",
    "        )\n",
    "        model_created = True\n",
    "        sm.create_endpoint_config(\n",
    "            EndpointConfigName=name,\n",
    "            ProductionVariants=[\n",
    "                {\n",
    "                    \"VariantName\": \"AllTraffic\",\n",
    "                    \"ModelName\": name,\n",
    "                    \"InstanceType\": \"ml.c5.xlarge\",\n",
    "                    \"InitialInstanceCount\": 1,\n",
    "                    \"InitialVariantWeight\": 1,\n",
    "                    \"ContainerStartupHealthCheckTimeoutInSeconds\": 180,\n",
    "                    \"ModelDataDownloadTimeoutInSeconds\": 300,\n",
    "                }\n",
    "            ],\n",
    "            Tags=tags,\n",
    "        )\n",
    "        config_created = True\n",
    "        sm.create_endpoint(EndpointName=name, EndpointConfigName=name, Tags=tags)\n",
    "        endpoint_created = True\n",
    "        sm.get_waiter(\"endpoint_in_service\").wait(EndpointName=name, WaiterConfig={\"Delay\": 15, \"MaxAttempts\": 120})\n",
    "        response = session.client(\"sagemaker-runtime\").invoke_endpoint(\n",
    "            EndpointName=name, ContentType=\"application/json\", Body=json.dumps(SAMPLE_REQUEST).encode()\n",
    "        )\n",
    "        result = json.loads(response[\"Body\"].read())\n",
    "        print(json.dumps(result, indent=2, ensure_ascii=False))\n",
    "        assert result[\"predictions\"][0][\"selection_required\"] is True\n",
    "        print(\"Review both suggestions and explicitly choose or reject them in your application.\")\n",
    "    finally:\n",
    "        # Only the uniquely named resources created by this invocation are removed.\n",
    "        if endpoint_created:\n",
    "            current = sm.describe_endpoint(EndpointName=name)\n",
    "            if current[\"EndpointConfigName\"] != name:\n",
    "                raise RuntimeError(\"Endpoint identity differs; preserve it for manual review.\")\n",
    "            sm.delete_endpoint(EndpointName=name)\n",
    "            sm.get_waiter(\"endpoint_deleted\").wait(EndpointName=name, WaiterConfig={\"Delay\": 15, \"MaxAttempts\": 120})\n",
    "            endpoint_created = False\n",
    "        if config_created:\n",
    "            current = sm.describe_endpoint_config(EndpointConfigName=name)\n",
    "            if len(current[\"ProductionVariants\"]) != 1 or current[\"ProductionVariants\"][0][\"ModelName\"] != name:\n",
    "                raise RuntimeError(\"Endpoint configuration differs; preserve it for manual review.\")\n",
    "            sm.delete_endpoint_config(EndpointConfigName=name)\n",
    "            config_created = False\n",
    "        if model_created:\n",
    "            current = sm.describe_model(ModelName=name)\n",
    "            if current[\"PrimaryContainer\"].get(\"ModelPackageName\") != PACKAGE_ARN:\n",
    "                raise RuntimeError(\"Model package identity differs; preserve it for manual review.\")\n",
    "            sm.delete_model(ModelName=name)\n",
    "            model_created = False\n",
    "        print(\"Temporary demo cleanup completed:\", name)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8dd0d8092fe74a7c96281538738b07e2",
   "metadata": {},
   "source": [
    "## Optional Batch Transform example\n",
    "\n",
    "Set `DOCUMENT_CLASSIFIER_BATCH_BUCKET` to an existing authorized bucket in\n",
    "us-east-1, review storage/compute/software charges, then enable `RUN_BATCH_DEMO`.\n",
    "The included ES/PT/EN text is fictional. No external dataset or file upload is\n",
    "needed. Keep the printed job/model/prefix for inspection. Input/output S3 objects\n",
    "are retained; remove those exact demo objects yourself when no longer needed.\n",
    "The code uses line splitting, SingleRecord, one C5 instance and concurrency one.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72eea5119410473aa328ad9291626812",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Default Run All remains offline.\n",
    "RUN_BATCH_DEMO = False\n",
    "BATCH_BUCKET = os.environ.get(\"DOCUMENT_CLASSIFIER_BATCH_BUCKET\", \"\").strip()\n",
    "BATCH_REQUESTS = [\n",
    "    {\n",
    "        \"instances\": [\n",
    "            {\n",
    "                \"filename\": \"document-025.txt\",\n",
    "                \"id\": \"final-en-bank_statement-01\",\n",
    "                \"text\": (\n",
    "                    \"Business Account Activity, Period Ending 31 October\\nFictional Sto\"\n",
    "                    \"nebridge Ledger Bank reports account 4408 for Northglass Exhibit \"\n",
    "                    \"Works. Opening balance was $9,840.00. Credits were $3,500.00; deb\"\n",
    "                    \"its were $1,120.00 for equipment rental and $340.00 in service fe\"\n",
    "                    \"es. Closing balance is $11,880.00. The cycle covers 1 through 31 \"\n",
    "                    \"October 2026. Reconcile outstanding entries before the next month\"\n",
    "                    \"ly close.\"\n",
    "                ),\n",
    "            }\n",
    "        ]\n",
    "    },\n",
    "    {\n",
    "        \"instances\": [\n",
    "            {\n",
    "                \"filename\": \"document-025.txt\",\n",
    "                \"id\": \"final-es-bank_statement-01\",\n",
    "                \"text\": (\n",
    "                    \"Estado de cuenta empresarial, período del 1 al 31 de enero. Coope\"\n",
    "                    \"rativa Horizonte registra saldo inicial de MXN 84.200, depósitos \"\n",
    "                    \"por 126.000 y débitos por 97.450. Se detallan nómina, renta de of\"\n",
    "                    \"icina y dos abonos de clientes. Saldo final: MXN 112.750. No hay \"\n",
    "                    \"cargos pendientes al cierre; las operaciones pueden objetarse dur\"\n",
    "                    \"ante los treinta días siguientes.\"\n",
    "                ),\n",
    "            }\n",
    "        ]\n",
    "    },\n",
    "    {\n",
    "        \"instances\": [\n",
    "            {\n",
    "                \"filename\": \"document-025.txt\",\n",
    "                \"id\": \"final-pt-bank_statement-01\",\n",
    "                \"text\": (\n",
    "                    \"EXTRATO EMPRESARIAL — Cooperativa Horizonte de Barro, conta de mo\"\n",
    "                    \"vimento 00418-7, período de 1 a 15 de novembro. Saldo inicial: R$\"\n",
    "                    \" 12.460,00. Entradas identificadas: vendas balcão, R$ 8.320,00; r\"\n",
    "                    \"epasse Feira do Vale, R$ 1.180,00. Saídas: aluguel do galpão, R$ \"\n",
    "                    \"2.100,00; fornecedor Argila Serena, R$ 860,00. Saldo final dispon\"\n",
    "                    \"ível: R$ 19.000,00.\"\n",
    "                ),\n",
    "            }\n",
    "        ]\n",
    "    },\n",
    "]\n",
    "\n",
    "if not RUN_BATCH_DEMO:\n",
    "    print(\"Offline batch preview only. Supply an authorized S3 bucket and explicitly enable the demo.\")\n",
    "else:\n",
    "    if any(globals().get(key, False) for key in (\"batch_model_created\", \"batch_job_started\")):\n",
    "        raise RuntimeError(\"Previous batch cleanup is incomplete; resource references are preserved.\")\n",
    "    if REGION != \"us-east-1\" or not re.fullmatch(r\"ss-document-demo-[0-9a-f]{12}\", DEMO_RUN_NAME):\n",
    "        raise ValueError(\"Use the qualified region and a unique task-owned demo name.\")\n",
    "    if not re.fullmatch(r\"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]\", BATCH_BUCKET):\n",
    "        raise ValueError(\"Supply an existing authorized S3 batch bucket.\")\n",
    "    if not re.fullmatch(r\"arn:aws:sagemaker:us-east-1:\\d{12}:model-package/[A-Za-z0-9-]+\", PACKAGE_ARN):\n",
    "        raise ValueError(\"Set the subscribed Marketplace package ARN before opting in.\")\n",
    "    session = boto3.Session(region_name=REGION)\n",
    "    account_id = session.client(\"sts\").get_caller_identity()[\"Account\"]\n",
    "    if not ROLE_ARN.startswith(f\"arn:aws:iam::{account_id}:role/\"):\n",
    "        raise ValueError(\"Provide an existing SageMaker execution role from your account.\")\n",
    "    sm, s3 = session.client(\"sagemaker\"), session.client(\"s3\")\n",
    "    validate_package(sm.describe_model_package(ModelPackageName=PACKAGE_ARN), session, account_id)\n",
    "    if (s3.get_bucket_location(Bucket=BATCH_BUCKET)[\"LocationConstraint\"] or \"us-east-1\") != REGION:\n",
    "        raise ValueError(\"Use an S3 bucket in the qualified region.\")\n",
    "    batch_name = DEMO_RUN_NAME + \"-batch\"\n",
    "    batch_prefix = \"document-classifier-qualification/notebook/\" + DEMO_RUN_NAME\n",
    "    input_key = batch_prefix + \"/input/examples.jsonl\"\n",
    "    output_prefix = batch_prefix + \"/output/\"\n",
    "    payload = \"\".join(json.dumps(row, ensure_ascii=False) + \"\\n\" for row in BATCH_REQUESTS).encode()\n",
    "    # Never overwrite an earlier run's input, even if a name is accidentally reused.\n",
    "    s3.put_object(\n",
    "        Bucket=BATCH_BUCKET,\n",
    "        Key=input_key,\n",
    "        Body=payload,\n",
    "        ContentType=\"application/jsonlines\",\n",
    "        ServerSideEncryption=\"AES256\",\n",
    "        IfNoneMatch=\"*\",\n",
    "    )\n",
    "    batch_model_created = batch_job_started = False\n",
    "    print(\"Batch model/job:\", batch_name, \"S3 prefix:\", batch_prefix)\n",
    "    try:\n",
    "        sm.create_model(\n",
    "            ModelName=batch_name,\n",
    "            ExecutionRoleArn=ROLE_ARN,\n",
    "            PrimaryContainer={\"ModelPackageName\": PACKAGE_ARN},\n",
    "            EnableNetworkIsolation=True,\n",
    "            Tags=[{\"Key\": \"SoftwareSushiDemoRun\", \"Value\": DEMO_RUN_NAME}],\n",
    "        )\n",
    "        batch_model_created = True\n",
    "        sm.create_transform_job(\n",
    "            TransformJobName=batch_name,\n",
    "            ModelName=batch_name,\n",
    "            BatchStrategy=\"SingleRecord\",\n",
    "            MaxConcurrentTransforms=1,\n",
    "            MaxPayloadInMB=1,\n",
    "            ModelClientConfig={\"InvocationsTimeoutInSeconds\": 60, \"InvocationsMaxRetries\": 0},\n",
    "            TransformInput={\n",
    "                \"DataSource\": {\"S3DataSource\": {\"S3DataType\": \"S3Prefix\", \"S3Uri\": f\"s3://{BATCH_BUCKET}/{input_key}\"}},\n",
    "                \"ContentType\": \"application/jsonlines\",\n",
    "                \"CompressionType\": \"None\",\n",
    "                \"SplitType\": \"Line\",\n",
    "            },\n",
    "            TransformOutput={\n",
    "                \"S3OutputPath\": f\"s3://{BATCH_BUCKET}/{output_prefix}\",\n",
    "                \"Accept\": \"application/jsonlines\",\n",
    "                \"AssembleWith\": \"Line\",\n",
    "            },\n",
    "            TransformResources={\"InstanceType\": \"ml.c5.xlarge\", \"InstanceCount\": 1},\n",
    "            Tags=[{\"Key\": \"SoftwareSushiDemoRun\", \"Value\": DEMO_RUN_NAME}],\n",
    "        )\n",
    "        batch_job_started = True\n",
    "        sm.get_waiter(\"transform_job_completed_or_stopped\").wait(\n",
    "            TransformJobName=batch_name, WaiterConfig={\"Delay\": 15, \"MaxAttempts\": 120}\n",
    "        )\n",
    "        job = sm.describe_transform_job(TransformJobName=batch_name)\n",
    "        if job[\"TransformJobStatus\"] != \"Completed\":\n",
    "            raise RuntimeError(\"Batch did not complete successfully; inspect the task job.\")\n",
    "        raw = s3.get_object(Bucket=BATCH_BUCKET, Key=output_prefix + \"examples.jsonl.out\")[\"Body\"].read()\n",
    "        results = [json.loads(line) for line in raw.splitlines()]\n",
    "        assert len(results) == len(BATCH_REQUESTS)\n",
    "        for request, response in zip(BATCH_REQUESTS, results, strict=True):\n",
    "            assert len(response[\"predictions\"]) == 1\n",
    "            row = response[\"predictions\"][0]\n",
    "            assert row[\"id\"] == request[\"instances\"][0][\"id\"]\n",
    "            assert row[\"selection_required\"] is True and row[\"needs_review\"] is True\n",
    "            assert len(row[\"suggestions\"]) == 2 and row[\"validation_basis\"] == \"generated_only\"\n",
    "        print(json.dumps(results, indent=2, ensure_ascii=False))\n",
    "    finally:\n",
    "        if batch_job_started:\n",
    "            current = sm.describe_transform_job(TransformJobName=batch_name)\n",
    "            if current[\"ModelName\"] != batch_name:\n",
    "                raise RuntimeError(\"Job model identity differs; preserve resources for review.\")\n",
    "            if current[\"TransformJobStatus\"] == \"InProgress\":\n",
    "                sm.stop_transform_job(TransformJobName=batch_name)\n",
    "            if current[\"TransformJobStatus\"] not in {\"Completed\", \"Failed\", \"Stopped\"}:\n",
    "                sm.get_waiter(\"transform_job_completed_or_stopped\").wait(\n",
    "                    TransformJobName=batch_name, WaiterConfig={\"Delay\": 15, \"MaxAttempts\": 120}\n",
    "                )\n",
    "            current = sm.describe_transform_job(TransformJobName=batch_name)\n",
    "            if current[\"TransformJobStatus\"] not in {\"Completed\", \"Failed\", \"Stopped\"}:\n",
    "                raise RuntimeError(\"Batch compute is still active; preserve model and retry cleanup.\")\n",
    "            batch_job_started = False\n",
    "        if batch_model_created:\n",
    "            current = sm.describe_model(ModelName=batch_name)\n",
    "            if current[\"PrimaryContainer\"].get(\"ModelPackageName\") != PACKAGE_ARN:\n",
    "                raise RuntimeError(\"Batch package identity differs; preserve the task model.\")\n",
    "            sm.delete_model(ModelName=batch_name)\n",
    "            batch_model_created = False\n",
    "        print(\"Batch compute stopped; model cleaned. Task S3 evidence retained:\", batch_prefix)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
