CatPtain's picture
Upload 2 files
4ebe091 verified
raw
history blame
6.93 kB
#!/usr/bin/env python3
"""
Huggingface Spaces entry point for MoneyPrinterTurbo
Optimized for FREE tier (2 vCPU + 16GB RAM)
"""
import os
import sys
import subprocess
import toml
from pathlib import Path
# 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 optimized for HF Spaces FREE tier"""
print("📁 Creating storage directories...")
# Create necessary directories
os.makedirs("storage/tasks", exist_ok=True)
os.makedirs("storage/temp", exist_ok=True)
os.makedirs("storage/cache_videos", exist_ok=True)
os.makedirs(".streamlit", exist_ok=True)
# Create .streamlit/config.toml for proper configuration
streamlit_config = """
[server]
port = 7860
address = "0.0.0.0"
enableCORS = true
enableXsrfProtection = false
enableWebsocketCompression = false
[browser]
gatherUsageStats = false
"""
with open(".streamlit/config.toml", "w") as f:
f.write(streamlit_config)
print("✅ Directories and Streamlit config created")
def load_env_variables():
"""Load environment variables into config.toml"""
config_path = "config.toml"
# Load existing config or create default
try:
if os.path.exists(config_path):
config = toml.load(config_path)
else:
config = {
"app": {"max_concurrent_tasks": 1, "api_enabled": True},
"ui": {"hide_log": False},
"azure": {},
"siliconflow": {}
}
except Exception:
config = {
"app": {"max_concurrent_tasks": 1, "api_enabled": True},
"ui": {"hide_log": False},
"azure": {},
"siliconflow": {}
}
# Load environment variables
env_mappings = {
# MoneyPrinter API
"MONEYPRINTER_API_KEY": ("app", "api_key"),
# LLM providers
"DEEPSEEK_API_KEY": ("app", "deepseek_api_key"),
"MOONSHOT_API_KEY": ("app", "moonshot_api_key"),
"OPENAI_API_KEY": ("app", "openai_api_key"),
# Video sources
"PEXELS_API_KEY": ("app", "pexels_api_keys"),
"PIXABAY_API_KEY": ("app", "pixabay_api_keys"),
# Azure Speech
"AZURE_SPEECH_KEY": ("azure", "speech_key"),
"AZURE_SPEECH_REGION": ("azure", "speech_region"),
# SiliconFlow
"SILICONFLOW_API_KEY": ("siliconflow", "api_key"),
}
env_vars_loaded = []
for env_var, (section, key) in env_mappings.items():
value = os.getenv(env_var)
if value:
if section not in config:
config[section] = {}
# Handle API keys that should be lists
if key in ["pexels_api_keys", "pixabay_api_keys"]:
config[section][key] = [value] if isinstance(value, str) else value
else:
config[section][key] = value
env_vars_loaded.append(env_var)
# Save updated config
try:
with open(config_path, "w") as f:
toml.dump(config, f)
if env_vars_loaded:
print(f"✅ Loaded environment variables: {', '.join(env_vars_loaded)}")
else:
print("ℹ️ No environment variables found, using WebUI configuration")
except Exception as e:
print(f"⚠️ Could not save config: {e}")
def optimize_for_free_tier():
"""Apply FREE tier optimizations"""
print("🔧 Applying FREE tier optimizations...")
# Set environment variables for optimization
os.environ["STREAMLIT_SERVER_MAX_UPLOAD_SIZE"] = "10" # 10MB limit
os.environ["STREAMLIT_SERVER_MAX_MESSAGE_SIZE"] = "10" # 10MB limit
print("✅ FREE tier optimizations applied")
def start_streamlit():
"""Start Streamlit application"""
print("🚀 Starting Streamlit application...")
# Check if we should use SimpleMain (FREE tier) or full Main
use_simple = os.getenv("USE_SIMPLE_UI", "true").lower() == "true"
if use_simple:
streamlit_file = "webui/SimpleMain.py"
print("📱 Using SimpleMain.py (FREE tier optimized)")
else:
streamlit_file = "webui/Main.py"
print("🖥️ Using Main.py (full features)")
# Start Streamlit
try:
subprocess.run([
sys.executable, "-m", "streamlit", "run", streamlit_file,
"--server.port", "7860",
"--server.address", "0.0.0.0",
"--server.enableCORS", "true",
"--server.enableXsrfProtection", "false",
"--browser.gatherUsageStats", "false"
], check=True)
except subprocess.CalledProcessError as e:
print(f"❌ Failed to start Streamlit: {e}")
# Fallback to simple HTTP server
print("🔄 Falling back to simple HTTP server...")
# Create a simple status page
html_content = """<!DOCTYPE html>
<html>
<head>
<title>MoneyPrinterTurbo - Starting</title>
<meta charset="utf-8">
<style>
body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
.container { max-width: 600px; margin: 0 auto; }
h1 { color: #4CAF50; }
.status { padding: 20px; background: #f0f8ff; border-radius: 10px; margin: 20px 0; }
</style>
</head>
<body>
<div class="container">
<h1>🎬 MoneyPrinterTurbo</h1>
<div class="status">
<h2>🔄 应用启动中...</h2>
<p>Streamlit 启动失败,正在尝试备用方案。</p>
<p>请稍后刷新页面或检查日志获取更多信息。</p>
</div>
</div>
</body>
</html>"""
with open("index.html", "w", encoding="utf-8") as f:
f.write(html_content)
subprocess.run([
sys.executable, "-m", "http.server", "7860",
"--bind", "0.0.0.0"
])
if __name__ == "__main__":
print("🎬 MoneyPrinterTurbo - Huggingface Spaces Edition")
print("=" * 50)
try:
# Setup environment
setup_environment()
# Load environment variables
load_env_variables()
# Apply FREE tier optimizations
optimize_for_free_tier()
# Start application
start_streamlit()
except Exception as e:
print(f"❌ Fatal error: {e}")
import traceback
traceback.print_exc()
# Keep the process alive for debugging
import time
print("⏰ Keeping process alive for debugging...")
while True:
time.sleep(60)