File size: 3,804 Bytes
6880cd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#!/usr/bin/env python3
"""
Startup script for Book Summarizer AI
This script helps you start both the FastAPI backend and Streamlit frontend.
"""

import subprocess
import sys
import time
import requests
import os
from pathlib import Path

def check_dependencies():
    """Check if required packages are installed."""
    required_packages = [
        'streamlit', 'fastapi', 'uvicorn', 'transformers', 
        'torch', 'PyPDF2', 'pdfplumber', 'nltk'
    ]
    
    missing_packages = []
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print("❌ Missing required packages:")
        for package in missing_packages:
            print(f"   - {package}")
        print("\nπŸ“¦ Install them with: pip install -r requirements.txt")
        return False
    
    print("βœ… All dependencies are installed")
    return True

def download_nltk_data():
    """Download required NLTK data."""
    try:
        import nltk
        nltk.download('punkt', quiet=True)
        nltk.download('stopwords', quiet=True)
        print("βœ… NLTK data downloaded")
    except Exception as e:
        print(f"⚠️  Warning: Could not download NLTK data: {e}")

def check_api_health():
    """Check if the API is running and healthy."""
    try:
        response = requests.get("http://localhost:8000/health", timeout=5)
        return response.status_code == 200
    except:
        return False

def start_api():
    """Start the FastAPI backend."""
    print("πŸš€ Starting FastAPI backend...")
    
    # Check if API is already running
    if check_api_health():
        print("βœ… API is already running")
        return True
    
    try:
        # Start the API server
        api_process = subprocess.Popen([
            sys.executable, "-m", "uvicorn", 
            "api.main:app", 
            "--reload", 
            "--port", "8000",
            "--host", "0.0.0.0"
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        # Wait for API to start
        print("⏳ Waiting for API to start...")
        for i in range(30):  # Wait up to 30 seconds
            time.sleep(1)
            if check_api_health():
                print("βœ… API started successfully")
                return True
        
        print("❌ API failed to start within 30 seconds")
        return False
        
    except Exception as e:
        print(f"❌ Error starting API: {e}")
        return False

def start_frontend():
    """Start the Streamlit frontend."""
    print("🌐 Starting Streamlit frontend...")
    
    try:
        # Start Streamlit
        subprocess.run([
            sys.executable, "-m", "streamlit", "run", "app.py",
            "--server.port", "8501",
            "--server.address", "0.0.0.0"
        ])
    except KeyboardInterrupt:
        print("\nπŸ‘‹ Shutting down...")
    except Exception as e:
        print(f"❌ Error starting frontend: {e}")

def main():
    """Main startup function."""
    print("πŸ“š Book Summarizer AI - Startup")
    print("=" * 40)
    
    # Check dependencies
    if not check_dependencies():
        sys.exit(1)
    
    # Download NLTK data
    download_nltk_data()
    
    print("\nπŸ”§ Starting services...")
    
    # Start API
    if not start_api():
        print("❌ Failed to start API. Please check the logs.")
        sys.exit(1)
    
    print("\nπŸŽ‰ Ready! Opening the application...")
    print("πŸ“– Frontend: http://localhost:8501")
    print("πŸ”Œ API: http://localhost:8000")
    print("πŸ“š API Docs: http://localhost:8000/docs")
    print("\nπŸ’‘ Press Ctrl+C to stop the application")
    
    # Start frontend
    start_frontend()

if __name__ == "__main__":
    main()