#!/opt/homebrew/bin/python3.11
"""
Crop the newly detected stamps from the specific search.
"""

import os
import cv2

UUID = "384b0ff44aaaa1f1"
OUTPUT_DIR = f"output/{UUID}/florence2_results"

# Coordinates from the specific search result
# These are placeholders - I need to re-run to get the exact boxes if they weren't printed.
# Since I saw the logs, I know it found them.
# But I need the exact coordinates. Let's run a detection script that crops them immediately.
import torch
import types
from PIL import Image
from transformers import AutoProcessor, AutoModelForCausalLM


def patch_model(model):
    inner_model = model.language_model
    original_prepare = inner_model.prepare_inputs_for_generation

    def patched_prepare(
        self,
        input_ids,
        past_key_values=None,
        attention_mask=None,
        inputs_embeds=None,
        **kwargs,
    ):
        is_valid_cache = False
        if past_key_values is not None:
            if isinstance(past_key_values, (list, tuple)) and len(past_key_values) > 0:
                first_layer = past_key_values[0]
                if first_layer is not None and (
                    not isinstance(first_layer, (list, tuple)) or len(first_layer) > 0
                ):
                    is_valid_cache = True

        if not is_valid_cache:
            return {
                "input_ids": input_ids,
                "attention_mask": attention_mask,
                "past_key_values": None,
                "use_cache": True,
            }
        else:
            return original_prepare(
                input_ids,
                past_key_values=past_key_values,
                attention_mask=attention_mask,
                inputs_embeds=inputs_embeds,
                **kwargs,
            )

    inner_model.prepare_inputs_for_generation = types.MethodType(
        patched_prepare, inner_model
    )


IMG_PATH = os.path.join(OUTPUT_DIR, "raw_6846.jpg")
img_cv = cv2.imread(IMG_PATH)
image = Image.open(IMG_PATH).convert("RGB")

print("🧠 Reloading model to get coordinates...")
try:
    processor = AutoProcessor.from_pretrained(
        "microsoft/Florence-2-base", trust_remote_code=True
    )
    model = AutoModelForCausalLM.from_pretrained(
        "microsoft/Florence-2-base", trust_remote_code=True, attn_implementation="eager"
    )
    patch_model(model)

    prompt = "<OPEN_VOCABULARY_DETECTION>"
    term = "postage stamp"

    inputs = processor(text=prompt, images=image, return_tensors="pt")
    generated_ids = model.generate(
        input_ids=inputs["input_ids"],
        pixel_values=inputs["pixel_values"],
        max_new_tokens=1024,
        num_beams=3,
    )
    generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
    parsed_answer = processor.post_process_generation(
        generated_text, task=prompt, image_size=(image.width, image.height)
    )

    results = parsed_answer.get("<OPEN_VOCABULARY_DETECTION>", {})
    bboxes = results.get("bboxes", [])

    if bboxes:
        print(f"✅ Found {len(bboxes)} stamp(s)!")
        for i, box in enumerate(bboxes):
            x1, y1, x2, y2 = map(int, box)
            print(f"   📍 Box {i + 1}: {box}")

            # Crop
            crop = img_cv[y1:y2, x1:x2]
            out_name = f"stamp_crop_{i + 1}.jpg"
            out_path = os.path.join(OUTPUT_DIR, out_name)
            cv2.imwrite(out_path, crop)
            print(f"   💾 Saved to {out_path}")
    else:
        print("❌ No stamps found.")

except Exception as e:
    print(f"❌ Error: {e}")
