import base64
import requests
import json

# API Key
API_KEY = "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"

# Đọc file PDF và convert sang base64
pdf_path = 'Chuan Muc Sadi/pdf/Sadi-206-210.pdf'
with open(pdf_path, 'rb') as f:
    pdf_base64 = base64.b64encode(f.read()).decode('utf-8')

# Prompt cho OCR
prompt = """Trích xuất toàn bộ văn bản tiếng Myanmar từ file PDF này. 
Giữ nguyên định dạng, số trang, và mọi ký tự. 
Xuất ra markdown với số trang rõ ràng. 
Đây là văn bản Phật pháp nên cần chính xác tuyệt đối, 
đặc biệt với thuật ngữ Pali và số Myanmar.
Không được bỏ sót bất kỳ nội dung nào."""

# API call đến OpenRouter với Qwen 3.5
headers = {
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/json',
    'HTTP-Referer': 'https://openclaw.ai',
    'X-Title': 'OpenClaw OCR'
}

payload = {
    "model": "qwen/qwen3.5-397b-a17b",
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": prompt
                },
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:application/pdf;base64,{pdf_base64}"
                    }
                }
            ]
        }
    ],
    "max_tokens": 16000
}

print("Đang gửi request đến OpenRouter...")
response = requests.post(
    "https://openrouter.ai/api/v1/chat/completions",
    headers=headers,
    json=payload
)

if response.status_code == 200:
    result = response.json()
    ocr_text = result['choices'][0]['message']['content']
    
    if ocr_text:
        # Lưu kết quả
        output_path = 'Chuan Muc Sadi/Sadi-206-210-qwen.md'
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(ocr_text)
        
        print(f"✅ OCR hoàn thành! Đã lưu vào: {output_path}")
        print(f"Số ký tự: {len(ocr_text)}")
    else:
        print("❌ Lỗi: Không có nội dung OCR trong response")
        print(json.dumps(result, indent=2, ensure_ascii=False))
else:
    print(f"❌ Lỗi: {response.status_code}")
    print(response.text)
