import requests
from io import BytesIO
import base64
import json
import time
from PIL import Image, ImageFilter, ImageEnhance


def image_to_base64(pil_image, image_format="JPEG"):
    """将PIL Image图像转换为Base64编码"""
    buffered = BytesIO()
    pil_image.save(buffered, format=image_format)
    img_byte_array = buffered.getvalue()
    encode_image = base64.b64encode(img_byte_array).decode('utf-8')
    return encode_image


def resize_image(image, max_size=512):
    """缩放图像尺寸，保持 OCR 质量"""
    width, height = image.size
    max_dim = max(width, height)

    if max_dim <= max_size:
        return image

    scaling_factor = max_size / max_dim
    new_width = int(width * scaling_factor)
    new_height = int(height * scaling_factor)

    resized = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
    resized = resized.filter(ImageFilter.UnsharpMask(radius=1, percent=120, threshold=3))

    enhancer = ImageEnhance.Contrast(resized)
    resized = enhancer.enhance(1.1)

    return resized


# ==================== 请求 agent_ocr 服务 ====================
image = Image.open('./test1.jpg')
image = resize_image(image)
image_base64 = image_to_base64(image)

print("发送请求到 agent_ocr 服务...")
start = time.time()

response = requests.post(
    "http://127.0.0.1:6006/api/v1/agent_ocr",
    json={
        "image": image_base64,
    },
    timeout=700
)

elapsed = time.time() - start
print(f"耗时: {elapsed:.2f}s  状态码: {response.status_code}")

result = response.json()
print(json.dumps(result, indent=2, ensure_ascii=False))
