CatPtain commited on
Commit
4ebe091
·
verified ·
1 Parent(s): d6bcd29

Upload 2 files

Browse files
Files changed (1) hide show
  1. app.py +178 -70
app.py CHANGED
@@ -1,106 +1,214 @@
1
  #!/usr/bin/env python3
2
  """
3
  Huggingface Spaces entry point for MoneyPrinterTurbo
4
- Stage 2: Streamlit Integration
5
  """
 
6
  import os
7
  import sys
8
  import subprocess
9
- import traceback
10
- import time
11
 
12
  # Add the root directory to Python path
13
  root_dir = os.path.dirname(os.path.abspath(__file__))
14
  sys.path.insert(0, root_dir)
15
 
16
  def setup_environment():
17
- """Setup environment for Huggingface Spaces"""
18
  print("📁 Creating storage directories...")
19
  # Create necessary directories
20
- os.makedirs(os.path.join(root_dir, "storage", "tasks"), exist_ok=True)
21
- os.makedirs(os.path.join(root_dir, "storage", "cache_videos"), exist_ok=True)
22
- os.makedirs(os.path.join(root_dir, "storage", "temp"), exist_ok=True)
23
- print(" Storage directories created successfully")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  def load_env_variables():
26
- """Load environment variables into config"""
27
- print("🔑 Loading environment variables...")
 
 
28
  try:
29
- # Try to load environment variables into config
30
- env_vars = {
31
- 'MONEYPRINTER_API_KEY': 'api_key',
32
- 'DEEPSEEK_API_KEY': 'deepseek_api_key',
33
- 'MOONSHOT_API_KEY': 'moonshot_api_key',
34
- 'OPENAI_API_KEY': 'openai_api_key',
35
- 'PEXELS_API_KEY': 'pexels_api_keys',
36
- 'PIXABAY_API_KEY': 'pixabay_api_keys',
37
- 'AZURE_SPEECH_KEY': 'azure_speech_key',
38
- 'AZURE_SPEECH_REGION': 'azure_speech_region'
 
 
 
 
 
39
  }
 
 
 
 
 
40
 
41
- loaded_count = 0
42
- for env_key, config_key in env_vars.items():
43
- value = os.getenv(env_key)
44
- if value:
45
- print(f"✅ Loaded {env_key}")
46
- loaded_count += 1
47
 
48
- if loaded_count > 0:
49
- print(f"🎯 Successfully loaded {loaded_count} environment variables")
50
- else:
51
- print("💡 No environment variables found - will use WebUI configuration")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
 
 
 
 
 
 
 
 
 
 
 
53
  except Exception as e:
54
- print(f"⚠️ Warning loading environment variables: {e}")
55
 
56
- def start_streamlit():
57
- """Start Streamlit app"""
58
- print("🚀 Starting MoneyPrinterTurbo Streamlit WebUI...")
59
- print("🎯 Stage 2: Basic Streamlit Integration")
60
 
61
- # Setup environment first
62
- setup_environment()
63
- load_env_variables()
64
 
65
- # Use SimpleMain.py for basic functionality
66
- streamlit_app = os.path.join(root_dir, "webui", "SimpleMain.py")
 
 
 
67
 
68
- if not os.path.exists(streamlit_app):
69
- print(f" SimpleMain.py not found at: {streamlit_app}")
70
- # Fallback to creating a minimal inline app
71
- minimal_app = os.path.join(root_dir, "minimal_app.py")
72
- with open(minimal_app, 'w', encoding='utf-8') as f:
73
- f.write('''
74
- import streamlit as st
75
- st.set_page_config(page_title="MoneyPrinterTurbo", page_icon="🎬")
76
- st.title("🎬 MoneyPrinterTurbo")
77
- st.success("✅ 应用成功启动!")
78
- st.info("这是一个最小化版本,用于验证 Streamlit 集成。")
79
- st.write("如果您看到这个页面,说明 Stage 2 部署成功!")
80
- ''')
81
- streamlit_app = minimal_app
82
- print(f"✅ Created fallback minimal app at: {minimal_app}")
83
 
84
- print(f"📄 Using Streamlit app: {streamlit_app}")
 
 
 
 
 
85
 
