File size: 4,345 Bytes
787c60a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ffb560
787c60a
 
 
 
 
 
 
 
937d315
1ffb560
 
937d315
 
 
 
 
1ffb560
b27a429
 
 
 
 
 
 
 
 
 
 
787c60a
 
 
 
 
 
 
 
 
937d315
1ffb560
 
937d315
 
787c60a
 
 
 
 
 
1ffb560
 
5f99700
 
 
 
 
 
 
1ffb560
5f99700
1ffb560
5f99700
 
 
 
 
 
 
 
1ffb560
 
5f99700
1ffb560
 
 
787c60a
 
5f99700
787c60a
 
 
 
5f99700
787c60a
 
 
 
 
 
 
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
"""
RoutePilot - GNN-LLM Intelligent Selection System
Hugging Face Spaces Entry Point

This is the main entry point for the Hugging Face Spaces deployment.
It imports the necessary components from the existing application and
sets up the Gradio interface for deployment.
"""

import os
import sys
import gradio as gr

# Add the current directory to Python path for imports
sys.path.append(os.path.dirname(__file__))

# Import the main application components
from demo import create_interface, initialize_nvidia_client, test_nvidia_api_connection

# Set up environment variables for Hugging Face Spaces
def setup_environment():
    """Set up environment variables for Hugging Face Spaces deployment"""
    # Check if we're running on Hugging Face Spaces
    if os.getenv("SPACE_ID"):
        print("πŸš€ Running on Hugging Face Spaces")
        
        # Check for NVIDIA API key
        api_key = os.getenv("NVIDIA_API_KEY")
        if not api_key:
            print("⚠️  NVIDIA_API_KEY not set in Space secrets.")
            print("   Please set NVIDIA_API_KEY in the Space Repository Secrets.")
            print("   Some features may be limited without API access.")
        else:
            print("βœ… NVIDIA_API_KEY found in Space secrets")
            print(f"   Key length: {len(api_key)} characters")
            print(f"   Key starts with: {api_key[:8]}...")
            print(f"   Key ends with: ...{api_key[-4:]}")
            print(f"   Key is all uppercase: {'Yes' if api_key.isupper() else 'No'}")
            
            # Check for common API key patterns
            if api_key.startswith('nvapi-'):
                print("   βœ… Key format appears correct (starts with 'nvapi-')")
            elif api_key.startswith('nv-'):
                print("   βœ… Key format appears correct (starts with 'nv-')")
            else:
                print("   ⚠️  Key format may be incorrect (should start with 'nvapi-' or 'nv-')")
        
        # Set CUDA device for Spaces (usually limited resources)
        os.environ["CUDA_VISIBLE_DEVICES"] = "0"
        
        # Set memory optimization flags
        os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:128"
        
    else:
        print("🏠 Running locally")
        # Check for local .env file
        api_key = os.getenv("NVIDIA_API_KEY")
        if not api_key:
            print("ℹ️  NVIDIA_API_KEY not found. For local development, create a .env file")
            print("   or set the environment variable manually.")

def main():
    """Main function to launch the application"""
    # Set up environment
    setup_environment()
    
    # Reinitialize NVIDIA client after environment setup
    print("πŸ”„ Reinitializing NVIDIA API client...")
    
    # Import demo module and reinitialize client
    import demo
    print(f"πŸ” Initial client status: {'βœ… Available' if demo.client is not None else '❌ None'}")
    print(f"πŸ” API key in environment: {'βœ… Present' if os.getenv('NVIDIA_API_KEY') else '❌ Missing'}")
    
    if demo.client is None and os.getenv("NVIDIA_API_KEY"):
        print("πŸ”„ Attempting to reinitialize client with environment variables...")
        # Reinitialize the client and update the module variable
        demo.client = initialize_nvidia_client()
        print(f"πŸ”„ Client reinitialized: {'βœ… Success' if demo.client is not None else '❌ Failed'}")
    elif demo.client is not None:
        print("βœ… Client already initialized")
    else:
        print("❌ No API key available for client initialization")
    
    # Final client status check
    print(f"πŸ” Final client status: {'βœ… Available' if demo.client is not None else '❌ None'}")
    
    # Test API connection
    if os.getenv("NVIDIA_API_KEY") and demo.client is not None:
        print("πŸ§ͺ Testing NVIDIA API connection...")
        test_nvidia_api_connection()
    
    # Create the Gradio interface
    print("🎯 Creating RoutePilot interface...")
    demo_interface = create_interface()
    
    # Launch the application
    # For Hugging Face Spaces, we don't need to specify server_name and port
    # The platform handles this automatically
    demo_interface.launch(
        show_error=True,
        debug=False,  # Set to False for production
        show_api=False
    )

if __name__ == "__main__":
    main()