#!/usr/bin/env python3
import pytesseract
from pdf2image import convert_from_path
import os

def pdf_to_text_ocr(pdf_path, output_path):
    try:
        print("🔄 转换PDF为图片...")
        pages = convert_from_path(pdf_path, dpi=300)
        
        print(f"📄 共找到 {len(pages)} 页")
        
        full_text = ""
        for i, page in enumerate(pages, 1):
            print(f"🔍 OCR识别第 {i} 页...")
            # 使用中文简体识别
            text = pytesseract.image_to_string(page, lang='chi_sim+eng')
            full_text += f"--- 第{i}页 ---\n{text}\n\n"
        
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(full_text)
        
        print(f"✅ 转换完成！")
        print(f"📁 输出文件: {output_path}")
        print(f"📊 文件大小: {os.path.getsize(output_path)} 字节")
        
    except Exception as e:
        print(f"❌ 转换失败: {e}")

if __name__ == "__main__":
    pdf_file = '/root/redirection?filename=许建平解说金瓶梅 (许建平著, Xu Jianping zhu, Jianping Xu, 许建平, 1958- etc.) (Z-Library).pdf&s=davinci&md5=v_T4LyrTS7Sj7g5fUgC3TA&expires=1769341948'
    output_file = '/root/金瓶梅解说_OCR.txt'
    
    pdf_to_text_ocr(pdf_file, output_file)
