l
File size: 4,746 Bytes
c089ca4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/env python3
"""
NZ Legislation Loophole Analysis Streamlit App Runner

This script runs the modern Streamlit application for analyzing New Zealand legislation
to identify potential loopholes, ambiguities, and unintended consequences using AI.

Features:
- Advanced UI with multi-page layout
- Context memory cache system for improved performance
- Real-time progress monitoring
- Interactive results visualization
- Batch processing capabilities
- Comprehensive configuration management

Usage:
    python run_streamlit_app.py

Requirements:
    - All dependencies from requirements.txt must be installed
    - Run from the project root directory
"""

import os
import sys
import subprocess
from pathlib import Path

def check_requirements():
    """Check if all required packages are installed"""
    required_packages = [
        'streamlit',
        'pandas',
        'plotly',
        'llama-cpp-python',
        'psutil',
        'numpy'
    ]

    missing_packages = []

    for package in required_packages:
        try:
            __import__(package.replace('-', '_'))
        except ImportError:
            missing_packages.append(package)

    if missing_packages:
        print("❌ Missing required packages:")
        for package in missing_packages:
            print(f"   - {package}")

        print("\nπŸ“¦ Installing missing packages...")
        try:
            subprocess.check_call([
                sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt'
            ])
            print("βœ… All packages installed successfully!")
        except subprocess.CalledProcessError:
            print("❌ Failed to install packages. Please install manually:")
            print("   pip install -r requirements.txt")
            return False

    return True

def check_app_structure():
    """Check if the app structure is correct"""
    app_dir = Path('streamlit_app')
    required_files = [
        'app.py',
        'core/cache_manager.py',
        'core/text_processor.py',
        'core/llm_analyzer.py',
        'core/dataset_builder.py',
        'utils/config.py',
        'utils/performance.py',
        'utils/ui_helpers.py'
    ]

    missing_files = []

    for file_path in required_files:
        full_path = app_dir / file_path
        if not full_path.exists():
            missing_files.append(str(full_path))

    if missing_files:
        print("❌ Missing app files:")
        for file_path in missing_files:
            print(f"   - {file_path}")
        return False

    print("βœ… App structure is complete!")
    return True

def create_directories():
    """Create necessary directories"""
    directories = [
        'streamlit_app/cache',
        'streamlit_app/config',
        'streamlit_app/datasets',
        'streamlit_app/logs'
    ]

    for dir_path in directories:
        Path(dir_path).mkdir(parents=True, exist_ok=True)
        print(f"πŸ“ Created directory: {dir_path}")

def setup_environment():
    """Setup environment variables and configuration"""
    # Add current directory to Python path for imports
    current_dir = os.path.dirname(os.path.abspath(__file__))
    if current_dir not in sys.path:
        sys.path.insert(0, current_dir)

    # Set environment variables
    os.environ.setdefault('STREAMLIT_SERVER_HEADLESS', 'true')
    os.environ.setdefault('STREAMLIT_BROWSER_GATHER_USAGE_STATS', 'false')

    print("πŸ”§ Environment setup complete!")

def run_app():
    """Run the Streamlit application"""
    print("\nπŸš€ Starting NZ Legislation Loophole Analyzer...")
    print("=" * 60)
    print("πŸ“± Access the app at: http://localhost:8501")
    print("πŸ›‘ Press Ctrl+C to stop the application")
    print("=" * 60)

    try:
        # Change to app directory
        os.chdir('streamlit_app')

        # Run Streamlit
        subprocess.run([
            sys.executable, '-m', 'streamlit', 'run', 'app.py',
            '--server.port', '8501',
            '--server.address', '0.0.0.0',
            '--theme.base', 'light'
        ])

    except KeyboardInterrupt:
        print("\n\nπŸ‘‹ Application stopped by user")
    except Exception as e:
        print(f"\n❌ Error running application: {e}")
        return False

    return True

def main():
    """Main function"""
    print("πŸ›οΈ  NZ Legislation Loophole Analysis Streamlit App")
    print("=" * 60)

    # Check requirements
    if not check_requirements():
        return 1

    # Check app structure
    if not check_app_structure():
        return 1

    # Create directories
    create_directories()

    # Setup environment
    setup_environment()

    # Run the app
    if not run_app():
        return 1

    return 0

if __name__ == "__main__":
    sys.exit(main())