86
- # Start Streamlit using exec to replace current process
87
- os.execvp(sys.executable, [
88
- sys.executable, "-m", "streamlit", "run",
89
- streamlit_app,
90
- "--server.port=7860",
91
- "--server.address=0.0.0.0",
92
- "--browser.gatherUsageStats=false"
93
- ])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  if __name__ == "__main__":
96
- print("🎬 MoneyPrinterTurbo - Stage 2: Streamlit Integration")
 
 
97
  try:
 
 
 
 
 
 
 
 
 
 
98
  start_streamlit()
 
99
  except Exception as e:
100
- print(f"❌ Error starting application: {e}")
 
101
  traceback.print_exc()
102
- # Keep process alive for debugging
103
- print("🔄 Keeping process alive for debugging...")
 
 
104
  while True:
105
- print("⏰ Process is alive, waiting...")
106
- time.sleep(30)
 
1
  #!/usr/bin/env python3
2
  """
3
  Huggingface Spaces entry point for MoneyPrinterTurbo
4
+ Optimized for FREE tier (2 vCPU + 16GB RAM)
5
  """
6
+
7
  import os
8
  import sys
9
  import subprocess
10
+ import toml
11
+ from pathlib import Path
12
 
13
  # Add the root directory to Python path
14
  root_dir = os.path.dirname(os.path.abspath(__file__))
15
  sys.path.insert(0, root_dir)
16
 
17
  def setup_environment():
18
+ """Setup environment optimized for HF Spaces FREE tier"""
19
  print("📁 Creating storage directories...")
20
  # Create necessary directories
21
+ os.makedirs("storage/tasks", exist_ok=True)
22
+ os.makedirs("storage/temp", exist_ok=True)
23
+ os.makedirs("storage/cache_videos", exist_ok=True)
24
+ os.makedirs(".streamlit", exist_ok=True)
25
+
26
+ # Create .streamlit/config.toml for proper configuration
27
+ streamlit_config = """
28
+ [server]
29
+ port = 7860
30
+ address = "0.0.0.0"
31
+ enableCORS = true
32
+ enableXsrfProtection = false
33
+ enableWebsocketCompression = false
34
+
35
+ [browser]
36
+ gatherUsageStats = false
37
+ """
38
+
39
+ with open(".streamlit/config.toml", "w") as f:
40
+ f.write(streamlit_config)
41
+
42
+ print("✅ Directories and Streamlit config created")
43
 
44
  def load_env_variables():
45
+ """Load environment variables into config.toml"""
46
+ config_path = "config.toml"
47
+
48
+ # Load existing config or create default
49
  try:
50
+ if os.path.exists(config_path):
51
+ config = toml.load(config_path)
52
+ else:
53
+ config = {
54
+ "app": {"max_concurrent_tasks": 1, "api_enabled": True},
55
+ "ui": {"hide_log": False},
56
+ "azure": {},
57
+ "siliconflow": {}
58
+ }
59
+ except Exception:
60
+ config = {
61
+ "app": {"max_concurrent_tasks": 1, "api_enabled": True},
62
+ "ui": {"hide_log": False},
63
+ "azure": {},
64
+ "siliconflow": {}
65
  }
66
+
67
+ # Load environment variables
68
+ env_mappings = {
69
+ # MoneyPrinter API
70
+ "MONEYPRINTER_API_KEY": ("app", "api_key"),
71
 
72
+ # LLM providers
73
+ "DEEPSEEK_API_KEY": ("app", "deepseek_api_key"),
74
+ "MOONSHOT_API_KEY": ("app", "moonshot_api_key"),
75
+ "OPENAI_API_KEY": ("app", "openai_api_key"),
 
 
76
 
77
+ # Video sources
78
+ "PEXELS_API_KEY": ("app", "pexels_api_keys"),
79
+ "PIXABAY_API_KEY": ("app", "pixabay_api_keys"),
80
+
81
+ # Azure Speech
82
+ "AZURE_SPEECH_KEY": ("azure", "speech_key"),
83
+ "AZURE_SPEECH_REGION": ("azure", "speech_region"),
84
+
85
+ # SiliconFlow
86
+ "SILICONFLOW_API_KEY": ("siliconflow", "api_key"),
87
+ }
88
+
89
+ env_vars_loaded = []
90
+ for env_var, (section, key) in env_mappings.items():
91
+ value = os.getenv(env_var)
92
+ if value:
93
+ if section not in config:
94
+ config[section] = {}
95
+
96
+ # Handle API keys that should be lists
97
+ if key in ["pexels_api_keys", "pixabay_api_keys"]:
98
+ config[section][key] = [value] if isinstance(value, str) else value
99
+ else:
100
+ config[section][key] = value
101
 
