#!/bin/bash

echo "OCR with IONOS AI Model Hub"
echo -e "===========================\n"

echo "Prerequisite: Access API Token from environment variable"
echo "--------------------------------------------------------"

# You typically do not want to display the IONOS_API_TOKEN in logs
# or your bash history. Hence, we only show the first 10 characters.
echo "IONOS_API_TOKEN: ${IONOS_API_TOKEN:0:10}"

IONOS_API_URL="https://openai.inference.de-txl.ionos.com/v1/chat/completions"
MODEL="lightonai/LightOnOCR-2-1B"

echo -e "\nStep 1: Basic OCR — Extract text from a URL image"
echo "--------------------------------------------------"

RESPONSE=$(curl -s -X POST "$IONOS_API_URL" \
  -H "Authorization: Bearer ${IONOS_API_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "image_url",
            "image_url": {
              "url": "https://example.com/document.png"
            }
          }
        ]
      }
    ],
    "max_tokens": 4096,
    "temperature": 0.2,
    "top_p": 0.9
  }')

echo "$RESPONSE" | jq -r '.choices[0].message.content'

echo -e "\nStep 2: OCR with a local image (base64 encoding)"
echo "--------------------------------------------------"

LOCAL_IMAGE="document.png"

if [ -f "$LOCAL_IMAGE" ]; then
    IMAGE_BASE64=$(base64 -w 0 "$LOCAL_IMAGE")
    IMAGE_DATA_URL="data:image/png;base64,${IMAGE_BASE64}"

    RESPONSE_LOCAL=$(curl -s -X POST "$IONOS_API_URL" \
      -H "Authorization: Bearer ${IONOS_API_TOKEN}" \
      -H "Content-Type: application/json" \
      -d "{
        \"model\": \"$MODEL\",
        \"messages\": [
          {
            \"role\": \"user\",
            \"content\": [
              {
                \"type\": \"image_url\",
                \"image_url\": {
                  \"url\": \"${IMAGE_DATA_URL}\"
                }
              }
            ]
          }
        ],
        \"max_tokens\": 4096,
        \"temperature\": 0.2,
        \"top_p\": 0.9
      }")

    echo "$RESPONSE_LOCAL" | jq -r '.choices[0].message.content'
else
    echo "Local image '$LOCAL_IMAGE' not found. Skipping this step."
    echo "Place a document image at this path to test local image OCR."
fi

echo -e "\nStep 3: Inspect usage details"
echo "-----------------------------"

echo "$RESPONSE" | jq '.usage'
