#!/usr/bin/env python3
"""
Crop header từ ảnh trang sách để loại bỏ page number/header trước khi OCR.
Usage: python3 crop_header.py <input> [--top N] [--output O]
"""

import argparse
import os
from PIL import Image

def main():
    parser = argparse.ArgumentParser(description="Crop header from book page")
    parser.add_argument("input", help="Input image path")
    parser.add_argument("--top", type=int, default=None, 
                        help="Pixels to crop from top (auto-detect if omitted)")
    parser.add_argument("--output", "-o", type=str, default=None,
                        help="Output path (default: input_cropped.ext)")
    args = parser.parse_args()

    img = Image.open(args.input)
    w, h = img.size
    print(f"📐 Kích thước gốc: {w}x{h} px")

    # Auto-estimate header: ~15% of height for typical Myanmar book pages
    # (Myanmar books have large top margins with page numbers + section titles)
    crop_top = args.top if args.top else int(h * 0.15)
    
    cropped = img.crop((0, crop_top, w, h))
    print(f"✂️  Crop {crop_top}px từ trên xuống → {cropped.size[0]}x{cropped.size[1]} px")

    if args.output:
        out = args.output
    else:
        base, ext = os.path.splitext(args.input)
        out = f"{base}_cropped{ext}"

    cropped.save(out, quality=95)
    print(f"💾 Đã lưu: {out}")

if __name__ == "__main__":
    main()
