#!/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-001-010.txt"
echo "" > "$OUTPUT_FILE"

for i in $(seq 1 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: "Extract all text exactly as appears. Preserve all characters, diacritics, punctuation, and line breaks. No commentary."
                },
                {
                    role: "user",
                    content: [
                        {
                            type: "text",
                            text: "Extract text."
                        },
                        {
                            type: "image_url",
                            image_url: {
                                url: ("data:image/jpeg;base64," + $b64)
                            }
                        }
                    ]
                }
            ],
            max_tokens: 4096,
            temperature: 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 1
done

echo "Done. First few lines of output:" >&2
cat "$OUTPUT_FILE" | head -30