#!/usr/bin/env python3
"""Cursive to text with a free AI model on your own computer. From brasspage.com/cursive-to-text/

1. Start llama.cpp's server with Qwen3-VL 8B (two files from huggingface.co/Qwen/Qwen3-VL-8B-Instruct-GGUF):
     llama-server -m Qwen3VL-8B-Instruct-Q4_K_M.gguf --mmproj mmproj-Qwen3VL-8B-Instruct-F16.gguf -ngl 99 -c 12288 --port 8080
2. Then, in a second window:
     python3 cursive_to_text.py letter1.jpg letter2.jpg
   Each photo gets a .txt file next to it. An existing .txt file is never overwritten.

Needs Python 3.9+ and Pillow (pip install pillow). It talks only to the server on your own computer.
AI readers can write words that are not on the page, so check names, dates and numbers against the photo.
"""

from __future__ import annotations

import argparse
import base64
import io
import json
import sys
import urllib.request
from pathlib import Path

from PIL import Image, ImageOps

PROMPT = "Read all the text in the image."


def jpeg(path: Path, side: int = 1920) -> bytes:
    """The photo as a JPEG with a long side of at most `side` px, turned upright."""
    im = ImageOps.exif_transpose(Image.open(path)).convert("RGB")
    im.thumbnail((side, side))
    buf = io.BytesIO()
    im.save(buf, "JPEG", quality=90)
    return buf.getvalue()


def read(path: Path, server: str) -> str:
    url = "data:image/jpeg;base64," + base64.b64encode(jpeg(path)).decode()
    body = {
        "temperature": 0,
        "max_tokens": 4096,
        "messages": [
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": url}},
                    {"type": "text", "text": PROMPT},
                ],
            }
        ],
    }
    req = urllib.request.Request(
        server.rstrip("/") + "/v1/chat/completions",
        json.dumps(body).encode(),
        {"Content-Type": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=600) as r:
        choice = json.load(r)["choices"][0]
    if choice.get("finish_reason") == "length":
        print(f"{path.name}: cut off at 4096 tokens", file=sys.stderr)
    return choice["message"]["content"] or ""


def main() -> int:
    ap = argparse.ArgumentParser(
        description="Turn photos of handwriting into .txt files."
    )
    ap.add_argument("images", nargs="+", type=Path)
    ap.add_argument(
        "--server", default="http://127.0.0.1:8080", help="llama-server address"
    )
    args = ap.parse_args()
    for img in args.images:
        out = img.with_suffix(".txt")
        if out.exists():
            print(f"{img.name}: {out.name} exists, skipped")
            continue
        out.write_text(read(img, args.server).strip() + "\n", encoding="utf-8")
        print(f"{img.name} -> {out.name}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
