#!/bin/bash
set -e

API_KEY="a1a09aad41aa43abbe23122fa1996544"
BASE_URL="https://api.clarifai.com/v2/ext/openai/v1"
MODEL_ID="https://clarifai.com/deepseek-ai/deepseek-ocr/models/DeepSeek-OCR/versions/c52cf7da9b1c4095b07e2a1ccb842811"
OUTPUT_FILE="monastic2-ocr-macron-001-010.txt"

for i in 9 10; do
    IMG=$(printf "%03d.jpg" $i)
    if [ ! -f "$IMG" ]; then
        echo "Image $IMG not found" >&2
        continue
    fi
    
    echo "Processing $IMG..." >&2
    
    B64_TMP=$(mktemp)
    base64 "$IMG" > "$B64_TMP"
    
    text=$(jq -n \
        --arg model "$MODEL_ID" \
        --rawfile b64 "$B64_TMP" \
        '{
            model: $model,
            messages: [
                {
                    role: "system",
                    content: "You are a precise OCR for Pali and Sanskrit texts. Extract all text exactly as it appears. CRITICAL RULES:\n1. Pali uses MACRON vowels: ā, ī, ū (NOT grave accents à, ì, ù).\n2. Preserve dot-below letters: ṭ, ḍ, ṇ, ṃ, ḷ, ṃ.\n3. Preserve s‑with‑diacritics: ś, ṣ.\n4. Preserve line breaks and punctuation.\n5. If uncertain, choose the standard Pali spelling.\nOutput only extracted text, no commentary."
                },
                {
                    role: "user",
                    content: [
                        {
                            type: "text",
                            text: "Extract text with correct Pali diacritics."
                        },
                        {
                            type: "image_url",
                            image_url: {
                                url: ("data:image/jpeg;base64," + $b64)
                            }
                        }
                    ]
                }
            ],
            max_tokens: 4096,
            temperature: 0.0
        }' | curl -s -X POST \
            -H "Authorization: Bearer $API_KEY" \
            -H "Content-Type: application/json" \
            -d @- \
            "$BASE_URL/chat/completions" | jq -r '.choices[0].message.content // empty')
    
    rm "$B64_TMP"
    
    if [ -z "$text" ]; then
        echo "OCR failed for $IMG" >&2
        text="[OCR failed for page $i]"
    fi
    
    echo "=== Page $i ===" >> "$OUTPUT_FILE"
    echo "$text" >> "$OUTPUT_FILE"
    echo "" >> "$OUTPUT_FILE"
    
    sleep 2
done

echo "Done. Appended pages 9‑10." >&2
grep -c "=== Page" "$OUTPUT_FILE"