File size: 5,753 Bytes
80323f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
178
179
180
181
182
#!/usr/bin/env python3
"""
Startup script for PerplexityViewer Gradio app
"""

import os
import sys
import subprocess
import argparse
import warnings

# Suppress warnings
warnings.filterwarnings("ignore")
os.environ["TOKENIZERS_PARALLELISM"] = "false"

def check_dependencies():
    """Check if required packages are installed"""
    required_packages = [
        "torch",
        "transformers",
        "gradio",
        "pandas",
        "spacy",
        "numpy"
    ]

    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 missing packages with:")
        print(f"   pip install {' '.join(missing_packages)}")
        return False

    print("βœ… All required packages are installed")
    return True

def install_dependencies():
    """Install dependencies from requirements.txt"""
    print("πŸ“¦ Installing dependencies...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        print("βœ… Dependencies installed successfully")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ Failed to install dependencies: {e}")
        return False

def run_tests():
    """Run the test suite"""
    print("πŸ§ͺ Running tests...")
    try:
        result = subprocess.run([sys.executable, "test_app.py"],
                              capture_output=True, text=True)

        if result.returncode == 0:
            print("βœ… All tests passed")
            return True
        else:
            print("❌ Some tests failed:")
            print(result.stdout)
            print(result.stderr)
            return False
    except FileNotFoundError:
        print("⚠️  Test file not found, skipping tests")
        return True

def launch_app(share=False, debug=False, port=7860):
    """Launch the Gradio app"""
    print("πŸš€ Starting PerplexityViewer...")

    # Set environment variables
    if debug:
        os.environ["GRADIO_DEBUG"] = "1"

    try:
        # Import and launch the app
        from app import demo

        # Prepare launch arguments with version compatibility
        launch_args = {
            "server_name": "0.0.0.0" if not debug else "127.0.0.1",
            "server_port": port,
            "share": share,
            "show_api": False
        }

        # Add quiet parameter only if supported (older Gradio versions)
        try:
            import gradio as gr
            # Check if quiet parameter is supported
            import inspect
            launch_signature = inspect.signature(demo.launch)
            if 'quiet' in launch_signature.parameters:
                launch_args["quiet"] = not debug
        except:
            pass  # If we can't check, just skip the quiet parameter

        demo.launch(**launch_args)

    except KeyboardInterrupt:
        print("\nπŸ‘‹ Shutting down PerplexityViewer")
    except Exception as e:
        print(f"❌ Failed to launch app: {e}")
        print("πŸ’‘ Try updating Gradio: pip install --upgrade gradio")
        sys.exit(1)

def main():
    """Main entry point"""
    parser = argparse.ArgumentParser(
        description="PerplexityViewer - Visualize text perplexity with color gradients",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python run.py                    # Launch with default settings
  python run.py --install          # Install dependencies first
  python run.py --test             # Run tests before launching
  python run.py --share             # Create shareable link
  python run.py --debug --port 8080 # Debug mode on custom port
        """
    )

    parser.add_argument("--install", action="store_true",
                       help="Install dependencies before launching")
    parser.add_argument("--test", action="store_true",
                       help="Run tests before launching")
    parser.add_argument("--share", action="store_true",
                       help="Create a shareable Gradio link")
    parser.add_argument("--debug", action="store_true",
                       help="Enable debug mode")
    parser.add_argument("--port", type=int, default=7860,
                       help="Port to run the server on (default: 7860)")
    parser.add_argument("--skip-checks", action="store_true",
                       help="Skip dependency checks")

    args = parser.parse_args()

    print("="*60)
    print("🎯 PerplexityViewer Startup")
    print("="*60)

    # Install dependencies if requested
    if args.install:
        if not install_dependencies():
            sys.exit(1)

    # Check dependencies unless skipped
    if not args.skip_checks:
        if not check_dependencies():
            print("\nπŸ’‘ Try running with --install to install missing packages")
            sys.exit(1)

    # Run tests if requested
    if args.test:
        if not run_tests():
            print("\n⚠️  Tests failed, but continuing anyway...")
            print("   Use Ctrl+C to cancel or wait to launch app")
            try:
                import time
                time.sleep(3)
            except KeyboardInterrupt:
                print("\nπŸ‘‹ Cancelled")
                sys.exit(0)

    # Launch the app
    print(f"\n🌐 App will be available at: http://localhost:{args.port}")
    if args.share:
        print("πŸ”— A shareable link will be created")

    launch_app(share=args.share, debug=args.debug, port=args.port)

if __name__ == "__main__":
    main()