#!/usr/bin/env python3
"""
Streamlit OCR校验工具启动脚本
"""

import subprocess
import sys
import os
from pathlib import Path

def check_streamlit():
    """检查Streamlit是否已安装"""
    try:
        import streamlit
        return True
    except ImportError:
        return False

def install_dependencies():
    """安装必要的依赖"""
    print("📦 安装Streamlit依赖...")
    
    dependencies = [
        "streamlit",
        "plotly", 
        "pandas",
        "pillow",
        "opencv-python"
    ]
    
    for dep in dependencies:
        try:
            print(f"   安装 {dep}...")
            subprocess.check_call([sys.executable, "-m", "pip", "install", dep], 
                                stdout=subprocess.DEVNULL, 
                                stderr=subprocess.DEVNULL)
            print(f"   ✅ {dep} 安装成功")
        except subprocess.CalledProcessError:
            print(f"   ❌ {dep} 安装失败")
            return False
    
    return True

def main():
    """主函数"""
    print("🚀 启动Streamlit OCR校验工具")
    print("=" * 50)
    
    # 检查Streamlit
    if not check_streamlit():
        print("❌ Streamlit未安装")
        choice = input("是否自动安装依赖？(y/n): ")
        if choice.lower() == 'y':
            if not install_dependencies():
                print("❌ 依赖安装失败，请手动安装:")
                print("pip install streamlit plotly pandas pillow opencv-python")
                return
        else:
            print("请手动安装依赖:")
            print("pip install streamlit plotly pandas pillow opencv-python")
            return
    
    # 检查OCR数据
    ocr_out_dir = Path("ocr_out_dir")
    if not ocr_out_dir.exists() or not any(ocr_out_dir.rglob("*.json")):
        print("⚠️  未找到OCR数据文件")
        print("   请先运行OCR处理生成数据文件")
        print("   python3 ocr_by_vlm.py sample_data/your_image.png")
        print("")
    
    # 启动Streamlit
    print("🌐 启动Streamlit应用...")
    print("   浏览器将自动打开 http://localhost:8501")
    print("   按 Ctrl+C 停止应用")
    print("")
    
    try:
        # 启动Streamlit应用
        subprocess.run([
            sys.executable, "-m", "streamlit", "run", 
            "streamlit_ocr_validator.py",
            "--server.headless", "false",
            "--server.port", "8501"
        ])
    except KeyboardInterrupt:
        print("\n👋 应用已停止")
    except FileNotFoundError:
        print("❌ streamlit_ocr_validator.py 文件不存在")
    except Exception as e:
        print(f"❌ 启动失败: {e}")

if __name__ == "__main__":
    main()
