File size: 6,282 Bytes
46ab29c
 
 
 
 
 
 
77fd65d
46ab29c
 
 
 
 
 
 
77fd65d
46ab29c
 
 
 
 
 
 
 
 
 
 
77fd65d
46ab29c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77fd65d
46ab29c
 
 
 
77fd65d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46ab29c
 
77fd65d
 
 
 
46ab29c
 
 
 
 
 
77fd65d
 
46ab29c
77fd65d
 
 
 
 
 
 
 
46ab29c
 
77fd65d
 
 
46ab29c
 
 
 
 
 
 
 
 
77fd65d
46ab29c
 
77fd65d
46ab29c
77fd65d
 
 
 
 
 
 
 
46ab29c
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
#!/usr/bin/env python3
"""

Huggingface Spaces entry point for MoneyPrinterTurbo

"""
import os
import sys
import subprocess
import time

# Add the root directory to Python path
root_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, root_dir)

def setup_environment():
    """Setup environment for Huggingface Spaces"""
    print("πŸ“ Creating storage directories...")
    # Create necessary directories
    os.makedirs(os.path.join(root_dir, "storage", "tasks"), exist_ok=True)
    os.makedirs(os.path.join(root_dir, "storage", "cache_videos"), exist_ok=True)
    os.makedirs(os.path.join(root_dir, "storage", "temp"), exist_ok=True)
    
    # Set environment variables for Huggingface Spaces
    os.environ["STREAMLIT_SERVER_PORT"] = "7860"
    os.environ["STREAMLIT_SERVER_ADDRESS"] = "0.0.0.0"
    os.environ["STREAMLIT_BROWSER_GATHER_USAGE_STATS"] = "false"
    os.environ["STREAMLIT_SERVER_ENABLE_CORS"] = "true"
    
    print("πŸ”§ Setting up configuration...")
    # Load API keys from environment variables if available
    setup_api_keys_from_env()

def setup_api_keys_from_env():
    """Setup API keys from environment variables"""
    try:
        from app.config import config
        
        keys_loaded = []
        
        # MoneyPrinterTurbo API Key for external access
        if os.getenv("MONEYPRINTER_API_KEY"):
            config.app["api_key"] = os.getenv("MONEYPRINTER_API_KEY")
            config.app["api_enabled"] = True
            keys_loaded.append("MoneyPrinter API")
        
        # LLM Provider API Keys
        if os.getenv("OPENAI_API_KEY"):
            config.app["openai_api_key"] = os.getenv("OPENAI_API_KEY")
            keys_loaded.append("OpenAI")
            
        if os.getenv("DEEPSEEK_API_KEY"):
            config.app["deepseek_api_key"] = os.getenv("DEEPSEEK_API_KEY")
            keys_loaded.append("DeepSeek")
            
        if os.getenv("MOONSHOT_API_KEY"):
            config.app["moonshot_api_key"] = os.getenv("MOONSHOT_API_KEY")
            keys_loaded.append("Moonshot")
            
        # Video Source API Keys
        if os.getenv("PEXELS_API_KEY"):
            config.app["pexels_api_keys"] = [os.getenv("PEXELS_API_KEY")]
            keys_loaded.append("Pexels")
            
        if os.getenv("PIXABAY_API_KEY"):
            config.app["pixabay_api_keys"] = [os.getenv("PIXABAY_API_KEY")]
            keys_loaded.append("Pixabay")
            
        # Azure Speech API
        if os.getenv("AZURE_SPEECH_KEY"):
            config.azure["speech_key"] = os.getenv("AZURE_SPEECH_KEY")
            keys_loaded.append("Azure Speech")
            
        if os.getenv("AZURE_SPEECH_REGION"):
            config.azure["speech_region"] = os.getenv("AZURE_SPEECH_REGION")
            
        # Set default LLM provider based on available keys
        if os.getenv("DEEPSEEK_API_KEY"):
            config.app["llm_provider"] = "deepseek"
            print("πŸ€– Default LLM provider: DeepSeek")
        elif os.getenv("MOONSHOT_API_KEY"):
            config.app["llm_provider"] = "moonshot"
            print("πŸ€– Default LLM provider: Moonshot")
        elif os.getenv("OPENAI_API_KEY"):
            config.app["llm_provider"] = "openai"
            print("πŸ€– Default LLM provider: OpenAI")
            
        if keys_loaded:
            print(f"βœ… API keys configured: {len(keys_loaded)} service(s)")
        else:
            print("πŸ“ No API keys found in environment variables")
            print("πŸ’‘ You can configure them in the WebUI after startup")
            
        config.save_config()
        
    except Exception as e:
        print(f"⚠️ Warning: Could not load API keys from environment: {e}")

def check_system_dependencies():
    """Check if required system dependencies are available"""
    print("πŸ” Checking system dependencies...")
    
    # Check for ffmpeg
    try:
        subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
        print("βœ… FFmpeg is available")
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("⚠️ FFmpeg not found - video processing may fail")
    
    # Check Python version
    if sys.version_info >= (3, 8):
        print(f"βœ… Python {sys.version_info.major}.{sys.version_info.minor} is compatible")
    else:
        print(f"⚠️ Python {sys.version_info.major}.{sys.version_info.minor} may have compatibility issues")

def start_streamlit():
    """Start Streamlit app with proper error handling"""
    print("πŸš€ Starting Streamlit application...")
    
    streamlit_cmd = [
        sys.executable, "-m", "streamlit", "run", 
        os.path.join(root_dir, "webui", "Main.py"),
        "--server.port=7860",
        "--server.address=0.0.0.0",
        "--browser.gatherUsageStats=false",
        "--server.enableCORS=true",
        "--theme.base=light",
        "--server.enableWebsocketCompression=false"
    ]
    
    try:
        # Use exec to replace the current process
        os.execvp(sys.executable, streamlit_cmd)
    except Exception as e:
        print(f"❌ Failed to start Streamlit: {e}")
        # Fallback to subprocess
        subprocess.run(streamlit_cmd)

if __name__ == "__main__":
    print("=" * 50)
    print("πŸš€ MoneyPrinterTurbo Starting on Huggingface Spaces")
    print("=" * 50)
    
    # Check for environment variables without exposing which ones
    env_check_keys = ["OPENAI_API_KEY", "DEEPSEEK_API_KEY", "MOONSHOT_API_KEY", 
                      "PEXELS_API_KEY", "PIXABAY_API_KEY"]
    env_keys_count = sum(1 for key in env_check_keys if os.getenv(key))
    
    if env_keys_count > 0:
        print(f"πŸ”‘ Found {env_keys_count} API key(s) in environment")
    else:
        print("πŸ“ No API keys found in environment variables")
        print("πŸ“‹ Required: LLM Provider API Key + Video Source API Key")
    
    # Setup environment
    setup_environment()
    
    # Check system dependencies
    check_system_dependencies()
    
    # Small delay to ensure everything is set up
    time.sleep(2)
    
    # Start the application
    start_streamlit()