102
+ env_vars_loaded.append(env_var)
103
+
104
+ # Save updated config
105
+ try:
106
+ with open(config_path, "w") as f:
107
+ toml.dump(config, f)
108
+
109
+ if env_vars_loaded:
110
+ print(f"✅ Loaded environment variables: {', '.join(env_vars_loaded)}")
111
+ else:
112
+ print("ℹ️ No environment variables found, using WebUI configuration")
113
  except Exception as e:
114
+ print(f"⚠️ Could not save config: {e}")
115
 
116
+ def optimize_for_free_tier():
117
+ """Apply FREE tier optimizations"""
118
+ print("🔧 Applying FREE tier optimizations...")
 
119
 
120
+ # Set environment variables for optimization
121
+ os.environ["STREAMLIT_SERVER_MAX_UPLOAD_SIZE"] = "10" # 10MB limit
122
+ os.environ["STREAMLIT_SERVER_MAX_MESSAGE_SIZE"] = "10" # 10MB limit
123
 
124
+ print("✅ FREE tier optimizations applied")
125
+
126
+ def start_streamlit():
127
+ """Start Streamlit application"""
128
+ print("🚀 Starting Streamlit application...")
129
 
130
+ # Check if we should use SimpleMain (FREE tier) or full Main
131
+ use_simple = os.getenv("USE_SIMPLE_UI", "true").lower() == "true"
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
+ if use_simple:
134
+ streamlit_file = "webui/SimpleMain.py"
135
+ print("📱 Using SimpleMain.py (FREE tier optimized)")
136
+ else:
137
+ streamlit_file = "webui/Main.py"
138
+ print("🖥️ Using Main.py (full features)")
139
 
140
+ # Start Streamlit
141
+ try:
142
+ subprocess.run([
143
+ sys.executable, "-m", "streamlit", "run", streamlit_file,
144
+ "--server.port", "7860",
145
+ "--server.address", "0.0.0.0",
146
+ "--server.enableCORS", "true",
147
+ "--server.enableXsrfProtection", "false",
148
+ "--browser.gatherUsageStats", "false"
149
+ ], check=True)
150
+ except subprocess.CalledProcessError as e:
151
+ print(f"❌ Failed to start Streamlit: {e}")
152
+ # Fallback to simple HTTP server
153
+ print("🔄 Falling back to simple HTTP server...")
154
+
155
+ # Create a simple status page
156
+ html_content = """<!DOCTYPE html>
157
+ <html>
158
+ <head>
159
+ <title>MoneyPrinterTurbo - Starting</title>
160
+ <meta charset="utf-8">
161
+ <style>
162
+ body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
163
+ .container { max-width: 600px; margin: 0 auto; }
164
+ h1 { color: #4CAF50; }
165
+ .status { padding: 20px; background: #f0f8ff; border-radius: 10px; margin: 20px 0; }
166
+ </style>
167
+ </head>
168
+ <body>
169
+ <div class="container">
170
+ <h1>🎬 MoneyPrinterTurbo</h1>
171
+ <div class="status">
172
+ <h2>🔄 应用启动中...</h2>
173
+ <p>Streamlit 启动失败,正在尝试备用方案。</p>
174
+ <p>请稍后刷新页面或检查日志获取更多信息。</p>
175
+ </div>
176
+ </div>
177
+ </body>
178
+ </html>"""
179
+
180
+ with open("index.html", "w", encoding="utf-8") as f:
181
+ f.write(html_content)
182
+
183
+ subprocess.run([
184
+ sys.executable, "-m", "http.server", "7860",
185
+ "--bind", "0.0.0.0"
186
+ ])
187
 
188
  if __name__ == "__main__":
189
+ print("🎬 MoneyPrinterTurbo - Huggingface Spaces Edition")
190
+ print("=" * 50)
191
+
192
  try:
193
+ # Setup environment
194
+ setup_environment()
195
+
196
+ # Load environment variables
197
+ load_env_variables()
198
+
199
+ # Apply FREE tier optimizations
200
+ optimize_for_free_tier()
201
+
202
+ # Start application
203
  start_streamlit()
204
+
205
  except Exception as e:
206
+ print(f"❌ Fatal error: {e}")
207
+ import traceback
208
  traceback.print_exc()
209
+
210
+ # Keep the process alive for debugging
211
+ import time
212
+ print("⏰ Keeping process alive for debugging...")
213
  while True:
214
+ time.sleep(60)