#!/usr/bin/env python3
"""
删除PDF中的空白页
"""

import sys
from pathlib import Path

try:
    import fitz  # PyMuPDF
except ImportError:
    print("错误: 需要安装PyMuPDF库")
    print("请运行: pip install PyMuPDF")
    sys.exit(1)

def is_blank_page(page, threshold=100):
    """
    判断页面是否为空白页
    threshold: 文本字符数阈值，少于此值认为是空白页
    """
    # 获取页面文本
    text = page.get_text().strip()
    
    # 如果文本很少，认为是空白页
    if len(text) < threshold:
        return True
    
    # 检查是否只包含页码或其他无意义内容
    # 如果文本只是数字（页码），也认为是空白页
    if text.isdigit() and len(text) <= 3:
        return True
    
    # 检查是否只包含空白字符和少量标点
    meaningful_chars = sum(1 for c in text if c.isalnum())
    if meaningful_chars < 10:  # 少于10个有意义的字符
        return True
    
    return False

def remove_blank_pages(input_pdf, output_pdf, threshold=100):
    """
    删除PDF中的空白页
    """
    try:
        doc = fitz.open(input_pdf)
        total_pages = len(doc)
        
        # 找出非空白页
        pages_to_keep = []
        for page_num in range(total_pages):
            page = doc[page_num]
            if not is_blank_page(page, threshold):
                pages_to_keep.append(page_num)
        
        # 创建新PDF，只包含非空白页
        if pages_to_keep:
            new_doc = fitz.open()
            for page_num in pages_to_keep:
                new_doc.insert_pdf(doc, from_page=page_num, to_page=page_num)
            
            new_doc.save(output_pdf)
            new_doc.close()
            
            removed_count = total_pages - len(pages_to_keep)
            print(f"成功: 总页数 {total_pages}, 删除空白页 {removed_count}, 保留页数 {len(pages_to_keep)}")
            return True
        else:
            print("错误: 所有页面都是空白页")
            return False
            
    except Exception as e:
        print(f"错误: {e}")
        return False
    finally:
        if 'doc' in locals():
            doc.close()

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("用法: python remove_blank_pages.py <输入PDF> <输出PDF> [阈值]")
        print("阈值默认为100，表示少于100个字符的页面视为空白页")
        sys.exit(1)
    
    input_pdf = sys.argv[1]
    output_pdf = sys.argv[2]
    threshold = int(sys.argv[3]) if len(sys.argv) > 3 else 100
    
    if not Path(input_pdf).exists():
        print(f"错误: 输入文件不存在: {input_pdf}")
        sys.exit(1)
    
    success = remove_blank_pages(input_pdf, output_pdf, threshold)
    sys.exit(0 if success else 1)
