Bram van Es
first push
80323f9
#!/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()